1 //===--- TokenAnnotator.cpp - Format C++ code -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file implements a token annotator, i.e. creates
12 /// \c AnnotatedTokens out of \c FormatTokens with required extra information.
14 //===----------------------------------------------------------------------===//
16 #include "TokenAnnotator.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/Support/Debug.h"
21 #define DEBUG_TYPE "format-token-annotator"
28 /// Returns \c true if the token can be used as an identifier in
29 /// an Objective-C \c @selector, \c false otherwise.
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.
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;
43 /// A parser that gathers additional information about tokens.
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 {
50 AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
51 const AdditionalKeywords &Keywords)
52 : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
54 Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
55 resetTokenMetadata(CurrentToken);
60 if (!CurrentToken || !CurrentToken->Previous)
62 if (NonTemplateLess.count(CurrentToken->Previous))
65 const FormatToken &Previous = *CurrentToken->Previous; // The '<'.
66 if (Previous.Previous) {
67 if (Previous.Previous->Tok.isLiteral())
69 if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 &&
70 (!Previous.Previous->MatchingParen ||
71 !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen)))
75 FormatToken *Left = CurrentToken->Previous;
76 Left->ParentBracket = Contexts.back().ContextKind;
77 ScopedContextCreator ContextCreator(*this, tok::less, 12);
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;
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);
89 if (Style.Language == FormatStyle::LK_Java &&
90 CurrentToken->is(tok::question))
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:
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;
107 CurrentToken->Type = TT_TemplateCloser;
111 if (CurrentToken->is(tok::question) &&
112 Style.Language == FormatStyle::LK_Java) {
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))
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
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))
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;
147 bool parseParens(bool LookForDecls = false) {
150 FormatToken *Left = CurrentToken->Previous;
151 Left->ParentBracket = Contexts.back().ContextKind;
152 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
154 // FIXME: This is a bit of a hack. Do better.
155 Contexts.back().ColonIsForRangeExpr =
156 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
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;
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,
174 // export type X = (...);
175 Contexts.back().IsExpression = false;
176 } else if (Left->Previous &&
177 (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
178 tok::kw_if, tok::kw_while, tok::l_paren,
180 Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
181 Left->Previous->is(TT_BinaryOperator))) {
182 // static_assert, if and while usually contain expressions.
183 Contexts.back().IsExpression = true;
184 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
185 (Left->Previous->is(Keywords.kw_function) ||
186 (Left->Previous->endsSequence(tok::identifier,
187 Keywords.kw_function)))) {
188 // function(...) or function f(...)
189 Contexts.back().IsExpression = false;
190 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
191 Left->Previous->is(TT_JsTypeColon)) {
192 // let x: (SomeType);
193 Contexts.back().IsExpression = false;
194 } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
195 Left->Previous->MatchingParen &&
196 Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
197 // This is a parameter list of a lambda expression.
198 Contexts.back().IsExpression = false;
199 } else if (Line.InPPDirective &&
200 (!Left->Previous || !Left->Previous->is(tok::identifier))) {
201 Contexts.back().IsExpression = true;
202 } else if (Contexts[Contexts.size() - 2].CaretFound) {
203 // This is the parameter list of an ObjC block.
204 Contexts.back().IsExpression = false;
205 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
206 Left->Type = TT_AttributeParen;
207 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
208 // The first argument to a foreach macro is a declaration.
209 Contexts.back().IsForEachMacro = true;
210 Contexts.back().IsExpression = false;
211 } else if (Left->Previous && Left->Previous->MatchingParen &&
212 Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
213 Contexts.back().IsExpression = false;
214 } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
216 Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
217 Contexts.back().IsExpression = !IsForOrCatch;
220 if (StartsObjCMethodExpr) {
221 Contexts.back().ColonIsObjCMethodExpr = true;
222 Left->Type = TT_ObjCMethodExpr;
225 // MightBeFunctionType and ProbablyFunctionType are used for
226 // function pointer and reference types as well as Objective-C
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();
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;
259 if (CurrentToken->Previous->is(TT_PointerOrReference) &&
260 CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
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;
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;
288 if (StartsObjCMethodExpr) {
289 CurrentToken->Type = TT_ObjCMethodExpr;
290 if (Contexts.back().FirstObjCSelectorName) {
291 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
292 Contexts.back().LongestObjCSelectorName;
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;
303 if (!HasMultipleLines)
304 Left->PackingKind = PPK_Inconclusive;
305 else if (HasMultipleParametersOnALine)
306 Left->PackingKind = PPK_BinPacked;
308 Left->PackingKind = PPK_OnePerLine;
313 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
316 if (CurrentToken->is(tok::l_brace))
317 Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
318 if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
319 !CurrentToken->Next->HasUnescapedNewline &&
320 !CurrentToken->Next->isTrailingComment())
321 HasMultipleParametersOnALine = true;
322 if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
323 CurrentToken->Previous->isSimpleTypeSpecifier()) &&
324 !CurrentToken->is(tok::l_brace))
325 Contexts.back().IsExpression = false;
326 if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
327 MightBeObjCForRangeLoop = false;
328 if (PossibleObjCForInToken) {
329 PossibleObjCForInToken->Type = TT_Unknown;
330 PossibleObjCForInToken = nullptr;
333 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
334 PossibleObjCForInToken = CurrentToken;
335 PossibleObjCForInToken->Type = TT_ObjCForIn;
337 // When we discover a 'new', we set CanBeExpression to 'false' in order to
338 // parse the type correctly. Reset that after a comma.
339 if (CurrentToken->is(tok::comma))
340 Contexts.back().CanBeExpression = true;
342 FormatToken *Tok = CurrentToken;
345 updateParameterCount(Left, Tok);
346 if (CurrentToken && CurrentToken->HasUnescapedNewline)
347 HasMultipleLines = true;
352 bool isCpp11AttributeSpecifier(const FormatToken &Tok) {
353 if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square))
355 const FormatToken *AttrTok = Tok.Next->Next;
358 // C++17 '[[using ns: foo, bar(baz, blech)]]'
359 // We assume nobody will name an ObjC variable 'using'.
360 if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
362 if (AttrTok->isNot(tok::identifier))
364 while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
365 // ObjC message send. We assume nobody will use : in a C++11 attribute
366 // specifier parameter, although this is technically valid:
368 if (AttrTok->is(tok::colon) ||
369 AttrTok->startsSequence(tok::identifier, tok::identifier))
371 if (AttrTok->is(tok::ellipsis))
373 AttrTok = AttrTok->Next;
375 return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
382 // A '[' could be an index subscript (after an identifier or after
383 // ')' or ']'), it could be the start of an Objective-C method
384 // expression, it could the start of an Objective-C array literal,
385 // or it could be a C++ attribute specifier [[foo::bar]].
386 FormatToken *Left = CurrentToken->Previous;
387 Left->ParentBracket = Contexts.back().ContextKind;
388 FormatToken *Parent = Left->getPreviousNonComment();
390 // Cases where '>' is followed by '['.
391 // In C++, this can happen either in array of templates (foo<int>[10])
392 // or when array is a nested template type (unique_ptr<type1<type2>[]>).
393 bool CppArrayTemplates =
394 Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
395 (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
396 Contexts.back().InTemplateArgument);
398 bool IsCpp11AttributeSpecifier = isCpp11AttributeSpecifier(*Left) ||
399 Contexts.back().InCpp11AttributeSpecifier;
401 bool StartsObjCMethodExpr =
402 !CppArrayTemplates && Style.isCpp() && !IsCpp11AttributeSpecifier &&
403 Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
404 !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
406 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
407 tok::kw_return, tok::kw_throw) ||
408 Parent->isUnaryOperator() ||
409 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
410 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
411 getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
412 bool ColonFound = false;
414 unsigned BindingIncrease = 1;
415 if (Left->isCppStructuredBinding(Style)) {
416 Left->Type = TT_StructuredBindingLSquare;
417 } else if (Left->is(TT_Unknown)) {
418 if (StartsObjCMethodExpr) {
419 Left->Type = TT_ObjCMethodExpr;
420 } else if (IsCpp11AttributeSpecifier) {
421 Left->Type = TT_AttributeSquare;
422 } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
423 Contexts.back().ContextKind == tok::l_brace &&
424 Parent->isOneOf(tok::l_brace, tok::comma)) {
425 Left->Type = TT_JsComputedPropertyName;
426 } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace &&
427 Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
428 Left->Type = TT_DesignatedInitializerLSquare;
429 } else if (CurrentToken->is(tok::r_square) && Parent &&
430 Parent->is(TT_TemplateCloser)) {
431 Left->Type = TT_ArraySubscriptLSquare;
432 } else if (Style.Language == FormatStyle::LK_Proto ||
433 Style.Language == FormatStyle::LK_TextProto) {
434 // Square braces in LK_Proto can either be message field attributes:
436 // optional Aaa aaa = 1 [
444 // or text proto extensions (in options):
446 // option (Aaa.options) = {
447 // [type.type/type] {
452 // or repeated fields (in options):
454 // option (Aaa.options) = {
458 // In the first and the third case we want to spread the contents inside
459 // the square braces; in the second we want to keep them inline.
460 Left->Type = TT_ArrayInitializerLSquare;
461 if (!Left->endsSequence(tok::l_square, tok::numeric_constant,
463 !Left->endsSequence(tok::l_square, tok::numeric_constant,
465 !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
466 Left->Type = TT_ProtoExtensionLSquare;
467 BindingIncrease = 10;
469 } else if (!CppArrayTemplates && Parent &&
470 Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
471 tok::comma, tok::l_paren, tok::l_square,
472 tok::question, tok::colon, tok::kw_return,
473 // Should only be relevant to JavaScript:
475 Left->Type = TT_ArrayInitializerLSquare;
477 BindingIncrease = 10;
478 Left->Type = TT_ArraySubscriptLSquare;
482 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
483 Contexts.back().IsExpression = true;
484 if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
485 Parent->is(TT_JsTypeColon))
486 Contexts.back().IsExpression = false;
488 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
489 Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
491 while (CurrentToken) {
492 if (CurrentToken->is(tok::r_square)) {
493 if (IsCpp11AttributeSpecifier)
494 CurrentToken->Type = TT_AttributeSquare;
495 else if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
496 Left->is(TT_ObjCMethodExpr)) {
497 // An ObjC method call is rarely followed by an open parenthesis.
498 // FIXME: Do we incorrectly label ":" with this?
499 StartsObjCMethodExpr = false;
500 Left->Type = TT_Unknown;
502 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
503 CurrentToken->Type = TT_ObjCMethodExpr;
504 // If we haven't seen a colon yet, make sure the last identifier
505 // before the r_square is tagged as a selector name component.
506 if (!ColonFound && CurrentToken->Previous &&
507 CurrentToken->Previous->is(TT_Unknown) &&
508 canBeObjCSelectorComponent(*CurrentToken->Previous))
509 CurrentToken->Previous->Type = TT_SelectorName;
510 // determineStarAmpUsage() thinks that '*' '[' is allocating an
511 // array of pointers, but if '[' starts a selector then '*' is a
513 if (Parent && Parent->is(TT_PointerOrReference))
514 Parent->Type = TT_BinaryOperator;
516 Left->MatchingParen = CurrentToken;
517 CurrentToken->MatchingParen = Left;
518 // FirstObjCSelectorName is set when a colon is found. This does
519 // not work, however, when the method has no parameters.
520 // Here, we set FirstObjCSelectorName when the end of the method call is
521 // reached, in case it was not set already.
522 if (!Contexts.back().FirstObjCSelectorName) {
523 FormatToken* Previous = CurrentToken->getPreviousNonComment();
524 if (Previous && Previous->is(TT_SelectorName)) {
525 Previous->ObjCSelectorNameParts = 1;
526 Contexts.back().FirstObjCSelectorName = Previous;
529 Left->ParameterCount =
530 Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
532 if (Contexts.back().FirstObjCSelectorName) {
533 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
534 Contexts.back().LongestObjCSelectorName;
535 if (Left->BlockParameterCount > 1)
536 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
541 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
543 if (CurrentToken->is(tok::colon)) {
544 if (IsCpp11AttributeSpecifier &&
545 CurrentToken->endsSequence(tok::colon, tok::identifier,
547 // Remember that this is a [[using ns: foo]] C++ attribute, so we
548 // don't add a space before the colon (unlike other colons).
549 CurrentToken->Type = TT_AttributeColon;
550 } else if (Left->isOneOf(TT_ArraySubscriptLSquare,
551 TT_DesignatedInitializerLSquare)) {
552 Left->Type = TT_ObjCMethodExpr;
553 StartsObjCMethodExpr = true;
554 Contexts.back().ColonIsObjCMethodExpr = true;
555 if (Parent && Parent->is(tok::r_paren))
556 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
557 Parent->Type = TT_CastRParen;
561 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
563 Left->Type = TT_ArrayInitializerLSquare;
564 FormatToken *Tok = CurrentToken;
567 updateParameterCount(Left, Tok);
574 FormatToken *Left = CurrentToken->Previous;
575 Left->ParentBracket = Contexts.back().ContextKind;
577 if (Contexts.back().CaretFound)
578 Left->Type = TT_ObjCBlockLBrace;
579 Contexts.back().CaretFound = false;
581 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
582 Contexts.back().ColonIsDictLiteral = true;
583 if (Left->BlockKind == BK_BracedInit)
584 Contexts.back().IsExpression = true;
585 if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
586 Left->Previous->is(TT_JsTypeColon))
587 Contexts.back().IsExpression = false;
589 while (CurrentToken) {
590 if (CurrentToken->is(tok::r_brace)) {
591 Left->MatchingParen = CurrentToken;
592 CurrentToken->MatchingParen = Left;
596 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
598 updateParameterCount(Left, CurrentToken);
599 if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
600 FormatToken *Previous = CurrentToken->getPreviousNonComment();
601 if (Previous->is(TT_JsTypeOptionalQuestion))
602 Previous = Previous->getPreviousNonComment();
603 if ((CurrentToken->is(tok::colon) &&
604 (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
605 Style.Language == FormatStyle::LK_Proto ||
606 Style.Language == FormatStyle::LK_TextProto) {
607 Left->Type = TT_DictLiteral;
608 if (Previous->Tok.getIdentifierInfo() ||
609 Previous->is(tok::string_literal))
610 Previous->Type = TT_SelectorName;
612 if (CurrentToken->is(tok::colon) ||
613 Style.Language == FormatStyle::LK_JavaScript)
614 Left->Type = TT_DictLiteral;
616 if (CurrentToken->is(tok::comma) &&
617 Style.Language == FormatStyle::LK_JavaScript)
618 Left->Type = TT_DictLiteral;
626 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
627 // For ObjC methods, the number of parameters is calculated differently as
628 // method declarations have a different structure (the parameters are not
629 // inside a bracket scope).
630 if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
631 ++Left->BlockParameterCount;
632 if (Current->is(tok::comma)) {
633 ++Left->ParameterCount;
635 Left->Role.reset(new CommaSeparatedList(Style));
636 Left->Role->CommaFound(Current);
637 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
638 Left->ParameterCount = 1;
642 bool parseConditional() {
643 while (CurrentToken) {
644 if (CurrentToken->is(tok::colon)) {
645 CurrentToken->Type = TT_ConditionalExpr;
655 bool parseTemplateDeclaration() {
656 if (CurrentToken && CurrentToken->is(tok::less)) {
657 CurrentToken->Type = TT_TemplateOpener;
662 CurrentToken->Previous->ClosesTemplateDeclaration = true;
668 bool consumeToken() {
669 FormatToken *Tok = CurrentToken;
671 switch (Tok->Tok.getKind()) {
674 if (!Tok->Previous && Line.MustBeDeclaration)
675 Tok->Type = TT_ObjCMethodSpecifier;
680 // Colons from ?: are handled in parseConditional().
681 if (Style.Language == FormatStyle::LK_JavaScript) {
682 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
683 (Contexts.size() == 1 && // switch/case labels
684 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
685 Contexts.back().ContextKind == tok::l_paren || // function params
686 Contexts.back().ContextKind == tok::l_square || // array type
687 (!Contexts.back().IsExpression &&
688 Contexts.back().ContextKind == tok::l_brace) || // object type
689 (Contexts.size() == 1 &&
690 Line.MustBeDeclaration)) { // method/property declaration
691 Contexts.back().IsExpression = false;
692 Tok->Type = TT_JsTypeColon;
696 if (Contexts.back().ColonIsDictLiteral ||
697 Style.Language == FormatStyle::LK_Proto ||
698 Style.Language == FormatStyle::LK_TextProto) {
699 Tok->Type = TT_DictLiteral;
700 if (Style.Language == FormatStyle::LK_TextProto) {
701 if (FormatToken *Previous = Tok->getPreviousNonComment())
702 Previous->Type = TT_SelectorName;
704 } else if (Contexts.back().ColonIsObjCMethodExpr ||
705 Line.startsWith(TT_ObjCMethodSpecifier)) {
706 Tok->Type = TT_ObjCMethodExpr;
707 const FormatToken *BeforePrevious = Tok->Previous->Previous;
708 // Ensure we tag all identifiers in method declarations as
710 bool UnknownIdentifierInMethodDeclaration =
711 Line.startsWith(TT_ObjCMethodSpecifier) &&
712 Tok->Previous->is(tok::identifier) && Tok->Previous->is(TT_Unknown);
713 if (!BeforePrevious ||
714 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
715 !(BeforePrevious->is(TT_CastRParen) ||
716 (BeforePrevious->is(TT_ObjCMethodExpr) &&
717 BeforePrevious->is(tok::colon))) ||
718 BeforePrevious->is(tok::r_square) ||
719 Contexts.back().LongestObjCSelectorName == 0 ||
720 UnknownIdentifierInMethodDeclaration) {
721 Tok->Previous->Type = TT_SelectorName;
722 if (!Contexts.back().FirstObjCSelectorName)
723 Contexts.back().FirstObjCSelectorName = Tok->Previous;
724 else if (Tok->Previous->ColumnWidth >
725 Contexts.back().LongestObjCSelectorName)
726 Contexts.back().LongestObjCSelectorName =
727 Tok->Previous->ColumnWidth;
728 Tok->Previous->ParameterIndex =
729 Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
730 ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
732 } else if (Contexts.back().ColonIsForRangeExpr) {
733 Tok->Type = TT_RangeBasedForLoopColon;
734 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
735 Tok->Type = TT_BitFieldColon;
736 } else if (Contexts.size() == 1 &&
737 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
738 if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren,
740 Tok->Type = TT_CtorInitializerColon;
742 Tok->Type = TT_InheritanceColon;
743 } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
744 (Tok->Next->isOneOf(tok::r_paren, tok::comma) ||
745 (canBeObjCSelectorComponent(*Tok->Next) && Tok->Next->Next &&
746 Tok->Next->Next->is(tok::colon)))) {
747 // This handles a special macro in ObjC code where selectors including
748 // the colon are passed as macro arguments.
749 Tok->Type = TT_ObjCMethodExpr;
750 } else if (Contexts.back().ContextKind == tok::l_paren) {
751 Tok->Type = TT_InlineASMColon;
756 // | and & in declarations/type expressions represent union and
757 // intersection types, respectively.
758 if (Style.Language == FormatStyle::LK_JavaScript &&
759 !Contexts.back().IsExpression)
760 Tok->Type = TT_JsTypeOperator;
764 if (Tok->is(tok::kw_if) && CurrentToken &&
765 CurrentToken->is(tok::kw_constexpr))
767 if (CurrentToken && CurrentToken->is(tok::l_paren)) {
769 if (!parseParens(/*LookForDecls=*/true))
774 if (Style.Language == FormatStyle::LK_JavaScript) {
775 // x.for and {for: ...}
776 if ((Tok->Previous && Tok->Previous->is(tok::period)) ||
777 (Tok->Next && Tok->Next->is(tok::colon)))
779 // JS' for await ( ...
780 if (CurrentToken && CurrentToken->is(Keywords.kw_await))
783 Contexts.back().ColonIsForRangeExpr = true;
789 // When faced with 'operator()()', the kw_operator handler incorrectly
790 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
791 // the first two parens OverloadedOperators and the second l_paren an
792 // OverloadedOperatorLParen.
793 if (Tok->Previous && Tok->Previous->is(tok::r_paren) &&
794 Tok->Previous->MatchingParen &&
795 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
796 Tok->Previous->Type = TT_OverloadedOperator;
797 Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
798 Tok->Type = TT_OverloadedOperatorLParen;
803 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
804 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
806 !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
807 TT_LeadingJavaAnnotation)))
808 Line.MightBeFunctionDecl = true;
815 if (Style.Language == FormatStyle::LK_TextProto) {
816 FormatToken *Previous = Tok->getPreviousNonComment();
817 if (Previous && Previous->Type != TT_DictLiteral)
818 Previous->Type = TT_SelectorName;
825 Tok->Type = TT_TemplateOpener;
826 // In TT_Proto, we must distignuish between:
828 // msg < item: data >
829 // msg: < item: data >
830 // In TT_TextProto, map<key, value> does not occur.
831 if (Style.Language == FormatStyle::LK_TextProto ||
832 (Style.Language == FormatStyle::LK_Proto && Tok->Previous &&
833 Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) {
834 Tok->Type = TT_DictLiteral;
835 FormatToken *Previous = Tok->getPreviousNonComment();
836 if (Previous && Previous->Type != TT_DictLiteral)
837 Previous->Type = TT_SelectorName;
840 Tok->Type = TT_BinaryOperator;
841 NonTemplateLess.insert(Tok);
850 // Lines can start with '}'.
855 if (Style.Language != FormatStyle::LK_TextProto)
856 Tok->Type = TT_BinaryOperator;
858 case tok::kw_operator:
859 if (Style.Language == FormatStyle::LK_TextProto ||
860 Style.Language == FormatStyle::LK_Proto)
862 while (CurrentToken &&
863 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
864 if (CurrentToken->isOneOf(tok::star, tok::amp))
865 CurrentToken->Type = TT_PointerOrReference;
868 CurrentToken->Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator,
870 CurrentToken->Previous->Type = TT_OverloadedOperator;
873 CurrentToken->Type = TT_OverloadedOperatorLParen;
874 if (CurrentToken->Previous->is(TT_BinaryOperator))
875 CurrentToken->Previous->Type = TT_OverloadedOperator;
879 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
880 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
882 // Question marks before semicolons, colons, etc. indicate optional
883 // types (fields, parameters), e.g.
884 // function(x?: string, y?) {...}
886 Tok->Type = TT_JsTypeOptionalQuestion;
889 // Declarations cannot be conditional expressions, this can only be part
890 // of a type declaration.
891 if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
892 Style.Language == FormatStyle::LK_JavaScript)
896 case tok::kw_template:
897 parseTemplateDeclaration();
900 if (Contexts.back().InCtorInitializer)
901 Tok->Type = TT_CtorInitializerComma;
902 else if (Contexts.back().InInheritanceList)
903 Tok->Type = TT_InheritanceComma;
904 else if (Contexts.back().FirstStartOfName &&
905 (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
906 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
907 Line.IsMultiVariableDeclStmt = true;
909 if (Contexts.back().IsForEachMacro)
910 Contexts.back().IsExpression = true;
912 case tok::identifier:
913 if (Tok->isOneOf(Keywords.kw___has_include,
914 Keywords.kw___has_include_next)) {
924 void parseIncludeDirective() {
925 if (CurrentToken && CurrentToken->is(tok::less)) {
927 while (CurrentToken) {
928 // Mark tokens up to the trailing line comments as implicit string
930 if (CurrentToken->isNot(tok::comment) &&
931 !CurrentToken->TokenText.startswith("//"))
932 CurrentToken->Type = TT_ImplicitStringLiteral;
938 void parseWarningOrError() {
940 // We still want to format the whitespace left of the first token of the
943 while (CurrentToken) {
944 CurrentToken->Type = TT_ImplicitStringLiteral;
950 next(); // Consume "pragma".
952 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
953 bool IsMark = CurrentToken->is(Keywords.kw_mark);
954 next(); // Consume "mark".
955 next(); // Consume first token (so we fix leading whitespace).
956 while (CurrentToken) {
957 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
958 CurrentToken->Type = TT_ImplicitStringLiteral;
964 void parseHasInclude() {
965 if (!CurrentToken || !CurrentToken->is(tok::l_paren))
968 parseIncludeDirective();
972 LineType parsePreprocessorDirective() {
973 bool IsFirstToken = CurrentToken->IsFirst;
974 LineType Type = LT_PreprocessorDirective;
979 if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
980 // JavaScript files can contain shebang lines of the form:
981 // #!/usr/bin/env node
982 // Treat these like C++ #include directives.
983 while (CurrentToken) {
984 // Tokens cannot be comments here.
985 CurrentToken->Type = TT_ImplicitStringLiteral;
988 return LT_ImportStatement;
991 if (CurrentToken->Tok.is(tok::numeric_constant)) {
992 CurrentToken->SpacesRequiredBefore = 1;
995 // Hashes in the middle of a line can lead to any strange token
997 if (!CurrentToken->Tok.getIdentifierInfo())
999 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
1000 case tok::pp_include:
1001 case tok::pp_include_next:
1002 case tok::pp_import:
1004 parseIncludeDirective();
1005 Type = LT_ImportStatement;
1008 case tok::pp_warning:
1009 parseWarningOrError();
1011 case tok::pp_pragma:
1016 Contexts.back().IsExpression = true;
1022 while (CurrentToken) {
1023 FormatToken *Tok = CurrentToken;
1025 if (Tok->is(tok::l_paren))
1027 else if (Tok->isOneOf(Keywords.kw___has_include,
1028 Keywords.kw___has_include_next))
1035 LineType parseLine() {
1036 NonTemplateLess.clear();
1037 if (CurrentToken->is(tok::hash))
1038 return parsePreprocessorDirective();
1040 // Directly allow to 'import <string-literal>' to support protocol buffer
1041 // definitions (github.com/google/protobuf) or missing "#" (either way we
1042 // should not break the line).
1043 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
1044 if ((Style.Language == FormatStyle::LK_Java &&
1045 CurrentToken->is(Keywords.kw_package)) ||
1046 (Info && Info->getPPKeywordID() == tok::pp_import &&
1047 CurrentToken->Next &&
1048 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
1051 parseIncludeDirective();
1052 return LT_ImportStatement;
1055 // If this line starts and ends in '<' and '>', respectively, it is likely
1056 // part of "#define <a/b.h>".
1057 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
1058 parseIncludeDirective();
1059 return LT_ImportStatement;
1062 // In .proto files, top-level options are very similar to import statements
1063 // and should not be line-wrapped.
1064 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
1065 CurrentToken->is(Keywords.kw_option)) {
1067 if (CurrentToken && CurrentToken->is(tok::identifier))
1068 return LT_ImportStatement;
1071 bool KeywordVirtualFound = false;
1072 bool ImportStatement = false;
1074 // import {...} from '...';
1075 if (Style.Language == FormatStyle::LK_JavaScript &&
1076 CurrentToken->is(Keywords.kw_import))
1077 ImportStatement = true;
1079 while (CurrentToken) {
1080 if (CurrentToken->is(tok::kw_virtual))
1081 KeywordVirtualFound = true;
1082 if (Style.Language == FormatStyle::LK_JavaScript) {
1083 // export {...} from '...';
1084 // An export followed by "from 'some string';" is a re-export from
1085 // another module identified by a URI and is treated as a
1086 // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
1087 // Just "export {...};" or "export class ..." should not be treated as
1088 // an import in this sense.
1089 if (Line.First->is(tok::kw_export) &&
1090 CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
1091 CurrentToken->Next->isStringLiteral())
1092 ImportStatement = true;
1093 if (isClosureImportStatement(*CurrentToken))
1094 ImportStatement = true;
1096 if (!consumeToken())
1099 if (KeywordVirtualFound)
1100 return LT_VirtualFunctionDecl;
1101 if (ImportStatement)
1102 return LT_ImportStatement;
1104 if (Line.startsWith(TT_ObjCMethodSpecifier)) {
1105 if (Contexts.back().FirstObjCSelectorName)
1106 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
1107 Contexts.back().LongestObjCSelectorName;
1108 return LT_ObjCMethodDecl;
1115 bool isClosureImportStatement(const FormatToken &Tok) {
1116 // FIXME: Closure-library specific stuff should not be hard-coded but be
1118 return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
1120 (Tok.Next->Next->TokenText == "module" ||
1121 Tok.Next->Next->TokenText == "provide" ||
1122 Tok.Next->Next->TokenText == "require" ||
1123 Tok.Next->Next->TokenText == "forwardDeclare") &&
1124 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
1127 void resetTokenMetadata(FormatToken *Token) {
1131 // Reset token type in case we have already looked at it and then
1132 // recovered from an error (e.g. failure to find the matching >).
1133 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
1134 TT_FunctionLBrace, TT_ImplicitStringLiteral,
1135 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
1136 TT_OverloadedOperator, TT_RegexLiteral,
1137 TT_TemplateString, TT_ObjCStringLiteral))
1138 CurrentToken->Type = TT_Unknown;
1139 CurrentToken->Role.reset();
1140 CurrentToken->MatchingParen = nullptr;
1141 CurrentToken->FakeLParens.clear();
1142 CurrentToken->FakeRParens = 0;
1147 CurrentToken->NestingLevel = Contexts.size() - 1;
1148 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
1149 modifyContext(*CurrentToken);
1150 determineTokenType(*CurrentToken);
1151 CurrentToken = CurrentToken->Next;
1154 resetTokenMetadata(CurrentToken);
1157 /// A struct to hold information valid in a specific context, e.g.
1158 /// a pair of parenthesis.
1160 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
1162 : ContextKind(ContextKind), BindingStrength(BindingStrength),
1163 IsExpression(IsExpression) {}
1165 tok::TokenKind ContextKind;
1166 unsigned BindingStrength;
1168 unsigned LongestObjCSelectorName = 0;
1169 bool ColonIsForRangeExpr = false;
1170 bool ColonIsDictLiteral = false;
1171 bool ColonIsObjCMethodExpr = false;
1172 FormatToken *FirstObjCSelectorName = nullptr;
1173 FormatToken *FirstStartOfName = nullptr;
1174 bool CanBeExpression = true;
1175 bool InTemplateArgument = false;
1176 bool InCtorInitializer = false;
1177 bool InInheritanceList = false;
1178 bool CaretFound = false;
1179 bool IsForEachMacro = false;
1180 bool InCpp11AttributeSpecifier = false;
1183 /// Puts a new \c Context onto the stack \c Contexts for the lifetime
1184 /// of each instance.
1185 struct ScopedContextCreator {
1186 AnnotatingParser &P;
1188 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
1191 P.Contexts.push_back(Context(ContextKind,
1192 P.Contexts.back().BindingStrength + Increase,
1193 P.Contexts.back().IsExpression));
1196 ~ScopedContextCreator() { P.Contexts.pop_back(); }
1199 void modifyContext(const FormatToken &Current) {
1200 if (Current.getPrecedence() == prec::Assignment &&
1201 !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
1202 // Type aliases use `type X = ...;` in TypeScript and can be exported
1203 // using `export type ...`.
1204 !(Style.Language == FormatStyle::LK_JavaScript &&
1205 (Line.startsWith(Keywords.kw_type, tok::identifier) ||
1206 Line.startsWith(tok::kw_export, Keywords.kw_type,
1207 tok::identifier))) &&
1208 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
1209 Contexts.back().IsExpression = true;
1210 if (!Line.startsWith(TT_UnaryOperator)) {
1211 for (FormatToken *Previous = Current.Previous;
1212 Previous && Previous->Previous &&
1213 !Previous->Previous->isOneOf(tok::comma, tok::semi);
1214 Previous = Previous->Previous) {
1215 if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
1216 Previous = Previous->MatchingParen;
1220 if (Previous->opensScope())
1222 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
1223 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
1224 Previous->Previous && Previous->Previous->isNot(tok::equal))
1225 Previous->Type = TT_PointerOrReference;
1228 } else if (Current.is(tok::lessless) &&
1229 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
1230 Contexts.back().IsExpression = true;
1231 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
1232 Contexts.back().IsExpression = true;
1233 } else if (Current.is(TT_TrailingReturnArrow)) {
1234 Contexts.back().IsExpression = false;
1235 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
1236 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
1237 } else if (Current.Previous &&
1238 Current.Previous->is(TT_CtorInitializerColon)) {
1239 Contexts.back().IsExpression = true;
1240 Contexts.back().InCtorInitializer = true;
1241 } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
1242 Contexts.back().InInheritanceList = true;
1243 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
1244 for (FormatToken *Previous = Current.Previous;
1245 Previous && Previous->isOneOf(tok::star, tok::amp);
1246 Previous = Previous->Previous)
1247 Previous->Type = TT_PointerOrReference;
1248 if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
1249 Contexts.back().IsExpression = false;
1250 } else if (Current.is(tok::kw_new)) {
1251 Contexts.back().CanBeExpression = false;
1252 } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
1253 // This should be the condition or increment in a for-loop.
1254 Contexts.back().IsExpression = true;
1258 void determineTokenType(FormatToken &Current) {
1259 if (!Current.is(TT_Unknown))
1260 // The token type is already known.
1263 if (Style.Language == FormatStyle::LK_JavaScript) {
1264 if (Current.is(tok::exclaim)) {
1265 if (Current.Previous &&
1266 (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace,
1267 tok::r_paren, tok::r_square,
1269 Current.Previous->Tok.isLiteral())) {
1270 Current.Type = TT_JsNonNullAssertion;
1274 Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
1275 Current.Type = TT_JsNonNullAssertion;
1281 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1282 // function declaration have been found. In this case, 'Current' is a
1283 // trailing token of this declaration and thus cannot be a name.
1284 if (Current.is(Keywords.kw_instanceof)) {
1285 Current.Type = TT_BinaryOperator;
1286 } else if (isStartOfName(Current) &&
1287 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
1288 Contexts.back().FirstStartOfName = &Current;
1289 Current.Type = TT_StartOfName;
1290 } else if (Current.is(tok::semi)) {
1291 // Reset FirstStartOfName after finding a semicolon so that a for loop
1292 // with multiple increment statements is not confused with a for loop
1293 // having multiple variable declarations.
1294 Contexts.back().FirstStartOfName = nullptr;
1295 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
1297 } else if (Current.is(tok::arrow) &&
1298 Style.Language == FormatStyle::LK_Java) {
1299 Current.Type = TT_LambdaArrow;
1300 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
1301 Current.NestingLevel == 0) {
1302 Current.Type = TT_TrailingReturnArrow;
1303 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
1304 Current.Type = determineStarAmpUsage(Current,
1305 Contexts.back().CanBeExpression &&
1306 Contexts.back().IsExpression,
1307 Contexts.back().InTemplateArgument);
1308 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
1309 Current.Type = determinePlusMinusCaretUsage(Current);
1310 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
1311 Contexts.back().CaretFound = true;
1312 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
1313 Current.Type = determineIncrementUsage(Current);
1314 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
1315 Current.Type = TT_UnaryOperator;
1316 } else if (Current.is(tok::question)) {
1317 if (Style.Language == FormatStyle::LK_JavaScript &&
1318 Line.MustBeDeclaration && !Contexts.back().IsExpression) {
1319 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
1320 // on the interface, not a ternary expression.
1321 Current.Type = TT_JsTypeOptionalQuestion;
1323 Current.Type = TT_ConditionalExpr;
1325 } else if (Current.isBinaryOperator() &&
1326 (!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
1327 (!Current.is(tok::greater) &&
1328 Style.Language != FormatStyle::LK_TextProto)) {
1329 Current.Type = TT_BinaryOperator;
1330 } else if (Current.is(tok::comment)) {
1331 if (Current.TokenText.startswith("/*")) {
1332 if (Current.TokenText.endswith("*/"))
1333 Current.Type = TT_BlockComment;
1335 // The lexer has for some reason determined a comment here. But we
1336 // cannot really handle it, if it isn't properly terminated.
1337 Current.Tok.setKind(tok::unknown);
1339 Current.Type = TT_LineComment;
1341 } else if (Current.is(tok::r_paren)) {
1342 if (rParenEndsCast(Current))
1343 Current.Type = TT_CastRParen;
1344 if (Current.MatchingParen && Current.Next &&
1345 !Current.Next->isBinaryOperator() &&
1346 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1347 tok::comma, tok::period, tok::arrow,
1349 if (FormatToken *AfterParen = Current.MatchingParen->Next) {
1350 // Make sure this isn't the return type of an Obj-C block declaration
1351 if (AfterParen->Tok.isNot(tok::caret)) {
1352 if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1353 if (BeforeParen->is(tok::identifier) &&
1354 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1355 (!BeforeParen->Previous ||
1356 BeforeParen->Previous->ClosesTemplateDeclaration))
1357 Current.Type = TT_FunctionAnnotationRParen;
1360 } else if (Current.is(tok::at) && Current.Next &&
1361 Style.Language != FormatStyle::LK_JavaScript &&
1362 Style.Language != FormatStyle::LK_Java) {
1363 // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
1364 // marks declarations and properties that need special formatting.
1365 switch (Current.Next->Tok.getObjCKeywordID()) {
1366 case tok::objc_interface:
1367 case tok::objc_implementation:
1368 case tok::objc_protocol:
1369 Current.Type = TT_ObjCDecl;
1371 case tok::objc_property:
1372 Current.Type = TT_ObjCProperty;
1377 } else if (Current.is(tok::period)) {
1378 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1379 if (PreviousNoComment &&
1380 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1381 Current.Type = TT_DesignatedInitializerPeriod;
1382 else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1383 Current.Previous->isOneOf(TT_JavaAnnotation,
1384 TT_LeadingJavaAnnotation)) {
1385 Current.Type = Current.Previous->Type;
1387 } else if (canBeObjCSelectorComponent(Current) &&
1388 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
1389 Current.Previous && Current.Previous->is(TT_CastRParen) &&
1390 Current.Previous->MatchingParen &&
1391 Current.Previous->MatchingParen->Previous &&
1392 Current.Previous->MatchingParen->Previous->is(
1393 TT_ObjCMethodSpecifier)) {
1394 // This is the first part of an Objective-C selector name. (If there's no
1395 // colon after this, this is the only place which annotates the identifier
1397 Current.Type = TT_SelectorName;
1398 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
1400 !Current.Previous->isOneOf(tok::equal, tok::at) &&
1401 Line.MightBeFunctionDecl && Contexts.size() == 1) {
1402 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1403 // function declaration have been found.
1404 Current.Type = TT_TrailingAnnotation;
1405 } else if ((Style.Language == FormatStyle::LK_Java ||
1406 Style.Language == FormatStyle::LK_JavaScript) &&
1408 if (Current.Previous->is(tok::at) &&
1409 Current.isNot(Keywords.kw_interface)) {
1410 const FormatToken &AtToken = *Current.Previous;
1411 const FormatToken *Previous = AtToken.getPreviousNonComment();
1412 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1413 Current.Type = TT_LeadingJavaAnnotation;
1415 Current.Type = TT_JavaAnnotation;
1416 } else if (Current.Previous->is(tok::period) &&
1417 Current.Previous->isOneOf(TT_JavaAnnotation,
1418 TT_LeadingJavaAnnotation)) {
1419 Current.Type = Current.Previous->Type;
1424 /// Take a guess at whether \p Tok starts a name of a function or
1425 /// variable declaration.
1427 /// This is a heuristic based on whether \p Tok is an identifier following
1428 /// something that is likely a type.
1429 bool isStartOfName(const FormatToken &Tok) {
1430 if (Tok.isNot(tok::identifier) || !Tok.Previous)
1433 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
1436 if (Style.Language == FormatStyle::LK_JavaScript &&
1437 Tok.Previous->is(Keywords.kw_in))
1440 // Skip "const" as it does not have an influence on whether this is a name.
1441 FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
1442 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1443 PreviousNotConst = PreviousNotConst->getPreviousNonComment();
1445 if (!PreviousNotConst)
1448 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1449 PreviousNotConst->Previous &&
1450 PreviousNotConst->Previous->is(tok::hash);
1452 if (PreviousNotConst->is(TT_TemplateCloser))
1453 return PreviousNotConst && PreviousNotConst->MatchingParen &&
1454 PreviousNotConst->MatchingParen->Previous &&
1455 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1456 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1458 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1459 PreviousNotConst->MatchingParen->Previous &&
1460 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1463 return (!IsPPKeyword &&
1464 PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1465 PreviousNotConst->is(TT_PointerOrReference) ||
1466 PreviousNotConst->isSimpleTypeSpecifier();
1469 /// Determine whether ')' is ending a cast.
1470 bool rParenEndsCast(const FormatToken &Tok) {
1471 // C-style casts are only used in C++ and Java.
1472 if (!Style.isCpp() && Style.Language != FormatStyle::LK_Java)
1475 // Empty parens aren't casts and there are no casts at the end of the line.
1476 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1479 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1481 // If there is a closing parenthesis left of the current parentheses,
1482 // look past it as these might be chained casts.
1483 if (LeftOfParens->is(tok::r_paren)) {
1484 if (!LeftOfParens->MatchingParen ||
1485 !LeftOfParens->MatchingParen->Previous)
1487 LeftOfParens = LeftOfParens->MatchingParen->Previous;
1490 // If there is an identifier (or with a few exceptions a keyword) right
1491 // before the parentheses, this is unlikely to be a cast.
1492 if (LeftOfParens->Tok.getIdentifierInfo() &&
1493 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1497 // Certain other tokens right before the parentheses are also signals that
1498 // this cannot be a cast.
1499 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1500 TT_TemplateCloser, tok::ellipsis))
1504 if (Tok.Next->is(tok::question))
1507 // As Java has no function types, a "(" after the ")" likely means that this
1509 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1512 // If a (non-string) literal follows, this is likely a cast.
1513 if (Tok.Next->isNot(tok::string_literal) &&
1514 (Tok.Next->Tok.isLiteral() ||
1515 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1518 // Heuristically try to determine whether the parentheses contain a type.
1519 bool ParensAreType =
1521 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1522 Tok.Previous->isSimpleTypeSpecifier();
1523 bool ParensCouldEndDecl =
1524 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1525 if (ParensAreType && !ParensCouldEndDecl)
1528 // At this point, we heuristically assume that there are no casts at the
1529 // start of the line. We assume that we have found most cases where there
1530 // are by the logic above, e.g. "(void)x;".
1534 // Certain token types inside the parentheses mean that this can't be a
1536 for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
1537 Token = Token->Next)
1538 if (Token->is(TT_BinaryOperator))
1541 // If the following token is an identifier or 'this', this is a cast. All
1542 // cases where this can be something else are handled above.
1543 if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
1546 if (!Tok.Next->Next)
1549 // If the next token after the parenthesis is a unary operator, assume
1550 // that this is cast, unless there are unexpected tokens inside the
1553 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1554 if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1555 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1557 // Search for unexpected tokens.
1558 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1559 Prev = Prev->Previous) {
1560 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1566 /// Return the type of the given token assuming it is * or &.
1567 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1568 bool InTemplateArgument) {
1569 if (Style.Language == FormatStyle::LK_JavaScript)
1570 return TT_BinaryOperator;
1572 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1574 return TT_UnaryOperator;
1576 const FormatToken *NextToken = Tok.getNextNonComment();
1578 NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const) ||
1579 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1580 return TT_PointerOrReference;
1582 if (PrevToken->is(tok::coloncolon))
1583 return TT_PointerOrReference;
1585 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1586 tok::comma, tok::semi, tok::kw_return, tok::colon,
1587 tok::equal, tok::kw_delete, tok::kw_sizeof,
1589 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1590 TT_UnaryOperator, TT_CastRParen))
1591 return TT_UnaryOperator;
1593 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1594 return TT_PointerOrReference;
1595 if (NextToken->is(tok::kw_operator) && !IsExpression)
1596 return TT_PointerOrReference;
1597 if (NextToken->isOneOf(tok::comma, tok::semi))
1598 return TT_PointerOrReference;
1600 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen) {
1601 FormatToken *TokenBeforeMatchingParen =
1602 PrevToken->MatchingParen->getPreviousNonComment();
1603 if (TokenBeforeMatchingParen &&
1604 TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
1605 return TT_PointerOrReference;
1608 if (PrevToken->Tok.isLiteral() ||
1609 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1610 tok::kw_false, tok::r_brace) ||
1611 NextToken->Tok.isLiteral() ||
1612 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1613 NextToken->isUnaryOperator() ||
1614 // If we know we're in a template argument, there are no named
1615 // declarations. Thus, having an identifier on the right-hand side
1616 // indicates a binary operator.
1617 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1618 return TT_BinaryOperator;
1620 // "&&(" is quite unlikely to be two successive unary "&".
1621 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1622 return TT_BinaryOperator;
1624 // This catches some cases where evaluation order is used as control flow:
1626 const FormatToken *NextNextToken = NextToken->getNextNonComment();
1627 if (NextNextToken && NextNextToken->is(tok::arrow))
1628 return TT_BinaryOperator;
1630 // It is very unlikely that we are going to find a pointer or reference type
1631 // definition on the RHS of an assignment.
1632 if (IsExpression && !Contexts.back().CaretFound)
1633 return TT_BinaryOperator;
1635 return TT_PointerOrReference;
1638 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1639 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1641 return TT_UnaryOperator;
1643 if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
1644 // This must be a sequence of leading unary operators.
1645 return TT_UnaryOperator;
1647 // Use heuristics to recognize unary operators.
1648 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1649 tok::question, tok::colon, tok::kw_return,
1650 tok::kw_case, tok::at, tok::l_brace))
1651 return TT_UnaryOperator;
1653 // There can't be two consecutive binary operators.
1654 if (PrevToken->is(TT_BinaryOperator))
1655 return TT_UnaryOperator;
1657 // Fall back to marking the token as binary operator.
1658 return TT_BinaryOperator;
1661 /// Determine whether ++/-- are pre- or post-increments/-decrements.
1662 TokenType determineIncrementUsage(const FormatToken &Tok) {
1663 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1664 if (!PrevToken || PrevToken->is(TT_CastRParen))
1665 return TT_UnaryOperator;
1666 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1667 return TT_TrailingUnaryOperator;
1669 return TT_UnaryOperator;
1672 SmallVector<Context, 8> Contexts;
1674 const FormatStyle &Style;
1675 AnnotatedLine &Line;
1676 FormatToken *CurrentToken;
1678 const AdditionalKeywords &Keywords;
1680 // Set of "<" tokens that do not open a template parameter list. If parseAngle
1681 // determines that a specific token can't be a template opener, it will make
1682 // same decision irrespective of the decisions for tokens leading up to it.
1683 // Store this information to prevent this from causing exponential runtime.
1684 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1687 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1688 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1690 /// Parses binary expressions by inserting fake parenthesis based on
1691 /// operator precedence.
1692 class ExpressionParser {
1694 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1695 AnnotatedLine &Line)
1696 : Style(Style), Keywords(Keywords), Current(Line.First) {}
1698 /// Parse expressions with the given operator precedence.
1699 void parse(int Precedence = 0) {
1700 // Skip 'return' and ObjC selector colons as they are not part of a binary
1702 while (Current && (Current->is(tok::kw_return) ||
1703 (Current->is(tok::colon) &&
1704 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1707 if (!Current || Precedence > PrecedenceArrowAndPeriod)
1710 // Conditional expressions need to be parsed separately for proper nesting.
1711 if (Precedence == prec::Conditional) {
1712 parseConditionalExpr();
1716 // Parse unary operators, which all have a higher precedence than binary
1718 if (Precedence == PrecedenceUnaryOperator) {
1719 parseUnaryOperator();
1723 FormatToken *Start = Current;
1724 FormatToken *LatestOperator = nullptr;
1725 unsigned OperatorIndex = 0;
1728 // Consume operators with higher precedence.
1729 parse(Precedence + 1);
1731 int CurrentPrecedence = getCurrentPrecedence();
1733 if (Current && Current->is(TT_SelectorName) &&
1734 Precedence == CurrentPrecedence) {
1736 addFakeParenthesis(Start, prec::Level(Precedence));
1740 // At the end of the line or when an operator with higher precedence is
1741 // found, insert fake parenthesis and return.
1743 (Current->closesScope() &&
1744 (Current->MatchingParen || Current->is(TT_TemplateString))) ||
1745 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1746 (CurrentPrecedence == prec::Conditional &&
1747 Precedence == prec::Assignment && Current->is(tok::colon))) {
1751 // Consume scopes: (), [], <> and {}
1752 if (Current->opensScope()) {
1753 // In fragment of a JavaScript template string can look like '}..${' and
1754 // thus close a scope and open a new one at the same time.
1755 while (Current && (!Current->closesScope() || Current->opensScope())) {
1762 if (CurrentPrecedence == Precedence) {
1764 LatestOperator->NextOperator = Current;
1765 LatestOperator = Current;
1766 Current->OperatorIndex = OperatorIndex;
1769 next(/*SkipPastLeadingComments=*/Precedence > 0);
1773 if (LatestOperator && (Current || Precedence > 0)) {
1774 // LatestOperator->LastOperator = true;
1775 if (Precedence == PrecedenceArrowAndPeriod) {
1776 // Call expressions don't have a binary operator precedence.
1777 addFakeParenthesis(Start, prec::Unknown);
1779 addFakeParenthesis(Start, prec::Level(Precedence));
1785 /// Gets the precedence (+1) of the given token for binary operators
1786 /// and other tokens that we treat like binary operators.
1787 int getCurrentPrecedence() {
1789 const FormatToken *NextNonComment = Current->getNextNonComment();
1790 if (Current->is(TT_ConditionalExpr))
1791 return prec::Conditional;
1792 if (NextNonComment && Current->is(TT_SelectorName) &&
1793 (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
1794 ((Style.Language == FormatStyle::LK_Proto ||
1795 Style.Language == FormatStyle::LK_TextProto) &&
1796 NextNonComment->is(tok::less))))
1797 return prec::Assignment;
1798 if (Current->is(TT_JsComputedPropertyName))
1799 return prec::Assignment;
1800 if (Current->is(TT_LambdaArrow))
1802 if (Current->is(TT_JsFatArrow))
1803 return prec::Assignment;
1804 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
1805 (Current->is(tok::comment) && NextNonComment &&
1806 NextNonComment->is(TT_SelectorName)))
1808 if (Current->is(TT_RangeBasedForLoopColon))
1810 if ((Style.Language == FormatStyle::LK_Java ||
1811 Style.Language == FormatStyle::LK_JavaScript) &&
1812 Current->is(Keywords.kw_instanceof))
1813 return prec::Relational;
1814 if (Style.Language == FormatStyle::LK_JavaScript &&
1815 Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
1816 return prec::Relational;
1817 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1818 return Current->getPrecedence();
1819 if (Current->isOneOf(tok::period, tok::arrow))
1820 return PrecedenceArrowAndPeriod;
1821 if ((Style.Language == FormatStyle::LK_Java ||
1822 Style.Language == FormatStyle::LK_JavaScript) &&
1823 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1824 Keywords.kw_throws))
1830 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1831 Start->FakeLParens.push_back(Precedence);
1832 if (Precedence > prec::Unknown)
1833 Start->StartsBinaryExpression = true;
1835 FormatToken *Previous = Current->Previous;
1836 while (Previous->is(tok::comment) && Previous->Previous)
1837 Previous = Previous->Previous;
1838 ++Previous->FakeRParens;
1839 if (Precedence > prec::Unknown)
1840 Previous->EndsBinaryExpression = true;
1844 /// Parse unary operator expressions and surround them with fake
1845 /// parentheses if appropriate.
1846 void parseUnaryOperator() {
1847 llvm::SmallVector<FormatToken *, 2> Tokens;
1848 while (Current && Current->is(TT_UnaryOperator)) {
1849 Tokens.push_back(Current);
1852 parse(PrecedenceArrowAndPeriod);
1853 for (FormatToken *Token : llvm::reverse(Tokens))
1854 // The actual precedence doesn't matter.
1855 addFakeParenthesis(Token, prec::Unknown);
1858 void parseConditionalExpr() {
1859 while (Current && Current->isTrailingComment()) {
1862 FormatToken *Start = Current;
1863 parse(prec::LogicalOr);
1864 if (!Current || !Current->is(tok::question))
1867 parse(prec::Assignment);
1868 if (!Current || Current->isNot(TT_ConditionalExpr))
1871 parse(prec::Assignment);
1872 addFakeParenthesis(Start, prec::Conditional);
1875 void next(bool SkipPastLeadingComments = true) {
1877 Current = Current->Next;
1879 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1880 Current->isTrailingComment())
1881 Current = Current->Next;
1884 const FormatStyle &Style;
1885 const AdditionalKeywords &Keywords;
1886 FormatToken *Current;
1889 } // end anonymous namespace
1891 void TokenAnnotator::setCommentLineLevels(
1892 SmallVectorImpl<AnnotatedLine *> &Lines) {
1893 const AnnotatedLine *NextNonCommentLine = nullptr;
1894 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1897 bool CommentLine = true;
1898 for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
1899 if (!Tok->is(tok::comment)) {
1900 CommentLine = false;
1905 // If the comment is currently aligned with the line immediately following
1906 // it, that's probably intentional and we should keep it.
1907 if (NextNonCommentLine && CommentLine &&
1908 NextNonCommentLine->First->NewlinesBefore <= 1 &&
1909 NextNonCommentLine->First->OriginalColumn ==
1910 (*I)->First->OriginalColumn) {
1911 // Align comments for preprocessor lines with the # in column 0.
1912 // Otherwise, align with the next line.
1913 (*I)->Level = (NextNonCommentLine->Type == LT_PreprocessorDirective ||
1914 NextNonCommentLine->Type == LT_ImportStatement)
1916 : NextNonCommentLine->Level;
1918 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1921 setCommentLineLevels((*I)->Children);
1925 static unsigned maxNestingDepth(const AnnotatedLine &Line) {
1926 unsigned Result = 0;
1927 for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
1928 Result = std::max(Result, Tok->NestingLevel);
1932 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1933 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1934 E = Line.Children.end();
1938 AnnotatingParser Parser(Style, Line, Keywords);
1939 Line.Type = Parser.parseLine();
1941 // With very deep nesting, ExpressionParser uses lots of stack and the
1942 // formatting algorithm is very slow. We're not going to do a good job here
1943 // anyway - it's probably generated code being formatted by mistake.
1944 // Just skip the whole line.
1945 if (maxNestingDepth(Line) > 50)
1946 Line.Type = LT_Invalid;
1948 if (Line.Type == LT_Invalid)
1951 ExpressionParser ExprParser(Style, Keywords, Line);
1954 if (Line.startsWith(TT_ObjCMethodSpecifier))
1955 Line.Type = LT_ObjCMethodDecl;
1956 else if (Line.startsWith(TT_ObjCDecl))
1957 Line.Type = LT_ObjCDecl;
1958 else if (Line.startsWith(TT_ObjCProperty))
1959 Line.Type = LT_ObjCProperty;
1961 Line.First->SpacesRequiredBefore = 1;
1962 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1965 // This function heuristically determines whether 'Current' starts the name of a
1966 // function declaration.
1967 static bool isFunctionDeclarationName(const FormatToken &Current,
1968 const AnnotatedLine &Line) {
1969 auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
1970 for (; Next; Next = Next->Next) {
1971 if (Next->is(TT_OverloadedOperatorLParen))
1973 if (Next->is(TT_OverloadedOperator))
1975 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1976 // For 'new[]' and 'delete[]'.
1977 if (Next->Next && Next->Next->is(tok::l_square) && Next->Next->Next &&
1978 Next->Next->Next->is(tok::r_square))
1979 Next = Next->Next->Next;
1988 // Find parentheses of parameter list.
1989 const FormatToken *Next = Current.Next;
1990 if (Current.is(tok::kw_operator)) {
1991 if (Current.Previous && Current.Previous->is(tok::coloncolon))
1993 Next = skipOperatorName(Next);
1995 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1997 for (; Next; Next = Next->Next) {
1998 if (Next->is(TT_TemplateOpener)) {
1999 Next = Next->MatchingParen;
2000 } else if (Next->is(tok::coloncolon)) {
2004 if (Next->is(tok::kw_operator)) {
2005 Next = skipOperatorName(Next->Next);
2008 if (!Next->is(tok::identifier))
2010 } else if (Next->is(tok::l_paren)) {
2018 // Check whether parameter list can belong to a function declaration.
2019 if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
2021 // If the lines ends with "{", this is likely an function definition.
2022 if (Line.Last->is(tok::l_brace))
2024 if (Next->Next == Next->MatchingParen)
2025 return true; // Empty parentheses.
2026 // If there is an &/&& after the r_paren, this is likely a function.
2027 if (Next->MatchingParen->Next &&
2028 Next->MatchingParen->Next->is(TT_PointerOrReference))
2030 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
2032 if (Tok->is(tok::l_paren) && Tok->MatchingParen) {
2033 Tok = Tok->MatchingParen;
2036 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
2037 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
2039 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
2040 Tok->Tok.isLiteral())
2046 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
2047 assert(Line.MightBeFunctionDecl);
2049 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
2050 Style.AlwaysBreakAfterReturnType ==
2051 FormatStyle::RTBS_TopLevelDefinitions) &&
2055 switch (Style.AlwaysBreakAfterReturnType) {
2056 case FormatStyle::RTBS_None:
2058 case FormatStyle::RTBS_All:
2059 case FormatStyle::RTBS_TopLevel:
2061 case FormatStyle::RTBS_AllDefinitions:
2062 case FormatStyle::RTBS_TopLevelDefinitions:
2063 return Line.mightBeFunctionDefinition();
2069 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
2070 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
2071 E = Line.Children.end();
2073 calculateFormattingInformation(**I);
2076 Line.First->TotalLength =
2077 Line.First->IsMultiline ? Style.ColumnLimit
2078 : Line.FirstStartColumn + Line.First->ColumnWidth;
2079 FormatToken *Current = Line.First->Next;
2080 bool InFunctionDecl = Line.MightBeFunctionDecl;
2082 if (isFunctionDeclarationName(*Current, Line))
2083 Current->Type = TT_FunctionDeclarationName;
2084 if (Current->is(TT_LineComment)) {
2085 if (Current->Previous->BlockKind == BK_BracedInit &&
2086 Current->Previous->opensScope())
2087 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
2089 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
2091 // If we find a trailing comment, iterate backwards to determine whether
2092 // it seems to relate to a specific parameter. If so, break before that
2093 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
2094 // to the previous line in:
2098 if (!Current->HasUnescapedNewline) {
2099 for (FormatToken *Parameter = Current->Previous; Parameter;
2100 Parameter = Parameter->Previous) {
2101 if (Parameter->isOneOf(tok::comment, tok::r_brace))
2103 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
2104 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
2105 Parameter->HasUnescapedNewline)
2106 Parameter->MustBreakBefore = true;
2111 } else if (Current->SpacesRequiredBefore == 0 &&
2112 spaceRequiredBefore(Line, *Current)) {
2113 Current->SpacesRequiredBefore = 1;
2116 Current->MustBreakBefore =
2117 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
2119 if (!Current->MustBreakBefore && InFunctionDecl &&
2120 Current->is(TT_FunctionDeclarationName))
2121 Current->MustBreakBefore = mustBreakForReturnType(Line);
2123 Current->CanBreakBefore =
2124 Current->MustBreakBefore || canBreakBefore(Line, *Current);
2125 unsigned ChildSize = 0;
2126 if (Current->Previous->Children.size() == 1) {
2127 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
2128 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
2129 : LastOfChild.TotalLength + 1;
2131 const FormatToken *Prev = Current->Previous;
2132 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
2133 (Prev->Children.size() == 1 &&
2134 Prev->Children[0]->First->MustBreakBefore) ||
2135 Current->IsMultiline)
2136 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
2138 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
2139 ChildSize + Current->SpacesRequiredBefore;
2141 if (Current->is(TT_CtorInitializerColon))
2142 InFunctionDecl = false;
2144 // FIXME: Only calculate this if CanBreakBefore is true once static
2145 // initializers etc. are sorted out.
2146 // FIXME: Move magic numbers to a better place.
2148 // Reduce penalty for aligning ObjC method arguments using the colon
2149 // alignment as this is the canonical way (still prefer fitting everything
2150 // into one line if possible). Trying to fit a whole expression into one
2151 // line should not force other line breaks (e.g. when ObjC method
2152 // expression is a part of other expression).
2153 Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
2154 if (Style.Language == FormatStyle::LK_ObjC &&
2155 Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
2156 if (Current->ParameterIndex == 1)
2157 Current->SplitPenalty += 5 * Current->BindingStrength;
2159 Current->SplitPenalty += 20 * Current->BindingStrength;
2162 Current = Current->Next;
2165 calculateUnbreakableTailLengths(Line);
2166 unsigned IndentLevel = Line.Level;
2167 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
2169 Current->Role->precomputeFormattingInfos(Current);
2170 if (Current->MatchingParen &&
2171 Current->MatchingParen->opensBlockOrBlockTypeList(Style)) {
2172 assert(IndentLevel > 0);
2175 Current->IndentLevel = IndentLevel;
2176 if (Current->opensBlockOrBlockTypeList(Style))
2180 LLVM_DEBUG({ printDebugInfo(Line); });
2183 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
2184 unsigned UnbreakableTailLength = 0;
2185 FormatToken *Current = Line.Last;
2187 Current->UnbreakableTailLength = UnbreakableTailLength;
2188 if (Current->CanBreakBefore ||
2189 Current->isOneOf(tok::comment, tok::string_literal)) {
2190 UnbreakableTailLength = 0;
2192 UnbreakableTailLength +=
2193 Current->ColumnWidth + Current->SpacesRequiredBefore;
2195 Current = Current->Previous;
2199 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
2200 const FormatToken &Tok,
2201 bool InFunctionDecl) {
2202 const FormatToken &Left = *Tok.Previous;
2203 const FormatToken &Right = Tok;
2205 if (Left.is(tok::semi))
2208 if (Style.Language == FormatStyle::LK_Java) {
2209 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
2211 if (Right.is(Keywords.kw_implements))
2213 if (Left.is(tok::comma) && Left.NestingLevel == 0)
2215 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2216 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
2218 if (Left.is(TT_JsTypeColon))
2220 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2221 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2223 // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
2224 if (Left.opensScope() && Right.closesScope())
2228 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2230 if (Right.is(tok::l_square)) {
2231 if (Style.Language == FormatStyle::LK_Proto)
2233 if (Left.is(tok::r_square))
2235 // Slightly prefer formatting local lambda definitions like functions.
2236 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
2238 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2239 TT_ArrayInitializerLSquare,
2240 TT_DesignatedInitializerLSquare, TT_AttributeSquare))
2244 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2245 Right.is(tok::kw_operator)) {
2246 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
2248 if (Left.is(TT_StartOfName))
2250 if (InFunctionDecl && Right.NestingLevel == 0)
2251 return Style.PenaltyReturnTypeOnItsOwnLine;
2254 if (Right.is(TT_PointerOrReference))
2256 if (Right.is(TT_LambdaArrow))
2258 if (Left.is(tok::equal) && Right.is(tok::l_brace))
2260 if (Left.is(TT_CastRParen))
2262 if (Left.is(tok::coloncolon) ||
2263 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
2265 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
2267 if (Left.is(tok::comment))
2270 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
2271 TT_CtorInitializerColon))
2274 if (Right.isMemberAccess()) {
2275 // Breaking before the "./->" of a chained call/member access is reasonably
2276 // cheap, as formatting those with one call per line is generally
2277 // desirable. In particular, it should be cheaper to break before the call
2278 // than it is to break inside a call's parameters, which could lead to weird
2279 // "hanging" indents. The exception is the very last "./->" to support this
2280 // frequent pattern:
2282 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
2285 // which might otherwise be blown up onto many lines. Here, clang-format
2286 // won't produce "hanging" indents anyway as there is no other trailing
2289 // Also apply higher penalty is not a call as that might lead to a wrapping
2293 // .aaaaaaaaa.bbbbbbbb(cccccccc);
2294 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
2299 if (Right.is(TT_TrailingAnnotation) &&
2300 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
2301 // Moving trailing annotations to the next line is fine for ObjC method
2303 if (Line.startsWith(TT_ObjCMethodSpecifier))
2305 // Generally, breaking before a trailing annotation is bad unless it is
2306 // function-like. It seems to be especially preferable to keep standard
2307 // annotations (i.e. "const", "final" and "override") on the same line.
2308 // Use a slightly higher penalty after ")" so that annotations like
2309 // "const override" are kept together.
2310 bool is_short_annotation = Right.TokenText.size() < 10;
2311 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
2314 // In for-loops, prefer breaking at ',' and ';'.
2315 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
2318 // In Objective-C method expressions, prefer breaking before "param:" over
2319 // breaking after it.
2320 if (Right.is(TT_SelectorName))
2322 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
2323 return Line.MightBeFunctionDecl ? 50 : 500;
2325 // In Objective-C type declarations, avoid breaking after the category's
2326 // open paren (we'll prefer breaking after the protocol list's opening
2327 // angle bracket, if present).
2328 if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
2329 Left.Previous->isOneOf(tok::identifier, tok::greater))
2332 if (Left.is(tok::l_paren) && InFunctionDecl &&
2333 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
2335 if (Left.is(tok::l_paren) && Left.Previous &&
2336 (Left.Previous->isOneOf(tok::kw_if, tok::kw_for) ||
2337 Left.Previous->endsSequence(tok::kw_constexpr, tok::kw_if)))
2339 if (Left.is(tok::equal) && InFunctionDecl)
2341 if (Right.is(tok::r_brace))
2343 if (Left.is(TT_TemplateOpener))
2345 if (Left.opensScope()) {
2346 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
2348 if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
2350 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
2353 if (Left.is(TT_JavaAnnotation))
2356 if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
2357 Left.Previous->isLabelString() &&
2358 (Left.NextOperator || Left.OperatorIndex != 0))
2360 if (Right.is(tok::plus) && Left.isLabelString() &&
2361 (Right.NextOperator || Right.OperatorIndex != 0))
2363 if (Left.is(tok::comma))
2365 if (Right.is(tok::lessless) && Left.isLabelString() &&
2366 (Right.NextOperator || Right.OperatorIndex != 1))
2368 if (Right.is(tok::lessless)) {
2369 // Breaking at a << is really cheap.
2370 if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
2371 // Slightly prefer to break before the first one in log-like statements.
2375 if (Left.ClosesTemplateDeclaration)
2376 return Style.PenaltyBreakTemplateDeclaration;
2377 if (Left.is(TT_ConditionalExpr))
2378 return prec::Conditional;
2379 prec::Level Level = Left.getPrecedence();
2380 if (Level == prec::Unknown)
2381 Level = Right.getPrecedence();
2382 if (Level == prec::Assignment)
2383 return Style.PenaltyBreakAssignment;
2384 if (Level != prec::Unknown)
2390 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
2391 const FormatToken &Left,
2392 const FormatToken &Right) {
2393 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
2395 if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
2397 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
2398 Left.Tok.getObjCKeywordID() == tok::objc_property)
2400 if (Right.is(tok::hashhash))
2401 return Left.is(tok::hash);
2402 if (Left.isOneOf(tok::hashhash, tok::hash))
2403 return Right.is(tok::hash);
2404 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
2405 return Style.SpaceInEmptyParentheses;
2406 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
2407 return (Right.is(TT_CastRParen) ||
2408 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
2409 ? Style.SpacesInCStyleCastParentheses
2410 : Style.SpacesInParentheses;
2411 if (Right.isOneOf(tok::semi, tok::comma))
2413 if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
2414 bool IsLightweightGeneric =
2415 Right.MatchingParen && Right.MatchingParen->Next &&
2416 Right.MatchingParen->Next->is(tok::colon);
2417 return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
2419 if (Right.is(tok::less) && Left.is(tok::kw_template))
2420 return Style.SpaceAfterTemplateKeyword;
2421 if (Left.isOneOf(tok::exclaim, tok::tilde))
2423 if (Left.is(tok::at) &&
2424 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
2425 tok::numeric_constant, tok::l_paren, tok::l_brace,
2426 tok::kw_true, tok::kw_false))
2428 if (Left.is(tok::colon))
2429 return !Left.is(TT_ObjCMethodExpr);
2430 if (Left.is(tok::coloncolon))
2432 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
2433 if (Style.Language == FormatStyle::LK_TextProto ||
2434 (Style.Language == FormatStyle::LK_Proto &&
2435 (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
2436 // Format empty list as `<>`.
2437 if (Left.is(tok::less) && Right.is(tok::greater))
2439 return !Style.Cpp11BracedListStyle;
2443 if (Right.is(tok::ellipsis))
2444 return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
2445 Left.Previous->is(tok::kw_case));
2446 if (Left.is(tok::l_square) && Right.is(tok::amp))
2448 if (Right.is(TT_PointerOrReference)) {
2449 if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
2450 if (!Left.MatchingParen)
2452 FormatToken *TokenBeforeMatchingParen =
2453 Left.MatchingParen->getPreviousNonComment();
2454 if (!TokenBeforeMatchingParen ||
2455 !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
2458 return (Left.Tok.isLiteral() ||
2459 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
2460 (Style.PointerAlignment != FormatStyle::PAS_Left ||
2461 (Line.IsMultiVariableDeclStmt &&
2462 (Left.NestingLevel == 0 ||
2463 (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
2465 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
2466 (!Left.is(TT_PointerOrReference) ||
2467 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2468 !Line.IsMultiVariableDeclStmt)))
2470 if (Left.is(TT_PointerOrReference))
2471 return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
2472 (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
2473 !Right.is(TT_StartOfName)) ||
2474 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
2475 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
2477 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2478 !Line.IsMultiVariableDeclStmt) &&
2480 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
2481 if (Right.is(tok::star) && Left.is(tok::l_paren))
2483 const auto SpaceRequiredForArrayInitializerLSquare =
2484 [](const FormatToken &LSquareTok, const FormatStyle &Style) {
2485 return Style.SpacesInContainerLiterals ||
2486 ((Style.Language == FormatStyle::LK_Proto ||
2487 Style.Language == FormatStyle::LK_TextProto) &&
2488 !Style.Cpp11BracedListStyle &&
2489 LSquareTok.endsSequence(tok::l_square, tok::colon,
2492 if (Left.is(tok::l_square))
2493 return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
2494 SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
2495 (Left.isOneOf(TT_ArraySubscriptLSquare,
2496 TT_StructuredBindingLSquare) &&
2497 Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
2498 if (Right.is(tok::r_square))
2499 return Right.MatchingParen &&
2500 ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
2501 SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
2503 (Style.SpacesInSquareBrackets &&
2504 Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
2505 TT_StructuredBindingLSquare)) ||
2506 Right.MatchingParen->is(TT_AttributeParen));
2507 if (Right.is(tok::l_square) &&
2508 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2509 TT_DesignatedInitializerLSquare,
2510 TT_StructuredBindingLSquare, TT_AttributeSquare) &&
2511 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
2513 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
2514 return !Left.Children.empty(); // No spaces in "{}".
2515 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
2516 (Right.is(tok::r_brace) && Right.MatchingParen &&
2517 Right.MatchingParen->BlockKind != BK_Block))
2518 return !Style.Cpp11BracedListStyle;
2519 if (Left.is(TT_BlockComment))
2520 return !Left.TokenText.endswith("=*/");
2521 if (Right.is(tok::l_paren)) {
2522 if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
2523 (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
2525 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
2526 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
2527 (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
2528 tok::kw_switch, tok::kw_case, TT_ForEachMacro,
2530 Left.endsSequence(tok::kw_constexpr, tok::kw_if) ||
2531 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
2532 tok::kw_new, tok::kw_delete) &&
2533 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
2534 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
2535 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
2536 Left.is(tok::r_paren)) &&
2537 Line.Type != LT_PreprocessorDirective);
2539 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
2541 if (Right.is(TT_UnaryOperator))
2542 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
2543 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
2544 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
2546 Left.isSimpleTypeSpecifier()) &&
2547 Right.is(tok::l_brace) && Right.getNextNonComment() &&
2548 Right.BlockKind != BK_Block)
2550 if (Left.is(tok::period) || Right.is(tok::period))
2552 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
2554 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
2555 Left.MatchingParen->Previous &&
2556 Left.MatchingParen->Previous->is(tok::period))
2557 // A.<B<C<...>>>DoSomething();
2559 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
2561 if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at))
2562 // Objective-C dictionary literal -> no space after opening brace.
2564 if (Right.is(tok::r_brace) && Right.MatchingParen &&
2565 Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at))
2566 // Objective-C dictionary literal -> no space before closing brace.
2571 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
2572 const FormatToken &Right) {
2573 const FormatToken &Left = *Right.Previous;
2574 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
2575 return true; // Never ever merge two identifiers.
2576 if (Style.isCpp()) {
2577 if (Left.is(tok::kw_operator))
2578 return Right.is(tok::coloncolon);
2579 if (Right.is(tok::l_brace) && Right.BlockKind == BK_BracedInit &&
2580 !Left.opensScope() && Style.SpaceBeforeCpp11BracedList)
2582 } else if (Style.Language == FormatStyle::LK_Proto ||
2583 Style.Language == FormatStyle::LK_TextProto) {
2584 if (Right.is(tok::period) &&
2585 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2586 Keywords.kw_repeated, Keywords.kw_extend))
2588 if (Right.is(tok::l_paren) &&
2589 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2591 if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
2593 // Slashes occur in text protocol extension syntax: [type/type] { ... }.
2594 if (Left.is(tok::slash) || Right.is(tok::slash))
2596 if (Left.MatchingParen && Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
2597 Right.isOneOf(tok::l_brace, tok::less))
2598 return !Style.Cpp11BracedListStyle;
2599 // A percent is probably part of a formatting specification, such as %lld.
2600 if (Left.is(tok::percent))
2602 // Preserve the existence of a space before a percent for cases like 0x%04x
2604 if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
2605 return Right.WhitespaceRange.getEnd() != Right.WhitespaceRange.getBegin();
2606 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2607 if (Left.is(TT_JsFatArrow))
2610 if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
2611 Left.Previous->is(tok::kw_for))
2613 if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
2614 Right.MatchingParen) {
2615 const FormatToken *Next = Right.MatchingParen->getNextNonComment();
2616 // An async arrow function, for example: `x = async () => foo();`,
2617 // as opposed to calling a function called async: `x = async();`
2618 if (Next && Next->is(TT_JsFatArrow))
2621 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2622 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2624 // In tagged template literals ("html`bar baz`"), there is no space between
2625 // the tag identifier and the template string. getIdentifierInfo makes sure
2626 // that the identifier is not a pseudo keyword like `yield`, either.
2627 if (Left.is(tok::identifier) && Keywords.IsJavaScriptIdentifier(Left) &&
2628 Right.is(TT_TemplateString))
2630 if (Right.is(tok::star) &&
2631 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2633 if (Right.isOneOf(tok::l_brace, tok::l_square) &&
2634 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
2635 Keywords.kw_extends, Keywords.kw_implements))
2637 if (Right.is(tok::l_paren)) {
2638 // JS methods can use some keywords as names (e.g. `delete()`).
2639 if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
2641 // Valid JS method names can include keywords, e.g. `foo.delete()` or
2642 // `bar.instanceof()`. Recognize call positions by preceding period.
2643 if (Left.Previous && Left.Previous->is(tok::period) &&
2644 Left.Tok.getIdentifierInfo())
2646 // Additional unary JavaScript operators that need a space after.
2647 if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
2651 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
2653 // "of" is only a keyword if it appears after another identifier
2654 // (e.g. as "const x of y" in a for loop), or after a destructuring
2655 // operation (const [x, y] of z, const {a, b} of c).
2656 (Left.is(Keywords.kw_of) && Left.Previous &&
2657 (Left.Previous->Tok.is(tok::identifier) ||
2658 Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) &&
2659 (!Left.Previous || !Left.Previous->is(tok::period)))
2661 if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
2662 Left.Previous->is(tok::period) && Right.is(tok::l_paren))
2664 if (Left.is(Keywords.kw_as) &&
2665 Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
2667 if (Left.is(tok::kw_default) && Left.Previous &&
2668 Left.Previous->is(tok::kw_export))
2670 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2672 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2674 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
2676 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2677 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2679 if (Left.is(tok::ellipsis))
2681 if (Left.is(TT_TemplateCloser) &&
2682 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2683 Keywords.kw_implements, Keywords.kw_extends))
2684 // Type assertions ('<type>expr') are not followed by whitespace. Other
2685 // locations that should have whitespace following are identified by the
2686 // above set of follower tokens.
2688 if (Right.is(TT_JsNonNullAssertion))
2690 if (Left.is(TT_JsNonNullAssertion) &&
2691 Right.isOneOf(Keywords.kw_as, Keywords.kw_in))
2692 return true; // "x! as string", "x! in y"
2693 } else if (Style.Language == FormatStyle::LK_Java) {
2694 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2696 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2697 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2698 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2699 tok::kw_protected) ||
2700 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2701 Keywords.kw_native)) &&
2702 Right.is(TT_TemplateOpener))
2705 if (Left.is(TT_ImplicitStringLiteral))
2706 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2707 if (Line.Type == LT_ObjCMethodDecl) {
2708 if (Left.is(TT_ObjCMethodSpecifier))
2710 if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right))
2711 // Don't space between ')' and <id> or ')' and 'new'. 'new' is not a
2712 // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
2713 // method declaration.
2716 if (Line.Type == LT_ObjCProperty &&
2717 (Right.is(tok::equal) || Left.is(tok::equal)))
2720 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2721 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2723 if (Right.is(TT_OverloadedOperatorLParen))
2724 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2725 if (Left.is(tok::comma))
2727 if (Right.is(tok::comma))
2729 if (Right.is(TT_ObjCBlockLParen))
2731 if (Right.is(TT_CtorInitializerColon))
2732 return Style.SpaceBeforeCtorInitializerColon;
2733 if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
2735 if (Right.is(TT_RangeBasedForLoopColon) &&
2736 !Style.SpaceBeforeRangeBasedForLoopColon)
2738 if (Right.is(tok::colon)) {
2739 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2740 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2742 if (Right.is(TT_ObjCMethodExpr))
2744 if (Left.is(tok::question))
2746 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2748 if (Right.is(TT_DictLiteral))
2749 return Style.SpacesInContainerLiterals;
2750 if (Right.is(TT_AttributeColon))
2754 if (Left.is(TT_UnaryOperator))
2755 return Right.is(TT_BinaryOperator);
2757 // If the next token is a binary operator or a selector name, we have
2758 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2759 if (Left.is(TT_CastRParen))
2760 return Style.SpaceAfterCStyleCast ||
2761 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2763 if (Left.is(tok::greater) && Right.is(tok::greater)) {
2764 if (Style.Language == FormatStyle::LK_TextProto ||
2765 (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral)))
2766 return !Style.Cpp11BracedListStyle;
2767 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2768 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2770 if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
2771 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2772 (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod)))
2774 if (!Style.SpaceBeforeAssignmentOperators &&
2775 Right.getPrecedence() == prec::Assignment)
2777 if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
2778 // Generally don't remove existing spaces between an identifier and "::".
2779 // The identifier might actually be a macro name such as ALWAYS_INLINE. If
2780 // this turns out to be too lenient, add analysis of the identifier itself.
2781 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2782 if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
2783 return (Left.is(TT_TemplateOpener) &&
2784 Style.Standard == FormatStyle::LS_Cpp03) ||
2785 !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
2786 tok::kw___super, TT_TemplateCloser,
2787 TT_TemplateOpener)) ||
2788 (Left.is(tok ::l_paren) && Style.SpacesInParentheses);
2789 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2790 return Style.SpacesInAngles;
2791 // Space before TT_StructuredBindingLSquare.
2792 if (Right.is(TT_StructuredBindingLSquare))
2793 return !Left.isOneOf(tok::amp, tok::ampamp) ||
2794 Style.PointerAlignment != FormatStyle::PAS_Right;
2795 // Space before & or && following a TT_StructuredBindingLSquare.
2796 if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
2797 Right.isOneOf(tok::amp, tok::ampamp))
2798 return Style.PointerAlignment != FormatStyle::PAS_Left;
2799 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2800 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2801 !Right.is(tok::r_paren)))
2803 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2804 Right.isNot(TT_FunctionTypeLParen))
2805 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2806 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2807 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2809 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2810 Line.startsWith(tok::hash))
2812 if (Right.is(TT_TrailingUnaryOperator))
2814 if (Left.is(TT_RegexLiteral))
2816 return spaceRequiredBetween(Line, Left, Right);
2819 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2820 static bool isAllmanBrace(const FormatToken &Tok) {
2821 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2822 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2825 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2826 const FormatToken &Right) {
2827 const FormatToken &Left = *Right.Previous;
2828 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2831 if (Style.Language == FormatStyle::LK_JavaScript) {
2832 // FIXME: This might apply to other languages and token kinds.
2833 if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
2834 Left.Previous->is(tok::string_literal))
2836 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2837 Left.Previous && Left.Previous->is(tok::equal) &&
2838 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2840 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2842 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2843 // Object literals on the top level of a file are treated as "enum-style".
2844 // Each key/value pair is put on a separate line, instead of bin-packing.
2846 if (Left.is(tok::l_brace) && Line.Level == 0 &&
2847 (Line.startsWith(tok::kw_enum) ||
2848 Line.startsWith(tok::kw_const, tok::kw_enum) ||
2849 Line.startsWith(tok::kw_export, tok::kw_enum) ||
2850 Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
2851 // JavaScript top-level enum key/value pairs are put on separate lines
2852 // instead of bin-packing.
2854 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2855 !Left.Children.empty())
2856 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2857 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2858 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2859 (Left.NestingLevel == 0 && Line.Level == 0 &&
2860 Style.AllowShortFunctionsOnASingleLine &
2861 FormatStyle::SFS_InlineOnly);
2862 } else if (Style.Language == FormatStyle::LK_Java) {
2863 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2864 Right.Next->is(tok::string_literal))
2866 } else if (Style.Language == FormatStyle::LK_Cpp ||
2867 Style.Language == FormatStyle::LK_ObjC ||
2868 Style.Language == FormatStyle::LK_Proto ||
2869 Style.Language == FormatStyle::LK_TextProto) {
2870 if (Left.isStringLiteral() && Right.isStringLiteral())
2874 // If the last token before a '}', ']', or ')' is a comma or a trailing
2875 // comment, the intention is to insert a line break after it in order to make
2876 // shuffling around entries easier. Import statements, especially in
2877 // JavaScript, can be an exception to this rule.
2878 if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
2879 const FormatToken *BeforeClosingBrace = nullptr;
2880 if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
2881 (Style.Language == FormatStyle::LK_JavaScript &&
2882 Left.is(tok::l_paren))) &&
2883 Left.BlockKind != BK_Block && Left.MatchingParen)
2884 BeforeClosingBrace = Left.MatchingParen->Previous;
2885 else if (Right.MatchingParen &&
2886 (Right.MatchingParen->isOneOf(tok::l_brace,
2887 TT_ArrayInitializerLSquare) ||
2888 (Style.Language == FormatStyle::LK_JavaScript &&
2889 Right.MatchingParen->is(tok::l_paren))))
2890 BeforeClosingBrace = &Left;
2891 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2892 BeforeClosingBrace->isTrailingComment()))
2896 if (Right.is(tok::comment))
2897 return Left.BlockKind != BK_BracedInit &&
2898 Left.isNot(TT_CtorInitializerColon) &&
2899 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2900 if (Left.isTrailingComment())
2902 if (Right.Previous->IsUnterminatedLiteral)
2904 if (Right.is(tok::lessless) && Right.Next &&
2905 Right.Previous->is(tok::string_literal) &&
2906 Right.Next->is(tok::string_literal))
2908 if (Right.Previous->ClosesTemplateDeclaration &&
2909 Right.Previous->MatchingParen &&
2910 Right.Previous->MatchingParen->NestingLevel == 0 &&
2911 Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes)
2913 if (Right.is(TT_CtorInitializerComma) &&
2914 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
2915 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2917 if (Right.is(TT_CtorInitializerColon) &&
2918 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
2919 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2921 // Break only if we have multiple inheritance.
2922 if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
2923 Right.is(TT_InheritanceComma))
2925 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2926 // Multiline raw string literals are special wrt. line breaks. The author
2927 // has made a deliberate choice and might have aligned the contents of the
2928 // string literal accordingly. Thus, we try keep existing line breaks.
2929 return Right.IsMultiline && Right.NewlinesBefore > 0;
2930 if ((Right.Previous->is(tok::l_brace) ||
2931 (Right.Previous->is(tok::less) && Right.Previous->Previous &&
2932 Right.Previous->Previous->is(tok::equal))) &&
2933 Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
2934 // Don't put enums or option definitions onto single lines in protocol
2938 if (Right.is(TT_InlineASMBrace))
2939 return Right.HasUnescapedNewline;
2940 if (isAllmanBrace(Left) || isAllmanBrace(Right))
2941 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2942 (Line.startsWith(tok::kw_typedef, tok::kw_enum) &&
2943 Style.BraceWrapping.AfterEnum) ||
2944 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2945 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2946 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2949 if ((Style.Language == FormatStyle::LK_Java ||
2950 Style.Language == FormatStyle::LK_JavaScript) &&
2951 Left.is(TT_LeadingJavaAnnotation) &&
2952 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2953 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2956 if (Right.is(TT_ProtoExtensionLSquare))
2959 // In text proto instances if a submessage contains at least 2 entries and at
2960 // least one of them is a submessage, like A { ... B { ... } ... },
2961 // put all of the entries of A on separate lines by forcing the selector of
2962 // the submessage B to be put on a newline.
2964 // Example: these can stay on one line:
2965 // a { scalar_1: 1 scalar_2: 2 }
2966 // a { b { key: value } }
2968 // and these entries need to be on a new line even if putting them all in one
2969 // line is under the column limit:
2975 // We enforce this by breaking before a submessage field that has previous
2976 // siblings, *and* breaking before a field that follows a submessage field.
2978 // Be careful to exclude the case [proto.ext] { ... } since the `]` is
2979 // the TT_SelectorName there, but we don't want to break inside the brackets.
2981 // Another edge case is @submessage { key: value }, which is a common
2982 // substitution placeholder. In this case we want to keep `@` and `submessage`
2985 // We ensure elsewhere that extensions are always on their own line.
2986 if ((Style.Language == FormatStyle::LK_Proto ||
2987 Style.Language == FormatStyle::LK_TextProto) &&
2988 Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) {
2989 // Keep `@submessage` together in:
2990 // @submessage { key: value }
2991 if (Right.Previous && Right.Previous->is(tok::at))
2993 // Look for the scope opener after selector in cases like:
2996 // selector: @base { ...
2997 FormatToken *LBrace = Right.Next;
2998 if (LBrace && LBrace->is(tok::colon)) {
2999 LBrace = LBrace->Next;
3000 if (LBrace && LBrace->is(tok::at)) {
3001 LBrace = LBrace->Next;
3003 LBrace = LBrace->Next;
3007 // The scope opener is one of {, [, <:
3012 // In case of selector { ... }, the l_brace is TT_DictLiteral.
3013 // In case of an empty selector {}, the l_brace is not TT_DictLiteral,
3014 // so we check for immediately following r_brace.
3015 ((LBrace->is(tok::l_brace) &&
3016 (LBrace->is(TT_DictLiteral) ||
3017 (LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
3018 LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) {
3019 // If Left.ParameterCount is 0, then this submessage entry is not the
3020 // first in its parent submessage, and we want to break before this entry.
3021 // If Left.ParameterCount is greater than 0, then its parent submessage
3022 // might contain 1 or more entries and we want to break before this entry
3023 // if it contains at least 2 entries. We deal with this case later by
3024 // detecting and breaking before the next entry in the parent submessage.
3025 if (Left.ParameterCount == 0)
3027 // However, if this submessage is the first entry in its parent
3028 // submessage, Left.ParameterCount might be 1 in some cases.
3029 // We deal with this case later by detecting an entry
3030 // following a closing paren of this submessage.
3033 // If this is an entry immediately following a submessage, it will be
3034 // preceded by a closing paren of that submessage, like in:
3035 // left---. .---right
3037 // sub: { ... } key: value
3038 // If there was a comment between `}` an `key` above, then `key` would be
3039 // put on a new line anyways.
3040 if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
3047 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
3048 const FormatToken &Right) {
3049 const FormatToken &Left = *Right.Previous;
3051 // Language-specific stuff.
3052 if (Style.Language == FormatStyle::LK_Java) {
3053 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
3054 Keywords.kw_implements))
3056 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
3057 Keywords.kw_implements))
3059 } else if (Style.Language == FormatStyle::LK_JavaScript) {
3060 const FormatToken *NonComment = Right.getPreviousNonComment();
3062 NonComment->isOneOf(
3063 tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
3064 tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
3065 tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected,
3066 Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
3067 Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
3068 return false; // Otherwise automatic semicolon insertion would trigger.
3069 if (Right.NestingLevel == 0 &&
3070 (Left.Tok.getIdentifierInfo() ||
3071 Left.isOneOf(tok::r_square, tok::r_paren)) &&
3072 Right.isOneOf(tok::l_square, tok::l_paren))
3073 return false; // Otherwise automatic semicolon insertion would trigger.
3074 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
3076 if (Left.is(TT_JsTypeColon))
3078 // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
3079 if (Left.is(tok::exclaim) && Right.is(tok::colon))
3081 if (Right.is(Keywords.kw_is))
3083 if (Left.is(Keywords.kw_in))
3084 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
3085 if (Right.is(Keywords.kw_in))
3086 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
3087 if (Right.is(Keywords.kw_as))
3088 return false; // must not break before as in 'x as type' casts
3089 if (Left.is(Keywords.kw_as))
3091 if (Left.is(TT_JsNonNullAssertion))
3093 if (Left.is(Keywords.kw_declare) &&
3094 Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
3095 Keywords.kw_function, tok::kw_class, tok::kw_enum,
3096 Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
3097 Keywords.kw_let, tok::kw_const))
3098 // See grammar for 'declare' statements at:
3099 // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10
3101 if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
3102 Right.isOneOf(tok::identifier, tok::string_literal))
3103 return false; // must not break in "module foo { ...}"
3104 if (Right.is(TT_TemplateString) && Right.closesScope())
3106 if (Left.is(TT_TemplateString) && Left.opensScope())
3110 if (Left.is(tok::at))
3112 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
3114 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
3115 return !Right.is(tok::l_paren);
3116 if (Right.is(TT_PointerOrReference))
3117 return Line.IsMultiVariableDeclStmt ||
3118 (Style.PointerAlignment == FormatStyle::PAS_Right &&
3119 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
3120 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
3121 Right.is(tok::kw_operator))
3123 if (Left.is(TT_PointerOrReference))
3125 if (Right.isTrailingComment())
3126 // We rely on MustBreakBefore being set correctly here as we should not
3127 // change the "binding" behavior of a comment.
3128 // The first comment in a braced lists is always interpreted as belonging to
3129 // the first list element. Otherwise, it should be placed outside of the
3131 return Left.BlockKind == BK_BracedInit ||
3132 (Left.is(TT_CtorInitializerColon) &&
3133 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
3134 if (Left.is(tok::question) && Right.is(tok::colon))
3136 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
3137 return Style.BreakBeforeTernaryOperators;
3138 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
3139 return !Style.BreakBeforeTernaryOperators;
3140 if (Left.is(TT_InheritanceColon))
3141 return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
3142 if (Right.is(TT_InheritanceColon))
3143 return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon;
3144 if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
3145 Left.isNot(TT_SelectorName))
3148 if (Right.is(tok::colon) &&
3149 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
3151 if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
3152 if (Style.Language == FormatStyle::LK_Proto ||
3153 Style.Language == FormatStyle::LK_TextProto) {
3154 if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
3156 // Prevent cases like:
3159 // { key: valueeeeeeeeeeee }
3161 // when the snippet does not fit into one line.
3165 // key: valueeeeeeeeeeee
3168 // instead, even if it is longer by one line.
3170 // Note that this allows allows the "{" to go over the column limit
3171 // when the column limit is just between ":" and "{", but that does
3172 // not happen too often and alternative formattings in this case are
3175 // The code covers the cases:
3177 // submessage: { ... }
3178 // submessage: < ... >
3179 // repeated: [ ... ]
3180 if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
3181 Right.is(TT_DictLiteral)) ||
3182 Right.is(TT_ArrayInitializerLSquare))
3187 if (Right.is(tok::r_square) && Right.MatchingParen &&
3188 Right.MatchingParen->is(TT_ProtoExtensionLSquare))
3190 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
3191 Right.Next->is(TT_ObjCMethodExpr)))
3192 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
3193 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
3195 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
3197 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
3198 TT_OverloadedOperator))
3200 if (Left.is(TT_RangeBasedForLoopColon))
3202 if (Right.is(TT_RangeBasedForLoopColon))
3204 if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
3206 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
3207 Left.is(tok::kw_operator))
3209 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
3210 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
3212 if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
3213 !Style.Cpp11BracedListStyle)
3215 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
3217 if (Left.is(tok::l_paren) && Left.Previous &&
3218 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
3220 if (Right.is(TT_ImplicitStringLiteral))
3223 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
3225 if (Right.is(tok::r_square) && Right.MatchingParen &&
3226 Right.MatchingParen->is(TT_LambdaLSquare))
3229 // We only break before r_brace if there was a corresponding break before
3230 // the l_brace, which is tracked by BreakBeforeClosingBrace.
3231 if (Right.is(tok::r_brace))
3232 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
3234 // Allow breaking after a trailing annotation, e.g. after a method
3236 if (Left.is(TT_TrailingAnnotation))
3237 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
3238 tok::less, tok::coloncolon);
3240 if (Right.is(tok::kw___attribute) ||
3241 (Right.is(tok::l_square) && Right.is(TT_AttributeSquare)))
3244 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
3247 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
3250 if (Left.is(TT_CtorInitializerColon))
3251 return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
3252 if (Right.is(TT_CtorInitializerColon))
3253 return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon;
3254 if (Left.is(TT_CtorInitializerComma) &&
3255 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
3257 if (Right.is(TT_CtorInitializerComma) &&
3258 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
3260 if (Left.is(TT_InheritanceComma) &&
3261 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
3263 if (Right.is(TT_InheritanceComma) &&
3264 Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma)
3266 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
3267 (Left.is(tok::less) && Right.is(tok::less)))
3269 if (Right.is(TT_BinaryOperator) &&
3270 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
3271 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
3272 Right.getPrecedence() != prec::Assignment))
3274 if (Left.is(TT_ArrayInitializerLSquare))
3276 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
3278 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
3279 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
3280 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
3281 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
3282 Left.getPrecedence() == prec::Assignment))
3284 if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) ||
3285 (Left.is(tok::r_square) && Right.is(TT_AttributeSquare)))
3287 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
3288 tok::kw_class, tok::kw_struct, tok::comment) ||
3289 Right.isMemberAccess() ||
3290 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
3291 tok::colon, tok::l_square, tok::at) ||
3292 (Left.is(tok::r_paren) &&
3293 Right.isOneOf(tok::identifier, tok::kw_const)) ||
3294 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
3295 (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
3298 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
3299 llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
3300 const FormatToken *Tok = Line.First;
3302 llvm::errs() << " M=" << Tok->MustBreakBefore
3303 << " C=" << Tok->CanBreakBefore
3304 << " T=" << getTokenTypeName(Tok->Type)
3305 << " S=" << Tok->SpacesRequiredBefore
3306 << " B=" << Tok->BlockParameterCount
3307 << " BK=" << Tok->BlockKind << " P=" << Tok->SplitPenalty
3308 << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
3309 << " PPK=" << Tok->PackingKind << " FakeLParens=";
3310 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
3311 llvm::errs() << Tok->FakeLParens[i] << "/";
3312 llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
3313 llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
3314 llvm::errs() << " Text='" << Tok->TokenText << "'\n";
3316 assert(Tok == Line.Last);
3319 llvm::errs() << "----\n";
3322 } // namespace format
3323 } // namespace clang