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 /// \brief 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 /// \brief A parser that gathers additional information about tokens.
30 /// The \c TokenAnnotator tries to match parenthesis and square brakets and
31 /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
32 /// into template parameter lists.
33 class AnnotatingParser {
35 AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
36 const AdditionalKeywords &Keywords)
37 : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
39 Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
40 resetTokenMetadata(CurrentToken);
45 if (!CurrentToken || !CurrentToken->Previous)
47 if (NonTemplateLess.count(CurrentToken->Previous))
50 const FormatToken &Previous = *CurrentToken->Previous; // The '<'.
51 if (Previous.Previous) {
52 if (Previous.Previous->Tok.isLiteral())
54 if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 &&
55 (!Previous.Previous->MatchingParen ||
56 !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen)))
60 FormatToken *Left = CurrentToken->Previous;
61 Left->ParentBracket = Contexts.back().ContextKind;
62 ScopedContextCreator ContextCreator(*this, tok::less, 12);
64 // If this angle is in the context of an expression, we need to be more
65 // hesitant to detect it as opening template parameters.
66 bool InExprContext = Contexts.back().IsExpression;
68 Contexts.back().IsExpression = false;
69 // If there's a template keyword before the opening angle bracket, this is a
70 // template parameter, not an argument.
71 Contexts.back().InTemplateArgument =
72 Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);
74 if (Style.Language == FormatStyle::LK_Java &&
75 CurrentToken->is(tok::question))
78 while (CurrentToken) {
79 if (CurrentToken->is(tok::greater)) {
80 Left->MatchingParen = CurrentToken;
81 CurrentToken->MatchingParen = Left;
82 // In TT_Proto, we must distignuish between:
85 // msg: < item: data >
86 // In TT_TextProto, map<key, value> does not occur.
87 if (Style.Language == FormatStyle::LK_TextProto ||
88 (Style.Language == FormatStyle::LK_Proto && Left->Previous &&
89 Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral)))
90 CurrentToken->Type = TT_DictLiteral;
92 CurrentToken->Type = TT_TemplateCloser;
96 if (CurrentToken->is(tok::question) &&
97 Style.Language == FormatStyle::LK_Java) {
101 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) ||
102 (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext &&
103 Style.Language != FormatStyle::LK_Proto &&
104 Style.Language != FormatStyle::LK_TextProto))
106 // If a && or || is found and interpreted as a binary operator, this set
107 // of angles is likely part of something like "a < b && c > d". If the
108 // angles are inside an expression, the ||/&& might also be a binary
109 // operator that was misinterpreted because we are parsing template
111 // FIXME: This is getting out of hand, write a decent parser.
112 if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
113 CurrentToken->Previous->is(TT_BinaryOperator) &&
114 Contexts[Contexts.size() - 2].IsExpression &&
115 !Line.startsWith(tok::kw_template))
117 updateParameterCount(Left, CurrentToken);
118 if (Style.Language == FormatStyle::LK_Proto) {
119 if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
120 if (CurrentToken->is(tok::colon) ||
121 (CurrentToken->isOneOf(tok::l_brace, tok::less) &&
122 Previous->isNot(tok::colon)))
123 Previous->Type = TT_SelectorName;
132 bool parseParens(bool LookForDecls = false) {
135 FormatToken *Left = CurrentToken->Previous;
136 Left->ParentBracket = Contexts.back().ContextKind;
137 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
139 // FIXME: This is a bit of a hack. Do better.
140 Contexts.back().ColonIsForRangeExpr =
141 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
143 bool StartsObjCMethodExpr = false;
144 if (CurrentToken->is(tok::caret)) {
145 // (^ can start a block type.
146 Left->Type = TT_ObjCBlockLParen;
147 } else if (FormatToken *MaybeSel = Left->Previous) {
148 // @selector( starts a selector.
149 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
150 MaybeSel->Previous->is(tok::at)) {
151 StartsObjCMethodExpr = true;
155 if (Left->is(TT_OverloadedOperatorLParen)) {
156 Contexts.back().IsExpression = false;
157 } else if (Style.Language == FormatStyle::LK_JavaScript &&
158 (Line.startsWith(Keywords.kw_type, tok::identifier) ||
159 Line.startsWith(tok::kw_export, Keywords.kw_type,
162 // export type X = (...);
163 Contexts.back().IsExpression = false;
164 } else if (Left->Previous &&
165 (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
166 tok::kw_if, tok::kw_while, tok::l_paren,
168 Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
169 Left->Previous->is(TT_BinaryOperator))) {
170 // static_assert, if and while usually contain expressions.
171 Contexts.back().IsExpression = true;
172 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
173 (Left->Previous->is(Keywords.kw_function) ||
174 (Left->Previous->endsSequence(tok::identifier,
175 Keywords.kw_function)))) {
176 // function(...) or function f(...)
177 Contexts.back().IsExpression = false;
178 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
179 Left->Previous->is(TT_JsTypeColon)) {
180 // let x: (SomeType);
181 Contexts.back().IsExpression = false;
182 } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
183 Left->Previous->MatchingParen &&
184 Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
185 // This is a parameter list of a lambda expression.
186 Contexts.back().IsExpression = false;
187 } else if (Line.InPPDirective &&
188 (!Left->Previous || !Left->Previous->is(tok::identifier))) {
189 Contexts.back().IsExpression = true;
190 } else if (Contexts[Contexts.size() - 2].CaretFound) {
191 // This is the parameter list of an ObjC block.
192 Contexts.back().IsExpression = false;
193 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
194 Left->Type = TT_AttributeParen;
195 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
196 // The first argument to a foreach macro is a declaration.
197 Contexts.back().IsForEachMacro = true;
198 Contexts.back().IsExpression = false;
199 } else if (Left->Previous && Left->Previous->MatchingParen &&
200 Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
201 Contexts.back().IsExpression = false;
202 } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
204 Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
205 Contexts.back().IsExpression = !IsForOrCatch;
208 if (StartsObjCMethodExpr) {
209 Contexts.back().ColonIsObjCMethodExpr = true;
210 Left->Type = TT_ObjCMethodExpr;
213 bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
214 bool ProbablyFunctionType = CurrentToken->isOneOf(tok::star, tok::amp);
215 bool HasMultipleLines = false;
216 bool HasMultipleParametersOnALine = false;
217 bool MightBeObjCForRangeLoop =
218 Left->Previous && Left->Previous->is(tok::kw_for);
219 FormatToken *PossibleObjCForInToken = nullptr;
220 while (CurrentToken) {
221 // LookForDecls is set when "if (" has been seen. Check for
222 // 'identifier' '*' 'identifier' followed by not '=' -- this
223 // '*' has to be a binary operator but determineStarAmpUsage() will
224 // categorize it as an unary operator, so set the right type here.
225 if (LookForDecls && CurrentToken->Next) {
226 FormatToken *Prev = CurrentToken->getPreviousNonComment();
228 FormatToken *PrevPrev = Prev->getPreviousNonComment();
229 FormatToken *Next = CurrentToken->Next;
230 if (PrevPrev && PrevPrev->is(tok::identifier) &&
231 Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
232 CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
233 Prev->Type = TT_BinaryOperator;
234 LookForDecls = false;
239 if (CurrentToken->Previous->is(TT_PointerOrReference) &&
240 CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
242 ProbablyFunctionType = true;
243 if (CurrentToken->is(tok::comma))
244 MightBeFunctionType = false;
245 if (CurrentToken->Previous->is(TT_BinaryOperator))
246 Contexts.back().IsExpression = true;
247 if (CurrentToken->is(tok::r_paren)) {
248 if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next &&
249 (CurrentToken->Next->is(tok::l_paren) ||
250 (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration)))
251 Left->Type = TT_FunctionTypeLParen;
252 Left->MatchingParen = CurrentToken;
253 CurrentToken->MatchingParen = Left;
255 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
256 Left->Previous && Left->Previous->is(tok::l_paren)) {
257 // Detect the case where macros are used to generate lambdas or
258 // function bodies, e.g.:
259 // auto my_lambda = MARCO((Type *type, int i) { .. body .. });
260 for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
261 if (Tok->is(TT_BinaryOperator) &&
262 Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
263 Tok->Type = TT_PointerOrReference;
267 if (StartsObjCMethodExpr) {
268 CurrentToken->Type = TT_ObjCMethodExpr;
269 if (Contexts.back().FirstObjCSelectorName) {
270 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
271 Contexts.back().LongestObjCSelectorName;
275 if (Left->is(TT_AttributeParen))
276 CurrentToken->Type = TT_AttributeParen;
277 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
278 CurrentToken->Type = TT_JavaAnnotation;
279 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
280 CurrentToken->Type = TT_LeadingJavaAnnotation;
282 if (!HasMultipleLines)
283 Left->PackingKind = PPK_Inconclusive;
284 else if (HasMultipleParametersOnALine)
285 Left->PackingKind = PPK_BinPacked;
287 Left->PackingKind = PPK_OnePerLine;
292 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
295 if (CurrentToken->is(tok::l_brace))
296 Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
297 if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
298 !CurrentToken->Next->HasUnescapedNewline &&
299 !CurrentToken->Next->isTrailingComment())
300 HasMultipleParametersOnALine = true;
301 if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
302 CurrentToken->Previous->isSimpleTypeSpecifier()) &&
303 !CurrentToken->is(tok::l_brace))
304 Contexts.back().IsExpression = false;
305 if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
306 MightBeObjCForRangeLoop = false;
307 if (PossibleObjCForInToken) {
308 PossibleObjCForInToken->Type = TT_Unknown;
309 PossibleObjCForInToken = nullptr;
312 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
313 PossibleObjCForInToken = CurrentToken;
314 PossibleObjCForInToken->Type = TT_ObjCForIn;
316 // When we discover a 'new', we set CanBeExpression to 'false' in order to
317 // parse the type correctly. Reset that after a comma.
318 if (CurrentToken->is(tok::comma))
319 Contexts.back().CanBeExpression = true;
321 FormatToken *Tok = CurrentToken;
324 updateParameterCount(Left, Tok);
325 if (CurrentToken && CurrentToken->HasUnescapedNewline)
326 HasMultipleLines = true;
331 bool isCpp11AttributeSpecifier(const FormatToken &Tok) {
332 if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square))
334 const FormatToken *AttrTok = Tok.Next->Next;
337 // C++17 '[[using ns: foo, bar(baz, blech)]]'
338 // We assume nobody will name an ObjC variable 'using'.
339 if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
341 if (AttrTok->isNot(tok::identifier))
343 while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
344 // ObjC message send. We assume nobody will use : in a C++11 attribute
345 // specifier parameter, although this is technically valid:
347 if (AttrTok->is(tok::colon) ||
348 AttrTok->startsSequence(tok::identifier, tok::identifier))
350 if (AttrTok->is(tok::ellipsis))
352 AttrTok = AttrTok->Next;
354 return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
361 // A '[' could be an index subscript (after an identifier or after
362 // ')' or ']'), it could be the start of an Objective-C method
363 // expression, it could the start of an Objective-C array literal,
364 // or it could be a C++ attribute specifier [[foo::bar]].
365 FormatToken *Left = CurrentToken->Previous;
366 Left->ParentBracket = Contexts.back().ContextKind;
367 FormatToken *Parent = Left->getPreviousNonComment();
369 // Cases where '>' is followed by '['.
370 // In C++, this can happen either in array of templates (foo<int>[10])
371 // or when array is a nested template type (unique_ptr<type1<type2>[]>).
372 bool CppArrayTemplates =
373 Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
374 (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
375 Contexts.back().InTemplateArgument);
377 bool IsCpp11AttributeSpecifier = isCpp11AttributeSpecifier(*Left) ||
378 Contexts.back().InCpp11AttributeSpecifier;
380 bool StartsObjCMethodExpr =
381 !CppArrayTemplates && Style.isCpp() && !IsCpp11AttributeSpecifier &&
382 Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
383 CurrentToken->isNot(tok::l_brace) &&
385 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
386 tok::kw_return, tok::kw_throw) ||
387 Parent->isUnaryOperator() ||
388 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
389 getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
390 bool ColonFound = false;
392 unsigned BindingIncrease = 1;
393 if (Left->isCppStructuredBinding(Style)) {
394 Left->Type = TT_StructuredBindingLSquare;
395 } else if (Left->is(TT_Unknown)) {
396 if (StartsObjCMethodExpr) {
397 Left->Type = TT_ObjCMethodExpr;
398 } else if (IsCpp11AttributeSpecifier) {
399 Left->Type = TT_AttributeSquare;
400 } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
401 Contexts.back().ContextKind == tok::l_brace &&
402 Parent->isOneOf(tok::l_brace, tok::comma)) {
403 Left->Type = TT_JsComputedPropertyName;
404 } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace &&
405 Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
406 Left->Type = TT_DesignatedInitializerLSquare;
407 } else if (CurrentToken->is(tok::r_square) && Parent &&
408 Parent->is(TT_TemplateCloser)) {
409 Left->Type = TT_ArraySubscriptLSquare;
410 } else if (Style.Language == FormatStyle::LK_Proto ||
411 Style.Language == FormatStyle::LK_TextProto) {
412 // Square braces in LK_Proto can either be message field attributes:
414 // optional Aaa aaa = 1 [
422 // or text proto extensions (in options):
424 // option (Aaa.options) = {
425 // [type.type/type] {
430 // or repeated fields (in options):
432 // option (Aaa.options) = {
436 // In the first and the third case we want to spread the contents inside
437 // the square braces; in the second we want to keep them inline.
438 Left->Type = TT_ArrayInitializerLSquare;
439 if (!Left->endsSequence(tok::l_square, tok::numeric_constant,
441 !Left->endsSequence(tok::l_square, tok::numeric_constant,
443 !Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
444 Left->Type = TT_ProtoExtensionLSquare;
445 BindingIncrease = 10;
447 } else if (!CppArrayTemplates && Parent &&
448 Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
449 tok::comma, tok::l_paren, tok::l_square,
450 tok::question, tok::colon, tok::kw_return,
451 // Should only be relevant to JavaScript:
453 Left->Type = TT_ArrayInitializerLSquare;
455 BindingIncrease = 10;
456 Left->Type = TT_ArraySubscriptLSquare;
460 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
461 Contexts.back().IsExpression = true;
462 if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
463 Parent->is(TT_JsTypeColon))
464 Contexts.back().IsExpression = false;
466 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
467 Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
469 while (CurrentToken) {
470 if (CurrentToken->is(tok::r_square)) {
471 if (IsCpp11AttributeSpecifier)
472 CurrentToken->Type = TT_AttributeSquare;
473 else if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
474 Left->is(TT_ObjCMethodExpr)) {
475 // An ObjC method call is rarely followed by an open parenthesis.
476 // FIXME: Do we incorrectly label ":" with this?
477 StartsObjCMethodExpr = false;
478 Left->Type = TT_Unknown;
480 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
481 CurrentToken->Type = TT_ObjCMethodExpr;
482 // determineStarAmpUsage() thinks that '*' '[' is allocating an
483 // array of pointers, but if '[' starts a selector then '*' is a
485 if (Parent && Parent->is(TT_PointerOrReference))
486 Parent->Type = TT_BinaryOperator;
488 Left->MatchingParen = CurrentToken;
489 CurrentToken->MatchingParen = Left;
490 if (Contexts.back().FirstObjCSelectorName) {
491 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
492 Contexts.back().LongestObjCSelectorName;
493 Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts =
494 Left->ParameterCount;
495 if (Left->BlockParameterCount > 1)
496 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
501 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
503 if (CurrentToken->is(tok::colon)) {
504 if (IsCpp11AttributeSpecifier &&
505 CurrentToken->endsSequence(tok::colon, tok::identifier,
507 // Remember that this is a [[using ns: foo]] C++ attribute, so we
508 // don't add a space before the colon (unlike other colons).
509 CurrentToken->Type = TT_AttributeColon;
510 } else if (Left->isOneOf(TT_ArraySubscriptLSquare,
511 TT_DesignatedInitializerLSquare)) {
512 Left->Type = TT_ObjCMethodExpr;
513 StartsObjCMethodExpr = true;
514 // ParameterCount might have been set to 1 before expression was
515 // recognized as ObjCMethodExpr (as '1 + number of commas' formula is
516 // used for other expression types). Parameter counter has to be,
517 // therefore, reset to 0.
518 Left->ParameterCount = 0;
519 Contexts.back().ColonIsObjCMethodExpr = true;
520 if (Parent && Parent->is(tok::r_paren))
521 Parent->Type = TT_CastRParen;
525 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
527 Left->Type = TT_ArrayInitializerLSquare;
528 FormatToken *Tok = CurrentToken;
531 updateParameterCount(Left, Tok);
538 FormatToken *Left = CurrentToken->Previous;
539 Left->ParentBracket = Contexts.back().ContextKind;
541 if (Contexts.back().CaretFound)
542 Left->Type = TT_ObjCBlockLBrace;
543 Contexts.back().CaretFound = false;
545 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
546 Contexts.back().ColonIsDictLiteral = true;
547 if (Left->BlockKind == BK_BracedInit)
548 Contexts.back().IsExpression = true;
549 if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
550 Left->Previous->is(TT_JsTypeColon))
551 Contexts.back().IsExpression = false;
553 while (CurrentToken) {
554 if (CurrentToken->is(tok::r_brace)) {
555 Left->MatchingParen = CurrentToken;
556 CurrentToken->MatchingParen = Left;
560 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
562 updateParameterCount(Left, CurrentToken);
563 if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
564 FormatToken *Previous = CurrentToken->getPreviousNonComment();
565 if (Previous->is(TT_JsTypeOptionalQuestion))
566 Previous = Previous->getPreviousNonComment();
567 if ((CurrentToken->is(tok::colon) &&
568 (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
569 Style.Language == FormatStyle::LK_Proto ||
570 Style.Language == FormatStyle::LK_TextProto) {
571 Left->Type = TT_DictLiteral;
572 if (Previous->Tok.getIdentifierInfo() ||
573 Previous->is(tok::string_literal))
574 Previous->Type = TT_SelectorName;
576 if (CurrentToken->is(tok::colon) ||
577 Style.Language == FormatStyle::LK_JavaScript)
578 Left->Type = TT_DictLiteral;
580 if (CurrentToken->is(tok::comma) &&
581 Style.Language == FormatStyle::LK_JavaScript)
582 Left->Type = TT_DictLiteral;
590 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
591 if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
592 ++Left->BlockParameterCount;
593 if (Left->Type == TT_ObjCMethodExpr) {
594 if (Current->is(tok::colon))
595 ++Left->ParameterCount;
596 } else if (Current->is(tok::comma)) {
597 ++Left->ParameterCount;
599 Left->Role.reset(new CommaSeparatedList(Style));
600 Left->Role->CommaFound(Current);
601 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
602 Left->ParameterCount = 1;
606 bool parseConditional() {
607 while (CurrentToken) {
608 if (CurrentToken->is(tok::colon)) {
609 CurrentToken->Type = TT_ConditionalExpr;
619 bool parseTemplateDeclaration() {
620 if (CurrentToken && CurrentToken->is(tok::less)) {
621 CurrentToken->Type = TT_TemplateOpener;
626 CurrentToken->Previous->ClosesTemplateDeclaration = true;
632 bool consumeToken() {
633 FormatToken *Tok = CurrentToken;
635 switch (Tok->Tok.getKind()) {
638 if (!Tok->Previous && Line.MustBeDeclaration)
639 Tok->Type = TT_ObjCMethodSpecifier;
644 // Colons from ?: are handled in parseConditional().
645 if (Style.Language == FormatStyle::LK_JavaScript) {
646 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
647 (Contexts.size() == 1 && // switch/case labels
648 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
649 Contexts.back().ContextKind == tok::l_paren || // function params
650 Contexts.back().ContextKind == tok::l_square || // array type
651 (!Contexts.back().IsExpression &&
652 Contexts.back().ContextKind == tok::l_brace) || // object type
653 (Contexts.size() == 1 &&
654 Line.MustBeDeclaration)) { // method/property declaration
655 Contexts.back().IsExpression = false;
656 Tok->Type = TT_JsTypeColon;
660 if (Contexts.back().ColonIsDictLiteral ||
661 Style.Language == FormatStyle::LK_Proto ||
662 Style.Language == FormatStyle::LK_TextProto) {
663 Tok->Type = TT_DictLiteral;
664 if (Style.Language == FormatStyle::LK_TextProto) {
665 if (FormatToken *Previous = Tok->getPreviousNonComment())
666 Previous->Type = TT_SelectorName;
668 } else if (Contexts.back().ColonIsObjCMethodExpr ||
669 Line.startsWith(TT_ObjCMethodSpecifier)) {
670 Tok->Type = TT_ObjCMethodExpr;
671 const FormatToken *BeforePrevious = Tok->Previous->Previous;
672 if (!BeforePrevious ||
673 !(BeforePrevious->is(TT_CastRParen) ||
674 (BeforePrevious->is(TT_ObjCMethodExpr) &&
675 BeforePrevious->is(tok::colon))) ||
676 BeforePrevious->is(tok::r_square) ||
677 Contexts.back().LongestObjCSelectorName == 0) {
678 Tok->Previous->Type = TT_SelectorName;
679 if (!Contexts.back().FirstObjCSelectorName)
680 Contexts.back().FirstObjCSelectorName = Tok->Previous;
681 else if (Tok->Previous->ColumnWidth >
682 Contexts.back().LongestObjCSelectorName)
683 Contexts.back().LongestObjCSelectorName =
684 Tok->Previous->ColumnWidth;
686 } else if (Contexts.back().ColonIsForRangeExpr) {
687 Tok->Type = TT_RangeBasedForLoopColon;
688 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
689 Tok->Type = TT_BitFieldColon;
690 } else if (Contexts.size() == 1 &&
691 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
692 if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren,
694 Tok->Type = TT_CtorInitializerColon;
696 Tok->Type = TT_InheritanceColon;
697 } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
698 Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
699 // This handles a special macro in ObjC code where selectors including
700 // the colon are passed as macro arguments.
701 Tok->Type = TT_ObjCMethodExpr;
702 } else if (Contexts.back().ContextKind == tok::l_paren) {
703 Tok->Type = TT_InlineASMColon;
708 // | and & in declarations/type expressions represent union and
709 // intersection types, respectively.
710 if (Style.Language == FormatStyle::LK_JavaScript &&
711 !Contexts.back().IsExpression)
712 Tok->Type = TT_JsTypeOperator;
716 if (Tok->is(tok::kw_if) && CurrentToken &&
717 CurrentToken->is(tok::kw_constexpr))
719 if (CurrentToken && CurrentToken->is(tok::l_paren)) {
721 if (!parseParens(/*LookForDecls=*/true))
726 if (Style.Language == FormatStyle::LK_JavaScript) {
727 // x.for and {for: ...}
728 if ((Tok->Previous && Tok->Previous->is(tok::period)) ||
729 (Tok->Next && Tok->Next->is(tok::colon)))
731 // JS' for await ( ...
732 if (CurrentToken && CurrentToken->is(Keywords.kw_await))
735 Contexts.back().ColonIsForRangeExpr = true;
741 // When faced with 'operator()()', the kw_operator handler incorrectly
742 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
743 // the first two parens OverloadedOperators and the second l_paren an
744 // OverloadedOperatorLParen.
745 if (Tok->Previous && Tok->Previous->is(tok::r_paren) &&
746 Tok->Previous->MatchingParen &&
747 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
748 Tok->Previous->Type = TT_OverloadedOperator;
749 Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
750 Tok->Type = TT_OverloadedOperatorLParen;
755 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
756 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
758 !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
759 TT_LeadingJavaAnnotation)))
760 Line.MightBeFunctionDecl = true;
767 if (Style.Language == FormatStyle::LK_TextProto) {
768 FormatToken *Previous = Tok->getPreviousNonComment();
769 if (Previous && Previous->Type != TT_DictLiteral)
770 Previous->Type = TT_SelectorName;
777 Tok->Type = TT_TemplateOpener;
778 // In TT_Proto, we must distignuish between:
780 // msg < item: data >
781 // msg: < item: data >
782 // In TT_TextProto, map<key, value> does not occur.
783 if (Style.Language == FormatStyle::LK_TextProto ||
784 (Style.Language == FormatStyle::LK_Proto && Tok->Previous &&
785 Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) {
786 Tok->Type = TT_DictLiteral;
787 FormatToken *Previous = Tok->getPreviousNonComment();
788 if (Previous && Previous->Type != TT_DictLiteral)
789 Previous->Type = TT_SelectorName;
792 Tok->Type = TT_BinaryOperator;
793 NonTemplateLess.insert(Tok);
802 // Lines can start with '}'.
807 if (Style.Language != FormatStyle::LK_TextProto)
808 Tok->Type = TT_BinaryOperator;
810 case tok::kw_operator:
811 if (Style.Language == FormatStyle::LK_TextProto ||
812 Style.Language == FormatStyle::LK_Proto)
814 while (CurrentToken &&
815 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
816 if (CurrentToken->isOneOf(tok::star, tok::amp))
817 CurrentToken->Type = TT_PointerOrReference;
820 CurrentToken->Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator,
822 CurrentToken->Previous->Type = TT_OverloadedOperator;
825 CurrentToken->Type = TT_OverloadedOperatorLParen;
826 if (CurrentToken->Previous->is(TT_BinaryOperator))
827 CurrentToken->Previous->Type = TT_OverloadedOperator;
831 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
832 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
834 // Question marks before semicolons, colons, etc. indicate optional
835 // types (fields, parameters), e.g.
836 // function(x?: string, y?) {...}
838 Tok->Type = TT_JsTypeOptionalQuestion;
841 // Declarations cannot be conditional expressions, this can only be part
842 // of a type declaration.
843 if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
844 Style.Language == FormatStyle::LK_JavaScript)
848 case tok::kw_template:
849 parseTemplateDeclaration();
852 if (Contexts.back().InCtorInitializer)
853 Tok->Type = TT_CtorInitializerComma;
854 else if (Contexts.back().InInheritanceList)
855 Tok->Type = TT_InheritanceComma;
856 else if (Contexts.back().FirstStartOfName &&
857 (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
858 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
859 Line.IsMultiVariableDeclStmt = true;
861 if (Contexts.back().IsForEachMacro)
862 Contexts.back().IsExpression = true;
864 case tok::identifier:
865 if (Tok->isOneOf(Keywords.kw___has_include,
866 Keywords.kw___has_include_next)) {
876 void parseIncludeDirective() {
877 if (CurrentToken && CurrentToken->is(tok::less)) {
879 while (CurrentToken) {
880 // Mark tokens up to the trailing line comments as implicit string
882 if (CurrentToken->isNot(tok::comment) &&
883 !CurrentToken->TokenText.startswith("//"))
884 CurrentToken->Type = TT_ImplicitStringLiteral;
890 void parseWarningOrError() {
892 // We still want to format the whitespace left of the first token of the
895 while (CurrentToken) {
896 CurrentToken->Type = TT_ImplicitStringLiteral;
902 next(); // Consume "pragma".
904 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
905 bool IsMark = CurrentToken->is(Keywords.kw_mark);
906 next(); // Consume "mark".
907 next(); // Consume first token (so we fix leading whitespace).
908 while (CurrentToken) {
909 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
910 CurrentToken->Type = TT_ImplicitStringLiteral;
916 void parseHasInclude() {
917 if (!CurrentToken || !CurrentToken->is(tok::l_paren))
920 parseIncludeDirective();
924 LineType parsePreprocessorDirective() {
925 bool IsFirstToken = CurrentToken->IsFirst;
926 LineType Type = LT_PreprocessorDirective;
931 if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
932 // JavaScript files can contain shebang lines of the form:
933 // #!/usr/bin/env node
934 // Treat these like C++ #include directives.
935 while (CurrentToken) {
936 // Tokens cannot be comments here.
937 CurrentToken->Type = TT_ImplicitStringLiteral;
940 return LT_ImportStatement;
943 if (CurrentToken->Tok.is(tok::numeric_constant)) {
944 CurrentToken->SpacesRequiredBefore = 1;
947 // Hashes in the middle of a line can lead to any strange token
949 if (!CurrentToken->Tok.getIdentifierInfo())
951 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
952 case tok::pp_include:
953 case tok::pp_include_next:
956 parseIncludeDirective();
957 Type = LT_ImportStatement;
960 case tok::pp_warning:
961 parseWarningOrError();
968 Contexts.back().IsExpression = true;
974 while (CurrentToken) {
975 FormatToken *Tok = CurrentToken;
977 if (Tok->is(tok::l_paren))
979 else if (Tok->isOneOf(Keywords.kw___has_include,
980 Keywords.kw___has_include_next))
987 LineType parseLine() {
988 NonTemplateLess.clear();
989 if (CurrentToken->is(tok::hash))
990 return parsePreprocessorDirective();
992 // Directly allow to 'import <string-literal>' to support protocol buffer
993 // definitions (github.com/google/protobuf) or missing "#" (either way we
994 // should not break the line).
995 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
996 if ((Style.Language == FormatStyle::LK_Java &&
997 CurrentToken->is(Keywords.kw_package)) ||
998 (Info && Info->getPPKeywordID() == tok::pp_import &&
999 CurrentToken->Next &&
1000 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
1003 parseIncludeDirective();
1004 return LT_ImportStatement;
1007 // If this line starts and ends in '<' and '>', respectively, it is likely
1008 // part of "#define <a/b.h>".
1009 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
1010 parseIncludeDirective();
1011 return LT_ImportStatement;
1014 // In .proto files, top-level options are very similar to import statements
1015 // and should not be line-wrapped.
1016 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
1017 CurrentToken->is(Keywords.kw_option)) {
1019 if (CurrentToken && CurrentToken->is(tok::identifier))
1020 return LT_ImportStatement;
1023 bool KeywordVirtualFound = false;
1024 bool ImportStatement = false;
1026 // import {...} from '...';
1027 if (Style.Language == FormatStyle::LK_JavaScript &&
1028 CurrentToken->is(Keywords.kw_import))
1029 ImportStatement = true;
1031 while (CurrentToken) {
1032 if (CurrentToken->is(tok::kw_virtual))
1033 KeywordVirtualFound = true;
1034 if (Style.Language == FormatStyle::LK_JavaScript) {
1035 // export {...} from '...';
1036 // An export followed by "from 'some string';" is a re-export from
1037 // another module identified by a URI and is treated as a
1038 // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
1039 // Just "export {...};" or "export class ..." should not be treated as
1040 // an import in this sense.
1041 if (Line.First->is(tok::kw_export) &&
1042 CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
1043 CurrentToken->Next->isStringLiteral())
1044 ImportStatement = true;
1045 if (isClosureImportStatement(*CurrentToken))
1046 ImportStatement = true;
1048 if (!consumeToken())
1051 if (KeywordVirtualFound)
1052 return LT_VirtualFunctionDecl;
1053 if (ImportStatement)
1054 return LT_ImportStatement;
1056 if (Line.startsWith(TT_ObjCMethodSpecifier)) {
1057 if (Contexts.back().FirstObjCSelectorName)
1058 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
1059 Contexts.back().LongestObjCSelectorName;
1060 return LT_ObjCMethodDecl;
1067 bool isClosureImportStatement(const FormatToken &Tok) {
1068 // FIXME: Closure-library specific stuff should not be hard-coded but be
1070 return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
1072 (Tok.Next->Next->TokenText == "module" ||
1073 Tok.Next->Next->TokenText == "provide" ||
1074 Tok.Next->Next->TokenText == "require" ||
1075 Tok.Next->Next->TokenText == "forwardDeclare") &&
1076 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
1079 void resetTokenMetadata(FormatToken *Token) {
1083 // Reset token type in case we have already looked at it and then
1084 // recovered from an error (e.g. failure to find the matching >).
1085 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
1086 TT_FunctionLBrace, TT_ImplicitStringLiteral,
1087 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
1088 TT_OverloadedOperator, TT_RegexLiteral,
1089 TT_TemplateString, TT_ObjCStringLiteral))
1090 CurrentToken->Type = TT_Unknown;
1091 CurrentToken->Role.reset();
1092 CurrentToken->MatchingParen = nullptr;
1093 CurrentToken->FakeLParens.clear();
1094 CurrentToken->FakeRParens = 0;
1099 CurrentToken->NestingLevel = Contexts.size() - 1;
1100 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
1101 modifyContext(*CurrentToken);
1102 determineTokenType(*CurrentToken);
1103 CurrentToken = CurrentToken->Next;
1106 resetTokenMetadata(CurrentToken);
1109 /// \brief A struct to hold information valid in a specific context, e.g.
1110 /// a pair of parenthesis.
1112 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
1114 : ContextKind(ContextKind), BindingStrength(BindingStrength),
1115 IsExpression(IsExpression) {}
1117 tok::TokenKind ContextKind;
1118 unsigned BindingStrength;
1120 unsigned LongestObjCSelectorName = 0;
1121 bool ColonIsForRangeExpr = false;
1122 bool ColonIsDictLiteral = false;
1123 bool ColonIsObjCMethodExpr = false;
1124 FormatToken *FirstObjCSelectorName = nullptr;
1125 FormatToken *FirstStartOfName = nullptr;
1126 bool CanBeExpression = true;
1127 bool InTemplateArgument = false;
1128 bool InCtorInitializer = false;
1129 bool InInheritanceList = false;
1130 bool CaretFound = false;
1131 bool IsForEachMacro = false;
1132 bool InCpp11AttributeSpecifier = false;
1135 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
1136 /// of each instance.
1137 struct ScopedContextCreator {
1138 AnnotatingParser &P;
1140 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
1143 P.Contexts.push_back(Context(ContextKind,
1144 P.Contexts.back().BindingStrength + Increase,
1145 P.Contexts.back().IsExpression));
1148 ~ScopedContextCreator() { P.Contexts.pop_back(); }
1151 void modifyContext(const FormatToken &Current) {
1152 if (Current.getPrecedence() == prec::Assignment &&
1153 !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
1154 // Type aliases use `type X = ...;` in TypeScript and can be exported
1155 // using `export type ...`.
1156 !(Style.Language == FormatStyle::LK_JavaScript &&
1157 (Line.startsWith(Keywords.kw_type, tok::identifier) ||
1158 Line.startsWith(tok::kw_export, Keywords.kw_type,
1159 tok::identifier))) &&
1160 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
1161 Contexts.back().IsExpression = true;
1162 if (!Line.startsWith(TT_UnaryOperator)) {
1163 for (FormatToken *Previous = Current.Previous;
1164 Previous && Previous->Previous &&
1165 !Previous->Previous->isOneOf(tok::comma, tok::semi);
1166 Previous = Previous->Previous) {
1167 if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
1168 Previous = Previous->MatchingParen;
1172 if (Previous->opensScope())
1174 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
1175 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
1176 Previous->Previous && Previous->Previous->isNot(tok::equal))
1177 Previous->Type = TT_PointerOrReference;
1180 } else if (Current.is(tok::lessless) &&
1181 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
1182 Contexts.back().IsExpression = true;
1183 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
1184 Contexts.back().IsExpression = true;
1185 } else if (Current.is(TT_TrailingReturnArrow)) {
1186 Contexts.back().IsExpression = false;
1187 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
1188 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
1189 } else if (Current.Previous &&
1190 Current.Previous->is(TT_CtorInitializerColon)) {
1191 Contexts.back().IsExpression = true;
1192 Contexts.back().InCtorInitializer = true;
1193 } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
1194 Contexts.back().InInheritanceList = true;
1195 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
1196 for (FormatToken *Previous = Current.Previous;
1197 Previous && Previous->isOneOf(tok::star, tok::amp);
1198 Previous = Previous->Previous)
1199 Previous->Type = TT_PointerOrReference;
1200 if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
1201 Contexts.back().IsExpression = false;
1202 } else if (Current.is(tok::kw_new)) {
1203 Contexts.back().CanBeExpression = false;
1204 } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
1205 // This should be the condition or increment in a for-loop.
1206 Contexts.back().IsExpression = true;
1210 void determineTokenType(FormatToken &Current) {
1211 if (!Current.is(TT_Unknown))
1212 // The token type is already known.
1215 if (Style.Language == FormatStyle::LK_JavaScript) {
1216 if (Current.is(tok::exclaim)) {
1217 if (Current.Previous &&
1218 (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace,
1219 tok::r_paren, tok::r_square,
1221 Current.Previous->Tok.isLiteral())) {
1222 Current.Type = TT_JsNonNullAssertion;
1226 Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
1227 Current.Type = TT_JsNonNullAssertion;
1233 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1234 // function declaration have been found. In this case, 'Current' is a
1235 // trailing token of this declaration and thus cannot be a name.
1236 if (Current.is(Keywords.kw_instanceof)) {
1237 Current.Type = TT_BinaryOperator;
1238 } else if (isStartOfName(Current) &&
1239 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
1240 Contexts.back().FirstStartOfName = &Current;
1241 Current.Type = TT_StartOfName;
1242 } else if (Current.is(tok::semi)) {
1243 // Reset FirstStartOfName after finding a semicolon so that a for loop
1244 // with multiple increment statements is not confused with a for loop
1245 // having multiple variable declarations.
1246 Contexts.back().FirstStartOfName = nullptr;
1247 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
1249 } else if (Current.is(tok::arrow) &&
1250 Style.Language == FormatStyle::LK_Java) {
1251 Current.Type = TT_LambdaArrow;
1252 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
1253 Current.NestingLevel == 0) {
1254 Current.Type = TT_TrailingReturnArrow;
1255 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
1256 Current.Type = determineStarAmpUsage(Current,
1257 Contexts.back().CanBeExpression &&
1258 Contexts.back().IsExpression,
1259 Contexts.back().InTemplateArgument);
1260 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
1261 Current.Type = determinePlusMinusCaretUsage(Current);
1262 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
1263 Contexts.back().CaretFound = true;
1264 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
1265 Current.Type = determineIncrementUsage(Current);
1266 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
1267 Current.Type = TT_UnaryOperator;
1268 } else if (Current.is(tok::question)) {
1269 if (Style.Language == FormatStyle::LK_JavaScript &&
1270 Line.MustBeDeclaration && !Contexts.back().IsExpression) {
1271 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
1272 // on the interface, not a ternary expression.
1273 Current.Type = TT_JsTypeOptionalQuestion;
1275 Current.Type = TT_ConditionalExpr;
1277 } else if (Current.isBinaryOperator() &&
1278 (!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
1279 (!Current.is(tok::greater) &&
1280 Style.Language != FormatStyle::LK_TextProto)) {
1281 Current.Type = TT_BinaryOperator;
1282 } else if (Current.is(tok::comment)) {
1283 if (Current.TokenText.startswith("/*")) {
1284 if (Current.TokenText.endswith("*/"))
1285 Current.Type = TT_BlockComment;
1287 // The lexer has for some reason determined a comment here. But we
1288 // cannot really handle it, if it isn't properly terminated.
1289 Current.Tok.setKind(tok::unknown);
1291 Current.Type = TT_LineComment;
1293 } else if (Current.is(tok::r_paren)) {
1294 if (rParenEndsCast(Current))
1295 Current.Type = TT_CastRParen;
1296 if (Current.MatchingParen && Current.Next &&
1297 !Current.Next->isBinaryOperator() &&
1298 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1299 tok::comma, tok::period, tok::arrow,
1301 if (FormatToken *AfterParen = Current.MatchingParen->Next) {
1302 // Make sure this isn't the return type of an Obj-C block declaration
1303 if (AfterParen->Tok.isNot(tok::caret)) {
1304 if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1305 if (BeforeParen->is(tok::identifier) &&
1306 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1307 (!BeforeParen->Previous ||
1308 BeforeParen->Previous->ClosesTemplateDeclaration))
1309 Current.Type = TT_FunctionAnnotationRParen;
1312 } else if (Current.is(tok::at) && Current.Next &&
1313 Style.Language != FormatStyle::LK_JavaScript &&
1314 Style.Language != FormatStyle::LK_Java) {
1315 // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
1316 // marks declarations and properties that need special formatting.
1317 switch (Current.Next->Tok.getObjCKeywordID()) {
1318 case tok::objc_interface:
1319 case tok::objc_implementation:
1320 case tok::objc_protocol:
1321 Current.Type = TT_ObjCDecl;
1323 case tok::objc_property:
1324 Current.Type = TT_ObjCProperty;
1329 } else if (Current.is(tok::period)) {
1330 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1331 if (PreviousNoComment &&
1332 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1333 Current.Type = TT_DesignatedInitializerPeriod;
1334 else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1335 Current.Previous->isOneOf(TT_JavaAnnotation,
1336 TT_LeadingJavaAnnotation)) {
1337 Current.Type = Current.Previous->Type;
1339 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
1341 !Current.Previous->isOneOf(tok::equal, tok::at) &&
1342 Line.MightBeFunctionDecl && Contexts.size() == 1) {
1343 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1344 // function declaration have been found.
1345 Current.Type = TT_TrailingAnnotation;
1346 } else if ((Style.Language == FormatStyle::LK_Java ||
1347 Style.Language == FormatStyle::LK_JavaScript) &&
1349 if (Current.Previous->is(tok::at) &&
1350 Current.isNot(Keywords.kw_interface)) {
1351 const FormatToken &AtToken = *Current.Previous;
1352 const FormatToken *Previous = AtToken.getPreviousNonComment();
1353 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1354 Current.Type = TT_LeadingJavaAnnotation;
1356 Current.Type = TT_JavaAnnotation;
1357 } else if (Current.Previous->is(tok::period) &&
1358 Current.Previous->isOneOf(TT_JavaAnnotation,
1359 TT_LeadingJavaAnnotation)) {
1360 Current.Type = Current.Previous->Type;
1365 /// \brief Take a guess at whether \p Tok starts a name of a function or
1366 /// variable declaration.
1368 /// This is a heuristic based on whether \p Tok is an identifier following
1369 /// something that is likely a type.
1370 bool isStartOfName(const FormatToken &Tok) {
1371 if (Tok.isNot(tok::identifier) || !Tok.Previous)
1374 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
1377 if (Style.Language == FormatStyle::LK_JavaScript &&
1378 Tok.Previous->is(Keywords.kw_in))
1381 // Skip "const" as it does not have an influence on whether this is a name.
1382 FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
1383 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1384 PreviousNotConst = PreviousNotConst->getPreviousNonComment();
1386 if (!PreviousNotConst)
1389 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1390 PreviousNotConst->Previous &&
1391 PreviousNotConst->Previous->is(tok::hash);
1393 if (PreviousNotConst->is(TT_TemplateCloser))
1394 return PreviousNotConst && PreviousNotConst->MatchingParen &&
1395 PreviousNotConst->MatchingParen->Previous &&
1396 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1397 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1399 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1400 PreviousNotConst->MatchingParen->Previous &&
1401 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1404 return (!IsPPKeyword &&
1405 PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1406 PreviousNotConst->is(TT_PointerOrReference) ||
1407 PreviousNotConst->isSimpleTypeSpecifier();
1410 /// \brief Determine whether ')' is ending a cast.
1411 bool rParenEndsCast(const FormatToken &Tok) {
1412 // C-style casts are only used in C++ and Java.
1413 if (!Style.isCpp() && Style.Language != FormatStyle::LK_Java)
1416 // Empty parens aren't casts and there are no casts at the end of the line.
1417 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1420 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1422 // If there is a closing parenthesis left of the current parentheses,
1423 // look past it as these might be chained casts.
1424 if (LeftOfParens->is(tok::r_paren)) {
1425 if (!LeftOfParens->MatchingParen ||
1426 !LeftOfParens->MatchingParen->Previous)
1428 LeftOfParens = LeftOfParens->MatchingParen->Previous;
1431 // If there is an identifier (or with a few exceptions a keyword) right
1432 // before the parentheses, this is unlikely to be a cast.
1433 if (LeftOfParens->Tok.getIdentifierInfo() &&
1434 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1438 // Certain other tokens right before the parentheses are also signals that
1439 // this cannot be a cast.
1440 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1441 TT_TemplateCloser, tok::ellipsis))
1445 if (Tok.Next->is(tok::question))
1448 // As Java has no function types, a "(" after the ")" likely means that this
1450 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1453 // If a (non-string) literal follows, this is likely a cast.
1454 if (Tok.Next->isNot(tok::string_literal) &&
1455 (Tok.Next->Tok.isLiteral() ||
1456 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1459 // Heuristically try to determine whether the parentheses contain a type.
1460 bool ParensAreType =
1462 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1463 Tok.Previous->isSimpleTypeSpecifier();
1464 bool ParensCouldEndDecl =
1465 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1466 if (ParensAreType && !ParensCouldEndDecl)
1469 // At this point, we heuristically assume that there are no casts at the
1470 // start of the line. We assume that we have found most cases where there
1471 // are by the logic above, e.g. "(void)x;".
1475 // Certain token types inside the parentheses mean that this can't be a
1477 for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
1478 Token = Token->Next)
1479 if (Token->is(TT_BinaryOperator))
1482 // If the following token is an identifier or 'this', this is a cast. All
1483 // cases where this can be something else are handled above.
1484 if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
1487 if (!Tok.Next->Next)
1490 // If the next token after the parenthesis is a unary operator, assume
1491 // that this is cast, unless there are unexpected tokens inside the
1494 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1495 if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1496 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1498 // Search for unexpected tokens.
1499 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1500 Prev = Prev->Previous) {
1501 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1507 /// \brief Return the type of the given token assuming it is * or &.
1508 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1509 bool InTemplateArgument) {
1510 if (Style.Language == FormatStyle::LK_JavaScript)
1511 return TT_BinaryOperator;
1513 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1515 return TT_UnaryOperator;
1517 const FormatToken *NextToken = Tok.getNextNonComment();
1519 NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const) ||
1520 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1521 return TT_PointerOrReference;
1523 if (PrevToken->is(tok::coloncolon))
1524 return TT_PointerOrReference;
1526 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1527 tok::comma, tok::semi, tok::kw_return, tok::colon,
1528 tok::equal, tok::kw_delete, tok::kw_sizeof,
1530 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1531 TT_UnaryOperator, TT_CastRParen))
1532 return TT_UnaryOperator;
1534 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1535 return TT_PointerOrReference;
1536 if (NextToken->is(tok::kw_operator) && !IsExpression)
1537 return TT_PointerOrReference;
1538 if (NextToken->isOneOf(tok::comma, tok::semi))
1539 return TT_PointerOrReference;
1541 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen) {
1542 FormatToken *TokenBeforeMatchingParen =
1543 PrevToken->MatchingParen->getPreviousNonComment();
1544 if (TokenBeforeMatchingParen &&
1545 TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
1546 return TT_PointerOrReference;
1549 if (PrevToken->Tok.isLiteral() ||
1550 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1551 tok::kw_false, tok::r_brace) ||
1552 NextToken->Tok.isLiteral() ||
1553 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1554 NextToken->isUnaryOperator() ||
1555 // If we know we're in a template argument, there are no named
1556 // declarations. Thus, having an identifier on the right-hand side
1557 // indicates a binary operator.
1558 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1559 return TT_BinaryOperator;
1561 // "&&(" is quite unlikely to be two successive unary "&".
1562 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1563 return TT_BinaryOperator;
1565 // This catches some cases where evaluation order is used as control flow:
1567 const FormatToken *NextNextToken = NextToken->getNextNonComment();
1568 if (NextNextToken && NextNextToken->is(tok::arrow))
1569 return TT_BinaryOperator;
1571 // It is very unlikely that we are going to find a pointer or reference type
1572 // definition on the RHS of an assignment.
1573 if (IsExpression && !Contexts.back().CaretFound)
1574 return TT_BinaryOperator;
1576 return TT_PointerOrReference;
1579 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1580 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1582 return TT_UnaryOperator;
1584 if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
1585 // This must be a sequence of leading unary operators.
1586 return TT_UnaryOperator;
1588 // Use heuristics to recognize unary operators.
1589 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1590 tok::question, tok::colon, tok::kw_return,
1591 tok::kw_case, tok::at, tok::l_brace))
1592 return TT_UnaryOperator;
1594 // There can't be two consecutive binary operators.
1595 if (PrevToken->is(TT_BinaryOperator))
1596 return TT_UnaryOperator;
1598 // Fall back to marking the token as binary operator.
1599 return TT_BinaryOperator;
1602 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1603 TokenType determineIncrementUsage(const FormatToken &Tok) {
1604 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1605 if (!PrevToken || PrevToken->is(TT_CastRParen))
1606 return TT_UnaryOperator;
1607 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1608 return TT_TrailingUnaryOperator;
1610 return TT_UnaryOperator;
1613 SmallVector<Context, 8> Contexts;
1615 const FormatStyle &Style;
1616 AnnotatedLine &Line;
1617 FormatToken *CurrentToken;
1619 const AdditionalKeywords &Keywords;
1621 // Set of "<" tokens that do not open a template parameter list. If parseAngle
1622 // determines that a specific token can't be a template opener, it will make
1623 // same decision irrespective of the decisions for tokens leading up to it.
1624 // Store this information to prevent this from causing exponential runtime.
1625 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1628 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1629 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1631 /// \brief Parses binary expressions by inserting fake parenthesis based on
1632 /// operator precedence.
1633 class ExpressionParser {
1635 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1636 AnnotatedLine &Line)
1637 : Style(Style), Keywords(Keywords), Current(Line.First) {}
1639 /// \brief Parse expressions with the given operator precedence.
1640 void parse(int Precedence = 0) {
1641 // Skip 'return' and ObjC selector colons as they are not part of a binary
1643 while (Current && (Current->is(tok::kw_return) ||
1644 (Current->is(tok::colon) &&
1645 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1648 if (!Current || Precedence > PrecedenceArrowAndPeriod)
1651 // Conditional expressions need to be parsed separately for proper nesting.
1652 if (Precedence == prec::Conditional) {
1653 parseConditionalExpr();
1657 // Parse unary operators, which all have a higher precedence than binary
1659 if (Precedence == PrecedenceUnaryOperator) {
1660 parseUnaryOperator();
1664 FormatToken *Start = Current;
1665 FormatToken *LatestOperator = nullptr;
1666 unsigned OperatorIndex = 0;
1669 // Consume operators with higher precedence.
1670 parse(Precedence + 1);
1672 int CurrentPrecedence = getCurrentPrecedence();
1674 if (Current && Current->is(TT_SelectorName) &&
1675 Precedence == CurrentPrecedence) {
1677 addFakeParenthesis(Start, prec::Level(Precedence));
1681 // At the end of the line or when an operator with higher precedence is
1682 // found, insert fake parenthesis and return.
1684 (Current->closesScope() &&
1685 (Current->MatchingParen || Current->is(TT_TemplateString))) ||
1686 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1687 (CurrentPrecedence == prec::Conditional &&
1688 Precedence == prec::Assignment && Current->is(tok::colon))) {
1692 // Consume scopes: (), [], <> and {}
1693 if (Current->opensScope()) {
1694 // In fragment of a JavaScript template string can look like '}..${' and
1695 // thus close a scope and open a new one at the same time.
1696 while (Current && (!Current->closesScope() || Current->opensScope())) {
1703 if (CurrentPrecedence == Precedence) {
1705 LatestOperator->NextOperator = Current;
1706 LatestOperator = Current;
1707 Current->OperatorIndex = OperatorIndex;
1710 next(/*SkipPastLeadingComments=*/Precedence > 0);
1714 if (LatestOperator && (Current || Precedence > 0)) {
1715 // LatestOperator->LastOperator = true;
1716 if (Precedence == PrecedenceArrowAndPeriod) {
1717 // Call expressions don't have a binary operator precedence.
1718 addFakeParenthesis(Start, prec::Unknown);
1720 addFakeParenthesis(Start, prec::Level(Precedence));
1726 /// \brief Gets the precedence (+1) of the given token for binary operators
1727 /// and other tokens that we treat like binary operators.
1728 int getCurrentPrecedence() {
1730 const FormatToken *NextNonComment = Current->getNextNonComment();
1731 if (Current->is(TT_ConditionalExpr))
1732 return prec::Conditional;
1733 if (NextNonComment && Current->is(TT_SelectorName) &&
1734 (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
1735 ((Style.Language == FormatStyle::LK_Proto ||
1736 Style.Language == FormatStyle::LK_TextProto) &&
1737 NextNonComment->is(tok::less))))
1738 return prec::Assignment;
1739 if (Current->is(TT_JsComputedPropertyName))
1740 return prec::Assignment;
1741 if (Current->is(TT_LambdaArrow))
1743 if (Current->is(TT_JsFatArrow))
1744 return prec::Assignment;
1745 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
1746 (Current->is(tok::comment) && NextNonComment &&
1747 NextNonComment->is(TT_SelectorName)))
1749 if (Current->is(TT_RangeBasedForLoopColon))
1751 if ((Style.Language == FormatStyle::LK_Java ||
1752 Style.Language == FormatStyle::LK_JavaScript) &&
1753 Current->is(Keywords.kw_instanceof))
1754 return prec::Relational;
1755 if (Style.Language == FormatStyle::LK_JavaScript &&
1756 Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
1757 return prec::Relational;
1758 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1759 return Current->getPrecedence();
1760 if (Current->isOneOf(tok::period, tok::arrow))
1761 return PrecedenceArrowAndPeriod;
1762 if ((Style.Language == FormatStyle::LK_Java ||
1763 Style.Language == FormatStyle::LK_JavaScript) &&
1764 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1765 Keywords.kw_throws))
1771 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1772 Start->FakeLParens.push_back(Precedence);
1773 if (Precedence > prec::Unknown)
1774 Start->StartsBinaryExpression = true;
1776 FormatToken *Previous = Current->Previous;
1777 while (Previous->is(tok::comment) && Previous->Previous)
1778 Previous = Previous->Previous;
1779 ++Previous->FakeRParens;
1780 if (Precedence > prec::Unknown)
1781 Previous->EndsBinaryExpression = true;
1785 /// \brief Parse unary operator expressions and surround them with fake
1786 /// parentheses if appropriate.
1787 void parseUnaryOperator() {
1788 llvm::SmallVector<FormatToken *, 2> Tokens;
1789 while (Current && Current->is(TT_UnaryOperator)) {
1790 Tokens.push_back(Current);
1793 parse(PrecedenceArrowAndPeriod);
1794 for (FormatToken *Token : llvm::reverse(Tokens))
1795 // The actual precedence doesn't matter.
1796 addFakeParenthesis(Token, prec::Unknown);
1799 void parseConditionalExpr() {
1800 while (Current && Current->isTrailingComment()) {
1803 FormatToken *Start = Current;
1804 parse(prec::LogicalOr);
1805 if (!Current || !Current->is(tok::question))
1808 parse(prec::Assignment);
1809 if (!Current || Current->isNot(TT_ConditionalExpr))
1812 parse(prec::Assignment);
1813 addFakeParenthesis(Start, prec::Conditional);
1816 void next(bool SkipPastLeadingComments = true) {
1818 Current = Current->Next;
1820 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1821 Current->isTrailingComment())
1822 Current = Current->Next;
1825 const FormatStyle &Style;
1826 const AdditionalKeywords &Keywords;
1827 FormatToken *Current;
1830 } // end anonymous namespace
1832 void TokenAnnotator::setCommentLineLevels(
1833 SmallVectorImpl<AnnotatedLine *> &Lines) {
1834 const AnnotatedLine *NextNonCommentLine = nullptr;
1835 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1838 bool CommentLine = true;
1839 for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
1840 if (!Tok->is(tok::comment)) {
1841 CommentLine = false;
1846 // If the comment is currently aligned with the line immediately following
1847 // it, that's probably intentional and we should keep it.
1848 if (NextNonCommentLine && CommentLine &&
1849 NextNonCommentLine->First->NewlinesBefore <= 1 &&
1850 NextNonCommentLine->First->OriginalColumn ==
1851 (*I)->First->OriginalColumn) {
1852 // Align comments for preprocessor lines with the # in column 0.
1853 // Otherwise, align with the next line.
1854 (*I)->Level = (NextNonCommentLine->Type == LT_PreprocessorDirective ||
1855 NextNonCommentLine->Type == LT_ImportStatement)
1857 : NextNonCommentLine->Level;
1859 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1862 setCommentLineLevels((*I)->Children);
1866 static unsigned maxNestingDepth(const AnnotatedLine &Line) {
1867 unsigned Result = 0;
1868 for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
1869 Result = std::max(Result, Tok->NestingLevel);
1873 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1874 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1875 E = Line.Children.end();
1879 AnnotatingParser Parser(Style, Line, Keywords);
1880 Line.Type = Parser.parseLine();
1882 // With very deep nesting, ExpressionParser uses lots of stack and the
1883 // formatting algorithm is very slow. We're not going to do a good job here
1884 // anyway - it's probably generated code being formatted by mistake.
1885 // Just skip the whole line.
1886 if (maxNestingDepth(Line) > 50)
1887 Line.Type = LT_Invalid;
1889 if (Line.Type == LT_Invalid)
1892 ExpressionParser ExprParser(Style, Keywords, Line);
1895 if (Line.startsWith(TT_ObjCMethodSpecifier))
1896 Line.Type = LT_ObjCMethodDecl;
1897 else if (Line.startsWith(TT_ObjCDecl))
1898 Line.Type = LT_ObjCDecl;
1899 else if (Line.startsWith(TT_ObjCProperty))
1900 Line.Type = LT_ObjCProperty;
1902 Line.First->SpacesRequiredBefore = 1;
1903 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1906 // This function heuristically determines whether 'Current' starts the name of a
1907 // function declaration.
1908 static bool isFunctionDeclarationName(const FormatToken &Current,
1909 const AnnotatedLine &Line) {
1910 auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
1911 for (; Next; Next = Next->Next) {
1912 if (Next->is(TT_OverloadedOperatorLParen))
1914 if (Next->is(TT_OverloadedOperator))
1916 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1917 // For 'new[]' and 'delete[]'.
1918 if (Next->Next && Next->Next->is(tok::l_square) && Next->Next->Next &&
1919 Next->Next->Next->is(tok::r_square))
1920 Next = Next->Next->Next;
1929 // Find parentheses of parameter list.
1930 const FormatToken *Next = Current.Next;
1931 if (Current.is(tok::kw_operator)) {
1932 if (Current.Previous && Current.Previous->is(tok::coloncolon))
1934 Next = skipOperatorName(Next);
1936 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1938 for (; Next; Next = Next->Next) {
1939 if (Next->is(TT_TemplateOpener)) {
1940 Next = Next->MatchingParen;
1941 } else if (Next->is(tok::coloncolon)) {
1945 if (Next->is(tok::kw_operator)) {
1946 Next = skipOperatorName(Next->Next);
1949 if (!Next->is(tok::identifier))
1951 } else if (Next->is(tok::l_paren)) {
1959 // Check whether parameter list can belong to a function declaration.
1960 if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
1962 // If the lines ends with "{", this is likely an function definition.
1963 if (Line.Last->is(tok::l_brace))
1965 if (Next->Next == Next->MatchingParen)
1966 return true; // Empty parentheses.
1967 // If there is an &/&& after the r_paren, this is likely a function.
1968 if (Next->MatchingParen->Next &&
1969 Next->MatchingParen->Next->is(TT_PointerOrReference))
1971 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1973 if (Tok->is(tok::l_paren) && Tok->MatchingParen) {
1974 Tok = Tok->MatchingParen;
1977 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1978 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
1980 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1981 Tok->Tok.isLiteral())
1987 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
1988 assert(Line.MightBeFunctionDecl);
1990 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
1991 Style.AlwaysBreakAfterReturnType ==
1992 FormatStyle::RTBS_TopLevelDefinitions) &&
1996 switch (Style.AlwaysBreakAfterReturnType) {
1997 case FormatStyle::RTBS_None:
1999 case FormatStyle::RTBS_All:
2000 case FormatStyle::RTBS_TopLevel:
2002 case FormatStyle::RTBS_AllDefinitions:
2003 case FormatStyle::RTBS_TopLevelDefinitions:
2004 return Line.mightBeFunctionDefinition();
2010 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
2011 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
2012 E = Line.Children.end();
2014 calculateFormattingInformation(**I);
2017 Line.First->TotalLength =
2018 Line.First->IsMultiline ? Style.ColumnLimit
2019 : Line.FirstStartColumn + Line.First->ColumnWidth;
2020 FormatToken *Current = Line.First->Next;
2021 bool InFunctionDecl = Line.MightBeFunctionDecl;
2023 if (isFunctionDeclarationName(*Current, Line))
2024 Current->Type = TT_FunctionDeclarationName;
2025 if (Current->is(TT_LineComment)) {
2026 if (Current->Previous->BlockKind == BK_BracedInit &&
2027 Current->Previous->opensScope())
2028 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
2030 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
2032 // If we find a trailing comment, iterate backwards to determine whether
2033 // it seems to relate to a specific parameter. If so, break before that
2034 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
2035 // to the previous line in:
2039 if (!Current->HasUnescapedNewline) {
2040 for (FormatToken *Parameter = Current->Previous; Parameter;
2041 Parameter = Parameter->Previous) {
2042 if (Parameter->isOneOf(tok::comment, tok::r_brace))
2044 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
2045 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
2046 Parameter->HasUnescapedNewline)
2047 Parameter->MustBreakBefore = true;
2052 } else if (Current->SpacesRequiredBefore == 0 &&
2053 spaceRequiredBefore(Line, *Current)) {
2054 Current->SpacesRequiredBefore = 1;
2057 Current->MustBreakBefore =
2058 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
2060 if (!Current->MustBreakBefore && InFunctionDecl &&
2061 Current->is(TT_FunctionDeclarationName))
2062 Current->MustBreakBefore = mustBreakForReturnType(Line);
2064 Current->CanBreakBefore =
2065 Current->MustBreakBefore || canBreakBefore(Line, *Current);
2066 unsigned ChildSize = 0;
2067 if (Current->Previous->Children.size() == 1) {
2068 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
2069 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
2070 : LastOfChild.TotalLength + 1;
2072 const FormatToken *Prev = Current->Previous;
2073 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
2074 (Prev->Children.size() == 1 &&
2075 Prev->Children[0]->First->MustBreakBefore) ||
2076 Current->IsMultiline)
2077 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
2079 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
2080 ChildSize + Current->SpacesRequiredBefore;
2082 if (Current->is(TT_CtorInitializerColon))
2083 InFunctionDecl = false;
2085 // FIXME: Only calculate this if CanBreakBefore is true once static
2086 // initializers etc. are sorted out.
2087 // FIXME: Move magic numbers to a better place.
2088 Current->SplitPenalty = 20 * Current->BindingStrength +
2089 splitPenalty(Line, *Current, InFunctionDecl);
2091 Current = Current->Next;
2094 calculateUnbreakableTailLengths(Line);
2095 unsigned IndentLevel = Line.Level;
2096 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
2098 Current->Role->precomputeFormattingInfos(Current);
2099 if (Current->MatchingParen &&
2100 Current->MatchingParen->opensBlockOrBlockTypeList(Style)) {
2101 assert(IndentLevel > 0);
2104 Current->IndentLevel = IndentLevel;
2105 if (Current->opensBlockOrBlockTypeList(Style))
2109 DEBUG({ printDebugInfo(Line); });
2112 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
2113 unsigned UnbreakableTailLength = 0;
2114 FormatToken *Current = Line.Last;
2116 Current->UnbreakableTailLength = UnbreakableTailLength;
2117 if (Current->CanBreakBefore ||
2118 Current->isOneOf(tok::comment, tok::string_literal)) {
2119 UnbreakableTailLength = 0;
2121 UnbreakableTailLength +=
2122 Current->ColumnWidth + Current->SpacesRequiredBefore;
2124 Current = Current->Previous;
2128 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
2129 const FormatToken &Tok,
2130 bool InFunctionDecl) {
2131 const FormatToken &Left = *Tok.Previous;
2132 const FormatToken &Right = Tok;
2134 if (Left.is(tok::semi))
2137 if (Style.Language == FormatStyle::LK_Java) {
2138 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
2140 if (Right.is(Keywords.kw_implements))
2142 if (Left.is(tok::comma) && Left.NestingLevel == 0)
2144 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2145 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
2147 if (Left.is(TT_JsTypeColon))
2149 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2150 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2152 // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
2153 if (Left.opensScope() && Right.closesScope())
2157 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2159 if (Right.is(tok::l_square)) {
2160 if (Style.Language == FormatStyle::LK_Proto)
2162 if (Left.is(tok::r_square))
2164 // Slightly prefer formatting local lambda definitions like functions.
2165 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
2167 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2168 TT_ArrayInitializerLSquare,
2169 TT_DesignatedInitializerLSquare, TT_AttributeSquare))
2173 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2174 Right.is(tok::kw_operator)) {
2175 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
2177 if (Left.is(TT_StartOfName))
2179 if (InFunctionDecl && Right.NestingLevel == 0)
2180 return Style.PenaltyReturnTypeOnItsOwnLine;
2183 if (Right.is(TT_PointerOrReference))
2185 if (Right.is(TT_LambdaArrow))
2187 if (Left.is(tok::equal) && Right.is(tok::l_brace))
2189 if (Left.is(TT_CastRParen))
2191 if (Left.is(tok::coloncolon) ||
2192 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
2194 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
2196 if (Left.is(tok::comment))
2199 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
2200 TT_CtorInitializerColon))
2203 if (Right.isMemberAccess()) {
2204 // Breaking before the "./->" of a chained call/member access is reasonably
2205 // cheap, as formatting those with one call per line is generally
2206 // desirable. In particular, it should be cheaper to break before the call
2207 // than it is to break inside a call's parameters, which could lead to weird
2208 // "hanging" indents. The exception is the very last "./->" to support this
2209 // frequent pattern:
2211 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
2214 // which might otherwise be blown up onto many lines. Here, clang-format
2215 // won't produce "hanging" indents anyway as there is no other trailing
2218 // Also apply higher penalty is not a call as that might lead to a wrapping
2222 // .aaaaaaaaa.bbbbbbbb(cccccccc);
2223 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
2228 if (Right.is(TT_TrailingAnnotation) &&
2229 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
2230 // Moving trailing annotations to the next line is fine for ObjC method
2232 if (Line.startsWith(TT_ObjCMethodSpecifier))
2234 // Generally, breaking before a trailing annotation is bad unless it is
2235 // function-like. It seems to be especially preferable to keep standard
2236 // annotations (i.e. "const", "final" and "override") on the same line.
2237 // Use a slightly higher penalty after ")" so that annotations like
2238 // "const override" are kept together.
2239 bool is_short_annotation = Right.TokenText.size() < 10;
2240 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
2243 // In for-loops, prefer breaking at ',' and ';'.
2244 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
2247 // In Objective-C method expressions, prefer breaking before "param:" over
2248 // breaking after it.
2249 if (Right.is(TT_SelectorName))
2251 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
2252 return Line.MightBeFunctionDecl ? 50 : 500;
2254 if (Left.is(tok::l_paren) && InFunctionDecl &&
2255 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
2257 if (Left.is(tok::l_paren) && Left.Previous &&
2258 (Left.Previous->isOneOf(tok::kw_if, tok::kw_for) ||
2259 Left.Previous->endsSequence(tok::kw_constexpr, tok::kw_if)))
2261 if (Left.is(tok::equal) && InFunctionDecl)
2263 if (Right.is(tok::r_brace))
2265 if (Left.is(TT_TemplateOpener))
2267 if (Left.opensScope()) {
2268 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
2270 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
2273 if (Left.is(TT_JavaAnnotation))
2276 if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
2277 Left.Previous->isLabelString() &&
2278 (Left.NextOperator || Left.OperatorIndex != 0))
2280 if (Right.is(tok::plus) && Left.isLabelString() &&
2281 (Right.NextOperator || Right.OperatorIndex != 0))
2283 if (Left.is(tok::comma))
2285 if (Right.is(tok::lessless) && Left.isLabelString() &&
2286 (Right.NextOperator || Right.OperatorIndex != 1))
2288 if (Right.is(tok::lessless)) {
2289 // Breaking at a << is really cheap.
2290 if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
2291 // Slightly prefer to break before the first one in log-like statements.
2295 if (Left.is(TT_ConditionalExpr))
2296 return prec::Conditional;
2297 prec::Level Level = Left.getPrecedence();
2298 if (Level == prec::Unknown)
2299 Level = Right.getPrecedence();
2300 if (Level == prec::Assignment)
2301 return Style.PenaltyBreakAssignment;
2302 if (Level != prec::Unknown)
2308 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
2309 const FormatToken &Left,
2310 const FormatToken &Right) {
2311 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
2313 if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
2315 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
2316 Left.Tok.getObjCKeywordID() == tok::objc_property)
2318 if (Right.is(tok::hashhash))
2319 return Left.is(tok::hash);
2320 if (Left.isOneOf(tok::hashhash, tok::hash))
2321 return Right.is(tok::hash);
2322 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
2323 return Style.SpaceInEmptyParentheses;
2324 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
2325 return (Right.is(TT_CastRParen) ||
2326 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
2327 ? Style.SpacesInCStyleCastParentheses
2328 : Style.SpacesInParentheses;
2329 if (Right.isOneOf(tok::semi, tok::comma))
2331 if (Right.is(tok::less) && Line.Type == LT_ObjCDecl &&
2332 Style.ObjCSpaceBeforeProtocolList)
2334 if (Right.is(tok::less) && Left.is(tok::kw_template))
2335 return Style.SpaceAfterTemplateKeyword;
2336 if (Left.isOneOf(tok::exclaim, tok::tilde))
2338 if (Left.is(tok::at) &&
2339 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
2340 tok::numeric_constant, tok::l_paren, tok::l_brace,
2341 tok::kw_true, tok::kw_false))
2343 if (Left.is(tok::colon))
2344 return !Left.is(TT_ObjCMethodExpr);
2345 if (Left.is(tok::coloncolon))
2347 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
2348 if (Style.Language == FormatStyle::LK_TextProto ||
2349 (Style.Language == FormatStyle::LK_Proto &&
2350 (Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
2351 // Format empty list as `<>`.
2352 if (Left.is(tok::less) && Right.is(tok::greater))
2354 return !Style.Cpp11BracedListStyle;
2358 if (Right.is(tok::ellipsis))
2359 return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
2360 Left.Previous->is(tok::kw_case));
2361 if (Left.is(tok::l_square) && Right.is(tok::amp))
2363 if (Right.is(TT_PointerOrReference)) {
2364 if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
2365 if (!Left.MatchingParen)
2367 FormatToken *TokenBeforeMatchingParen =
2368 Left.MatchingParen->getPreviousNonComment();
2369 if (!TokenBeforeMatchingParen ||
2370 !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
2373 return (Left.Tok.isLiteral() ||
2374 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
2375 (Style.PointerAlignment != FormatStyle::PAS_Left ||
2376 (Line.IsMultiVariableDeclStmt &&
2377 (Left.NestingLevel == 0 ||
2378 (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
2380 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
2381 (!Left.is(TT_PointerOrReference) ||
2382 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2383 !Line.IsMultiVariableDeclStmt)))
2385 if (Left.is(TT_PointerOrReference))
2386 return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
2387 (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
2388 !Right.is(TT_StartOfName)) ||
2389 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
2390 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
2392 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2393 !Line.IsMultiVariableDeclStmt) &&
2395 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
2396 if (Right.is(tok::star) && Left.is(tok::l_paren))
2398 const auto SpaceRequiredForArrayInitializerLSquare =
2399 [](const FormatToken &LSquareTok, const FormatStyle &Style) {
2400 return Style.SpacesInContainerLiterals ||
2401 ((Style.Language == FormatStyle::LK_Proto ||
2402 Style.Language == FormatStyle::LK_TextProto) &&
2403 !Style.Cpp11BracedListStyle &&
2404 LSquareTok.endsSequence(tok::l_square, tok::colon,
2407 if (Left.is(tok::l_square))
2408 return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) &&
2409 SpaceRequiredForArrayInitializerLSquare(Left, Style)) ||
2410 (Left.isOneOf(TT_ArraySubscriptLSquare,
2411 TT_StructuredBindingLSquare) &&
2412 Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
2413 if (Right.is(tok::r_square))
2414 return Right.MatchingParen &&
2415 ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
2416 SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
2418 (Style.SpacesInSquareBrackets &&
2419 Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
2420 TT_StructuredBindingLSquare)) ||
2421 Right.MatchingParen->is(TT_AttributeParen));
2422 if (Right.is(tok::l_square) &&
2423 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2424 TT_DesignatedInitializerLSquare,
2425 TT_StructuredBindingLSquare, TT_AttributeSquare) &&
2426 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
2428 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
2429 return !Left.Children.empty(); // No spaces in "{}".
2430 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
2431 (Right.is(tok::r_brace) && Right.MatchingParen &&
2432 Right.MatchingParen->BlockKind != BK_Block))
2433 return !Style.Cpp11BracedListStyle;
2434 if (Left.is(TT_BlockComment))
2435 return !Left.TokenText.endswith("=*/");
2436 if (Right.is(tok::l_paren)) {
2437 if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) ||
2438 (Left.is(tok::r_square) && Left.is(TT_AttributeSquare)))
2440 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
2441 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
2442 (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
2443 tok::kw_switch, tok::kw_case, TT_ForEachMacro,
2445 Left.endsSequence(tok::kw_constexpr, tok::kw_if) ||
2446 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
2447 tok::kw_new, tok::kw_delete) &&
2448 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
2449 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
2450 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
2451 Left.is(tok::r_paren)) &&
2452 Line.Type != LT_PreprocessorDirective);
2454 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
2456 if (Right.is(TT_UnaryOperator))
2457 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
2458 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
2459 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
2461 Left.isSimpleTypeSpecifier()) &&
2462 Right.is(tok::l_brace) && Right.getNextNonComment() &&
2463 Right.BlockKind != BK_Block)
2465 if (Left.is(tok::period) || Right.is(tok::period))
2467 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
2469 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
2470 Left.MatchingParen->Previous &&
2471 Left.MatchingParen->Previous->is(tok::period))
2472 // A.<B<C<...>>>DoSomething();
2474 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
2479 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
2480 const FormatToken &Right) {
2481 const FormatToken &Left = *Right.Previous;
2482 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
2483 return true; // Never ever merge two identifiers.
2484 if (Style.isCpp()) {
2485 if (Left.is(tok::kw_operator))
2486 return Right.is(tok::coloncolon);
2487 } else if (Style.Language == FormatStyle::LK_Proto ||
2488 Style.Language == FormatStyle::LK_TextProto) {
2489 if (Right.is(tok::period) &&
2490 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2491 Keywords.kw_repeated, Keywords.kw_extend))
2493 if (Right.is(tok::l_paren) &&
2494 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2496 if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
2498 // Slashes occur in text protocol extension syntax: [type/type] { ... }.
2499 if (Left.is(tok::slash) || Right.is(tok::slash))
2501 if (Left.MatchingParen && Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
2502 Right.isOneOf(tok::l_brace, tok::less))
2503 return !Style.Cpp11BracedListStyle;
2504 // A percent is probably part of a formatting specification, such as %lld.
2505 if (Left.is(tok::percent))
2507 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2508 if (Left.is(TT_JsFatArrow))
2511 if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
2512 Left.Previous->is(tok::kw_for))
2514 if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
2515 Right.MatchingParen) {
2516 const FormatToken *Next = Right.MatchingParen->getNextNonComment();
2517 // An async arrow function, for example: `x = async () => foo();`,
2518 // as opposed to calling a function called async: `x = async();`
2519 if (Next && Next->is(TT_JsFatArrow))
2522 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2523 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2525 // In tagged template literals ("html`bar baz`"), there is no space between
2526 // the tag identifier and the template string. getIdentifierInfo makes sure
2527 // that the identifier is not a pseudo keyword like `yield`, either.
2528 if (Left.is(tok::identifier) && Keywords.IsJavaScriptIdentifier(Left) &&
2529 Right.is(TT_TemplateString))
2531 if (Right.is(tok::star) &&
2532 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2534 if (Right.isOneOf(tok::l_brace, tok::l_square) &&
2535 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
2536 Keywords.kw_extends, Keywords.kw_implements))
2538 if (Right.is(tok::l_paren)) {
2539 // JS methods can use some keywords as names (e.g. `delete()`).
2540 if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
2542 // Valid JS method names can include keywords, e.g. `foo.delete()` or
2543 // `bar.instanceof()`. Recognize call positions by preceding period.
2544 if (Left.Previous && Left.Previous->is(tok::period) &&
2545 Left.Tok.getIdentifierInfo())
2547 // Additional unary JavaScript operators that need a space after.
2548 if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
2552 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
2554 // "of" is only a keyword if it appears after another identifier
2555 // (e.g. as "const x of y" in a for loop), or after a destructuring
2556 // operation (const [x, y] of z, const {a, b} of c).
2557 (Left.is(Keywords.kw_of) && Left.Previous &&
2558 (Left.Previous->Tok.is(tok::identifier) ||
2559 Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) &&
2560 (!Left.Previous || !Left.Previous->is(tok::period)))
2562 if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
2563 Left.Previous->is(tok::period) && Right.is(tok::l_paren))
2565 if (Left.is(Keywords.kw_as) &&
2566 Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
2568 if (Left.is(tok::kw_default) && Left.Previous &&
2569 Left.Previous->is(tok::kw_export))
2571 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2573 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2575 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
2577 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2578 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2580 if (Left.is(tok::ellipsis))
2582 if (Left.is(TT_TemplateCloser) &&
2583 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2584 Keywords.kw_implements, Keywords.kw_extends))
2585 // Type assertions ('<type>expr') are not followed by whitespace. Other
2586 // locations that should have whitespace following are identified by the
2587 // above set of follower tokens.
2589 if (Right.is(TT_JsNonNullAssertion))
2591 if (Left.is(TT_JsNonNullAssertion) &&
2592 Right.isOneOf(Keywords.kw_as, Keywords.kw_in))
2593 return true; // "x! as string", "x! in y"
2594 } else if (Style.Language == FormatStyle::LK_Java) {
2595 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2597 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2598 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2599 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2600 tok::kw_protected) ||
2601 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2602 Keywords.kw_native)) &&
2603 Right.is(TT_TemplateOpener))
2606 if (Left.is(TT_ImplicitStringLiteral))
2607 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2608 if (Line.Type == LT_ObjCMethodDecl) {
2609 if (Left.is(TT_ObjCMethodSpecifier))
2611 if (Left.is(tok::r_paren) && Right.is(tok::identifier))
2612 // Don't space between ')' and <id>
2615 if (Line.Type == LT_ObjCProperty &&
2616 (Right.is(tok::equal) || Left.is(tok::equal)))
2619 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2620 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2622 if (Right.is(TT_OverloadedOperatorLParen))
2623 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2624 if (Left.is(tok::comma))
2626 if (Right.is(tok::comma))
2628 if (Right.is(TT_ObjCBlockLParen))
2630 if (Right.is(TT_CtorInitializerColon))
2631 return Style.SpaceBeforeCtorInitializerColon;
2632 if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
2634 if (Right.is(TT_RangeBasedForLoopColon) &&
2635 !Style.SpaceBeforeRangeBasedForLoopColon)
2637 if (Right.is(tok::colon)) {
2638 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2639 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2641 if (Right.is(TT_ObjCMethodExpr))
2643 if (Left.is(tok::question))
2645 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2647 if (Right.is(TT_DictLiteral))
2648 return Style.SpacesInContainerLiterals;
2649 if (Right.is(TT_AttributeColon))
2653 if (Left.is(TT_UnaryOperator))
2654 return Right.is(TT_BinaryOperator);
2656 // If the next token is a binary operator or a selector name, we have
2657 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2658 if (Left.is(TT_CastRParen))
2659 return Style.SpaceAfterCStyleCast ||
2660 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2662 if (Left.is(tok::greater) && Right.is(tok::greater)) {
2663 if (Style.Language == FormatStyle::LK_TextProto ||
2664 (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral)))
2665 return !Style.Cpp11BracedListStyle;
2666 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2667 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2669 if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
2670 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2671 (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod)))
2673 if (!Style.SpaceBeforeAssignmentOperators &&
2674 Right.getPrecedence() == prec::Assignment)
2676 if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
2677 // Generally don't remove existing spaces between an identifier and "::".
2678 // The identifier might actually be a macro name such as ALWAYS_INLINE. If
2679 // this turns out to be too lenient, add analysis of the identifier itself.
2680 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2681 if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
2682 return (Left.is(TT_TemplateOpener) &&
2683 Style.Standard == FormatStyle::LS_Cpp03) ||
2684 !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
2685 tok::kw___super, TT_TemplateCloser,
2686 TT_TemplateOpener));
2687 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2688 return Style.SpacesInAngles;
2689 // Space before TT_StructuredBindingLSquare.
2690 if (Right.is(TT_StructuredBindingLSquare))
2691 return !Left.isOneOf(tok::amp, tok::ampamp) ||
2692 Style.PointerAlignment != FormatStyle::PAS_Right;
2693 // Space before & or && following a TT_StructuredBindingLSquare.
2694 if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
2695 Right.isOneOf(tok::amp, tok::ampamp))
2696 return Style.PointerAlignment != FormatStyle::PAS_Left;
2697 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2698 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2699 !Right.is(tok::r_paren)))
2701 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2702 Right.isNot(TT_FunctionTypeLParen))
2703 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2704 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2705 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2707 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2708 Line.startsWith(tok::hash))
2710 if (Right.is(TT_TrailingUnaryOperator))
2712 if (Left.is(TT_RegexLiteral))
2714 return spaceRequiredBetween(Line, Left, Right);
2717 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2718 static bool isAllmanBrace(const FormatToken &Tok) {
2719 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2720 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2723 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2724 const FormatToken &Right) {
2725 const FormatToken &Left = *Right.Previous;
2726 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2729 if (Style.Language == FormatStyle::LK_JavaScript) {
2730 // FIXME: This might apply to other languages and token kinds.
2731 if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
2732 Left.Previous->is(tok::string_literal))
2734 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2735 Left.Previous && Left.Previous->is(tok::equal) &&
2736 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2738 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2740 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2741 // Object literals on the top level of a file are treated as "enum-style".
2742 // Each key/value pair is put on a separate line, instead of bin-packing.
2744 if (Left.is(tok::l_brace) && Line.Level == 0 &&
2745 (Line.startsWith(tok::kw_enum) ||
2746 Line.startsWith(tok::kw_const, tok::kw_enum) ||
2747 Line.startsWith(tok::kw_export, tok::kw_enum) ||
2748 Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
2749 // JavaScript top-level enum key/value pairs are put on separate lines
2750 // instead of bin-packing.
2752 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2753 !Left.Children.empty())
2754 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2755 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2756 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2757 (Left.NestingLevel == 0 && Line.Level == 0 &&
2758 Style.AllowShortFunctionsOnASingleLine &
2759 FormatStyle::SFS_InlineOnly);
2760 } else if (Style.Language == FormatStyle::LK_Java) {
2761 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2762 Right.Next->is(tok::string_literal))
2764 } else if (Style.Language == FormatStyle::LK_Cpp ||
2765 Style.Language == FormatStyle::LK_ObjC ||
2766 Style.Language == FormatStyle::LK_Proto ||
2767 Style.Language == FormatStyle::LK_TextProto) {
2768 if (Left.isStringLiteral() && Right.isStringLiteral())
2772 // If the last token before a '}', ']', or ')' is a comma or a trailing
2773 // comment, the intention is to insert a line break after it in order to make
2774 // shuffling around entries easier. Import statements, especially in
2775 // JavaScript, can be an exception to this rule.
2776 if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
2777 const FormatToken *BeforeClosingBrace = nullptr;
2778 if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
2779 (Style.Language == FormatStyle::LK_JavaScript &&
2780 Left.is(tok::l_paren))) &&
2781 Left.BlockKind != BK_Block && Left.MatchingParen)
2782 BeforeClosingBrace = Left.MatchingParen->Previous;
2783 else if (Right.MatchingParen &&
2784 (Right.MatchingParen->isOneOf(tok::l_brace,
2785 TT_ArrayInitializerLSquare) ||
2786 (Style.Language == FormatStyle::LK_JavaScript &&
2787 Right.MatchingParen->is(tok::l_paren))))
2788 BeforeClosingBrace = &Left;
2789 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2790 BeforeClosingBrace->isTrailingComment()))
2794 if (Right.is(tok::comment))
2795 return Left.BlockKind != BK_BracedInit &&
2796 Left.isNot(TT_CtorInitializerColon) &&
2797 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2798 if (Left.isTrailingComment())
2800 if (Right.Previous->IsUnterminatedLiteral)
2802 if (Right.is(tok::lessless) && Right.Next &&
2803 Right.Previous->is(tok::string_literal) &&
2804 Right.Next->is(tok::string_literal))
2806 if (Right.Previous->ClosesTemplateDeclaration &&
2807 Right.Previous->MatchingParen &&
2808 Right.Previous->MatchingParen->NestingLevel == 0 &&
2809 Style.AlwaysBreakTemplateDeclarations)
2811 if (Right.is(TT_CtorInitializerComma) &&
2812 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
2813 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2815 if (Right.is(TT_CtorInitializerColon) &&
2816 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
2817 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2819 // Break only if we have multiple inheritance.
2820 if (Style.BreakBeforeInheritanceComma && Right.is(TT_InheritanceComma))
2822 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2823 // Raw string literals are special wrt. line breaks. The author has made a
2824 // deliberate choice and might have aligned the contents of the string
2825 // literal accordingly. Thus, we try keep existing line breaks.
2826 return Right.NewlinesBefore > 0;
2827 if ((Right.Previous->is(tok::l_brace) ||
2828 (Right.Previous->is(tok::less) && Right.Previous->Previous &&
2829 Right.Previous->Previous->is(tok::equal))) &&
2830 Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
2831 // Don't put enums or option definitions onto single lines in protocol
2835 if (Right.is(TT_InlineASMBrace))
2836 return Right.HasUnescapedNewline;
2837 if (isAllmanBrace(Left) || isAllmanBrace(Right))
2838 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2839 (Line.startsWith(tok::kw_typedef, tok::kw_enum) &&
2840 Style.BraceWrapping.AfterEnum) ||
2841 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2842 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2843 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2846 if ((Style.Language == FormatStyle::LK_Java ||
2847 Style.Language == FormatStyle::LK_JavaScript) &&
2848 Left.is(TT_LeadingJavaAnnotation) &&
2849 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2850 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2853 if (Right.is(TT_ProtoExtensionLSquare))
2859 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2860 const FormatToken &Right) {
2861 const FormatToken &Left = *Right.Previous;
2863 // Language-specific stuff.
2864 if (Style.Language == FormatStyle::LK_Java) {
2865 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2866 Keywords.kw_implements))
2868 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2869 Keywords.kw_implements))
2871 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2872 const FormatToken *NonComment = Right.getPreviousNonComment();
2874 NonComment->isOneOf(
2875 tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
2876 tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
2877 tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected,
2878 Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
2879 Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
2880 return false; // Otherwise automatic semicolon insertion would trigger.
2881 if (Right.NestingLevel == 0 &&
2882 (Left.Tok.getIdentifierInfo() ||
2883 Left.isOneOf(tok::r_square, tok::r_paren)) &&
2884 Right.isOneOf(tok::l_square, tok::l_paren))
2885 return false; // Otherwise automatic semicolon insertion would trigger.
2886 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2888 if (Left.is(TT_JsTypeColon))
2890 if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is))
2892 if (Left.is(Keywords.kw_in))
2893 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
2894 if (Right.is(Keywords.kw_in))
2895 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
2896 if (Right.is(Keywords.kw_as))
2897 return false; // must not break before as in 'x as type' casts
2898 if (Left.is(Keywords.kw_as))
2900 if (Left.is(TT_JsNonNullAssertion))
2902 if (Left.is(Keywords.kw_declare) &&
2903 Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
2904 Keywords.kw_function, tok::kw_class, tok::kw_enum,
2905 Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
2906 Keywords.kw_let, tok::kw_const))
2907 // See grammar for 'declare' statements at:
2908 // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10
2910 if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
2911 Right.isOneOf(tok::identifier, tok::string_literal))
2912 return false; // must not break in "module foo { ...}"
2913 if (Right.is(TT_TemplateString) && Right.closesScope())
2915 if (Left.is(TT_TemplateString) && Left.opensScope())
2919 if (Left.is(tok::at))
2921 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2923 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2924 return !Right.is(tok::l_paren);
2925 if (Right.is(TT_PointerOrReference))
2926 return Line.IsMultiVariableDeclStmt ||
2927 (Style.PointerAlignment == FormatStyle::PAS_Right &&
2928 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2929 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2930 Right.is(tok::kw_operator))
2932 if (Left.is(TT_PointerOrReference))
2934 if (Right.isTrailingComment())
2935 // We rely on MustBreakBefore being set correctly here as we should not
2936 // change the "binding" behavior of a comment.
2937 // The first comment in a braced lists is always interpreted as belonging to
2938 // the first list element. Otherwise, it should be placed outside of the
2940 return Left.BlockKind == BK_BracedInit ||
2941 (Left.is(TT_CtorInitializerColon) &&
2942 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
2943 if (Left.is(tok::question) && Right.is(tok::colon))
2945 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2946 return Style.BreakBeforeTernaryOperators;
2947 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2948 return !Style.BreakBeforeTernaryOperators;
2949 if (Right.is(TT_InheritanceColon))
2951 if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
2952 Left.isNot(TT_SelectorName))
2955 if (Right.is(tok::colon) &&
2956 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2958 if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
2959 if ((Style.Language == FormatStyle::LK_Proto ||
2960 Style.Language == FormatStyle::LK_TextProto) &&
2961 !Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
2965 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2966 Right.Next->is(TT_ObjCMethodExpr)))
2967 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2968 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2970 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
2972 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2973 TT_OverloadedOperator))
2975 if (Left.is(TT_RangeBasedForLoopColon))
2977 if (Right.is(TT_RangeBasedForLoopColon))
2979 if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
2981 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2982 Left.is(tok::kw_operator))
2984 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2985 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
2987 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2989 if (Left.is(tok::l_paren) && Left.Previous &&
2990 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2992 if (Right.is(TT_ImplicitStringLiteral))
2995 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2997 if (Right.is(tok::r_square) && Right.MatchingParen &&
2998 Right.MatchingParen->is(TT_LambdaLSquare))
3001 // We only break before r_brace if there was a corresponding break before
3002 // the l_brace, which is tracked by BreakBeforeClosingBrace.
3003 if (Right.is(tok::r_brace))
3004 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
3006 // Allow breaking after a trailing annotation, e.g. after a method
3008 if (Left.is(TT_TrailingAnnotation))
3009 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
3010 tok::less, tok::coloncolon);
3012 if (Right.is(tok::kw___attribute) ||
3013 (Right.is(tok::l_square) && Right.is(TT_AttributeSquare)))
3016 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
3019 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
3022 if (Left.is(TT_CtorInitializerColon))
3023 return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
3024 if (Right.is(TT_CtorInitializerColon))
3025 return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon;
3026 if (Left.is(TT_CtorInitializerComma) &&
3027 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
3029 if (Right.is(TT_CtorInitializerComma) &&
3030 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
3032 if (Left.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma)
3034 if (Right.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma)
3036 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
3037 (Left.is(tok::less) && Right.is(tok::less)))
3039 if (Right.is(TT_BinaryOperator) &&
3040 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
3041 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
3042 Right.getPrecedence() != prec::Assignment))
3044 if (Left.is(TT_ArrayInitializerLSquare))
3046 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
3048 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
3049 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
3050 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
3051 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
3052 Left.getPrecedence() == prec::Assignment))
3054 if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) ||
3055 (Left.is(tok::r_square) && Right.is(TT_AttributeSquare)))
3057 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
3058 tok::kw_class, tok::kw_struct, tok::comment) ||
3059 Right.isMemberAccess() ||
3060 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
3061 tok::colon, tok::l_square, tok::at) ||
3062 (Left.is(tok::r_paren) &&
3063 Right.isOneOf(tok::identifier, tok::kw_const)) ||
3064 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
3065 (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
3068 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
3069 llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
3070 const FormatToken *Tok = Line.First;
3072 llvm::errs() << " M=" << Tok->MustBreakBefore
3073 << " C=" << Tok->CanBreakBefore
3074 << " T=" << getTokenTypeName(Tok->Type)
3075 << " S=" << Tok->SpacesRequiredBefore
3076 << " B=" << Tok->BlockParameterCount
3077 << " BK=" << Tok->BlockKind << " P=" << Tok->SplitPenalty
3078 << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
3079 << " PPK=" << Tok->PackingKind << " FakeLParens=";
3080 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
3081 llvm::errs() << Tok->FakeLParens[i] << "/";
3082 llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
3083 llvm::errs() << " Text='" << Tok->TokenText << "'\n";
3085 assert(Tok == Line.Last);
3088 llvm::errs() << "----\n";
3091 } // namespace format
3092 } // namespace clang