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