1 //===--- TokenAnnotator.cpp - Format C++ code -----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements a token annotator, i.e. creates
11 /// \c AnnotatedTokens out of \c FormatTokens with required extra information.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "TokenAnnotator.h"
16 #include "FormatToken.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 /// Returns \c true if the token can be used as an identifier in
29 /// an Objective-C \c @selector, \c false otherwise.
30 ///
31 /// Because getFormattingLangOpts() always lexes source code as
32 /// Objective-C++, C++ keywords like \c new and \c delete are
33 /// lexed as tok::kw_*, not tok::identifier, even for Objective-C.
34 ///
35 /// For Objective-C and Objective-C++, both identifiers and keywords
36 /// are valid inside @selector(...) (or a macro which
37 /// invokes @selector(...)). So, we allow treat any identifier or
38 /// keyword as a potential Objective-C selector component.
39 static bool canBeObjCSelectorComponent(const FormatToken &Tok) {
40   return Tok.Tok.getIdentifierInfo() != nullptr;
41 }
42 
43 /// A parser that gathers additional information about tokens.
44 ///
45 /// The \c TokenAnnotator tries to match parenthesis and square brakets and
46 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
47 /// into template parameter lists.
48 class AnnotatingParser {
49 public:
50   AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
51                    const AdditionalKeywords &Keywords)
52       : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
53         Keywords(Keywords) {
54     Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
55     resetTokenMetadata(CurrentToken);
56   }
57 
58 private:
59   bool parseAngle() {
60     if (!CurrentToken || !CurrentToken->Previous)
61       return false;
62     if (NonTemplateLess.count(CurrentToken->Previous))
63       return false;
64 
65     const FormatToken &Previous = *CurrentToken->Previous; // The '<'.
66     if (Previous.Previous) {
67       if (Previous.Previous->Tok.isLiteral())
68         return false;
69       if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 &&
70           (!Previous.Previous->MatchingParen ||
71            !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen)))
72         return false;
73     }
74 
75     FormatToken *Left = CurrentToken->Previous;
76     Left->ParentBracket = Contexts.back().ContextKind;
77     ScopedContextCreator ContextCreator(*this, tok::less, 12);
78 
79     // If this angle is in the context of an expression, we need to be more
80     // hesitant to detect it as opening template parameters.
81     bool InExprContext = Contexts.back().IsExpression;
82 
83     Contexts.back().IsExpression = false;
84     // If there's a template keyword before the opening angle bracket, this is a
85     // template parameter, not an argument.
86     Contexts.back().InTemplateArgument =
87         Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);
88 
89     if (Style.Language == FormatStyle::LK_Java &&
90         CurrentToken->is(tok::question))
91       next();
92 
93     while (CurrentToken) {
94       if (CurrentToken->is(tok::greater)) {
95         Left->MatchingParen = CurrentToken;
96         CurrentToken->MatchingParen = Left;
97         // In TT_Proto, we must distignuish between:
98         //   map<key, value>
99         //   msg < item: data >
100         //   msg: < item: data >
101         // In TT_TextProto, map<key, value> does not occur.
102         if (Style.Language == FormatStyle::LK_TextProto ||
103             (Style.Language == FormatStyle::LK_Proto && Left->Previous &&
104              Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral)))
105           CurrentToken->Type = TT_DictLiteral;
106         else
107           CurrentToken->Type = TT_TemplateCloser;
108         next();
109         return true;
110       }
111       if (CurrentToken->is(tok::question) &&
112           Style.Language == FormatStyle::LK_Java) {
113         next();
114         continue;
115       }
116       if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) ||
117           (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext &&
118            Style.Language != FormatStyle::LK_Proto &&
119            Style.Language != FormatStyle::LK_TextProto))
120         return false;
121       // If a && or || is found and interpreted as a binary operator, this set
122       // of angles is likely part of something like "a < b && c > d". If the
123       // angles are inside an expression, the ||/&& might also be a binary
124       // operator that was misinterpreted because we are parsing template
125       // parameters.
126       // FIXME: This is getting out of hand, write a decent parser.
127       if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
128           CurrentToken->Previous->is(TT_BinaryOperator) &&
129           Contexts[Contexts.size() - 2].IsExpression &&
130           !Line.startsWith(tok::kw_template))
131         return false;
132       updateParameterCount(Left, CurrentToken);
133       if (Style.Language == FormatStyle::LK_Proto) {
134         if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
135           if (CurrentToken->is(tok::colon) ||
136               (CurrentToken->isOneOf(tok::l_brace, tok::less) &&
137                Previous->isNot(tok::colon)))
138             Previous->Type = TT_SelectorName;
139         }
140       }
141       if (!consumeToken())
142         return false;
143     }
144     return false;
145   }
146 
147   bool parseParens(bool LookForDecls = false) {
148     if (!CurrentToken)
149       return false;
150     FormatToken *Left = CurrentToken->Previous;
151     Left->ParentBracket = Contexts.back().ContextKind;
152     ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
153 
154     // FIXME: This is a bit of a hack. Do better.
155     Contexts.back().ColonIsForRangeExpr =
156         Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
157 
158     bool StartsObjCMethodExpr = false;
159     if (FormatToken *MaybeSel = Left->Previous) {
160       // @selector( starts a selector.
161       if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
162           MaybeSel->Previous->is(tok::at)) {
163         StartsObjCMethodExpr = true;
164       }
165     }
166 
167     if (Left->is(TT_OverloadedOperatorLParen)) {
168       Contexts.back().IsExpression = false;
169     } else if (Style.Language == FormatStyle::LK_JavaScript &&
170                (Line.startsWith(Keywords.kw_type, tok::identifier) ||
171                 Line.startsWith(tok::kw_export, Keywords.kw_type,
172                                 tok::identifier))) {
173       // type X = (...);
174       // export type X = (...);
175       Contexts.back().IsExpression = false;
176     } else if (Left->Previous &&
177                (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
178                                         tok::kw_while, tok::l_paren,
179                                         tok::comma) ||
180                 Left->Previous->isIf() ||
181                 Left->Previous->is(TT_BinaryOperator))) {
182       // static_assert, if and while usually contain expressions.
183       Contexts.back().IsExpression = true;
184     } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
185                (Left->Previous->is(Keywords.kw_function) ||
186                 (Left->Previous->endsSequence(tok::identifier,
187                                               Keywords.kw_function)))) {
188       // function(...) or function f(...)
189       Contexts.back().IsExpression = false;
190     } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
191                Left->Previous->is(TT_JsTypeColon)) {
192       // let x: (SomeType);
193       Contexts.back().IsExpression = false;
194     } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
195                Left->Previous->MatchingParen &&
196                Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
197       // This is a parameter list of a lambda expression.
198       Contexts.back().IsExpression = false;
199     } else if (Line.InPPDirective &&
200                (!Left->Previous || !Left->Previous->is(tok::identifier))) {
201       Contexts.back().IsExpression = true;
202     } else if (Contexts[Contexts.size() - 2].CaretFound) {
203       // This is the parameter list of an ObjC block.
204       Contexts.back().IsExpression = false;
205     } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
206       Left->Type = TT_AttributeParen;
207     } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
208       // The first argument to a foreach macro is a declaration.
209       Contexts.back().IsForEachMacro = true;
210       Contexts.back().IsExpression = false;
211     } else if (Left->Previous && Left->Previous->MatchingParen &&
212                Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
213       Contexts.back().IsExpression = false;
214     } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
215       bool IsForOrCatch =
216           Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
217       Contexts.back().IsExpression = !IsForOrCatch;
218     }
219 
220     if (StartsObjCMethodExpr) {
221       Contexts.back().ColonIsObjCMethodExpr = true;
222       Left->Type = TT_ObjCMethodExpr;
223     }
224 
225     // MightBeFunctionType and ProbablyFunctionType are used for
226     // function pointer and reference types as well as Objective-C
227     // block types:
228     //
229     // void (*FunctionPointer)(void);
230     // void (&FunctionReference)(void);
231     // void (^ObjCBlock)(void);
232     bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
233     bool ProbablyFunctionType =
234         CurrentToken->isOneOf(tok::star, tok::amp, tok::caret);
235     bool HasMultipleLines = false;
236     bool HasMultipleParametersOnALine = false;
237     bool MightBeObjCForRangeLoop =
238         Left->Previous && Left->Previous->is(tok::kw_for);
239     FormatToken *PossibleObjCForInToken = nullptr;
240     while (CurrentToken) {
241       // LookForDecls is set when "if (" has been seen. Check for
242       // 'identifier' '*' 'identifier' followed by not '=' -- this
243       // '*' has to be a binary operator but determineStarAmpUsage() will
244       // categorize it as an unary operator, so set the right type here.
245       if (LookForDecls && CurrentToken->Next) {
246         FormatToken *Prev = CurrentToken->getPreviousNonComment();
247         if (Prev) {
248           FormatToken *PrevPrev = Prev->getPreviousNonComment();
249           FormatToken *Next = CurrentToken->Next;
250           if (PrevPrev && PrevPrev->is(tok::identifier) &&
251               Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
252               CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
253             Prev->Type = TT_BinaryOperator;
254             LookForDecls = false;
255           }
256         }
257       }
258 
259       if (CurrentToken->Previous->is(TT_PointerOrReference) &&
260           CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
261                                                     tok::coloncolon))
262         ProbablyFunctionType = true;
263       if (CurrentToken->is(tok::comma))
264         MightBeFunctionType = false;
265       if (CurrentToken->Previous->is(TT_BinaryOperator))
266         Contexts.back().IsExpression = true;
267       if (CurrentToken->is(tok::r_paren)) {
268         if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next &&
269             (CurrentToken->Next->is(tok::l_paren) ||
270              (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration)))
271           Left->Type = Left->Next->is(tok::caret) ? TT_ObjCBlockLParen
272                                                   : TT_FunctionTypeLParen;
273         Left->MatchingParen = CurrentToken;
274         CurrentToken->MatchingParen = Left;
275 
276         if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
277             Left->Previous && Left->Previous->is(tok::l_paren)) {
278           // Detect the case where macros are used to generate lambdas or
279           // function bodies, e.g.:
280           //   auto my_lambda = MARCO((Type *type, int i) { .. body .. });
281           for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
282             if (Tok->is(TT_BinaryOperator) &&
283                 Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
284               Tok->Type = TT_PointerOrReference;
285           }
286         }
287 
288         if (StartsObjCMethodExpr) {
289           CurrentToken->Type = TT_ObjCMethodExpr;
290           if (Contexts.back().FirstObjCSelectorName) {
291             Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
292                 Contexts.back().LongestObjCSelectorName;
293           }
294         }
295 
296         if (Left->is(TT_AttributeParen))
297           CurrentToken->Type = TT_AttributeParen;
298         if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
299           CurrentToken->Type = TT_JavaAnnotation;
300         if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
301           CurrentToken->Type = TT_LeadingJavaAnnotation;
302         if (Left->Previous && Left->Previous->is(TT_AttributeSquare))
303           CurrentToken->Type = TT_AttributeSquare;
304 
305         if (!HasMultipleLines)
306           Left->PackingKind = PPK_Inconclusive;
307         else if (HasMultipleParametersOnALine)
308           Left->PackingKind = PPK_BinPacked;
309         else
310           Left->PackingKind = PPK_OnePerLine;
311 
312         next();
313         return true;
314       }
315       if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
316         return false;
317 
318       if (CurrentToken->is(tok::l_brace))
319         Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
320       if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
321           !CurrentToken->Next->HasUnescapedNewline &&
322           !CurrentToken->Next->isTrailingComment())
323         HasMultipleParametersOnALine = true;
324       if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
325            CurrentToken->Previous->isSimpleTypeSpecifier()) &&
326           !CurrentToken->is(tok::l_brace))
327         Contexts.back().IsExpression = false;
328       if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
329         MightBeObjCForRangeLoop = false;
330         if (PossibleObjCForInToken) {
331           PossibleObjCForInToken->Type = TT_Unknown;
332           PossibleObjCForInToken = nullptr;
333         }
334       }
335       if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
336         PossibleObjCForInToken = CurrentToken;
337         PossibleObjCForInToken->Type = TT_ObjCForIn;
338       }
339       // When we discover a 'new', we set CanBeExpression to 'false' in order to
340       // parse the type correctly. Reset that after a comma.
341       if (CurrentToken->is(tok::comma))
342         Contexts.back().CanBeExpression = true;
343 
344       FormatToken *Tok = CurrentToken;
345       if (!consumeToken())
346         return false;
347       updateParameterCount(Left, Tok);
348       if (CurrentToken && CurrentToken->HasUnescapedNewline)
349         HasMultipleLines = true;
350     }
351     return false;
352   }
353 
354   bool isCSharpAttributeSpecifier(const FormatToken &Tok) {
355     if (!Style.isCSharp())
356       return false;
357 
358     const FormatToken *AttrTok = Tok.Next;
359     if (!AttrTok)
360       return false;
361 
362     // Just an empty declaration e.g. string [].
363     if (AttrTok->is(tok::r_square))
364       return false;
365 
366     // Move along the tokens inbetween the '[' and ']' e.g. [STAThread].
367     while (AttrTok && AttrTok->isNot(tok::r_square)) {
368       AttrTok = AttrTok->Next;
369     }
370 
371     if (!AttrTok)
372       return false;
373 
374     // Move past the end of ']'.
375     AttrTok = AttrTok->Next;
376     if (!AttrTok)
377       return false;
378 
379     // Limit this to being an access modifier that follows.
380     if (AttrTok->isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
381                          tok::kw_class, tok::kw_static, tok::l_square,
382                          Keywords.kw_internal)) {
383       return true;
384     }
385     return false;
386   }
387 
388   bool isCpp11AttributeSpecifier(const FormatToken &Tok) {
389     if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square))
390       return false;
391     // The first square bracket is part of an ObjC array literal
392     if (Tok.Previous && Tok.Previous->is(tok::at)) {
393       return false;
394     }
395     const FormatToken *AttrTok = Tok.Next->Next;
396     if (!AttrTok)
397       return false;
398     // C++17 '[[using ns: foo, bar(baz, blech)]]'
399     // We assume nobody will name an ObjC variable 'using'.
400     if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
401       return true;
402     if (AttrTok->isNot(tok::identifier))
403       return false;
404     while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
405       // ObjC message send. We assume nobody will use : in a C++11 attribute
406       // specifier parameter, although this is technically valid:
407       // [[foo(:)]].
408       if (AttrTok->is(tok::colon) ||
409           AttrTok->startsSequence(tok::identifier, tok::identifier) ||
410           AttrTok->startsSequence(tok::r_paren, tok::identifier))
411         return false;
412       if (AttrTok->is(tok::ellipsis))
413         return true;
414       AttrTok = AttrTok->Next;
415     }
416     return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
417   }
418 
419   bool parseSquare() {
420     if (!CurrentToken)
421       return false;
422 
423     // A '[' could be an index subscript (after an identifier or after
424     // ')' or ']'), it could be the start of an Objective-C method
425     // expression, it could the start of an Objective-C array literal,
426     // or it could be a C++ attribute specifier [[foo::bar]].
427     FormatToken *Left = CurrentToken->Previous;
428     Left->ParentBracket = Contexts.back().ContextKind;
429     FormatToken *Parent = Left->getPreviousNonComment();
430 
431     // Cases where '>' is followed by '['.
432     // In C++, this can happen either in array of templates (foo<int>[10])
433     // or when array is a nested template type (unique_ptr<type1<type2>[]>).
434     bool CppArrayTemplates =
435         Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
436         (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
437          Contexts.back().InTemplateArgument);
438 
439     bool IsCpp11AttributeSpecifier = isCpp11AttributeSpecifier(*Left) ||
440                                      Contexts.back().InCpp11AttributeSpecifier;
441 
442     // Treat C# Attributes [STAThread] much like C++ attributes [[...]].
443     bool IsCSharp11AttributeSpecifier =
444         isCSharpAttributeSpecifier(*Left) ||
445         Contexts.back().InCSharpAttributeSpecifier;
446 
447     bool InsideInlineASM = Line.startsWith(tok::kw_asm);
448     bool IsCppStructuredBinding = Left->isCppStructuredBinding(Style);
449     bool StartsObjCMethodExpr =
450         !IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates &&
451         Style.isCpp() && !IsCpp11AttributeSpecifier &&
452         Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
453         !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
454         (!Parent ||
455          Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
456                          tok::kw_return, tok::kw_throw) ||
457          Parent->isUnaryOperator() ||
458          // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
459          Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
460          (getBinOpPrecedence(Parent->Tok.getKind(), true, true) >
461           prec::Unknown));
462     bool ColonFound = false;
463 
464     unsigned BindingIncrease = 1;
465     if (IsCppStructuredBinding) {
466       Left->Type = TT_StructuredBindingLSquare;
467     } else if (Left->is(TT_Unknown)) {
468       if (StartsObjCMethodExpr) {
469         Left->Type = TT_ObjCMethodExpr;
470       } else if (IsCpp11AttributeSpecifier) {
471         Left->Type = TT_AttributeSquare;
472       } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
473                  Contexts.back().ContextKind == tok::l_brace &&
474                  Parent->isOneOf(tok::l_brace, tok::comma)) {
475         Left->Type = TT_JsComputedPropertyName;
476       } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace &&
477                  Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
478         Left->Type = TT_DesignatedInitializerLSquare;
479       } else if (CurrentToken->is(tok::r_square) && Parent &&
480                  Parent->is(TT_TemplateCloser)) {
481         Left->Type = TT_ArraySubscriptLSquare;
482       } else if (Style.Language == FormatStyle::LK_Proto ||
483                  Style.Language == FormatStyle::LK_TextProto) {
484         // Square braces in LK_Proto can either be message field attributes:
485         //
486         // optional Aaa aaa = 1 [
487         //   (aaa) = aaa
488         // ];
489         //
490         // extensions 123 [
491         //   (aaa) = aaa
492         // ];
493         //
494         // or text proto extensions (in options):
495         //
496         // option (Aaa.options) = {
497         //   [type.type/type] {
498         //     key: value
499         //   }
500         // }
501         //
502         // or repeated fields (in options):
503         //
504         // option (Aaa.options) = {
505         //   keys: [ 1, 2, 3 ]
506         // }
507         //
508         // In the first and the third case we want to spread the contents inside
509         // the square braces; in the second we want to keep them inline.
510         Left->Type = TT_ArrayInitializerLSquare;
511         if (!Left->endsSequence(tok::l_square, tok::numeric_constant,
512                                 tok::equal) &&
513             !Left->endsSequence(tok::l_square, tok::numeric_constant,
514                                 tok::identifier) &&
515             !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
516           Left->Type = TT_ProtoExtensionLSquare;
517           BindingIncrease = 10;
518         }
519       } else if (!CppArrayTemplates && Parent &&
520                  Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
521                                  tok::comma, tok::l_paren, tok::l_square,
522                                  tok::question, tok::colon, tok::kw_return,
523                                  // Should only be relevant to JavaScript:
524                                  tok::kw_default)) {
525         Left->Type = TT_ArrayInitializerLSquare;
526       } else if (IsCSharp11AttributeSpecifier) {
527         Left->Type = TT_AttributeSquare;
528       } else {
529         BindingIncrease = 10;
530         Left->Type = TT_ArraySubscriptLSquare;
531       }
532     }
533 
534     ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
535     Contexts.back().IsExpression = true;
536     if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
537         Parent->is(TT_JsTypeColon))
538       Contexts.back().IsExpression = false;
539 
540     Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
541     Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
542     Contexts.back().InCSharpAttributeSpecifier = IsCSharp11AttributeSpecifier;
543 
544     while (CurrentToken) {
545       if (CurrentToken->is(tok::r_square)) {
546         if (IsCpp11AttributeSpecifier)
547           CurrentToken->Type = TT_AttributeSquare;
548         if (IsCSharp11AttributeSpecifier)
549           CurrentToken->Type = TT_AttributeSquare;
550         else if (((CurrentToken->Next &&
551                    CurrentToken->Next->is(tok::l_paren)) ||
552                   (CurrentToken->Previous &&
553                    CurrentToken->Previous->Previous == Left)) &&
554                  Left->is(TT_ObjCMethodExpr)) {
555           // An ObjC method call is rarely followed by an open parenthesis. It
556           // also can't be composed of just one token, unless it's a macro that
557           // will be expanded to more tokens.
558           // FIXME: Do we incorrectly label ":" with this?
559           StartsObjCMethodExpr = false;
560           Left->Type = TT_Unknown;
561         }
562         if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
563           CurrentToken->Type = TT_ObjCMethodExpr;
564           // If we haven't seen a colon yet, make sure the last identifier
565           // before the r_square is tagged as a selector name component.
566           if (!ColonFound && CurrentToken->Previous &&
567               CurrentToken->Previous->is(TT_Unknown) &&
568               canBeObjCSelectorComponent(*CurrentToken->Previous))
569             CurrentToken->Previous->Type = TT_SelectorName;
570           // determineStarAmpUsage() thinks that '*' '[' is allocating an
571           // array of pointers, but if '[' starts a selector then '*' is a
572           // binary operator.
573           if (Parent && Parent->is(TT_PointerOrReference))
574             Parent->Type = TT_BinaryOperator;
575         }
576         // An arrow after an ObjC method expression is not a lambda arrow.
577         if (CurrentToken->Type == TT_ObjCMethodExpr && CurrentToken->Next &&
578             CurrentToken->Next->is(TT_LambdaArrow))
579           CurrentToken->Next->Type = TT_Unknown;
580         Left->MatchingParen = CurrentToken;
581         CurrentToken->MatchingParen = Left;
582         // FirstObjCSelectorName is set when a colon is found. This does
583         // not work, however, when the method has no parameters.
584         // Here, we set FirstObjCSelectorName when the end of the method call is
585         // reached, in case it was not set already.
586         if (!Contexts.back().FirstObjCSelectorName) {
587           FormatToken *Previous = CurrentToken->getPreviousNonComment();
588           if (Previous && Previous->is(TT_SelectorName)) {
589             Previous->ObjCSelectorNameParts = 1;
590             Contexts.back().FirstObjCSelectorName = Previous;
591           }
592         } else {
593           Left->ParameterCount =
594               Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
595         }
596         if (Contexts.back().FirstObjCSelectorName) {
597           Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
598               Contexts.back().LongestObjCSelectorName;
599           if (Left->BlockParameterCount > 1)
600             Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
601         }
602         next();
603         return true;
604       }
605       if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
606         return false;
607       if (CurrentToken->is(tok::colon)) {
608         if (IsCpp11AttributeSpecifier &&
609             CurrentToken->endsSequence(tok::colon, tok::identifier,
610                                        tok::kw_using)) {
611           // Remember that this is a [[using ns: foo]] C++ attribute, so we
612           // don't add a space before the colon (unlike other colons).
613           CurrentToken->Type = TT_AttributeColon;
614         } else if (Left->isOneOf(TT_ArraySubscriptLSquare,
615                                  TT_DesignatedInitializerLSquare)) {
616           Left->Type = TT_ObjCMethodExpr;
617           StartsObjCMethodExpr = true;
618           Contexts.back().ColonIsObjCMethodExpr = true;
619           if (Parent && Parent->is(tok::r_paren))
620             // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
621             Parent->Type = TT_CastRParen;
622         }
623         ColonFound = true;
624       }
625       if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
626           !ColonFound)
627         Left->Type = TT_ArrayInitializerLSquare;
628       FormatToken *Tok = CurrentToken;
629       if (!consumeToken())
630         return false;
631       updateParameterCount(Left, Tok);
632     }
633     return false;
634   }
635 
636   bool parseBrace() {
637     if (CurrentToken) {
638       FormatToken *Left = CurrentToken->Previous;
639       Left->ParentBracket = Contexts.back().ContextKind;
640 
641       if (Contexts.back().CaretFound)
642         Left->Type = TT_ObjCBlockLBrace;
643       Contexts.back().CaretFound = false;
644 
645       ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
646       Contexts.back().ColonIsDictLiteral = true;
647       if (Left->BlockKind == BK_BracedInit)
648         Contexts.back().IsExpression = true;
649       if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
650           Left->Previous->is(TT_JsTypeColon))
651         Contexts.back().IsExpression = false;
652 
653       while (CurrentToken) {
654         if (CurrentToken->is(tok::r_brace)) {
655           Left->MatchingParen = CurrentToken;
656           CurrentToken->MatchingParen = Left;
657           next();
658           return true;
659         }
660         if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
661           return false;
662         updateParameterCount(Left, CurrentToken);
663         if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
664           FormatToken *Previous = CurrentToken->getPreviousNonComment();
665           if (Previous->is(TT_JsTypeOptionalQuestion))
666             Previous = Previous->getPreviousNonComment();
667           if ((CurrentToken->is(tok::colon) &&
668                (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
669               Style.Language == FormatStyle::LK_Proto ||
670               Style.Language == FormatStyle::LK_TextProto) {
671             Left->Type = TT_DictLiteral;
672             if (Previous->Tok.getIdentifierInfo() ||
673                 Previous->is(tok::string_literal))
674               Previous->Type = TT_SelectorName;
675           }
676           if (CurrentToken->is(tok::colon) ||
677               Style.Language == FormatStyle::LK_JavaScript)
678             Left->Type = TT_DictLiteral;
679         }
680         if (CurrentToken->is(tok::comma) &&
681             Style.Language == FormatStyle::LK_JavaScript)
682           Left->Type = TT_DictLiteral;
683         if (!consumeToken())
684           return false;
685       }
686     }
687     return true;
688   }
689 
690   void updateParameterCount(FormatToken *Left, FormatToken *Current) {
691     // For ObjC methods, the number of parameters is calculated differently as
692     // method declarations have a different structure (the parameters are not
693     // inside a bracket scope).
694     if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
695       ++Left->BlockParameterCount;
696     if (Current->is(tok::comma)) {
697       ++Left->ParameterCount;
698       if (!Left->Role)
699         Left->Role.reset(new CommaSeparatedList(Style));
700       Left->Role->CommaFound(Current);
701     } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
702       Left->ParameterCount = 1;
703     }
704   }
705 
706   bool parseConditional() {
707     while (CurrentToken) {
708       if (CurrentToken->is(tok::colon)) {
709         CurrentToken->Type = TT_ConditionalExpr;
710         next();
711         return true;
712       }
713       if (!consumeToken())
714         return false;
715     }
716     return false;
717   }
718 
719   bool parseTemplateDeclaration() {
720     if (CurrentToken && CurrentToken->is(tok::less)) {
721       CurrentToken->Type = TT_TemplateOpener;
722       next();
723       if (!parseAngle())
724         return false;
725       if (CurrentToken)
726         CurrentToken->Previous->ClosesTemplateDeclaration = true;
727       return true;
728     }
729     return false;
730   }
731 
732   bool consumeToken() {
733     FormatToken *Tok = CurrentToken;
734     next();
735     switch (Tok->Tok.getKind()) {
736     case tok::plus:
737     case tok::minus:
738       if (!Tok->Previous && Line.MustBeDeclaration)
739         Tok->Type = TT_ObjCMethodSpecifier;
740       break;
741     case tok::colon:
742       if (!Tok->Previous)
743         return false;
744       // Colons from ?: are handled in parseConditional().
745       if (Style.Language == FormatStyle::LK_JavaScript) {
746         if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
747             (Contexts.size() == 1 &&               // switch/case labels
748              !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
749             Contexts.back().ContextKind == tok::l_paren ||  // function params
750             Contexts.back().ContextKind == tok::l_square || // array type
751             (!Contexts.back().IsExpression &&
752              Contexts.back().ContextKind == tok::l_brace) || // object type
753             (Contexts.size() == 1 &&
754              Line.MustBeDeclaration)) { // method/property declaration
755           Contexts.back().IsExpression = false;
756           Tok->Type = TT_JsTypeColon;
757           break;
758         }
759       }
760       if (Contexts.back().ColonIsDictLiteral ||
761           Style.Language == FormatStyle::LK_Proto ||
762           Style.Language == FormatStyle::LK_TextProto) {
763         Tok->Type = TT_DictLiteral;
764         if (Style.Language == FormatStyle::LK_TextProto) {
765           if (FormatToken *Previous = Tok->getPreviousNonComment())
766             Previous->Type = TT_SelectorName;
767         }
768       } else if (Contexts.back().ColonIsObjCMethodExpr ||
769                  Line.startsWith(TT_ObjCMethodSpecifier)) {
770         Tok->Type = TT_ObjCMethodExpr;
771         const FormatToken *BeforePrevious = Tok->Previous->Previous;
772         // Ensure we tag all identifiers in method declarations as
773         // TT_SelectorName.
774         bool UnknownIdentifierInMethodDeclaration =
775             Line.startsWith(TT_ObjCMethodSpecifier) &&
776             Tok->Previous->is(tok::identifier) && Tok->Previous->is(TT_Unknown);
777         if (!BeforePrevious ||
778             // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
779             !(BeforePrevious->is(TT_CastRParen) ||
780               (BeforePrevious->is(TT_ObjCMethodExpr) &&
781                BeforePrevious->is(tok::colon))) ||
782             BeforePrevious->is(tok::r_square) ||
783             Contexts.back().LongestObjCSelectorName == 0 ||
784             UnknownIdentifierInMethodDeclaration) {
785           Tok->Previous->Type = TT_SelectorName;
786           if (!Contexts.back().FirstObjCSelectorName)
787             Contexts.back().FirstObjCSelectorName = Tok->Previous;
788           else if (Tok->Previous->ColumnWidth >
789                    Contexts.back().LongestObjCSelectorName)
790             Contexts.back().LongestObjCSelectorName =
791                 Tok->Previous->ColumnWidth;
792           Tok->Previous->ParameterIndex =
793               Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
794           ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
795         }
796       } else if (Contexts.back().ColonIsForRangeExpr) {
797         Tok->Type = TT_RangeBasedForLoopColon;
798       } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
799         Tok->Type = TT_BitFieldColon;
800       } else if (Contexts.size() == 1 &&
801                  !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
802         if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren,
803                                                   tok::kw_noexcept))
804           Tok->Type = TT_CtorInitializerColon;
805         else
806           Tok->Type = TT_InheritanceColon;
807       } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
808                  (Tok->Next->isOneOf(tok::r_paren, tok::comma) ||
809                   (canBeObjCSelectorComponent(*Tok->Next) && Tok->Next->Next &&
810                    Tok->Next->Next->is(tok::colon)))) {
811         // This handles a special macro in ObjC code where selectors including
812         // the colon are passed as macro arguments.
813         Tok->Type = TT_ObjCMethodExpr;
814       } else if (Contexts.back().ContextKind == tok::l_paren) {
815         Tok->Type = TT_InlineASMColon;
816       }
817       break;
818     case tok::pipe:
819     case tok::amp:
820       // | and & in declarations/type expressions represent union and
821       // intersection types, respectively.
822       if (Style.Language == FormatStyle::LK_JavaScript &&
823           !Contexts.back().IsExpression)
824         Tok->Type = TT_JsTypeOperator;
825       break;
826     case tok::kw_if:
827     case tok::kw_while:
828       assert(!Line.startsWith(tok::hash));
829       if (Tok->is(tok::kw_if) && CurrentToken &&
830           CurrentToken->isOneOf(tok::kw_constexpr, tok::identifier))
831         next();
832       if (CurrentToken && CurrentToken->is(tok::l_paren)) {
833         next();
834         if (!parseParens(/*LookForDecls=*/true))
835           return false;
836       }
837       break;
838     case tok::kw_for:
839       if (Style.Language == FormatStyle::LK_JavaScript) {
840         // x.for and {for: ...}
841         if ((Tok->Previous && Tok->Previous->is(tok::period)) ||
842             (Tok->Next && Tok->Next->is(tok::colon)))
843           break;
844         // JS' for await ( ...
845         if (CurrentToken && CurrentToken->is(Keywords.kw_await))
846           next();
847       }
848       Contexts.back().ColonIsForRangeExpr = true;
849       next();
850       if (!parseParens())
851         return false;
852       break;
853     case tok::l_paren:
854       // When faced with 'operator()()', the kw_operator handler incorrectly
855       // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
856       // the first two parens OverloadedOperators and the second l_paren an
857       // OverloadedOperatorLParen.
858       if (Tok->Previous && Tok->Previous->is(tok::r_paren) &&
859           Tok->Previous->MatchingParen &&
860           Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
861         Tok->Previous->Type = TT_OverloadedOperator;
862         Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
863         Tok->Type = TT_OverloadedOperatorLParen;
864       }
865 
866       if (!parseParens())
867         return false;
868       if (Line.MustBeDeclaration && Contexts.size() == 1 &&
869           !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
870           (!Tok->Previous ||
871            !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
872                                    TT_LeadingJavaAnnotation)))
873         Line.MightBeFunctionDecl = true;
874       break;
875     case tok::l_square:
876       if (!parseSquare())
877         return false;
878       break;
879     case tok::l_brace:
880       if (Style.Language == FormatStyle::LK_TextProto) {
881         FormatToken *Previous = Tok->getPreviousNonComment();
882         if (Previous && Previous->Type != TT_DictLiteral)
883           Previous->Type = TT_SelectorName;
884       }
885       if (!parseBrace())
886         return false;
887       break;
888     case tok::less:
889       if (parseAngle()) {
890         Tok->Type = TT_TemplateOpener;
891         // In TT_Proto, we must distignuish between:
892         //   map<key, value>
893         //   msg < item: data >
894         //   msg: < item: data >
895         // In TT_TextProto, map<key, value> does not occur.
896         if (Style.Language == FormatStyle::LK_TextProto ||
897             (Style.Language == FormatStyle::LK_Proto && Tok->Previous &&
898              Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) {
899           Tok->Type = TT_DictLiteral;
900           FormatToken *Previous = Tok->getPreviousNonComment();
901           if (Previous && Previous->Type != TT_DictLiteral)
902             Previous->Type = TT_SelectorName;
903         }
904       } else {
905         Tok->Type = TT_BinaryOperator;
906         NonTemplateLess.insert(Tok);
907         CurrentToken = Tok;
908         next();
909       }
910       break;
911     case tok::r_paren:
912     case tok::r_square:
913       return false;
914     case tok::r_brace:
915       // Lines can start with '}'.
916       if (Tok->Previous)
917         return false;
918       break;
919     case tok::greater:
920       if (Style.Language != FormatStyle::LK_TextProto)
921         Tok->Type = TT_BinaryOperator;
922       break;
923     case tok::kw_operator:
924       if (Style.Language == FormatStyle::LK_TextProto ||
925           Style.Language == FormatStyle::LK_Proto)
926         break;
927       while (CurrentToken &&
928              !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
929         if (CurrentToken->isOneOf(tok::star, tok::amp))
930           CurrentToken->Type = TT_PointerOrReference;
931         consumeToken();
932         if (CurrentToken &&
933             CurrentToken->Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator,
934                                             tok::comma))
935           CurrentToken->Previous->Type = TT_OverloadedOperator;
936       }
937       if (CurrentToken) {
938         CurrentToken->Type = TT_OverloadedOperatorLParen;
939         if (CurrentToken->Previous->is(TT_BinaryOperator))
940           CurrentToken->Previous->Type = TT_OverloadedOperator;
941       }
942       break;
943     case tok::question:
944       if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
945           Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
946                              tok::r_brace)) {
947         // Question marks before semicolons, colons, etc. indicate optional
948         // types (fields, parameters), e.g.
949         //   function(x?: string, y?) {...}
950         //   class X { y?; }
951         Tok->Type = TT_JsTypeOptionalQuestion;
952         break;
953       }
954       // Declarations cannot be conditional expressions, this can only be part
955       // of a type declaration.
956       if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
957           Style.Language == FormatStyle::LK_JavaScript)
958         break;
959       parseConditional();
960       break;
961     case tok::kw_template:
962       parseTemplateDeclaration();
963       break;
964     case tok::comma:
965       if (Contexts.back().InCtorInitializer)
966         Tok->Type = TT_CtorInitializerComma;
967       else if (Contexts.back().InInheritanceList)
968         Tok->Type = TT_InheritanceComma;
969       else if (Contexts.back().FirstStartOfName &&
970                (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
971         Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
972         Line.IsMultiVariableDeclStmt = true;
973       }
974       if (Contexts.back().IsForEachMacro)
975         Contexts.back().IsExpression = true;
976       break;
977     case tok::identifier:
978       if (Tok->isOneOf(Keywords.kw___has_include,
979                        Keywords.kw___has_include_next)) {
980         parseHasInclude();
981       }
982       break;
983     default:
984       break;
985     }
986     return true;
987   }
988 
989   void parseIncludeDirective() {
990     if (CurrentToken && CurrentToken->is(tok::less)) {
991       next();
992       while (CurrentToken) {
993         // Mark tokens up to the trailing line comments as implicit string
994         // literals.
995         if (CurrentToken->isNot(tok::comment) &&
996             !CurrentToken->TokenText.startswith("//"))
997           CurrentToken->Type = TT_ImplicitStringLiteral;
998         next();
999       }
1000     }
1001   }
1002 
1003   void parseWarningOrError() {
1004     next();
1005     // We still want to format the whitespace left of the first token of the
1006     // warning or error.
1007     next();
1008     while (CurrentToken) {
1009       CurrentToken->Type = TT_ImplicitStringLiteral;
1010       next();
1011     }
1012   }
1013 
1014   void parsePragma() {
1015     next(); // Consume "pragma".
1016     if (CurrentToken &&
1017         CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
1018       bool IsMark = CurrentToken->is(Keywords.kw_mark);
1019       next(); // Consume "mark".
1020       next(); // Consume first token (so we fix leading whitespace).
1021       while (CurrentToken) {
1022         if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
1023           CurrentToken->Type = TT_ImplicitStringLiteral;
1024         next();
1025       }
1026     }
1027   }
1028 
1029   void parseHasInclude() {
1030     if (!CurrentToken || !CurrentToken->is(tok::l_paren))
1031       return;
1032     next(); // '('
1033     parseIncludeDirective();
1034     next(); // ')'
1035   }
1036 
1037   LineType parsePreprocessorDirective() {
1038     bool IsFirstToken = CurrentToken->IsFirst;
1039     LineType Type = LT_PreprocessorDirective;
1040     next();
1041     if (!CurrentToken)
1042       return Type;
1043 
1044     if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
1045       // JavaScript files can contain shebang lines of the form:
1046       // #!/usr/bin/env node
1047       // Treat these like C++ #include directives.
1048       while (CurrentToken) {
1049         // Tokens cannot be comments here.
1050         CurrentToken->Type = TT_ImplicitStringLiteral;
1051         next();
1052       }
1053       return LT_ImportStatement;
1054     }
1055 
1056     if (CurrentToken->Tok.is(tok::numeric_constant)) {
1057       CurrentToken->SpacesRequiredBefore = 1;
1058       return Type;
1059     }
1060     // Hashes in the middle of a line can lead to any strange token
1061     // sequence.
1062     if (!CurrentToken->Tok.getIdentifierInfo())
1063       return Type;
1064     switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
1065     case tok::pp_include:
1066     case tok::pp_include_next:
1067     case tok::pp_import:
1068       next();
1069       parseIncludeDirective();
1070       Type = LT_ImportStatement;
1071       break;
1072     case tok::pp_error:
1073     case tok::pp_warning:
1074       parseWarningOrError();
1075       break;
1076     case tok::pp_pragma:
1077       parsePragma();
1078       break;
1079     case tok::pp_if:
1080     case tok::pp_elif:
1081       Contexts.back().IsExpression = true;
1082       next();
1083       parseLine();
1084       break;
1085     default:
1086       break;
1087     }
1088     while (CurrentToken) {
1089       FormatToken *Tok = CurrentToken;
1090       next();
1091       if (Tok->is(tok::l_paren))
1092         parseParens();
1093       else if (Tok->isOneOf(Keywords.kw___has_include,
1094                             Keywords.kw___has_include_next))
1095         parseHasInclude();
1096     }
1097     return Type;
1098   }
1099 
1100 public:
1101   LineType parseLine() {
1102     if (!CurrentToken)
1103       return LT_Invalid;
1104     NonTemplateLess.clear();
1105     if (CurrentToken->is(tok::hash))
1106       return parsePreprocessorDirective();
1107 
1108     // Directly allow to 'import <string-literal>' to support protocol buffer
1109     // definitions (github.com/google/protobuf) or missing "#" (either way we
1110     // should not break the line).
1111     IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
1112     if ((Style.Language == FormatStyle::LK_Java &&
1113          CurrentToken->is(Keywords.kw_package)) ||
1114         (Info && Info->getPPKeywordID() == tok::pp_import &&
1115          CurrentToken->Next &&
1116          CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
1117                                      tok::kw_static))) {
1118       next();
1119       parseIncludeDirective();
1120       return LT_ImportStatement;
1121     }
1122 
1123     // If this line starts and ends in '<' and '>', respectively, it is likely
1124     // part of "#define <a/b.h>".
1125     if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
1126       parseIncludeDirective();
1127       return LT_ImportStatement;
1128     }
1129 
1130     // In .proto files, top-level options and package statements are very
1131     // similar to import statements and should not be line-wrapped.
1132     if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
1133         CurrentToken->isOneOf(Keywords.kw_option, Keywords.kw_package)) {
1134       next();
1135       if (CurrentToken && CurrentToken->is(tok::identifier)) {
1136         while (CurrentToken)
1137           next();
1138         return LT_ImportStatement;
1139       }
1140     }
1141 
1142     bool KeywordVirtualFound = false;
1143     bool ImportStatement = false;
1144 
1145     // import {...} from '...';
1146     if (Style.Language == FormatStyle::LK_JavaScript &&
1147         CurrentToken->is(Keywords.kw_import))
1148       ImportStatement = true;
1149 
1150     while (CurrentToken) {
1151       if (CurrentToken->is(tok::kw_virtual))
1152         KeywordVirtualFound = true;
1153       if (Style.Language == FormatStyle::LK_JavaScript) {
1154         // export {...} from '...';
1155         // An export followed by "from 'some string';" is a re-export from
1156         // another module identified by a URI and is treated as a
1157         // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
1158         // Just "export {...};" or "export class ..." should not be treated as
1159         // an import in this sense.
1160         if (Line.First->is(tok::kw_export) &&
1161             CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
1162             CurrentToken->Next->isStringLiteral())
1163           ImportStatement = true;
1164         if (isClosureImportStatement(*CurrentToken))
1165           ImportStatement = true;
1166       }
1167       if (!consumeToken())
1168         return LT_Invalid;
1169     }
1170     if (KeywordVirtualFound)
1171       return LT_VirtualFunctionDecl;
1172     if (ImportStatement)
1173       return LT_ImportStatement;
1174 
1175     if (Line.startsWith(TT_ObjCMethodSpecifier)) {
1176       if (Contexts.back().FirstObjCSelectorName)
1177         Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
1178             Contexts.back().LongestObjCSelectorName;
1179       return LT_ObjCMethodDecl;
1180     }
1181 
1182     return LT_Other;
1183   }
1184 
1185 private:
1186   bool isClosureImportStatement(const FormatToken &Tok) {
1187     // FIXME: Closure-library specific stuff should not be hard-coded but be
1188     // configurable.
1189     return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
1190            Tok.Next->Next &&
1191            (Tok.Next->Next->TokenText == "module" ||
1192             Tok.Next->Next->TokenText == "provide" ||
1193             Tok.Next->Next->TokenText == "require" ||
1194             Tok.Next->Next->TokenText == "requireType" ||
1195             Tok.Next->Next->TokenText == "forwardDeclare") &&
1196            Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
1197   }
1198 
1199   void resetTokenMetadata(FormatToken *Token) {
1200     if (!Token)
1201       return;
1202 
1203     // Reset token type in case we have already looked at it and then
1204     // recovered from an error (e.g. failure to find the matching >).
1205     if (!CurrentToken->isOneOf(
1206             TT_LambdaLSquare, TT_LambdaLBrace, TT_ForEachMacro,
1207             TT_TypenameMacro, TT_FunctionLBrace, TT_ImplicitStringLiteral,
1208             TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow, TT_NamespaceMacro,
1209             TT_OverloadedOperator, TT_RegexLiteral, TT_TemplateString,
1210             TT_ObjCStringLiteral))
1211       CurrentToken->Type = TT_Unknown;
1212     CurrentToken->Role.reset();
1213     CurrentToken->MatchingParen = nullptr;
1214     CurrentToken->FakeLParens.clear();
1215     CurrentToken->FakeRParens = 0;
1216   }
1217 
1218   void next() {
1219     if (CurrentToken) {
1220       CurrentToken->NestingLevel = Contexts.size() - 1;
1221       CurrentToken->BindingStrength = Contexts.back().BindingStrength;
1222       modifyContext(*CurrentToken);
1223       determineTokenType(*CurrentToken);
1224       CurrentToken = CurrentToken->Next;
1225     }
1226 
1227     resetTokenMetadata(CurrentToken);
1228   }
1229 
1230   /// A struct to hold information valid in a specific context, e.g.
1231   /// a pair of parenthesis.
1232   struct Context {
1233     Context(tok::TokenKind ContextKind, unsigned BindingStrength,
1234             bool IsExpression)
1235         : ContextKind(ContextKind), BindingStrength(BindingStrength),
1236           IsExpression(IsExpression) {}
1237 
1238     tok::TokenKind ContextKind;
1239     unsigned BindingStrength;
1240     bool IsExpression;
1241     unsigned LongestObjCSelectorName = 0;
1242     bool ColonIsForRangeExpr = false;
1243     bool ColonIsDictLiteral = false;
1244     bool ColonIsObjCMethodExpr = false;
1245     FormatToken *FirstObjCSelectorName = nullptr;
1246     FormatToken *FirstStartOfName = nullptr;
1247     bool CanBeExpression = true;
1248     bool InTemplateArgument = false;
1249     bool InCtorInitializer = false;
1250     bool InInheritanceList = false;
1251     bool CaretFound = false;
1252     bool IsForEachMacro = false;
1253     bool InCpp11AttributeSpecifier = false;
1254     bool InCSharpAttributeSpecifier = false;
1255   };
1256 
1257   /// Puts a new \c Context onto the stack \c Contexts for the lifetime
1258   /// of each instance.
1259   struct ScopedContextCreator {
1260     AnnotatingParser &P;
1261 
1262     ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
1263                          unsigned Increase)
1264         : P(P) {
1265       P.Contexts.push_back(Context(ContextKind,
1266                                    P.Contexts.back().BindingStrength + Increase,
1267                                    P.Contexts.back().IsExpression));
1268     }
1269 
1270     ~ScopedContextCreator() { P.Contexts.pop_back(); }
1271   };
1272 
1273   void modifyContext(const FormatToken &Current) {
1274     if (Current.getPrecedence() == prec::Assignment &&
1275         !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
1276         // Type aliases use `type X = ...;` in TypeScript and can be exported
1277         // using `export type ...`.
1278         !(Style.Language == FormatStyle::LK_JavaScript &&
1279           (Line.startsWith(Keywords.kw_type, tok::identifier) ||
1280            Line.startsWith(tok::kw_export, Keywords.kw_type,
1281                            tok::identifier))) &&
1282         (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
1283       Contexts.back().IsExpression = true;
1284       if (!Line.startsWith(TT_UnaryOperator)) {
1285         for (FormatToken *Previous = Current.Previous;
1286              Previous && Previous->Previous &&
1287              !Previous->Previous->isOneOf(tok::comma, tok::semi);
1288              Previous = Previous->Previous) {
1289           if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
1290             Previous = Previous->MatchingParen;
1291             if (!Previous)
1292               break;
1293           }
1294           if (Previous->opensScope())
1295             break;
1296           if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
1297               Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
1298               Previous->Previous && Previous->Previous->isNot(tok::equal))
1299             Previous->Type = TT_PointerOrReference;
1300         }
1301       }
1302     } else if (Current.is(tok::lessless) &&
1303                (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
1304       Contexts.back().IsExpression = true;
1305     } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
1306       Contexts.back().IsExpression = true;
1307     } else if (Current.is(TT_TrailingReturnArrow)) {
1308       Contexts.back().IsExpression = false;
1309     } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
1310       Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
1311     } else if (Current.Previous &&
1312                Current.Previous->is(TT_CtorInitializerColon)) {
1313       Contexts.back().IsExpression = true;
1314       Contexts.back().InCtorInitializer = true;
1315     } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
1316       Contexts.back().InInheritanceList = true;
1317     } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
1318       for (FormatToken *Previous = Current.Previous;
1319            Previous && Previous->isOneOf(tok::star, tok::amp);
1320            Previous = Previous->Previous)
1321         Previous->Type = TT_PointerOrReference;
1322       if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
1323         Contexts.back().IsExpression = false;
1324     } else if (Current.is(tok::kw_new)) {
1325       Contexts.back().CanBeExpression = false;
1326     } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
1327       // This should be the condition or increment in a for-loop.
1328       Contexts.back().IsExpression = true;
1329     }
1330   }
1331 
1332   void determineTokenType(FormatToken &Current) {
1333     if (!Current.is(TT_Unknown))
1334       // The token type is already known.
1335       return;
1336 
1337     if (Style.Language == FormatStyle::LK_JavaScript) {
1338       if (Current.is(tok::exclaim)) {
1339         if (Current.Previous &&
1340             (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace,
1341                                        tok::r_paren, tok::r_square,
1342                                        tok::r_brace) ||
1343              Current.Previous->Tok.isLiteral())) {
1344           Current.Type = TT_JsNonNullAssertion;
1345           return;
1346         }
1347         if (Current.Next &&
1348             Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
1349           Current.Type = TT_JsNonNullAssertion;
1350           return;
1351         }
1352       }
1353     }
1354 
1355     // Line.MightBeFunctionDecl can only be true after the parentheses of a
1356     // function declaration have been found. In this case, 'Current' is a
1357     // trailing token of this declaration and thus cannot be a name.
1358     if (Current.is(Keywords.kw_instanceof)) {
1359       Current.Type = TT_BinaryOperator;
1360     } else if (isStartOfName(Current) &&
1361                (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
1362       Contexts.back().FirstStartOfName = &Current;
1363       Current.Type = TT_StartOfName;
1364     } else if (Current.is(tok::semi)) {
1365       // Reset FirstStartOfName after finding a semicolon so that a for loop
1366       // with multiple increment statements is not confused with a for loop
1367       // having multiple variable declarations.
1368       Contexts.back().FirstStartOfName = nullptr;
1369     } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
1370       AutoFound = true;
1371     } else if (Current.is(tok::arrow) &&
1372                Style.Language == FormatStyle::LK_Java) {
1373       Current.Type = TT_LambdaArrow;
1374     } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
1375                Current.NestingLevel == 0) {
1376       Current.Type = TT_TrailingReturnArrow;
1377     } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
1378       Current.Type = determineStarAmpUsage(Current,
1379                                            Contexts.back().CanBeExpression &&
1380                                                Contexts.back().IsExpression,
1381                                            Contexts.back().InTemplateArgument);
1382     } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
1383       Current.Type = determinePlusMinusCaretUsage(Current);
1384       if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
1385         Contexts.back().CaretFound = true;
1386     } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
1387       Current.Type = determineIncrementUsage(Current);
1388     } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
1389       Current.Type = TT_UnaryOperator;
1390     } else if (Current.is(tok::question)) {
1391       if (Style.Language == FormatStyle::LK_JavaScript &&
1392           Line.MustBeDeclaration && !Contexts.back().IsExpression) {
1393         // In JavaScript, `interface X { foo?(): bar; }` is an optional method
1394         // on the interface, not a ternary expression.
1395         Current.Type = TT_JsTypeOptionalQuestion;
1396       } else {
1397         Current.Type = TT_ConditionalExpr;
1398       }
1399     } else if (Current.isBinaryOperator() &&
1400                (!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
1401                (!Current.is(tok::greater) &&
1402                 Style.Language != FormatStyle::LK_TextProto)) {
1403       Current.Type = TT_BinaryOperator;
1404     } else if (Current.is(tok::comment)) {
1405       if (Current.TokenText.startswith("/*")) {
1406         if (Current.TokenText.endswith("*/"))
1407           Current.Type = TT_BlockComment;
1408         else
1409           // The lexer has for some reason determined a comment here. But we
1410           // cannot really handle it, if it isn't properly terminated.
1411           Current.Tok.setKind(tok::unknown);
1412       } else {
1413         Current.Type = TT_LineComment;
1414       }
1415     } else if (Current.is(tok::r_paren)) {
1416       if (rParenEndsCast(Current))
1417         Current.Type = TT_CastRParen;
1418       if (Current.MatchingParen && Current.Next &&
1419           !Current.Next->isBinaryOperator() &&
1420           !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1421                                  tok::comma, tok::period, tok::arrow,
1422                                  tok::coloncolon))
1423         if (FormatToken *AfterParen = Current.MatchingParen->Next) {
1424           // Make sure this isn't the return type of an Obj-C block declaration
1425           if (AfterParen->Tok.isNot(tok::caret)) {
1426             if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1427               if (BeforeParen->is(tok::identifier) &&
1428                   !BeforeParen->is(TT_TypenameMacro) &&
1429                   BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1430                   (!BeforeParen->Previous ||
1431                    BeforeParen->Previous->ClosesTemplateDeclaration))
1432                 Current.Type = TT_FunctionAnnotationRParen;
1433           }
1434         }
1435     } else if (Current.is(tok::at) && Current.Next &&
1436                Style.Language != FormatStyle::LK_JavaScript &&
1437                Style.Language != FormatStyle::LK_Java) {
1438       // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
1439       // marks declarations and properties that need special formatting.
1440       switch (Current.Next->Tok.getObjCKeywordID()) {
1441       case tok::objc_interface:
1442       case tok::objc_implementation:
1443       case tok::objc_protocol:
1444         Current.Type = TT_ObjCDecl;
1445         break;
1446       case tok::objc_property:
1447         Current.Type = TT_ObjCProperty;
1448         break;
1449       default:
1450         break;
1451       }
1452     } else if (Current.is(tok::period)) {
1453       FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1454       if (PreviousNoComment &&
1455           PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1456         Current.Type = TT_DesignatedInitializerPeriod;
1457       else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1458                Current.Previous->isOneOf(TT_JavaAnnotation,
1459                                          TT_LeadingJavaAnnotation)) {
1460         Current.Type = Current.Previous->Type;
1461       }
1462     } else if (canBeObjCSelectorComponent(Current) &&
1463                // FIXME(bug 36976): ObjC return types shouldn't use
1464                // TT_CastRParen.
1465                Current.Previous && Current.Previous->is(TT_CastRParen) &&
1466                Current.Previous->MatchingParen &&
1467                Current.Previous->MatchingParen->Previous &&
1468                Current.Previous->MatchingParen->Previous->is(
1469                    TT_ObjCMethodSpecifier)) {
1470       // This is the first part of an Objective-C selector name. (If there's no
1471       // colon after this, this is the only place which annotates the identifier
1472       // as a selector.)
1473       Current.Type = TT_SelectorName;
1474     } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
1475                Current.Previous &&
1476                !Current.Previous->isOneOf(tok::equal, tok::at) &&
1477                Line.MightBeFunctionDecl && Contexts.size() == 1) {
1478       // Line.MightBeFunctionDecl can only be true after the parentheses of a
1479       // function declaration have been found.
1480       Current.Type = TT_TrailingAnnotation;
1481     } else if ((Style.Language == FormatStyle::LK_Java ||
1482                 Style.Language == FormatStyle::LK_JavaScript) &&
1483                Current.Previous) {
1484       if (Current.Previous->is(tok::at) &&
1485           Current.isNot(Keywords.kw_interface)) {
1486         const FormatToken &AtToken = *Current.Previous;
1487         const FormatToken *Previous = AtToken.getPreviousNonComment();
1488         if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1489           Current.Type = TT_LeadingJavaAnnotation;
1490         else
1491           Current.Type = TT_JavaAnnotation;
1492       } else if (Current.Previous->is(tok::period) &&
1493                  Current.Previous->isOneOf(TT_JavaAnnotation,
1494                                            TT_LeadingJavaAnnotation)) {
1495         Current.Type = Current.Previous->Type;
1496       }
1497     }
1498   }
1499 
1500   /// Take a guess at whether \p Tok starts a name of a function or
1501   /// variable declaration.
1502   ///
1503   /// This is a heuristic based on whether \p Tok is an identifier following
1504   /// something that is likely a type.
1505   bool isStartOfName(const FormatToken &Tok) {
1506     if (Tok.isNot(tok::identifier) || !Tok.Previous)
1507       return false;
1508 
1509     if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
1510                               Keywords.kw_as))
1511       return false;
1512     if (Style.Language == FormatStyle::LK_JavaScript &&
1513         Tok.Previous->is(Keywords.kw_in))
1514       return false;
1515 
1516     // Skip "const" as it does not have an influence on whether this is a name.
1517     FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
1518     while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1519       PreviousNotConst = PreviousNotConst->getPreviousNonComment();
1520 
1521     if (!PreviousNotConst)
1522       return false;
1523 
1524     bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1525                        PreviousNotConst->Previous &&
1526                        PreviousNotConst->Previous->is(tok::hash);
1527 
1528     if (PreviousNotConst->is(TT_TemplateCloser))
1529       return PreviousNotConst && PreviousNotConst->MatchingParen &&
1530              PreviousNotConst->MatchingParen->Previous &&
1531              PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1532              PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1533 
1534     if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1535         PreviousNotConst->MatchingParen->Previous &&
1536         PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1537       return true;
1538 
1539     return (!IsPPKeyword &&
1540             PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1541            PreviousNotConst->is(TT_PointerOrReference) ||
1542            PreviousNotConst->isSimpleTypeSpecifier();
1543   }
1544 
1545   /// Determine whether ')' is ending a cast.
1546   bool rParenEndsCast(const FormatToken &Tok) {
1547     // C-style casts are only used in C++ and Java.
1548     if (!Style.isCpp() && Style.Language != FormatStyle::LK_Java)
1549       return false;
1550 
1551     // Empty parens aren't casts and there are no casts at the end of the line.
1552     if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1553       return false;
1554 
1555     FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1556     if (LeftOfParens) {
1557       // If there is a closing parenthesis left of the current parentheses,
1558       // look past it as these might be chained casts.
1559       if (LeftOfParens->is(tok::r_paren)) {
1560         if (!LeftOfParens->MatchingParen ||
1561             !LeftOfParens->MatchingParen->Previous)
1562           return false;
1563         LeftOfParens = LeftOfParens->MatchingParen->Previous;
1564       }
1565 
1566       // If there is an identifier (or with a few exceptions a keyword) right
1567       // before the parentheses, this is unlikely to be a cast.
1568       if (LeftOfParens->Tok.getIdentifierInfo() &&
1569           !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1570                                  tok::kw_delete))
1571         return false;
1572 
1573       // Certain other tokens right before the parentheses are also signals that
1574       // this cannot be a cast.
1575       if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1576                                 TT_TemplateCloser, tok::ellipsis))
1577         return false;
1578     }
1579 
1580     if (Tok.Next->is(tok::question))
1581       return false;
1582 
1583     // As Java has no function types, a "(" after the ")" likely means that this
1584     // is a cast.
1585     if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1586       return true;
1587 
1588     // If a (non-string) literal follows, this is likely a cast.
1589     if (Tok.Next->isNot(tok::string_literal) &&
1590         (Tok.Next->Tok.isLiteral() ||
1591          Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1592       return true;
1593 
1594     // Heuristically try to determine whether the parentheses contain a type.
1595     bool ParensAreType =
1596         !Tok.Previous ||
1597         Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1598         Tok.Previous->isSimpleTypeSpecifier();
1599     bool ParensCouldEndDecl =
1600         Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1601     if (ParensAreType && !ParensCouldEndDecl)
1602       return true;
1603 
1604     // At this point, we heuristically assume that there are no casts at the
1605     // start of the line. We assume that we have found most cases where there
1606     // are by the logic above, e.g. "(void)x;".
1607     if (!LeftOfParens)
1608       return false;
1609 
1610     // Certain token types inside the parentheses mean that this can't be a
1611     // cast.
1612     for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
1613          Token = Token->Next)
1614       if (Token->is(TT_BinaryOperator))
1615         return false;
1616 
1617     // If the following token is an identifier or 'this', this is a cast. All
1618     // cases where this can be something else are handled above.
1619     if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
1620       return true;
1621 
1622     if (!Tok.Next->Next)
1623       return false;
1624 
1625     // If the next token after the parenthesis is a unary operator, assume
1626     // that this is cast, unless there are unexpected tokens inside the
1627     // parenthesis.
1628     bool NextIsUnary =
1629         Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1630     if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1631         !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1632       return false;
1633     // Search for unexpected tokens.
1634     for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1635          Prev = Prev->Previous) {
1636       if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1637         return false;
1638     }
1639     return true;
1640   }
1641 
1642   /// Return the type of the given token assuming it is * or &.
1643   TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1644                                   bool InTemplateArgument) {
1645     if (Style.Language == FormatStyle::LK_JavaScript)
1646       return TT_BinaryOperator;
1647 
1648     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1649     if (!PrevToken)
1650       return TT_UnaryOperator;
1651 
1652     const FormatToken *NextToken = Tok.getNextNonComment();
1653     if (!NextToken ||
1654         NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const) ||
1655         (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1656       return TT_PointerOrReference;
1657 
1658     if (PrevToken->is(tok::coloncolon))
1659       return TT_PointerOrReference;
1660 
1661     if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1662                            tok::comma, tok::semi, tok::kw_return, tok::colon,
1663                            tok::equal, tok::kw_delete, tok::kw_sizeof,
1664                            tok::kw_throw) ||
1665         PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1666                            TT_UnaryOperator, TT_CastRParen))
1667       return TT_UnaryOperator;
1668 
1669     if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1670       return TT_PointerOrReference;
1671     if (NextToken->is(tok::kw_operator) && !IsExpression)
1672       return TT_PointerOrReference;
1673     if (NextToken->isOneOf(tok::comma, tok::semi))
1674       return TT_PointerOrReference;
1675 
1676     if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen) {
1677       FormatToken *TokenBeforeMatchingParen =
1678           PrevToken->MatchingParen->getPreviousNonComment();
1679       if (TokenBeforeMatchingParen &&
1680           TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype,
1681                                             TT_TypenameMacro))
1682         return TT_PointerOrReference;
1683     }
1684 
1685     if (PrevToken->Tok.isLiteral() ||
1686         PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1687                            tok::kw_false, tok::r_brace) ||
1688         NextToken->Tok.isLiteral() ||
1689         NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1690         NextToken->isUnaryOperator() ||
1691         // If we know we're in a template argument, there are no named
1692         // declarations. Thus, having an identifier on the right-hand side
1693         // indicates a binary operator.
1694         (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1695       return TT_BinaryOperator;
1696 
1697     // "&&(" is quite unlikely to be two successive unary "&".
1698     if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1699       return TT_BinaryOperator;
1700 
1701     // This catches some cases where evaluation order is used as control flow:
1702     //   aaa && aaa->f();
1703     const FormatToken *NextNextToken = NextToken->getNextNonComment();
1704     if (NextNextToken && NextNextToken->is(tok::arrow))
1705       return TT_BinaryOperator;
1706 
1707     // It is very unlikely that we are going to find a pointer or reference type
1708     // definition on the RHS of an assignment.
1709     if (IsExpression && !Contexts.back().CaretFound)
1710       return TT_BinaryOperator;
1711 
1712     return TT_PointerOrReference;
1713   }
1714 
1715   TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1716     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1717     if (!PrevToken)
1718       return TT_UnaryOperator;
1719 
1720     if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
1721       // This must be a sequence of leading unary operators.
1722       return TT_UnaryOperator;
1723 
1724     // Use heuristics to recognize unary operators.
1725     if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1726                            tok::question, tok::colon, tok::kw_return,
1727                            tok::kw_case, tok::at, tok::l_brace))
1728       return TT_UnaryOperator;
1729 
1730     // There can't be two consecutive binary operators.
1731     if (PrevToken->is(TT_BinaryOperator))
1732       return TT_UnaryOperator;
1733 
1734     // Fall back to marking the token as binary operator.
1735     return TT_BinaryOperator;
1736   }
1737 
1738   /// Determine whether ++/-- are pre- or post-increments/-decrements.
1739   TokenType determineIncrementUsage(const FormatToken &Tok) {
1740     const FormatToken *PrevToken = Tok.getPreviousNonComment();
1741     if (!PrevToken || PrevToken->is(TT_CastRParen))
1742       return TT_UnaryOperator;
1743     if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1744       return TT_TrailingUnaryOperator;
1745 
1746     return TT_UnaryOperator;
1747   }
1748 
1749   SmallVector<Context, 8> Contexts;
1750 
1751   const FormatStyle &Style;
1752   AnnotatedLine &Line;
1753   FormatToken *CurrentToken;
1754   bool AutoFound;
1755   const AdditionalKeywords &Keywords;
1756 
1757   // Set of "<" tokens that do not open a template parameter list. If parseAngle
1758   // determines that a specific token can't be a template opener, it will make
1759   // same decision irrespective of the decisions for tokens leading up to it.
1760   // Store this information to prevent this from causing exponential runtime.
1761   llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1762 };
1763 
1764 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1765 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1766 
1767 /// Parses binary expressions by inserting fake parenthesis based on
1768 /// operator precedence.
1769 class ExpressionParser {
1770 public:
1771   ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1772                    AnnotatedLine &Line)
1773       : Style(Style), Keywords(Keywords), Current(Line.First) {}
1774 
1775   /// Parse expressions with the given operator precedence.
1776   void parse(int Precedence = 0) {
1777     // Skip 'return' and ObjC selector colons as they are not part of a binary
1778     // expression.
1779     while (Current && (Current->is(tok::kw_return) ||
1780                        (Current->is(tok::colon) &&
1781                         Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1782       next();
1783 
1784     if (!Current || Precedence > PrecedenceArrowAndPeriod)
1785       return;
1786 
1787     // Conditional expressions need to be parsed separately for proper nesting.
1788     if (Precedence == prec::Conditional) {
1789       parseConditionalExpr();
1790       return;
1791     }
1792 
1793     // Parse unary operators, which all have a higher precedence than binary
1794     // operators.
1795     if (Precedence == PrecedenceUnaryOperator) {
1796       parseUnaryOperator();
1797       return;
1798     }
1799 
1800     FormatToken *Start = Current;
1801     FormatToken *LatestOperator = nullptr;
1802     unsigned OperatorIndex = 0;
1803 
1804     while (Current) {
1805       // Consume operators with higher precedence.
1806       parse(Precedence + 1);
1807 
1808       int CurrentPrecedence = getCurrentPrecedence();
1809 
1810       if (Current && Current->is(TT_SelectorName) &&
1811           Precedence == CurrentPrecedence) {
1812         if (LatestOperator)
1813           addFakeParenthesis(Start, prec::Level(Precedence));
1814         Start = Current;
1815       }
1816 
1817       // At the end of the line or when an operator with higher precedence is
1818       // found, insert fake parenthesis and return.
1819       if (!Current ||
1820           (Current->closesScope() &&
1821            (Current->MatchingParen || Current->is(TT_TemplateString))) ||
1822           (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1823           (CurrentPrecedence == prec::Conditional &&
1824            Precedence == prec::Assignment && Current->is(tok::colon))) {
1825         break;
1826       }
1827 
1828       // Consume scopes: (), [], <> and {}
1829       if (Current->opensScope()) {
1830         // In fragment of a JavaScript template string can look like '}..${' and
1831         // thus close a scope and open a new one at the same time.
1832         while (Current && (!Current->closesScope() || Current->opensScope())) {
1833           next();
1834           parse();
1835         }
1836         next();
1837       } else {
1838         // Operator found.
1839         if (CurrentPrecedence == Precedence) {
1840           if (LatestOperator)
1841             LatestOperator->NextOperator = Current;
1842           LatestOperator = Current;
1843           Current->OperatorIndex = OperatorIndex;
1844           ++OperatorIndex;
1845         }
1846         next(/*SkipPastLeadingComments=*/Precedence > 0);
1847       }
1848     }
1849 
1850     if (LatestOperator && (Current || Precedence > 0)) {
1851       // LatestOperator->LastOperator = true;
1852       if (Precedence == PrecedenceArrowAndPeriod) {
1853         // Call expressions don't have a binary operator precedence.
1854         addFakeParenthesis(Start, prec::Unknown);
1855       } else {
1856         addFakeParenthesis(Start, prec::Level(Precedence));
1857       }
1858     }
1859   }
1860 
1861 private:
1862   /// Gets the precedence (+1) of the given token for binary operators
1863   /// and other tokens that we treat like binary operators.
1864   int getCurrentPrecedence() {
1865     if (Current) {
1866       const FormatToken *NextNonComment = Current->getNextNonComment();
1867       if (Current->is(TT_ConditionalExpr))
1868         return prec::Conditional;
1869       if (NextNonComment && Current->is(TT_SelectorName) &&
1870           (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
1871            ((Style.Language == FormatStyle::LK_Proto ||
1872              Style.Language == FormatStyle::LK_TextProto) &&
1873             NextNonComment->is(tok::less))))
1874         return prec::Assignment;
1875       if (Current->is(TT_JsComputedPropertyName))
1876         return prec::Assignment;
1877       if (Current->is(TT_LambdaArrow))
1878         return prec::Comma;
1879       if (Current->is(TT_JsFatArrow))
1880         return prec::Assignment;
1881       if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
1882           (Current->is(tok::comment) && NextNonComment &&
1883            NextNonComment->is(TT_SelectorName)))
1884         return 0;
1885       if (Current->is(TT_RangeBasedForLoopColon))
1886         return prec::Comma;
1887       if ((Style.Language == FormatStyle::LK_Java ||
1888            Style.Language == FormatStyle::LK_JavaScript) &&
1889           Current->is(Keywords.kw_instanceof))
1890         return prec::Relational;
1891       if (Style.Language == FormatStyle::LK_JavaScript &&
1892           Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
1893         return prec::Relational;
1894       if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1895         return Current->getPrecedence();
1896       if (Current->isOneOf(tok::period, tok::arrow))
1897         return PrecedenceArrowAndPeriod;
1898       if ((Style.Language == FormatStyle::LK_Java ||
1899            Style.Language == FormatStyle::LK_JavaScript) &&
1900           Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1901                            Keywords.kw_throws))
1902         return 0;
1903     }
1904     return -1;
1905   }
1906 
1907   void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1908     Start->FakeLParens.push_back(Precedence);
1909     if (Precedence > prec::Unknown)
1910       Start->StartsBinaryExpression = true;
1911     if (Current) {
1912       FormatToken *Previous = Current->Previous;
1913       while (Previous->is(tok::comment) && Previous->Previous)
1914         Previous = Previous->Previous;
1915       ++Previous->FakeRParens;
1916       if (Precedence > prec::Unknown)
1917         Previous->EndsBinaryExpression = true;
1918     }
1919   }
1920 
1921   /// Parse unary operator expressions and surround them with fake
1922   /// parentheses if appropriate.
1923   void parseUnaryOperator() {
1924     llvm::SmallVector<FormatToken *, 2> Tokens;
1925     while (Current && Current->is(TT_UnaryOperator)) {
1926       Tokens.push_back(Current);
1927       next();
1928     }
1929     parse(PrecedenceArrowAndPeriod);
1930     for (FormatToken *Token : llvm::reverse(Tokens))
1931       // The actual precedence doesn't matter.
1932       addFakeParenthesis(Token, prec::Unknown);
1933   }
1934 
1935   void parseConditionalExpr() {
1936     while (Current && Current->isTrailingComment()) {
1937       next();
1938     }
1939     FormatToken *Start = Current;
1940     parse(prec::LogicalOr);
1941     if (!Current || !Current->is(tok::question))
1942       return;
1943     next();
1944     parse(prec::Assignment);
1945     if (!Current || Current->isNot(TT_ConditionalExpr))
1946       return;
1947     next();
1948     parse(prec::Assignment);
1949     addFakeParenthesis(Start, prec::Conditional);
1950   }
1951 
1952   void next(bool SkipPastLeadingComments = true) {
1953     if (Current)
1954       Current = Current->Next;
1955     while (Current &&
1956            (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1957            Current->isTrailingComment())
1958       Current = Current->Next;
1959   }
1960 
1961   const FormatStyle &Style;
1962   const AdditionalKeywords &Keywords;
1963   FormatToken *Current;
1964 };
1965 
1966 } // end anonymous namespace
1967 
1968 void TokenAnnotator::setCommentLineLevels(
1969     SmallVectorImpl<AnnotatedLine *> &Lines) {
1970   const AnnotatedLine *NextNonCommentLine = nullptr;
1971   for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1972                                                           E = Lines.rend();
1973        I != E; ++I) {
1974     bool CommentLine = true;
1975     for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
1976       if (!Tok->is(tok::comment)) {
1977         CommentLine = false;
1978         break;
1979       }
1980     }
1981 
1982     // If the comment is currently aligned with the line immediately following
1983     // it, that's probably intentional and we should keep it.
1984     if (NextNonCommentLine && CommentLine &&
1985         NextNonCommentLine->First->NewlinesBefore <= 1 &&
1986         NextNonCommentLine->First->OriginalColumn ==
1987             (*I)->First->OriginalColumn) {
1988       // Align comments for preprocessor lines with the # in column 0 if
1989       // preprocessor lines are not indented. Otherwise, align with the next
1990       // line.
1991       (*I)->Level =
1992           (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
1993            (NextNonCommentLine->Type == LT_PreprocessorDirective ||
1994             NextNonCommentLine->Type == LT_ImportStatement))
1995               ? 0
1996               : NextNonCommentLine->Level;
1997     } else {
1998       NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1999     }
2000 
2001     setCommentLineLevels((*I)->Children);
2002   }
2003 }
2004 
2005 static unsigned maxNestingDepth(const AnnotatedLine &Line) {
2006   unsigned Result = 0;
2007   for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
2008     Result = std::max(Result, Tok->NestingLevel);
2009   return Result;
2010 }
2011 
2012 void TokenAnnotator::annotate(AnnotatedLine &Line) {
2013   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
2014                                                   E = Line.Children.end();
2015        I != E; ++I) {
2016     annotate(**I);
2017   }
2018   AnnotatingParser Parser(Style, Line, Keywords);
2019   Line.Type = Parser.parseLine();
2020 
2021   // With very deep nesting, ExpressionParser uses lots of stack and the
2022   // formatting algorithm is very slow. We're not going to do a good job here
2023   // anyway - it's probably generated code being formatted by mistake.
2024   // Just skip the whole line.
2025   if (maxNestingDepth(Line) > 50)
2026     Line.Type = LT_Invalid;
2027 
2028   if (Line.Type == LT_Invalid)
2029     return;
2030 
2031   ExpressionParser ExprParser(Style, Keywords, Line);
2032   ExprParser.parse();
2033 
2034   if (Line.startsWith(TT_ObjCMethodSpecifier))
2035     Line.Type = LT_ObjCMethodDecl;
2036   else if (Line.startsWith(TT_ObjCDecl))
2037     Line.Type = LT_ObjCDecl;
2038   else if (Line.startsWith(TT_ObjCProperty))
2039     Line.Type = LT_ObjCProperty;
2040 
2041   Line.First->SpacesRequiredBefore = 1;
2042   Line.First->CanBreakBefore = Line.First->MustBreakBefore;
2043 }
2044 
2045 // This function heuristically determines whether 'Current' starts the name of a
2046 // function declaration.
2047 static bool isFunctionDeclarationName(const FormatToken &Current,
2048                                       const AnnotatedLine &Line) {
2049   auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
2050     for (; Next; Next = Next->Next) {
2051       if (Next->is(TT_OverloadedOperatorLParen))
2052         return Next;
2053       if (Next->is(TT_OverloadedOperator))
2054         continue;
2055       if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
2056         // For 'new[]' and 'delete[]'.
2057         if (Next->Next && Next->Next->is(tok::l_square) && Next->Next->Next &&
2058             Next->Next->Next->is(tok::r_square))
2059           Next = Next->Next->Next;
2060         continue;
2061       }
2062 
2063       break;
2064     }
2065     return nullptr;
2066   };
2067 
2068   // Find parentheses of parameter list.
2069   const FormatToken *Next = Current.Next;
2070   if (Current.is(tok::kw_operator)) {
2071     if (Current.Previous && Current.Previous->is(tok::coloncolon))
2072       return false;
2073     Next = skipOperatorName(Next);
2074   } else {
2075     if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
2076       return false;
2077     for (; Next; Next = Next->Next) {
2078       if (Next->is(TT_TemplateOpener)) {
2079         Next = Next->MatchingParen;
2080       } else if (Next->is(tok::coloncolon)) {
2081         Next = Next->Next;
2082         if (!Next)
2083           return false;
2084         if (Next->is(tok::kw_operator)) {
2085           Next = skipOperatorName(Next->Next);
2086           break;
2087         }
2088         if (!Next->is(tok::identifier))
2089           return false;
2090       } else if (Next->is(tok::l_paren)) {
2091         break;
2092       } else {
2093         return false;
2094       }
2095     }
2096   }
2097 
2098   // Check whether parameter list can belong to a function declaration.
2099   if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
2100     return false;
2101   // If the lines ends with "{", this is likely an function definition.
2102   if (Line.Last->is(tok::l_brace))
2103     return true;
2104   if (Next->Next == Next->MatchingParen)
2105     return true; // Empty parentheses.
2106   // If there is an &/&& after the r_paren, this is likely a function.
2107   if (Next->MatchingParen->Next &&
2108       Next->MatchingParen->Next->is(TT_PointerOrReference))
2109     return true;
2110   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
2111        Tok = Tok->Next) {
2112     if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
2113       Tok = Tok->MatchingParen;
2114       continue;
2115     }
2116     if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
2117         Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
2118       return true;
2119     if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
2120         Tok->Tok.isLiteral())
2121       return false;
2122   }
2123   return false;
2124 }
2125 
2126 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
2127   assert(Line.MightBeFunctionDecl);
2128 
2129   if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
2130        Style.AlwaysBreakAfterReturnType ==
2131            FormatStyle::RTBS_TopLevelDefinitions) &&
2132       Line.Level > 0)
2133     return false;
2134 
2135   switch (Style.AlwaysBreakAfterReturnType) {
2136   case FormatStyle::RTBS_None:
2137     return false;
2138   case FormatStyle::RTBS_All:
2139   case FormatStyle::RTBS_TopLevel:
2140     return true;
2141   case FormatStyle::RTBS_AllDefinitions:
2142   case FormatStyle::RTBS_TopLevelDefinitions:
2143     return Line.mightBeFunctionDefinition();
2144   }
2145 
2146   return false;
2147 }
2148 
2149 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
2150   for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
2151                                                   E = Line.Children.end();
2152        I != E; ++I) {
2153     calculateFormattingInformation(**I);
2154   }
2155 
2156   Line.First->TotalLength =
2157       Line.First->IsMultiline ? Style.ColumnLimit
2158                               : Line.FirstStartColumn + Line.First->ColumnWidth;
2159   FormatToken *Current = Line.First->Next;
2160   bool InFunctionDecl = Line.MightBeFunctionDecl;
2161   while (Current) {
2162     if (isFunctionDeclarationName(*Current, Line))
2163       Current->Type = TT_FunctionDeclarationName;
2164     if (Current->is(TT_LineComment)) {
2165       if (Current->Previous->BlockKind == BK_BracedInit &&
2166           Current->Previous->opensScope())
2167         Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
2168       else
2169         Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
2170 
2171       // If we find a trailing comment, iterate backwards to determine whether
2172       // it seems to relate to a specific parameter. If so, break before that
2173       // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
2174       // to the previous line in:
2175       //   SomeFunction(a,
2176       //                b, // comment
2177       //                c);
2178       if (!Current->HasUnescapedNewline) {
2179         for (FormatToken *Parameter = Current->Previous; Parameter;
2180              Parameter = Parameter->Previous) {
2181           if (Parameter->isOneOf(tok::comment, tok::r_brace))
2182             break;
2183           if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
2184             if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
2185                 Parameter->HasUnescapedNewline)
2186               Parameter->MustBreakBefore = true;
2187             break;
2188           }
2189         }
2190       }
2191     } else if (Current->SpacesRequiredBefore == 0 &&
2192                spaceRequiredBefore(Line, *Current)) {
2193       Current->SpacesRequiredBefore = 1;
2194     }
2195 
2196     Current->MustBreakBefore =
2197         Current->MustBreakBefore || mustBreakBefore(Line, *Current);
2198 
2199     if (!Current->MustBreakBefore && InFunctionDecl &&
2200         Current->is(TT_FunctionDeclarationName))
2201       Current->MustBreakBefore = mustBreakForReturnType(Line);
2202 
2203     Current->CanBreakBefore =
2204         Current->MustBreakBefore || canBreakBefore(Line, *Current);
2205     unsigned ChildSize = 0;
2206     if (Current->Previous->Children.size() == 1) {
2207       FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
2208       ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
2209                                                   : LastOfChild.TotalLength + 1;
2210     }
2211     const FormatToken *Prev = Current->Previous;
2212     if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
2213         (Prev->Children.size() == 1 &&
2214          Prev->Children[0]->First->MustBreakBefore) ||
2215         Current->IsMultiline)
2216       Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
2217     else
2218       Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
2219                              ChildSize + Current->SpacesRequiredBefore;
2220 
2221     if (Current->is(TT_CtorInitializerColon))
2222       InFunctionDecl = false;
2223 
2224     // FIXME: Only calculate this if CanBreakBefore is true once static
2225     // initializers etc. are sorted out.
2226     // FIXME: Move magic numbers to a better place.
2227 
2228     // Reduce penalty for aligning ObjC method arguments using the colon
2229     // alignment as this is the canonical way (still prefer fitting everything
2230     // into one line if possible). Trying to fit a whole expression into one
2231     // line should not force other line breaks (e.g. when ObjC method
2232     // expression is a part of other expression).
2233     Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
2234     if (Style.Language == FormatStyle::LK_ObjC &&
2235         Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
2236       if (Current->ParameterIndex == 1)
2237         Current->SplitPenalty += 5 * Current->BindingStrength;
2238     } else {
2239       Current->SplitPenalty += 20 * Current->BindingStrength;
2240     }
2241 
2242     Current = Current->Next;
2243   }
2244 
2245   calculateUnbreakableTailLengths(Line);
2246   unsigned IndentLevel = Line.Level;
2247   for (Current = Line.First; Current != nullptr; Current = Current->Next) {
2248     if (Current->Role)
2249       Current->Role->precomputeFormattingInfos(Current);
2250     if (Current->MatchingParen &&
2251         Current->MatchingParen->opensBlockOrBlockTypeList(Style)) {
2252       assert(IndentLevel > 0);
2253       --IndentLevel;
2254     }
2255     Current->IndentLevel = IndentLevel;
2256     if (Current->opensBlockOrBlockTypeList(Style))
2257       ++IndentLevel;
2258   }
2259 
2260   LLVM_DEBUG({ printDebugInfo(Line); });
2261 }
2262 
2263 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
2264   unsigned UnbreakableTailLength = 0;
2265   FormatToken *Current = Line.Last;
2266   while (Current) {
2267     Current->UnbreakableTailLength = UnbreakableTailLength;
2268     if (Current->CanBreakBefore ||
2269         Current->isOneOf(tok::comment, tok::string_literal)) {
2270       UnbreakableTailLength = 0;
2271     } else {
2272       UnbreakableTailLength +=
2273           Current->ColumnWidth + Current->SpacesRequiredBefore;
2274     }
2275     Current = Current->Previous;
2276   }
2277 }
2278 
2279 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
2280                                       const FormatToken &Tok,
2281                                       bool InFunctionDecl) {
2282   const FormatToken &Left = *Tok.Previous;
2283   const FormatToken &Right = Tok;
2284 
2285   if (Left.is(tok::semi))
2286     return 0;
2287 
2288   if (Style.Language == FormatStyle::LK_Java) {
2289     if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
2290       return 1;
2291     if (Right.is(Keywords.kw_implements))
2292       return 2;
2293     if (Left.is(tok::comma) && Left.NestingLevel == 0)
2294       return 3;
2295   } else if (Style.Language == FormatStyle::LK_JavaScript) {
2296     if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
2297       return 100;
2298     if (Left.is(TT_JsTypeColon))
2299       return 35;
2300     if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2301         (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2302       return 100;
2303     // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
2304     if (Left.opensScope() && Right.closesScope())
2305       return 200;
2306   }
2307 
2308   if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2309     return 1;
2310   if (Right.is(tok::l_square)) {
2311     if (Style.Language == FormatStyle::LK_Proto)
2312       return 1;
2313     if (Left.is(tok::r_square))
2314       return 200;
2315     // Slightly prefer formatting local lambda definitions like functions.
2316     if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
2317       return 35;
2318     if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2319                        TT_ArrayInitializerLSquare,
2320                        TT_DesignatedInitializerLSquare, TT_AttributeSquare))
2321       return 500;
2322   }
2323 
2324   if (Left.is(tok::coloncolon) ||
2325       (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
2326     return 500;
2327   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2328       Right.is(tok::kw_operator)) {
2329     if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
2330       return 3;
2331     if (Left.is(TT_StartOfName))
2332       return 110;
2333     if (InFunctionDecl && Right.NestingLevel == 0)
2334       return Style.PenaltyReturnTypeOnItsOwnLine;
2335     return 200;
2336   }
2337   if (Right.is(TT_PointerOrReference))
2338     return 190;
2339   if (Right.is(TT_LambdaArrow))
2340     return 110;
2341   if (Left.is(tok::equal) && Right.is(tok::l_brace))
2342     return 160;
2343   if (Left.is(TT_CastRParen))
2344     return 100;
2345   if (Left.isOneOf(tok::kw_class, tok::kw_struct))
2346     return 5000;
2347   if (Left.is(tok::comment))
2348     return 1000;
2349 
2350   if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
2351                    TT_CtorInitializerColon))
2352     return 2;
2353 
2354   if (Right.isMemberAccess()) {
2355     // Breaking before the "./->" of a chained call/member access is reasonably
2356     // cheap, as formatting those with one call per line is generally
2357     // desirable. In particular, it should be cheaper to break before the call
2358     // than it is to break inside a call's parameters, which could lead to weird
2359     // "hanging" indents. The exception is the very last "./->" to support this
2360     // frequent pattern:
2361     //
2362     //   aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
2363     //       dddddddd);
2364     //
2365     // which might otherwise be blown up onto many lines. Here, clang-format
2366     // won't produce "hanging" indents anyway as there is no other trailing
2367     // call.
2368     //
2369     // Also apply higher penalty is not a call as that might lead to a wrapping
2370     // like:
2371     //
2372     //   aaaaaaa
2373     //       .aaaaaaaaa.bbbbbbbb(cccccccc);
2374     return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
2375                ? 150
2376                : 35;
2377   }
2378 
2379   if (Right.is(TT_TrailingAnnotation) &&
2380       (!Right.Next || Right.Next->isNot(tok::l_paren))) {
2381     // Moving trailing annotations to the next line is fine for ObjC method
2382     // declarations.
2383     if (Line.startsWith(TT_ObjCMethodSpecifier))
2384       return 10;
2385     // Generally, breaking before a trailing annotation is bad unless it is
2386     // function-like. It seems to be especially preferable to keep standard
2387     // annotations (i.e. "const", "final" and "override") on the same line.
2388     // Use a slightly higher penalty after ")" so that annotations like
2389     // "const override" are kept together.
2390     bool is_short_annotation = Right.TokenText.size() < 10;
2391     return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
2392   }
2393 
2394   // In for-loops, prefer breaking at ',' and ';'.
2395   if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
2396     return 4;
2397 
2398   // In Objective-C method expressions, prefer breaking before "param:" over
2399   // breaking after it.
2400   if (Right.is(TT_SelectorName))
2401     return 0;
2402   if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
2403     return Line.MightBeFunctionDecl ? 50 : 500;
2404 
2405   // In Objective-C type declarations, avoid breaking after the category's
2406   // open paren (we'll prefer breaking after the protocol list's opening
2407   // angle bracket, if present).
2408   if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
2409       Left.Previous->isOneOf(tok::identifier, tok::greater))
2410     return 500;
2411 
2412   if (Left.is(tok::l_paren) && InFunctionDecl &&
2413       Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
2414     return 100;
2415   if (Left.is(tok::l_paren) && Left.Previous &&
2416       (Left.Previous->is(tok::kw_for) || Left.Previous->isIf()))
2417     return 1000;
2418   if (Left.is(tok::equal) && InFunctionDecl)
2419     return 110;
2420   if (Right.is(tok::r_brace))
2421     return 1;
2422   if (Left.is(TT_TemplateOpener))
2423     return 100;
2424   if (Left.opensScope()) {
2425     if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
2426       return 0;
2427     if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
2428       return 19;
2429     return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
2430                                    : 19;
2431   }
2432   if (Left.is(TT_JavaAnnotation))
2433     return 50;
2434 
2435   if (Left.is(TT_UnaryOperator))
2436     return 60;
2437   if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
2438       Left.Previous->isLabelString() &&
2439       (Left.NextOperator || Left.OperatorIndex != 0))
2440     return 50;
2441   if (Right.is(tok::plus) && Left.isLabelString() &&
2442       (Right.NextOperator || Right.OperatorIndex != 0))
2443     return 25;
2444   if (Left.is(tok::comma))
2445     return 1;
2446   if (Right.is(tok::lessless) && Left.isLabelString() &&
2447       (Right.NextOperator || Right.OperatorIndex != 1))
2448     return 25;
2449   if (Right.is(tok::lessless)) {
2450     // Breaking at a << is really cheap.
2451     if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
2452       // Slightly prefer to break before the first one in log-like statements.
2453       return 2;
2454     return 1;
2455   }
2456   if (Left.ClosesTemplateDeclaration)
2457     return Style.PenaltyBreakTemplateDeclaration;
2458   if (Left.is(TT_ConditionalExpr))
2459     return prec::Conditional;
2460   prec::Level Level = Left.getPrecedence();
2461   if (Level == prec::Unknown)
2462     Level = Right.getPrecedence();
2463   if (Level == prec::Assignment)
2464     return Style.PenaltyBreakAssignment;
2465   if (Level != prec::Unknown)
2466     return Level;
2467 
2468   return 3;
2469 }
2470 
2471 bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const {
2472   return Style.SpaceBeforeParens == FormatStyle::SBPO_Always ||
2473          (Style.SpaceBeforeParens == FormatStyle::SBPO_NonEmptyParentheses &&
2474           Right.ParameterCount > 0);
2475 }
2476 
2477 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
2478                                           const FormatToken &Left,
2479                                           const FormatToken &Right) {
2480   if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
2481     return true;
2482   if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
2483     return true;
2484   if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
2485       Left.Tok.getObjCKeywordID() == tok::objc_property)
2486     return true;
2487   if (Right.is(tok::hashhash))
2488     return Left.is(tok::hash);
2489   if (Left.isOneOf(tok::hashhash, tok::hash))
2490     return Right.is(tok::hash);
2491   if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
2492     return Style.SpaceInEmptyParentheses;
2493   if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
2494     return (Right.is(TT_CastRParen) ||
2495             (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
2496                ? Style.SpacesInCStyleCastParentheses
2497                : Style.SpacesInParentheses;
2498   if (Right.isOneOf(tok::semi, tok::comma))
2499     return false;
2500   if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
2501     bool IsLightweightGeneric = Right.MatchingParen &&
2502                                 Right.MatchingParen->Next &&
2503                                 Right.MatchingParen->Next->is(tok::colon);
2504     return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
2505   }
2506   if (Right.is(tok::less) && Left.is(tok::kw_template))
2507     return Style.SpaceAfterTemplateKeyword;
2508   if (Left.isOneOf(tok::exclaim, tok::tilde))
2509     return false;
2510   if (Left.is(tok::at) &&
2511       Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
2512                     tok::numeric_constant, tok::l_paren, tok::l_brace,
2513                     tok::kw_true, tok::kw_false))
2514     return false;
2515   if (Left.is(tok::colon))
2516     return !Left.is(TT_ObjCMethodExpr);
2517   if (Left.is(tok::coloncolon))
2518     return false;
2519   if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
2520     if (Style.Language == FormatStyle::LK_TextProto ||
2521         (Style.Language == FormatStyle::LK_Proto &&
2522          (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
2523       // Format empty list as `<>`.
2524       if (Left.is(tok::less) && Right.is(tok::greater))
2525         return false;
2526       return !Style.Cpp11BracedListStyle;
2527     }
2528     return false;
2529   }
2530   if (Right.is(tok::ellipsis))
2531     return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
2532                                     Left.Previous->is(tok::kw_case));
2533   if (Left.is(tok::l_square) && Right.is(tok::amp))
2534     return false;
2535   if (Right.is(TT_PointerOrReference)) {
2536     if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
2537       if (!Left.MatchingParen)
2538         return true;
2539       FormatToken *TokenBeforeMatchingParen =
2540           Left.MatchingParen->getPreviousNonComment();
2541       if (!TokenBeforeMatchingParen ||
2542           !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype,
2543                                              TT_TypenameMacro))
2544         return true;
2545     }
2546     return (Left.Tok.isLiteral() ||
2547             (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
2548              (Style.PointerAlignment != FormatStyle::PAS_Left ||
2549               (Line.IsMultiVariableDeclStmt &&
2550                (Left.NestingLevel == 0 ||
2551                 (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
2552   }
2553   if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
2554       (!Left.is(TT_PointerOrReference) ||
2555        (Style.PointerAlignment != FormatStyle::PAS_Right &&
2556         !Line.IsMultiVariableDeclStmt)))
2557     return true;
2558   if (Left.is(TT_PointerOrReference))
2559     return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
2560            (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
2561             !Right.is(TT_StartOfName)) ||
2562            (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
2563            (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
2564                            tok::l_paren) &&
2565             (Style.PointerAlignment != FormatStyle::PAS_Right &&
2566              !Line.IsMultiVariableDeclStmt) &&
2567             Left.Previous &&
2568             !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
2569   if (Right.is(tok::star) && Left.is(tok::l_paren))
2570     return false;
2571   const auto SpaceRequiredForArrayInitializerLSquare =
2572       [](const FormatToken &LSquareTok, const FormatStyle &Style) {
2573         return Style.SpacesInContainerLiterals ||
2574                ((Style.Language == FormatStyle::LK_Proto ||
2575                  Style.Language == FormatStyle::LK_TextProto) &&
2576                 !Style.Cpp11BracedListStyle &&
2577                 LSquareTok.endsSequence(tok::l_square, tok::colon,
2578                                         TT_SelectorName));
2579       };
2580   if (Left.is(tok::l_square))
2581     return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
2582             SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
2583            (Left.isOneOf(TT_ArraySubscriptLSquare,
2584                          TT_StructuredBindingLSquare) &&
2585             Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
2586   if (Right.is(tok::r_square))
2587     return Right.MatchingParen &&
2588            ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
2589              SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
2590                                                      Style)) ||
2591             (Style.SpacesInSquareBrackets &&
2592              Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
2593                                           TT_StructuredBindingLSquare)) ||
2594             Right.MatchingParen->is(TT_AttributeParen));
2595   if (Right.is(tok::l_square) &&
2596       !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2597                      TT_DesignatedInitializerLSquare,
2598                      TT_StructuredBindingLSquare, TT_AttributeSquare) &&
2599       !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
2600     return false;
2601   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
2602     return !Left.Children.empty(); // No spaces in "{}".
2603   if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
2604       (Right.is(tok::r_brace) && Right.MatchingParen &&
2605        Right.MatchingParen->BlockKind != BK_Block))
2606     return !Style.Cpp11BracedListStyle;
2607   if (Left.is(TT_BlockComment))
2608     // No whitespace in x(/*foo=*/1), except for JavaScript.
2609     return Style.Language == FormatStyle::LK_JavaScript ||
2610            !Left.TokenText.endswith("=*/");
2611   if (Right.is(tok::l_paren)) {
2612     if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
2613         (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
2614       return true;
2615     return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
2616            (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
2617             (Left.isOneOf(tok::pp_elif, tok::kw_for, tok::kw_while,
2618                           tok::kw_switch, tok::kw_case, TT_ForEachMacro,
2619                           TT_ObjCForIn) ||
2620              Left.isIf(Line.Type != LT_PreprocessorDirective) ||
2621              (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
2622                            tok::kw_new, tok::kw_delete) &&
2623               (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
2624            (spaceRequiredBeforeParens(Right) &&
2625             (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
2626              Left.is(tok::r_paren) || Left.isSimpleTypeSpecifier() ||
2627              (Left.is(tok::r_square) && Left.MatchingParen &&
2628               Left.MatchingParen->is(TT_LambdaLSquare))) &&
2629             Line.Type != LT_PreprocessorDirective);
2630   }
2631   if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
2632     return false;
2633   if (Right.is(TT_UnaryOperator))
2634     return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
2635            (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
2636   if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
2637                     tok::r_paren) ||
2638        Left.isSimpleTypeSpecifier()) &&
2639       Right.is(tok::l_brace) && Right.getNextNonComment() &&
2640       Right.BlockKind != BK_Block)
2641     return false;
2642   if (Left.is(tok::period) || Right.is(tok::period))
2643     return false;
2644   if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
2645     return false;
2646   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
2647       Left.MatchingParen->Previous &&
2648       (Left.MatchingParen->Previous->is(tok::period) ||
2649        Left.MatchingParen->Previous->is(tok::coloncolon)))
2650     // Java call to generic function with explicit type:
2651     // A.<B<C<...>>>DoSomething();
2652     // A::<B<C<...>>>DoSomething();  // With a Java 8 method reference.
2653     return false;
2654   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
2655     return false;
2656   if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at))
2657     // Objective-C dictionary literal -> no space after opening brace.
2658     return false;
2659   if (Right.is(tok::r_brace) && Right.MatchingParen &&
2660       Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at))
2661     // Objective-C dictionary literal -> no space before closing brace.
2662     return false;
2663   return true;
2664 }
2665 
2666 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
2667                                          const FormatToken &Right) {
2668   const FormatToken &Left = *Right.Previous;
2669   if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
2670     return true; // Never ever merge two identifiers.
2671   if (Style.isCpp()) {
2672     if (Left.is(tok::kw_operator))
2673       return Right.is(tok::coloncolon);
2674     if (Right.is(tok::l_brace) && Right.BlockKind == BK_BracedInit &&
2675         !Left.opensScope() && Style.SpaceBeforeCpp11BracedList)
2676       return true;
2677   } else if (Style.Language == FormatStyle::LK_Proto ||
2678              Style.Language == FormatStyle::LK_TextProto) {
2679     if (Right.is(tok::period) &&
2680         Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2681                      Keywords.kw_repeated, Keywords.kw_extend))
2682       return true;
2683     if (Right.is(tok::l_paren) &&
2684         Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2685       return true;
2686     if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
2687       return true;
2688     // Slashes occur in text protocol extension syntax: [type/type] { ... }.
2689     if (Left.is(tok::slash) || Right.is(tok::slash))
2690       return false;
2691     if (Left.MatchingParen &&
2692         Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
2693         Right.isOneOf(tok::l_brace, tok::less))
2694       return !Style.Cpp11BracedListStyle;
2695     // A percent is probably part of a formatting specification, such as %lld.
2696     if (Left.is(tok::percent))
2697       return false;
2698     // Preserve the existence of a space before a percent for cases like 0x%04x
2699     // and "%d %d"
2700     if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
2701       return Right.WhitespaceRange.getEnd() != Right.WhitespaceRange.getBegin();
2702   } else if (Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp()) {
2703     if (Left.is(TT_JsFatArrow))
2704       return true;
2705     // for await ( ...
2706     if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
2707         Left.Previous->is(tok::kw_for))
2708       return true;
2709     if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
2710         Right.MatchingParen) {
2711       const FormatToken *Next = Right.MatchingParen->getNextNonComment();
2712       // An async arrow function, for example: `x = async () => foo();`,
2713       // as opposed to calling a function called async: `x = async();`
2714       if (Next && Next->is(TT_JsFatArrow))
2715         return true;
2716     }
2717     if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2718         (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2719       return false;
2720     // In tagged template literals ("html`bar baz`"), there is no space between
2721     // the tag identifier and the template string. getIdentifierInfo makes sure
2722     // that the identifier is not a pseudo keyword like `yield`, either.
2723     if (Left.is(tok::identifier) && Keywords.IsJavaScriptIdentifier(Left) &&
2724         Right.is(TT_TemplateString))
2725       return false;
2726     if (Right.is(tok::star) &&
2727         Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2728       return false;
2729     if (Right.isOneOf(tok::l_brace, tok::l_square) &&
2730         Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
2731                      Keywords.kw_extends, Keywords.kw_implements))
2732       return true;
2733     if (Right.is(tok::l_paren)) {
2734       // JS methods can use some keywords as names (e.g. `delete()`).
2735       if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
2736         return false;
2737       // Valid JS method names can include keywords, e.g. `foo.delete()` or
2738       // `bar.instanceof()`. Recognize call positions by preceding period.
2739       if (Left.Previous && Left.Previous->is(tok::period) &&
2740           Left.Tok.getIdentifierInfo())
2741         return false;
2742       // Additional unary JavaScript operators that need a space after.
2743       if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
2744                        tok::kw_void))
2745         return true;
2746     }
2747     if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
2748                       tok::kw_const) ||
2749          // "of" is only a keyword if it appears after another identifier
2750          // (e.g. as "const x of y" in a for loop), or after a destructuring
2751          // operation (const [x, y] of z, const {a, b} of c).
2752          (Left.is(Keywords.kw_of) && Left.Previous &&
2753           (Left.Previous->Tok.is(tok::identifier) ||
2754            Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) &&
2755         (!Left.Previous || !Left.Previous->is(tok::period)))
2756       return true;
2757     if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
2758         Left.Previous->is(tok::period) && Right.is(tok::l_paren))
2759       return false;
2760     if (Left.is(Keywords.kw_as) &&
2761         Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
2762       return true;
2763     if (Left.is(tok::kw_default) && Left.Previous &&
2764         Left.Previous->is(tok::kw_export))
2765       return true;
2766     if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2767       return true;
2768     if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2769       return false;
2770     if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
2771       return false;
2772     if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2773         Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2774       return false;
2775     if (Left.is(tok::ellipsis))
2776       return false;
2777     if (Left.is(TT_TemplateCloser) &&
2778         !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2779                        Keywords.kw_implements, Keywords.kw_extends))
2780       // Type assertions ('<type>expr') are not followed by whitespace. Other
2781       // locations that should have whitespace following are identified by the
2782       // above set of follower tokens.
2783       return false;
2784     if (Right.is(TT_JsNonNullAssertion))
2785       return false;
2786     if (Left.is(TT_JsNonNullAssertion) &&
2787         Right.isOneOf(Keywords.kw_as, Keywords.kw_in))
2788       return true; // "x! as string", "x! in y"
2789   } else if (Style.Language == FormatStyle::LK_Java) {
2790     if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2791       return true;
2792     if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2793       return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2794     if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2795                       tok::kw_protected) ||
2796          Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2797                       Keywords.kw_native)) &&
2798         Right.is(TT_TemplateOpener))
2799       return true;
2800   }
2801   if (Left.is(TT_ImplicitStringLiteral))
2802     return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2803   if (Line.Type == LT_ObjCMethodDecl) {
2804     if (Left.is(TT_ObjCMethodSpecifier))
2805       return true;
2806     if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right))
2807       // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
2808       // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
2809       // method declaration.
2810       return false;
2811   }
2812   if (Line.Type == LT_ObjCProperty &&
2813       (Right.is(tok::equal) || Left.is(tok::equal)))
2814     return false;
2815 
2816   if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2817       Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2818     return true;
2819   if (Right.is(TT_OverloadedOperatorLParen))
2820     return spaceRequiredBeforeParens(Right);
2821   if (Left.is(tok::comma))
2822     return true;
2823   if (Right.is(tok::comma))
2824     return false;
2825   if (Right.is(TT_ObjCBlockLParen))
2826     return true;
2827   if (Right.is(TT_CtorInitializerColon))
2828     return Style.SpaceBeforeCtorInitializerColon;
2829   if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
2830     return false;
2831   if (Right.is(TT_RangeBasedForLoopColon) &&
2832       !Style.SpaceBeforeRangeBasedForLoopColon)
2833     return false;
2834   if (Right.is(tok::colon)) {
2835     if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2836         !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2837       return false;
2838     if (Right.is(TT_ObjCMethodExpr))
2839       return false;
2840     if (Left.is(tok::question))
2841       return false;
2842     if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2843       return false;
2844     if (Right.is(TT_DictLiteral))
2845       return Style.SpacesInContainerLiterals;
2846     if (Right.is(TT_AttributeColon))
2847       return false;
2848     return true;
2849   }
2850   if (Left.is(TT_UnaryOperator))
2851     return (Style.SpaceAfterLogicalNot && Left.is(tok::exclaim)) ||
2852            Right.is(TT_BinaryOperator);
2853 
2854   // If the next token is a binary operator or a selector name, we have
2855   // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2856   if (Left.is(TT_CastRParen))
2857     return Style.SpaceAfterCStyleCast ||
2858            Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2859 
2860   if (Left.is(tok::greater) && Right.is(tok::greater)) {
2861     if (Style.Language == FormatStyle::LK_TextProto ||
2862         (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral)))
2863       return !Style.Cpp11BracedListStyle;
2864     return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2865            (Style.Standard < FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2866   }
2867   if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
2868       Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2869       (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod)))
2870     return false;
2871   if (!Style.SpaceBeforeAssignmentOperators &&
2872       Right.getPrecedence() == prec::Assignment)
2873     return false;
2874   if (Style.Language == FormatStyle::LK_Java && Right.is(tok::coloncolon) &&
2875       (Left.is(tok::identifier) || Left.is(tok::kw_this)))
2876     return false;
2877   if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
2878     // Generally don't remove existing spaces between an identifier and "::".
2879     // The identifier might actually be a macro name such as ALWAYS_INLINE. If
2880     // this turns out to be too lenient, add analysis of the identifier itself.
2881     return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2882   if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
2883     return (Left.is(TT_TemplateOpener) &&
2884             Style.Standard < FormatStyle::LS_Cpp11) ||
2885            !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
2886                           tok::kw___super, TT_TemplateCloser,
2887                           TT_TemplateOpener)) ||
2888            (Left.is(tok ::l_paren) && Style.SpacesInParentheses);
2889   if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2890     return Style.SpacesInAngles;
2891   // Space before TT_StructuredBindingLSquare.
2892   if (Right.is(TT_StructuredBindingLSquare))
2893     return !Left.isOneOf(tok::amp, tok::ampamp) ||
2894            Style.PointerAlignment != FormatStyle::PAS_Right;
2895   // Space before & or && following a TT_StructuredBindingLSquare.
2896   if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
2897       Right.isOneOf(tok::amp, tok::ampamp))
2898     return Style.PointerAlignment != FormatStyle::PAS_Left;
2899   if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2900       (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2901        !Right.is(tok::r_paren)))
2902     return true;
2903   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2904       Right.isNot(TT_FunctionTypeLParen))
2905     return spaceRequiredBeforeParens(Right);
2906   if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2907       Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2908     return false;
2909   if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2910       Line.startsWith(tok::hash))
2911     return true;
2912   if (Right.is(TT_TrailingUnaryOperator))
2913     return false;
2914   if (Left.is(TT_RegexLiteral))
2915     return false;
2916   return spaceRequiredBetween(Line, Left, Right);
2917 }
2918 
2919 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2920 static bool isAllmanBrace(const FormatToken &Tok) {
2921   return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2922          !Tok.isOneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral);
2923 }
2924 
2925 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2926                                      const FormatToken &Right) {
2927   const FormatToken &Left = *Right.Previous;
2928   if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2929     return true;
2930 
2931   if (Style.Language == FormatStyle::LK_JavaScript) {
2932     // FIXME: This might apply to other languages and token kinds.
2933     if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
2934         Left.Previous->is(tok::string_literal))
2935       return true;
2936     if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2937         Left.Previous && Left.Previous->is(tok::equal) &&
2938         Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2939                             tok::kw_const) &&
2940         // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2941         // above.
2942         !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2943       // Object literals on the top level of a file are treated as "enum-style".
2944       // Each key/value pair is put on a separate line, instead of bin-packing.
2945       return true;
2946     if (Left.is(tok::l_brace) && Line.Level == 0 &&
2947         (Line.startsWith(tok::kw_enum) ||
2948          Line.startsWith(tok::kw_const, tok::kw_enum) ||
2949          Line.startsWith(tok::kw_export, tok::kw_enum) ||
2950          Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
2951       // JavaScript top-level enum key/value pairs are put on separate lines
2952       // instead of bin-packing.
2953       return true;
2954     if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2955         !Left.Children.empty())
2956       // Support AllowShortFunctionsOnASingleLine for JavaScript.
2957       return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2958              Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2959              (Left.NestingLevel == 0 && Line.Level == 0 &&
2960               Style.AllowShortFunctionsOnASingleLine &
2961                   FormatStyle::SFS_InlineOnly);
2962   } else if (Style.Language == FormatStyle::LK_Java) {
2963     if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2964         Right.Next->is(tok::string_literal))
2965       return true;
2966   } else if (Style.Language == FormatStyle::LK_Cpp ||
2967              Style.Language == FormatStyle::LK_ObjC ||
2968              Style.Language == FormatStyle::LK_Proto ||
2969              Style.Language == FormatStyle::LK_TableGen ||
2970              Style.Language == FormatStyle::LK_TextProto) {
2971     if (Left.isStringLiteral() && Right.isStringLiteral())
2972       return true;
2973   }
2974 
2975   // If the last token before a '}', ']', or ')' is a comma or a trailing
2976   // comment, the intention is to insert a line break after it in order to make
2977   // shuffling around entries easier. Import statements, especially in
2978   // JavaScript, can be an exception to this rule.
2979   if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
2980     const FormatToken *BeforeClosingBrace = nullptr;
2981     if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
2982          (Style.Language == FormatStyle::LK_JavaScript &&
2983           Left.is(tok::l_paren))) &&
2984         Left.BlockKind != BK_Block && Left.MatchingParen)
2985       BeforeClosingBrace = Left.MatchingParen->Previous;
2986     else if (Right.MatchingParen &&
2987              (Right.MatchingParen->isOneOf(tok::l_brace,
2988                                            TT_ArrayInitializerLSquare) ||
2989               (Style.Language == FormatStyle::LK_JavaScript &&
2990                Right.MatchingParen->is(tok::l_paren))))
2991       BeforeClosingBrace = &Left;
2992     if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2993                                BeforeClosingBrace->isTrailingComment()))
2994       return true;
2995   }
2996 
2997   if (Right.is(tok::comment))
2998     return Left.BlockKind != BK_BracedInit &&
2999            Left.isNot(TT_CtorInitializerColon) &&
3000            (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
3001   if (Left.isTrailingComment())
3002     return true;
3003   if (Right.Previous->IsUnterminatedLiteral)
3004     return true;
3005   if (Right.is(tok::lessless) && Right.Next &&
3006       Right.Previous->is(tok::string_literal) &&
3007       Right.Next->is(tok::string_literal))
3008     return true;
3009   if (Right.Previous->ClosesTemplateDeclaration &&
3010       Right.Previous->MatchingParen &&
3011       Right.Previous->MatchingParen->NestingLevel == 0 &&
3012       Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes)
3013     return true;
3014   if (Right.is(TT_CtorInitializerComma) &&
3015       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
3016       !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
3017     return true;
3018   if (Right.is(TT_CtorInitializerColon) &&
3019       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
3020       !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
3021     return true;
3022   // Break only if we have multiple inheritance.
3023   if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
3024       Right.is(TT_InheritanceComma))
3025     return true;
3026   if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
3027     // Multiline raw string literals are special wrt. line breaks. The author
3028     // has made a deliberate choice and might have aligned the contents of the
3029     // string literal accordingly. Thus, we try keep existing line breaks.
3030     return Right.IsMultiline && Right.NewlinesBefore > 0;
3031   if ((Right.Previous->is(tok::l_brace) ||
3032        (Right.Previous->is(tok::less) && Right.Previous->Previous &&
3033         Right.Previous->Previous->is(tok::equal))) &&
3034       Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
3035     // Don't put enums or option definitions onto single lines in protocol
3036     // buffers.
3037     return true;
3038   }
3039   if (Right.is(TT_InlineASMBrace))
3040     return Right.HasUnescapedNewline;
3041   if (isAllmanBrace(Left) || isAllmanBrace(Right))
3042     return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
3043            (Line.startsWith(tok::kw_typedef, tok::kw_enum) &&
3044             Style.BraceWrapping.AfterEnum) ||
3045            (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
3046            (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
3047   if (Left.is(TT_ObjCBlockLBrace) &&
3048       Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
3049     return true;
3050 
3051   if (Left.is(TT_LambdaLBrace)) {
3052     if (Left.MatchingParen && Left.MatchingParen->Next &&
3053         Left.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren) &&
3054         Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline)
3055       return false;
3056 
3057     if (Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_None ||
3058         Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline ||
3059         (!Left.Children.empty() &&
3060          Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty))
3061       return true;
3062   }
3063 
3064   // Put multiple C# attributes on a new line.
3065   if (Style.isCSharp() &&
3066       ((Left.is(TT_AttributeSquare) && Left.is(tok::r_square)) ||
3067        (Left.is(tok::r_square) && Right.is(TT_AttributeSquare) &&
3068         Right.is(tok::l_square))))
3069     return true;
3070 
3071   // Put multiple Java annotation on a new line.
3072   if ((Style.Language == FormatStyle::LK_Java ||
3073        Style.Language == FormatStyle::LK_JavaScript) &&
3074       Left.is(TT_LeadingJavaAnnotation) &&
3075       Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
3076       (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
3077     return true;
3078 
3079   if (Right.is(TT_ProtoExtensionLSquare))
3080     return true;
3081 
3082   // In text proto instances if a submessage contains at least 2 entries and at
3083   // least one of them is a submessage, like A { ... B { ... } ... },
3084   // put all of the entries of A on separate lines by forcing the selector of
3085   // the submessage B to be put on a newline.
3086   //
3087   // Example: these can stay on one line:
3088   // a { scalar_1: 1 scalar_2: 2 }
3089   // a { b { key: value } }
3090   //
3091   // and these entries need to be on a new line even if putting them all in one
3092   // line is under the column limit:
3093   // a {
3094   //   scalar: 1
3095   //   b { key: value }
3096   // }
3097   //
3098   // We enforce this by breaking before a submessage field that has previous
3099   // siblings, *and* breaking before a field that follows a submessage field.
3100   //
3101   // Be careful to exclude the case  [proto.ext] { ... } since the `]` is
3102   // the TT_SelectorName there, but we don't want to break inside the brackets.
3103   //
3104   // Another edge case is @submessage { key: value }, which is a common
3105   // substitution placeholder. In this case we want to keep `@` and `submessage`
3106   // together.
3107   //
3108   // We ensure elsewhere that extensions are always on their own line.
3109   if ((Style.Language == FormatStyle::LK_Proto ||
3110        Style.Language == FormatStyle::LK_TextProto) &&
3111       Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) {
3112     // Keep `@submessage` together in:
3113     // @submessage { key: value }
3114     if (Right.Previous && Right.Previous->is(tok::at))
3115       return false;
3116     // Look for the scope opener after selector in cases like:
3117     // selector { ...
3118     // selector: { ...
3119     // selector: @base { ...
3120     FormatToken *LBrace = Right.Next;
3121     if (LBrace && LBrace->is(tok::colon)) {
3122       LBrace = LBrace->Next;
3123       if (LBrace && LBrace->is(tok::at)) {
3124         LBrace = LBrace->Next;
3125         if (LBrace)
3126           LBrace = LBrace->Next;
3127       }
3128     }
3129     if (LBrace &&
3130         // The scope opener is one of {, [, <:
3131         // selector { ... }
3132         // selector [ ... ]
3133         // selector < ... >
3134         //
3135         // In case of selector { ... }, the l_brace is TT_DictLiteral.
3136         // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
3137         // so we check for immediately following r_brace.
3138         ((LBrace->is(tok::l_brace) &&
3139           (LBrace->is(TT_DictLiteral) ||
3140            (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
3141          LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) {
3142       // If Left.ParameterCount is 0, then this submessage entry is not the
3143       // first in its parent submessage, and we want to break before this entry.
3144       // If Left.ParameterCount is greater than 0, then its parent submessage
3145       // might contain 1 or more entries and we want to break before this entry
3146       // if it contains at least 2 entries. We deal with this case later by
3147       // detecting and breaking before the next entry in the parent submessage.
3148       if (Left.ParameterCount == 0)
3149         return true;
3150       // However, if this submessage is the first entry in its parent
3151       // submessage, Left.ParameterCount might be 1 in some cases.
3152       // We deal with this case later by detecting an entry
3153       // following a closing paren of this submessage.
3154     }
3155 
3156     // If this is an entry immediately following a submessage, it will be
3157     // preceded by a closing paren of that submessage, like in:
3158     //     left---.  .---right
3159     //            v  v
3160     // sub: { ... } key: value
3161     // If there was a comment between `}` an `key` above, then `key` would be
3162     // put on a new line anyways.
3163     if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
3164       return true;
3165   }
3166 
3167   // Deal with lambda arguments in C++ - we want consistent line breaks whether
3168   // they happen to be at arg0, arg1 or argN. The selection is a bit nuanced
3169   // as aggressive line breaks are placed when the lambda is not the last arg.
3170   if ((Style.Language == FormatStyle::LK_Cpp ||
3171        Style.Language == FormatStyle::LK_ObjC) &&
3172       Left.is(tok::l_paren) && Left.BlockParameterCount > 0 &&
3173       !Right.isOneOf(tok::l_paren, TT_LambdaLSquare)) {
3174     // Multiple lambdas in the same function call force line breaks.
3175     if (Left.BlockParameterCount > 1)
3176       return true;
3177 
3178     // A lambda followed by another arg forces a line break.
3179     if (!Left.Role)
3180       return false;
3181     auto Comma = Left.Role->lastComma();
3182     if (!Comma)
3183       return false;
3184     auto Next = Comma->getNextNonComment();
3185     if (!Next)
3186       return false;
3187     if (!Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret))
3188       return true;
3189   }
3190 
3191   return false;
3192 }
3193 
3194 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
3195                                     const FormatToken &Right) {
3196   const FormatToken &Left = *Right.Previous;
3197 
3198   // Language-specific stuff.
3199   if (Style.Language == FormatStyle::LK_Java) {
3200     if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
3201                      Keywords.kw_implements))
3202       return false;
3203     if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
3204                       Keywords.kw_implements))
3205       return true;
3206   } else if (Style.Language == FormatStyle::LK_JavaScript) {
3207     const FormatToken *NonComment = Right.getPreviousNonComment();
3208     if (NonComment &&
3209         NonComment->isOneOf(
3210             tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
3211             tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
3212             tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected,
3213             Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
3214             Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
3215       return false; // Otherwise automatic semicolon insertion would trigger.
3216     if (Right.NestingLevel == 0 &&
3217         (Left.Tok.getIdentifierInfo() ||
3218          Left.isOneOf(tok::r_square, tok::r_paren)) &&
3219         Right.isOneOf(tok::l_square, tok::l_paren))
3220       return false; // Otherwise automatic semicolon insertion would trigger.
3221     if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
3222       return false;
3223     if (Left.is(TT_JsTypeColon))
3224       return true;
3225     // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
3226     if (Left.is(tok::exclaim) && Right.is(tok::colon))
3227       return false;
3228     // Look for is type annotations like:
3229     // function f(): a is B { ... }
3230     // Do not break before is in these cases.
3231     if (Right.is(Keywords.kw_is)) {
3232       const FormatToken *Next = Right.getNextNonComment();
3233       // If `is` is followed by a colon, it's likely that it's a dict key, so
3234       // ignore it for this check.
3235       // For example this is common in Polymer:
3236       // Polymer({
3237       //   is: 'name',
3238       //   ...
3239       // });
3240       if (!Next || !Next->is(tok::colon))
3241         return false;
3242     }
3243     if (Left.is(Keywords.kw_in))
3244       return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
3245     if (Right.is(Keywords.kw_in))
3246       return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
3247     if (Right.is(Keywords.kw_as))
3248       return false; // must not break before as in 'x as type' casts
3249     if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_infer)) {
3250       // extends and infer can appear as keywords in conditional types:
3251       //   https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types
3252       // do not break before them, as the expressions are subject to ASI.
3253       return false;
3254     }
3255     if (Left.is(Keywords.kw_as))
3256       return true;
3257     if (Left.is(TT_JsNonNullAssertion))
3258       return true;
3259     if (Left.is(Keywords.kw_declare) &&
3260         Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
3261                       Keywords.kw_function, tok::kw_class, tok::kw_enum,
3262                       Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
3263                       Keywords.kw_let, tok::kw_const))
3264       // See grammar for 'declare' statements at:
3265       // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10
3266       return false;
3267     if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
3268         Right.isOneOf(tok::identifier, tok::string_literal))
3269       return false; // must not break in "module foo { ...}"
3270     if (Right.is(TT_TemplateString) && Right.closesScope())
3271       return false;
3272     // Don't split tagged template literal so there is a break between the tag
3273     // identifier and template string.
3274     if (Left.is(tok::identifier) && Right.is(TT_TemplateString)) {
3275       return false;
3276     }
3277     if (Left.is(TT_TemplateString) && Left.opensScope())
3278       return true;
3279   }
3280 
3281   if (Left.is(tok::at))
3282     return false;
3283   if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
3284     return false;
3285   if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
3286     return !Right.is(tok::l_paren);
3287   if (Right.is(TT_PointerOrReference))
3288     return Line.IsMultiVariableDeclStmt ||
3289            (Style.PointerAlignment == FormatStyle::PAS_Right &&
3290             (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
3291   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
3292       Right.is(tok::kw_operator))
3293     return true;
3294   if (Left.is(TT_PointerOrReference))
3295     return false;
3296   if (Right.isTrailingComment())
3297     // We rely on MustBreakBefore being set correctly here as we should not
3298     // change the "binding" behavior of a comment.
3299     // The first comment in a braced lists is always interpreted as belonging to
3300     // the first list element. Otherwise, it should be placed outside of the
3301     // list.
3302     return Left.BlockKind == BK_BracedInit ||
3303            (Left.is(TT_CtorInitializerColon) &&
3304             Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
3305   if (Left.is(tok::question) && Right.is(tok::colon))
3306     return false;
3307   if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
3308     return Style.BreakBeforeTernaryOperators;
3309   if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
3310     return !Style.BreakBeforeTernaryOperators;
3311   if (Left.is(TT_InheritanceColon))
3312     return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
3313   if (Right.is(TT_InheritanceColon))
3314     return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
3315   if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
3316       Left.isNot(TT_SelectorName))
3317     return true;
3318 
3319   if (Right.is(tok::colon) &&
3320       !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
3321     return false;
3322   if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
3323     if (Style.Language == FormatStyle::LK_Proto ||
3324         Style.Language == FormatStyle::LK_TextProto) {
3325       if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
3326         return false;
3327       // Prevent cases like:
3328       //
3329       // submessage:
3330       //     { key: valueeeeeeeeeeee }
3331       //
3332       // when the snippet does not fit into one line.
3333       // Prefer:
3334       //
3335       // submessage: {
3336       //   key: valueeeeeeeeeeee
3337       // }
3338       //
3339       // instead, even if it is longer by one line.
3340       //
3341       // Note that this allows allows the "{" to go over the column limit
3342       // when the column limit is just between ":" and "{", but that does
3343       // not happen too often and alternative formattings in this case are
3344       // not much better.
3345       //
3346       // The code covers the cases:
3347       //
3348       // submessage: { ... }
3349       // submessage: < ... >
3350       // repeated: [ ... ]
3351       if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
3352            Right.is(TT_DictLiteral)) ||
3353           Right.is(TT_ArrayInitializerLSquare))
3354         return false;
3355     }
3356     return true;
3357   }
3358   if (Right.is(tok::r_square) && Right.MatchingParen &&
3359       Right.MatchingParen->is(TT_ProtoExtensionLSquare))
3360     return false;
3361   if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
3362                                     Right.Next->is(TT_ObjCMethodExpr)))
3363     return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
3364   if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
3365     return true;
3366   if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
3367     return true;
3368   if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
3369                     TT_OverloadedOperator))
3370     return false;
3371   if (Left.is(TT_RangeBasedForLoopColon))
3372     return true;
3373   if (Right.is(TT_RangeBasedForLoopColon))
3374     return false;
3375   if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
3376     return true;
3377   if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
3378       Left.is(tok::kw_operator))
3379     return false;
3380   if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
3381       Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
3382     return false;
3383   if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
3384       !Style.Cpp11BracedListStyle)
3385     return false;
3386   if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
3387     return false;
3388   if (Left.is(tok::l_paren) && Left.Previous &&
3389       (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
3390     return false;
3391   if (Right.is(TT_ImplicitStringLiteral))
3392     return false;
3393 
3394   if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
3395     return false;
3396   if (Right.is(tok::r_square) && Right.MatchingParen &&
3397       Right.MatchingParen->is(TT_LambdaLSquare))
3398     return false;
3399 
3400   // We only break before r_brace if there was a corresponding break before
3401   // the l_brace, which is tracked by BreakBeforeClosingBrace.
3402   if (Right.is(tok::r_brace))
3403     return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
3404 
3405   // Allow breaking after a trailing annotation, e.g. after a method
3406   // declaration.
3407   if (Left.is(TT_TrailingAnnotation))
3408     return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
3409                           tok::less, tok::coloncolon);
3410 
3411   if (Right.is(tok::kw___attribute) ||
3412       (Right.is(tok::l_square) && Right.is(TT_AttributeSquare)))
3413     return true;
3414 
3415   if (Left.is(tok::identifier) && Right.is(tok::string_literal))
3416     return true;
3417 
3418   if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
3419     return true;
3420 
3421   if (Left.is(TT_CtorInitializerColon))
3422     return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
3423   if (Right.is(TT_CtorInitializerColon))
3424     return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon;
3425   if (Left.is(TT_CtorInitializerComma) &&
3426       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
3427     return false;
3428   if (Right.is(TT_CtorInitializerComma) &&
3429       Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
3430     return true;
3431   if (Left.is(TT_InheritanceComma) &&
3432       Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
3433     return false;
3434   if (Right.is(TT_InheritanceComma) &&
3435       Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
3436     return true;
3437   if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
3438       (Left.is(tok::less) && Right.is(tok::less)))
3439     return false;
3440   if (Right.is(TT_BinaryOperator) &&
3441       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
3442       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
3443        Right.getPrecedence() != prec::Assignment))
3444     return true;
3445   if (Left.is(TT_ArrayInitializerLSquare))
3446     return true;
3447   if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
3448     return true;
3449   if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
3450       !Left.isOneOf(tok::arrowstar, tok::lessless) &&
3451       Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
3452       (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
3453        Left.getPrecedence() == prec::Assignment))
3454     return true;
3455   if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) ||
3456       (Left.is(tok::r_square) && Right.is(TT_AttributeSquare)))
3457     return false;
3458   return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
3459                       tok::kw_class, tok::kw_struct, tok::comment) ||
3460          Right.isMemberAccess() ||
3461          Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
3462                        tok::colon, tok::l_square, tok::at) ||
3463          (Left.is(tok::r_paren) &&
3464           Right.isOneOf(tok::identifier, tok::kw_const)) ||
3465          (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
3466          (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
3467 }
3468 
3469 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
3470   llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
3471   const FormatToken *Tok = Line.First;
3472   while (Tok) {
3473     llvm::errs() << " M=" << Tok->MustBreakBefore
3474                  << " C=" << Tok->CanBreakBefore
3475                  << " T=" << getTokenTypeName(Tok->Type)
3476                  << " S=" << Tok->SpacesRequiredBefore
3477                  << " B=" << Tok->BlockParameterCount
3478                  << " BK=" << Tok->BlockKind << " P=" << Tok->SplitPenalty
3479                  << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
3480                  << " PPK=" << Tok->PackingKind << " FakeLParens=";
3481     for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
3482       llvm::errs() << Tok->FakeLParens[i] << "/";
3483     llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
3484     llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
3485     llvm::errs() << " Text='" << Tok->TokenText << "'\n";
3486     if (!Tok->Next)
3487       assert(Tok == Line.Last);
3488     Tok = Tok->Next;
3489   }
3490   llvm::errs() << "----\n";
3491 }
3492 
3493 } // namespace format
3494 } // namespace clang
3495