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