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 CurrentToken->Type = TT_TemplateCloser;
86 if (CurrentToken->is(tok::question) &&
87 Style.Language == FormatStyle::LK_Java) {
91 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) ||
92 (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext &&
93 Style.Language != FormatStyle::LK_Proto &&
94 Style.Language != FormatStyle::LK_TextProto))
96 // If a && or || is found and interpreted as a binary operator, this set
97 // of angles is likely part of something like "a < b && c > d". If the
98 // angles are inside an expression, the ||/&& might also be a binary
99 // operator that was misinterpreted because we are parsing template
101 // FIXME: This is getting out of hand, write a decent parser.
102 if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
103 CurrentToken->Previous->is(TT_BinaryOperator) &&
104 Contexts[Contexts.size() - 2].IsExpression &&
105 !Line.startsWith(tok::kw_template))
107 updateParameterCount(Left, CurrentToken);
108 if (Style.Language == FormatStyle::LK_Proto) {
109 if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
110 if (CurrentToken->is(tok::colon) ||
111 (CurrentToken->isOneOf(tok::l_brace, tok::less) &&
112 Previous->isNot(tok::colon)))
113 Previous->Type = TT_SelectorName;
122 bool parseParens(bool LookForDecls = false) {
125 FormatToken *Left = CurrentToken->Previous;
126 Left->ParentBracket = Contexts.back().ContextKind;
127 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
129 // FIXME: This is a bit of a hack. Do better.
130 Contexts.back().ColonIsForRangeExpr =
131 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
133 bool StartsObjCMethodExpr = false;
134 if (CurrentToken->is(tok::caret)) {
135 // (^ can start a block type.
136 Left->Type = TT_ObjCBlockLParen;
137 } else if (FormatToken *MaybeSel = Left->Previous) {
138 // @selector( starts a selector.
139 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
140 MaybeSel->Previous->is(tok::at)) {
141 StartsObjCMethodExpr = true;
145 if (Left->is(TT_OverloadedOperatorLParen)) {
146 Contexts.back().IsExpression = false;
147 } else if (Style.Language == FormatStyle::LK_JavaScript &&
148 (Line.startsWith(Keywords.kw_type, tok::identifier) ||
149 Line.startsWith(tok::kw_export, Keywords.kw_type,
152 // export type X = (...);
153 Contexts.back().IsExpression = false;
154 } else if (Left->Previous &&
155 (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
156 tok::kw_if, tok::kw_while, tok::l_paren,
158 Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
159 Left->Previous->is(TT_BinaryOperator))) {
160 // static_assert, if and while usually contain expressions.
161 Contexts.back().IsExpression = true;
162 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
163 (Left->Previous->is(Keywords.kw_function) ||
164 (Left->Previous->endsSequence(tok::identifier,
165 Keywords.kw_function)))) {
166 // function(...) or function f(...)
167 Contexts.back().IsExpression = false;
168 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
169 Left->Previous->is(TT_JsTypeColon)) {
170 // let x: (SomeType);
171 Contexts.back().IsExpression = false;
172 } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
173 Left->Previous->MatchingParen &&
174 Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
175 // This is a parameter list of a lambda expression.
176 Contexts.back().IsExpression = false;
177 } else if (Line.InPPDirective &&
178 (!Left->Previous || !Left->Previous->is(tok::identifier))) {
179 Contexts.back().IsExpression = true;
180 } else if (Contexts[Contexts.size() - 2].CaretFound) {
181 // This is the parameter list of an ObjC block.
182 Contexts.back().IsExpression = false;
183 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
184 Left->Type = TT_AttributeParen;
185 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
186 // The first argument to a foreach macro is a declaration.
187 Contexts.back().IsForEachMacro = true;
188 Contexts.back().IsExpression = false;
189 } else if (Left->Previous && Left->Previous->MatchingParen &&
190 Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
191 Contexts.back().IsExpression = false;
192 } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
194 Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
195 Contexts.back().IsExpression = !IsForOrCatch;
198 if (StartsObjCMethodExpr) {
199 Contexts.back().ColonIsObjCMethodExpr = true;
200 Left->Type = TT_ObjCMethodExpr;
203 bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
204 bool ProbablyFunctionType = CurrentToken->isOneOf(tok::star, tok::amp);
205 bool HasMultipleLines = false;
206 bool HasMultipleParametersOnALine = false;
207 bool MightBeObjCForRangeLoop =
208 Left->Previous && Left->Previous->is(tok::kw_for);
209 while (CurrentToken) {
210 // LookForDecls is set when "if (" has been seen. Check for
211 // 'identifier' '*' 'identifier' followed by not '=' -- this
212 // '*' has to be a binary operator but determineStarAmpUsage() will
213 // categorize it as an unary operator, so set the right type here.
214 if (LookForDecls && CurrentToken->Next) {
215 FormatToken *Prev = CurrentToken->getPreviousNonComment();
217 FormatToken *PrevPrev = Prev->getPreviousNonComment();
218 FormatToken *Next = CurrentToken->Next;
219 if (PrevPrev && PrevPrev->is(tok::identifier) &&
220 Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
221 CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
222 Prev->Type = TT_BinaryOperator;
223 LookForDecls = false;
228 if (CurrentToken->Previous->is(TT_PointerOrReference) &&
229 CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
231 ProbablyFunctionType = true;
232 if (CurrentToken->is(tok::comma))
233 MightBeFunctionType = false;
234 if (CurrentToken->Previous->is(TT_BinaryOperator))
235 Contexts.back().IsExpression = true;
236 if (CurrentToken->is(tok::r_paren)) {
237 if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next &&
238 (CurrentToken->Next->is(tok::l_paren) ||
239 (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration)))
240 Left->Type = TT_FunctionTypeLParen;
241 Left->MatchingParen = CurrentToken;
242 CurrentToken->MatchingParen = Left;
244 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
245 Left->Previous && Left->Previous->is(tok::l_paren)) {
246 // Detect the case where macros are used to generate lambdas or
247 // function bodies, e.g.:
248 // auto my_lambda = MARCO((Type *type, int i) { .. body .. });
249 for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
250 if (Tok->is(TT_BinaryOperator) &&
251 Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
252 Tok->Type = TT_PointerOrReference;
256 if (StartsObjCMethodExpr) {
257 CurrentToken->Type = TT_ObjCMethodExpr;
258 if (Contexts.back().FirstObjCSelectorName) {
259 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
260 Contexts.back().LongestObjCSelectorName;
264 if (Left->is(TT_AttributeParen))
265 CurrentToken->Type = TT_AttributeParen;
266 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
267 CurrentToken->Type = TT_JavaAnnotation;
268 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
269 CurrentToken->Type = TT_LeadingJavaAnnotation;
271 if (!HasMultipleLines)
272 Left->PackingKind = PPK_Inconclusive;
273 else if (HasMultipleParametersOnALine)
274 Left->PackingKind = PPK_BinPacked;
276 Left->PackingKind = PPK_OnePerLine;
281 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
284 if (CurrentToken->is(tok::l_brace))
285 Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
286 if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
287 !CurrentToken->Next->HasUnescapedNewline &&
288 !CurrentToken->Next->isTrailingComment())
289 HasMultipleParametersOnALine = true;
290 if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
291 CurrentToken->Previous->isSimpleTypeSpecifier()) &&
292 !CurrentToken->is(tok::l_brace))
293 Contexts.back().IsExpression = false;
294 if (CurrentToken->isOneOf(tok::semi, tok::colon))
295 MightBeObjCForRangeLoop = false;
296 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
297 CurrentToken->Type = TT_ObjCForIn;
298 // When we discover a 'new', we set CanBeExpression to 'false' in order to
299 // parse the type correctly. Reset that after a comma.
300 if (CurrentToken->is(tok::comma))
301 Contexts.back().CanBeExpression = true;
303 FormatToken *Tok = CurrentToken;
306 updateParameterCount(Left, Tok);
307 if (CurrentToken && CurrentToken->HasUnescapedNewline)
308 HasMultipleLines = true;
317 // A '[' could be an index subscript (after an identifier or after
318 // ')' or ']'), it could be the start of an Objective-C method
319 // expression, or it could the start of an Objective-C array literal.
320 FormatToken *Left = CurrentToken->Previous;
321 Left->ParentBracket = Contexts.back().ContextKind;
322 FormatToken *Parent = Left->getPreviousNonComment();
324 // Cases where '>' is followed by '['.
325 // In C++, this can happen either in array of templates (foo<int>[10])
326 // or when array is a nested template type (unique_ptr<type1<type2>[]>).
327 bool CppArrayTemplates =
328 Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
329 (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
330 Contexts.back().InTemplateArgument);
332 bool StartsObjCMethodExpr =
333 !CppArrayTemplates && Style.isCpp() &&
334 Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
335 CurrentToken->isNot(tok::l_brace) &&
337 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
338 tok::kw_return, tok::kw_throw) ||
339 Parent->isUnaryOperator() ||
340 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
341 getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
342 bool ColonFound = false;
344 unsigned BindingIncrease = 1;
345 if (Left->isCppStructuredBinding(Style)) {
346 Left->Type = TT_StructuredBindingLSquare;
347 } else if (Left->is(TT_Unknown)) {
348 if (StartsObjCMethodExpr) {
349 Left->Type = TT_ObjCMethodExpr;
350 } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
351 Contexts.back().ContextKind == tok::l_brace &&
352 Parent->isOneOf(tok::l_brace, tok::comma)) {
353 Left->Type = TT_JsComputedPropertyName;
354 } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace &&
355 Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
356 Left->Type = TT_DesignatedInitializerLSquare;
357 } else if (CurrentToken->is(tok::r_square) && Parent &&
358 Parent->is(TT_TemplateCloser)) {
359 Left->Type = TT_ArraySubscriptLSquare;
360 } else if (Style.Language == FormatStyle::LK_Proto ||
361 (!CppArrayTemplates && Parent &&
362 Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
363 tok::comma, tok::l_paren, tok::l_square,
364 tok::question, tok::colon, tok::kw_return,
365 // Should only be relevant to JavaScript:
367 Left->Type = TT_ArrayInitializerLSquare;
369 BindingIncrease = 10;
370 Left->Type = TT_ArraySubscriptLSquare;
374 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
375 Contexts.back().IsExpression = true;
376 if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
377 Parent->is(TT_JsTypeColon))
378 Contexts.back().IsExpression = false;
380 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
382 while (CurrentToken) {
383 if (CurrentToken->is(tok::r_square)) {
384 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
385 Left->is(TT_ObjCMethodExpr)) {
386 // An ObjC method call is rarely followed by an open parenthesis.
387 // FIXME: Do we incorrectly label ":" with this?
388 StartsObjCMethodExpr = false;
389 Left->Type = TT_Unknown;
391 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
392 CurrentToken->Type = TT_ObjCMethodExpr;
393 // determineStarAmpUsage() thinks that '*' '[' is allocating an
394 // array of pointers, but if '[' starts a selector then '*' is a
396 if (Parent && Parent->is(TT_PointerOrReference))
397 Parent->Type = TT_BinaryOperator;
399 Left->MatchingParen = CurrentToken;
400 CurrentToken->MatchingParen = Left;
401 if (Contexts.back().FirstObjCSelectorName) {
402 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
403 Contexts.back().LongestObjCSelectorName;
404 if (Left->BlockParameterCount > 1)
405 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
410 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
412 if (CurrentToken->is(tok::colon)) {
413 if (Left->isOneOf(TT_ArraySubscriptLSquare,
414 TT_DesignatedInitializerLSquare)) {
415 Left->Type = TT_ObjCMethodExpr;
416 StartsObjCMethodExpr = true;
417 Contexts.back().ColonIsObjCMethodExpr = true;
418 if (Parent && Parent->is(tok::r_paren))
419 Parent->Type = TT_CastRParen;
423 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
425 Left->Type = TT_ArrayInitializerLSquare;
426 FormatToken *Tok = CurrentToken;
429 updateParameterCount(Left, Tok);
436 FormatToken *Left = CurrentToken->Previous;
437 Left->ParentBracket = Contexts.back().ContextKind;
439 if (Contexts.back().CaretFound)
440 Left->Type = TT_ObjCBlockLBrace;
441 Contexts.back().CaretFound = false;
443 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
444 Contexts.back().ColonIsDictLiteral = true;
445 if (Left->BlockKind == BK_BracedInit)
446 Contexts.back().IsExpression = true;
447 if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
448 Left->Previous->is(TT_JsTypeColon))
449 Contexts.back().IsExpression = false;
451 while (CurrentToken) {
452 if (CurrentToken->is(tok::r_brace)) {
453 Left->MatchingParen = CurrentToken;
454 CurrentToken->MatchingParen = Left;
458 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
460 updateParameterCount(Left, CurrentToken);
461 if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
462 FormatToken *Previous = CurrentToken->getPreviousNonComment();
463 if (Previous->is(TT_JsTypeOptionalQuestion))
464 Previous = Previous->getPreviousNonComment();
465 if (((CurrentToken->is(tok::colon) &&
466 (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
467 Style.Language == FormatStyle::LK_Proto ||
468 Style.Language == FormatStyle::LK_TextProto) &&
469 (Previous->Tok.getIdentifierInfo() ||
470 Previous->is(tok::string_literal)))
471 Previous->Type = TT_SelectorName;
472 if (CurrentToken->is(tok::colon) ||
473 Style.Language == FormatStyle::LK_JavaScript)
474 Left->Type = TT_DictLiteral;
476 if (CurrentToken->is(tok::comma) &&
477 Style.Language == FormatStyle::LK_JavaScript)
478 Left->Type = TT_DictLiteral;
486 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
487 if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
488 ++Left->BlockParameterCount;
489 if (Current->is(tok::comma)) {
490 ++Left->ParameterCount;
492 Left->Role.reset(new CommaSeparatedList(Style));
493 Left->Role->CommaFound(Current);
494 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
495 Left->ParameterCount = 1;
499 bool parseConditional() {
500 while (CurrentToken) {
501 if (CurrentToken->is(tok::colon)) {
502 CurrentToken->Type = TT_ConditionalExpr;
512 bool parseTemplateDeclaration() {
513 if (CurrentToken && CurrentToken->is(tok::less)) {
514 CurrentToken->Type = TT_TemplateOpener;
519 CurrentToken->Previous->ClosesTemplateDeclaration = true;
525 bool consumeToken() {
526 FormatToken *Tok = CurrentToken;
528 switch (Tok->Tok.getKind()) {
531 if (!Tok->Previous && Line.MustBeDeclaration)
532 Tok->Type = TT_ObjCMethodSpecifier;
537 // Colons from ?: are handled in parseConditional().
538 if (Style.Language == FormatStyle::LK_JavaScript) {
539 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
540 (Contexts.size() == 1 && // switch/case labels
541 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
542 Contexts.back().ContextKind == tok::l_paren || // function params
543 Contexts.back().ContextKind == tok::l_square || // array type
544 (!Contexts.back().IsExpression &&
545 Contexts.back().ContextKind == tok::l_brace) || // object type
546 (Contexts.size() == 1 &&
547 Line.MustBeDeclaration)) { // method/property declaration
548 Contexts.back().IsExpression = false;
549 Tok->Type = TT_JsTypeColon;
553 if (Contexts.back().ColonIsDictLiteral ||
554 Style.Language == FormatStyle::LK_Proto ||
555 Style.Language == FormatStyle::LK_TextProto) {
556 Tok->Type = TT_DictLiteral;
557 if (Style.Language == FormatStyle::LK_TextProto) {
558 if (FormatToken *Previous = Tok->getPreviousNonComment())
559 Previous->Type = TT_SelectorName;
561 } else if (Contexts.back().ColonIsObjCMethodExpr ||
562 Line.startsWith(TT_ObjCMethodSpecifier)) {
563 Tok->Type = TT_ObjCMethodExpr;
564 const FormatToken *BeforePrevious = Tok->Previous->Previous;
565 if (!BeforePrevious ||
566 !(BeforePrevious->is(TT_CastRParen) ||
567 (BeforePrevious->is(TT_ObjCMethodExpr) &&
568 BeforePrevious->is(tok::colon))) ||
569 BeforePrevious->is(tok::r_square) ||
570 Contexts.back().LongestObjCSelectorName == 0) {
571 Tok->Previous->Type = TT_SelectorName;
572 if (Tok->Previous->ColumnWidth >
573 Contexts.back().LongestObjCSelectorName)
574 Contexts.back().LongestObjCSelectorName =
575 Tok->Previous->ColumnWidth;
576 if (!Contexts.back().FirstObjCSelectorName)
577 Contexts.back().FirstObjCSelectorName = Tok->Previous;
579 } else if (Contexts.back().ColonIsForRangeExpr) {
580 Tok->Type = TT_RangeBasedForLoopColon;
581 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
582 Tok->Type = TT_BitFieldColon;
583 } else if (Contexts.size() == 1 &&
584 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
585 if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren,
587 Tok->Type = TT_CtorInitializerColon;
589 Tok->Type = TT_InheritanceColon;
590 } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
591 Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
592 // This handles a special macro in ObjC code where selectors including
593 // the colon are passed as macro arguments.
594 Tok->Type = TT_ObjCMethodExpr;
595 } else if (Contexts.back().ContextKind == tok::l_paren) {
596 Tok->Type = TT_InlineASMColon;
601 // | and & in declarations/type expressions represent union and
602 // intersection types, respectively.
603 if (Style.Language == FormatStyle::LK_JavaScript &&
604 !Contexts.back().IsExpression)
605 Tok->Type = TT_JsTypeOperator;
609 if (Tok->is(tok::kw_if) && CurrentToken &&
610 CurrentToken->is(tok::kw_constexpr))
612 if (CurrentToken && CurrentToken->is(tok::l_paren)) {
614 if (!parseParens(/*LookForDecls=*/true))
619 if (Style.Language == FormatStyle::LK_JavaScript) {
620 // x.for and {for: ...}
621 if ((Tok->Previous && Tok->Previous->is(tok::period)) ||
622 (Tok->Next && Tok->Next->is(tok::colon)))
624 // JS' for await ( ...
625 if (CurrentToken && CurrentToken->is(Keywords.kw_await))
628 Contexts.back().ColonIsForRangeExpr = true;
634 // When faced with 'operator()()', the kw_operator handler incorrectly
635 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
636 // the first two parens OverloadedOperators and the second l_paren an
637 // OverloadedOperatorLParen.
638 if (Tok->Previous && Tok->Previous->is(tok::r_paren) &&
639 Tok->Previous->MatchingParen &&
640 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
641 Tok->Previous->Type = TT_OverloadedOperator;
642 Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
643 Tok->Type = TT_OverloadedOperatorLParen;
648 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
649 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
651 !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
652 TT_LeadingJavaAnnotation)))
653 Line.MightBeFunctionDecl = true;
660 if (Style.Language == FormatStyle::LK_TextProto) {
661 FormatToken *Previous = Tok->getPreviousNonComment();
662 if (Previous && Previous->Type != TT_DictLiteral)
663 Previous->Type = TT_SelectorName;
670 Tok->Type = TT_TemplateOpener;
671 if (Style.Language == FormatStyle::LK_TextProto) {
672 FormatToken *Previous = Tok->getPreviousNonComment();
673 if (Previous && Previous->Type != TT_DictLiteral)
674 Previous->Type = TT_SelectorName;
677 Tok->Type = TT_BinaryOperator;
678 NonTemplateLess.insert(Tok);
687 // Lines can start with '}'.
692 Tok->Type = TT_BinaryOperator;
694 case tok::kw_operator:
695 while (CurrentToken &&
696 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
697 if (CurrentToken->isOneOf(tok::star, tok::amp))
698 CurrentToken->Type = TT_PointerOrReference;
701 CurrentToken->Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator,
703 CurrentToken->Previous->Type = TT_OverloadedOperator;
706 CurrentToken->Type = TT_OverloadedOperatorLParen;
707 if (CurrentToken->Previous->is(TT_BinaryOperator))
708 CurrentToken->Previous->Type = TT_OverloadedOperator;
712 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
713 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
715 // Question marks before semicolons, colons, etc. indicate optional
716 // types (fields, parameters), e.g.
717 // function(x?: string, y?) {...}
719 Tok->Type = TT_JsTypeOptionalQuestion;
722 // Declarations cannot be conditional expressions, this can only be part
723 // of a type declaration.
724 if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
725 Style.Language == FormatStyle::LK_JavaScript)
729 case tok::kw_template:
730 parseTemplateDeclaration();
733 if (Contexts.back().InCtorInitializer)
734 Tok->Type = TT_CtorInitializerComma;
735 else if (Contexts.back().InInheritanceList)
736 Tok->Type = TT_InheritanceComma;
737 else if (Contexts.back().FirstStartOfName &&
738 (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
739 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
740 Line.IsMultiVariableDeclStmt = true;
742 if (Contexts.back().IsForEachMacro)
743 Contexts.back().IsExpression = true;
745 case tok::identifier:
746 if (Tok->isOneOf(Keywords.kw___has_include,
747 Keywords.kw___has_include_next)) {
757 void parseIncludeDirective() {
758 if (CurrentToken && CurrentToken->is(tok::less)) {
760 while (CurrentToken) {
761 // Mark tokens up to the trailing line comments as implicit string
763 if (CurrentToken->isNot(tok::comment) &&
764 !CurrentToken->TokenText.startswith("//"))
765 CurrentToken->Type = TT_ImplicitStringLiteral;
771 void parseWarningOrError() {
773 // We still want to format the whitespace left of the first token of the
776 while (CurrentToken) {
777 CurrentToken->Type = TT_ImplicitStringLiteral;
783 next(); // Consume "pragma".
785 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
786 bool IsMark = CurrentToken->is(Keywords.kw_mark);
787 next(); // Consume "mark".
788 next(); // Consume first token (so we fix leading whitespace).
789 while (CurrentToken) {
790 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
791 CurrentToken->Type = TT_ImplicitStringLiteral;
797 void parseHasInclude() {
798 if (!CurrentToken || !CurrentToken->is(tok::l_paren))
801 parseIncludeDirective();
805 LineType parsePreprocessorDirective() {
806 bool IsFirstToken = CurrentToken->IsFirst;
807 LineType Type = LT_PreprocessorDirective;
812 if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
813 // JavaScript files can contain shebang lines of the form:
814 // #!/usr/bin/env node
815 // Treat these like C++ #include directives.
816 while (CurrentToken) {
817 // Tokens cannot be comments here.
818 CurrentToken->Type = TT_ImplicitStringLiteral;
821 return LT_ImportStatement;
824 if (CurrentToken->Tok.is(tok::numeric_constant)) {
825 CurrentToken->SpacesRequiredBefore = 1;
828 // Hashes in the middle of a line can lead to any strange token
830 if (!CurrentToken->Tok.getIdentifierInfo())
832 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
833 case tok::pp_include:
834 case tok::pp_include_next:
837 parseIncludeDirective();
838 Type = LT_ImportStatement;
841 case tok::pp_warning:
842 parseWarningOrError();
849 Contexts.back().IsExpression = true;
855 while (CurrentToken) {
856 FormatToken *Tok = CurrentToken;
858 if (Tok->is(tok::l_paren))
860 else if (Tok->isOneOf(Keywords.kw___has_include,
861 Keywords.kw___has_include_next))
868 LineType parseLine() {
869 NonTemplateLess.clear();
870 if (CurrentToken->is(tok::hash))
871 return parsePreprocessorDirective();
873 // Directly allow to 'import <string-literal>' to support protocol buffer
874 // definitions (github.com/google/protobuf) or missing "#" (either way we
875 // should not break the line).
876 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
877 if ((Style.Language == FormatStyle::LK_Java &&
878 CurrentToken->is(Keywords.kw_package)) ||
879 (Info && Info->getPPKeywordID() == tok::pp_import &&
880 CurrentToken->Next &&
881 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
884 parseIncludeDirective();
885 return LT_ImportStatement;
888 // If this line starts and ends in '<' and '>', respectively, it is likely
889 // part of "#define <a/b.h>".
890 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
891 parseIncludeDirective();
892 return LT_ImportStatement;
895 // In .proto files, top-level options are very similar to import statements
896 // and should not be line-wrapped.
897 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
898 CurrentToken->is(Keywords.kw_option)) {
900 if (CurrentToken && CurrentToken->is(tok::identifier))
901 return LT_ImportStatement;
904 bool KeywordVirtualFound = false;
905 bool ImportStatement = false;
907 // import {...} from '...';
908 if (Style.Language == FormatStyle::LK_JavaScript &&
909 CurrentToken->is(Keywords.kw_import))
910 ImportStatement = true;
912 while (CurrentToken) {
913 if (CurrentToken->is(tok::kw_virtual))
914 KeywordVirtualFound = true;
915 if (Style.Language == FormatStyle::LK_JavaScript) {
916 // export {...} from '...';
917 // An export followed by "from 'some string';" is a re-export from
918 // another module identified by a URI and is treated as a
919 // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
920 // Just "export {...};" or "export class ..." should not be treated as
921 // an import in this sense.
922 if (Line.First->is(tok::kw_export) &&
923 CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
924 CurrentToken->Next->isStringLiteral())
925 ImportStatement = true;
926 if (isClosureImportStatement(*CurrentToken))
927 ImportStatement = true;
932 if (KeywordVirtualFound)
933 return LT_VirtualFunctionDecl;
935 return LT_ImportStatement;
937 if (Line.startsWith(TT_ObjCMethodSpecifier)) {
938 if (Contexts.back().FirstObjCSelectorName)
939 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
940 Contexts.back().LongestObjCSelectorName;
941 return LT_ObjCMethodDecl;
948 bool isClosureImportStatement(const FormatToken &Tok) {
949 // FIXME: Closure-library specific stuff should not be hard-coded but be
951 return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
953 (Tok.Next->Next->TokenText == "module" ||
954 Tok.Next->Next->TokenText == "provide" ||
955 Tok.Next->Next->TokenText == "require" ||
956 Tok.Next->Next->TokenText == "forwardDeclare") &&
957 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
960 void resetTokenMetadata(FormatToken *Token) {
964 // Reset token type in case we have already looked at it and then
965 // recovered from an error (e.g. failure to find the matching >).
966 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
967 TT_FunctionLBrace, TT_ImplicitStringLiteral,
968 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
969 TT_OverloadedOperator, TT_RegexLiteral,
970 TT_TemplateString, TT_ObjCStringLiteral))
971 CurrentToken->Type = TT_Unknown;
972 CurrentToken->Role.reset();
973 CurrentToken->MatchingParen = nullptr;
974 CurrentToken->FakeLParens.clear();
975 CurrentToken->FakeRParens = 0;
980 CurrentToken->NestingLevel = Contexts.size() - 1;
981 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
982 modifyContext(*CurrentToken);
983 determineTokenType(*CurrentToken);
984 CurrentToken = CurrentToken->Next;
987 resetTokenMetadata(CurrentToken);
990 /// \brief A struct to hold information valid in a specific context, e.g.
991 /// a pair of parenthesis.
993 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
995 : ContextKind(ContextKind), BindingStrength(BindingStrength),
996 IsExpression(IsExpression) {}
998 tok::TokenKind ContextKind;
999 unsigned BindingStrength;
1001 unsigned LongestObjCSelectorName = 0;
1002 bool ColonIsForRangeExpr = false;
1003 bool ColonIsDictLiteral = false;
1004 bool ColonIsObjCMethodExpr = false;
1005 FormatToken *FirstObjCSelectorName = nullptr;
1006 FormatToken *FirstStartOfName = nullptr;
1007 bool CanBeExpression = true;
1008 bool InTemplateArgument = false;
1009 bool InCtorInitializer = false;
1010 bool InInheritanceList = false;
1011 bool CaretFound = false;
1012 bool IsForEachMacro = false;
1015 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
1016 /// of each instance.
1017 struct ScopedContextCreator {
1018 AnnotatingParser &P;
1020 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
1023 P.Contexts.push_back(Context(ContextKind,
1024 P.Contexts.back().BindingStrength + Increase,
1025 P.Contexts.back().IsExpression));
1028 ~ScopedContextCreator() { P.Contexts.pop_back(); }
1031 void modifyContext(const FormatToken &Current) {
1032 if (Current.getPrecedence() == prec::Assignment &&
1033 !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
1034 // Type aliases use `type X = ...;` in TypeScript and can be exported
1035 // using `export type ...`.
1036 !(Style.Language == FormatStyle::LK_JavaScript &&
1037 (Line.startsWith(Keywords.kw_type, tok::identifier) ||
1038 Line.startsWith(tok::kw_export, Keywords.kw_type,
1039 tok::identifier))) &&
1040 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
1041 Contexts.back().IsExpression = true;
1042 if (!Line.startsWith(TT_UnaryOperator)) {
1043 for (FormatToken *Previous = Current.Previous;
1044 Previous && Previous->Previous &&
1045 !Previous->Previous->isOneOf(tok::comma, tok::semi);
1046 Previous = Previous->Previous) {
1047 if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
1048 Previous = Previous->MatchingParen;
1052 if (Previous->opensScope())
1054 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
1055 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
1056 Previous->Previous && Previous->Previous->isNot(tok::equal))
1057 Previous->Type = TT_PointerOrReference;
1060 } else if (Current.is(tok::lessless) &&
1061 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
1062 Contexts.back().IsExpression = true;
1063 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
1064 Contexts.back().IsExpression = true;
1065 } else if (Current.is(TT_TrailingReturnArrow)) {
1066 Contexts.back().IsExpression = false;
1067 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
1068 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
1069 } else if (Current.Previous &&
1070 Current.Previous->is(TT_CtorInitializerColon)) {
1071 Contexts.back().IsExpression = true;
1072 Contexts.back().InCtorInitializer = true;
1073 } else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
1074 Contexts.back().InInheritanceList = true;
1075 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
1076 for (FormatToken *Previous = Current.Previous;
1077 Previous && Previous->isOneOf(tok::star, tok::amp);
1078 Previous = Previous->Previous)
1079 Previous->Type = TT_PointerOrReference;
1080 if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
1081 Contexts.back().IsExpression = false;
1082 } else if (Current.is(tok::kw_new)) {
1083 Contexts.back().CanBeExpression = false;
1084 } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
1085 // This should be the condition or increment in a for-loop.
1086 Contexts.back().IsExpression = true;
1090 void determineTokenType(FormatToken &Current) {
1091 if (!Current.is(TT_Unknown))
1092 // The token type is already known.
1095 if (Style.Language == FormatStyle::LK_JavaScript) {
1096 if (Current.is(tok::exclaim)) {
1097 if (Current.Previous &&
1098 (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace,
1099 tok::r_paren, tok::r_square,
1101 Current.Previous->Tok.isLiteral())) {
1102 Current.Type = TT_JsNonNullAssertion;
1106 Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
1107 Current.Type = TT_JsNonNullAssertion;
1113 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1114 // function declaration have been found. In this case, 'Current' is a
1115 // trailing token of this declaration and thus cannot be a name.
1116 if (Current.is(Keywords.kw_instanceof)) {
1117 Current.Type = TT_BinaryOperator;
1118 } else if (isStartOfName(Current) &&
1119 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
1120 Contexts.back().FirstStartOfName = &Current;
1121 Current.Type = TT_StartOfName;
1122 } else if (Current.is(tok::semi)) {
1123 // Reset FirstStartOfName after finding a semicolon so that a for loop
1124 // with multiple increment statements is not confused with a for loop
1125 // having multiple variable declarations.
1126 Contexts.back().FirstStartOfName = nullptr;
1127 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
1129 } else if (Current.is(tok::arrow) &&
1130 Style.Language == FormatStyle::LK_Java) {
1131 Current.Type = TT_LambdaArrow;
1132 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
1133 Current.NestingLevel == 0) {
1134 Current.Type = TT_TrailingReturnArrow;
1135 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
1136 Current.Type = determineStarAmpUsage(Current,
1137 Contexts.back().CanBeExpression &&
1138 Contexts.back().IsExpression,
1139 Contexts.back().InTemplateArgument);
1140 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
1141 Current.Type = determinePlusMinusCaretUsage(Current);
1142 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
1143 Contexts.back().CaretFound = true;
1144 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
1145 Current.Type = determineIncrementUsage(Current);
1146 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
1147 Current.Type = TT_UnaryOperator;
1148 } else if (Current.is(tok::question)) {
1149 if (Style.Language == FormatStyle::LK_JavaScript &&
1150 Line.MustBeDeclaration && !Contexts.back().IsExpression) {
1151 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
1152 // on the interface, not a ternary expression.
1153 Current.Type = TT_JsTypeOptionalQuestion;
1155 Current.Type = TT_ConditionalExpr;
1157 } else if (Current.isBinaryOperator() &&
1158 (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
1159 Current.Type = TT_BinaryOperator;
1160 } else if (Current.is(tok::comment)) {
1161 if (Current.TokenText.startswith("/*")) {
1162 if (Current.TokenText.endswith("*/"))
1163 Current.Type = TT_BlockComment;
1165 // The lexer has for some reason determined a comment here. But we
1166 // cannot really handle it, if it isn't properly terminated.
1167 Current.Tok.setKind(tok::unknown);
1169 Current.Type = TT_LineComment;
1171 } else if (Current.is(tok::r_paren)) {
1172 if (rParenEndsCast(Current))
1173 Current.Type = TT_CastRParen;
1174 if (Current.MatchingParen && Current.Next &&
1175 !Current.Next->isBinaryOperator() &&
1176 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1177 tok::comma, tok::period, tok::arrow,
1179 if (FormatToken *AfterParen = Current.MatchingParen->Next) {
1180 // Make sure this isn't the return type of an Obj-C block declaration
1181 if (AfterParen->Tok.isNot(tok::caret)) {
1182 if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1183 if (BeforeParen->is(tok::identifier) &&
1184 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1185 (!BeforeParen->Previous ||
1186 BeforeParen->Previous->ClosesTemplateDeclaration))
1187 Current.Type = TT_FunctionAnnotationRParen;
1190 } else if (Current.is(tok::at) && Current.Next &&
1191 Style.Language != FormatStyle::LK_JavaScript &&
1192 Style.Language != FormatStyle::LK_Java) {
1193 // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
1194 // marks declarations and properties that need special formatting.
1195 switch (Current.Next->Tok.getObjCKeywordID()) {
1196 case tok::objc_interface:
1197 case tok::objc_implementation:
1198 case tok::objc_protocol:
1199 Current.Type = TT_ObjCDecl;
1201 case tok::objc_property:
1202 Current.Type = TT_ObjCProperty;
1207 } else if (Current.is(tok::period)) {
1208 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1209 if (PreviousNoComment &&
1210 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1211 Current.Type = TT_DesignatedInitializerPeriod;
1212 else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1213 Current.Previous->isOneOf(TT_JavaAnnotation,
1214 TT_LeadingJavaAnnotation)) {
1215 Current.Type = Current.Previous->Type;
1217 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
1219 !Current.Previous->isOneOf(tok::equal, tok::at) &&
1220 Line.MightBeFunctionDecl && Contexts.size() == 1) {
1221 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1222 // function declaration have been found.
1223 Current.Type = TT_TrailingAnnotation;
1224 } else if ((Style.Language == FormatStyle::LK_Java ||
1225 Style.Language == FormatStyle::LK_JavaScript) &&
1227 if (Current.Previous->is(tok::at) &&
1228 Current.isNot(Keywords.kw_interface)) {
1229 const FormatToken &AtToken = *Current.Previous;
1230 const FormatToken *Previous = AtToken.getPreviousNonComment();
1231 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1232 Current.Type = TT_LeadingJavaAnnotation;
1234 Current.Type = TT_JavaAnnotation;
1235 } else if (Current.Previous->is(tok::period) &&
1236 Current.Previous->isOneOf(TT_JavaAnnotation,
1237 TT_LeadingJavaAnnotation)) {
1238 Current.Type = Current.Previous->Type;
1243 /// \brief Take a guess at whether \p Tok starts a name of a function or
1244 /// variable declaration.
1246 /// This is a heuristic based on whether \p Tok is an identifier following
1247 /// something that is likely a type.
1248 bool isStartOfName(const FormatToken &Tok) {
1249 if (Tok.isNot(tok::identifier) || !Tok.Previous)
1252 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
1255 if (Style.Language == FormatStyle::LK_JavaScript &&
1256 Tok.Previous->is(Keywords.kw_in))
1259 // Skip "const" as it does not have an influence on whether this is a name.
1260 FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
1261 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1262 PreviousNotConst = PreviousNotConst->getPreviousNonComment();
1264 if (!PreviousNotConst)
1267 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1268 PreviousNotConst->Previous &&
1269 PreviousNotConst->Previous->is(tok::hash);
1271 if (PreviousNotConst->is(TT_TemplateCloser))
1272 return PreviousNotConst && PreviousNotConst->MatchingParen &&
1273 PreviousNotConst->MatchingParen->Previous &&
1274 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1275 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1277 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1278 PreviousNotConst->MatchingParen->Previous &&
1279 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1282 return (!IsPPKeyword &&
1283 PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1284 PreviousNotConst->is(TT_PointerOrReference) ||
1285 PreviousNotConst->isSimpleTypeSpecifier();
1288 /// \brief Determine whether ')' is ending a cast.
1289 bool rParenEndsCast(const FormatToken &Tok) {
1290 // C-style casts are only used in C++ and Java.
1291 if (!Style.isCpp() && Style.Language != FormatStyle::LK_Java)
1294 // Empty parens aren't casts and there are no casts at the end of the line.
1295 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1298 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1300 // If there is a closing parenthesis left of the current parentheses,
1301 // look past it as these might be chained casts.
1302 if (LeftOfParens->is(tok::r_paren)) {
1303 if (!LeftOfParens->MatchingParen ||
1304 !LeftOfParens->MatchingParen->Previous)
1306 LeftOfParens = LeftOfParens->MatchingParen->Previous;
1309 // If there is an identifier (or with a few exceptions a keyword) right
1310 // before the parentheses, this is unlikely to be a cast.
1311 if (LeftOfParens->Tok.getIdentifierInfo() &&
1312 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1316 // Certain other tokens right before the parentheses are also signals that
1317 // this cannot be a cast.
1318 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1319 TT_TemplateCloser, tok::ellipsis))
1323 if (Tok.Next->is(tok::question))
1326 // As Java has no function types, a "(" after the ")" likely means that this
1328 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1331 // If a (non-string) literal follows, this is likely a cast.
1332 if (Tok.Next->isNot(tok::string_literal) &&
1333 (Tok.Next->Tok.isLiteral() ||
1334 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1337 // Heuristically try to determine whether the parentheses contain a type.
1338 bool ParensAreType =
1340 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1341 Tok.Previous->isSimpleTypeSpecifier();
1342 bool ParensCouldEndDecl =
1343 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1344 if (ParensAreType && !ParensCouldEndDecl)
1347 // At this point, we heuristically assume that there are no casts at the
1348 // start of the line. We assume that we have found most cases where there
1349 // are by the logic above, e.g. "(void)x;".
1353 // Certain token types inside the parentheses mean that this can't be a
1355 for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
1356 Token = Token->Next)
1357 if (Token->is(TT_BinaryOperator))
1360 // If the following token is an identifier or 'this', this is a cast. All
1361 // cases where this can be something else are handled above.
1362 if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
1365 if (!Tok.Next->Next)
1368 // If the next token after the parenthesis is a unary operator, assume
1369 // that this is cast, unless there are unexpected tokens inside the
1372 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1373 if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1374 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1376 // Search for unexpected tokens.
1377 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1378 Prev = Prev->Previous) {
1379 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1385 /// \brief Return the type of the given token assuming it is * or &.
1386 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1387 bool InTemplateArgument) {
1388 if (Style.Language == FormatStyle::LK_JavaScript)
1389 return TT_BinaryOperator;
1391 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1393 return TT_UnaryOperator;
1395 const FormatToken *NextToken = Tok.getNextNonComment();
1397 NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const) ||
1398 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1399 return TT_PointerOrReference;
1401 if (PrevToken->is(tok::coloncolon))
1402 return TT_PointerOrReference;
1404 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1405 tok::comma, tok::semi, tok::kw_return, tok::colon,
1406 tok::equal, tok::kw_delete, tok::kw_sizeof,
1408 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1409 TT_UnaryOperator, TT_CastRParen))
1410 return TT_UnaryOperator;
1412 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1413 return TT_PointerOrReference;
1414 if (NextToken->is(tok::kw_operator) && !IsExpression)
1415 return TT_PointerOrReference;
1416 if (NextToken->isOneOf(tok::comma, tok::semi))
1417 return TT_PointerOrReference;
1419 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen) {
1420 FormatToken *TokenBeforeMatchingParen =
1421 PrevToken->MatchingParen->getPreviousNonComment();
1422 if (TokenBeforeMatchingParen &&
1423 TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
1424 return TT_PointerOrReference;
1427 if (PrevToken->Tok.isLiteral() ||
1428 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1429 tok::kw_false, tok::r_brace) ||
1430 NextToken->Tok.isLiteral() ||
1431 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1432 NextToken->isUnaryOperator() ||
1433 // If we know we're in a template argument, there are no named
1434 // declarations. Thus, having an identifier on the right-hand side
1435 // indicates a binary operator.
1436 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1437 return TT_BinaryOperator;
1439 // "&&(" is quite unlikely to be two successive unary "&".
1440 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1441 return TT_BinaryOperator;
1443 // This catches some cases where evaluation order is used as control flow:
1445 const FormatToken *NextNextToken = NextToken->getNextNonComment();
1446 if (NextNextToken && NextNextToken->is(tok::arrow))
1447 return TT_BinaryOperator;
1449 // It is very unlikely that we are going to find a pointer or reference type
1450 // definition on the RHS of an assignment.
1451 if (IsExpression && !Contexts.back().CaretFound)
1452 return TT_BinaryOperator;
1454 return TT_PointerOrReference;
1457 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1458 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1460 return TT_UnaryOperator;
1462 if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator) &&
1463 !PrevToken->is(tok::exclaim))
1464 // There aren't any trailing unary operators except for TypeScript's
1465 // non-null operator (!). Thus, this must be squence of leading operators.
1466 return TT_UnaryOperator;
1468 // Use heuristics to recognize unary operators.
1469 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1470 tok::question, tok::colon, tok::kw_return,
1471 tok::kw_case, tok::at, tok::l_brace))
1472 return TT_UnaryOperator;
1474 // There can't be two consecutive binary operators.
1475 if (PrevToken->is(TT_BinaryOperator))
1476 return TT_UnaryOperator;
1478 // Fall back to marking the token as binary operator.
1479 return TT_BinaryOperator;
1482 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1483 TokenType determineIncrementUsage(const FormatToken &Tok) {
1484 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1485 if (!PrevToken || PrevToken->is(TT_CastRParen))
1486 return TT_UnaryOperator;
1487 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1488 return TT_TrailingUnaryOperator;
1490 return TT_UnaryOperator;
1493 SmallVector<Context, 8> Contexts;
1495 const FormatStyle &Style;
1496 AnnotatedLine &Line;
1497 FormatToken *CurrentToken;
1499 const AdditionalKeywords &Keywords;
1501 // Set of "<" tokens that do not open a template parameter list. If parseAngle
1502 // determines that a specific token can't be a template opener, it will make
1503 // same decision irrespective of the decisions for tokens leading up to it.
1504 // Store this information to prevent this from causing exponential runtime.
1505 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1508 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1509 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1511 /// \brief Parses binary expressions by inserting fake parenthesis based on
1512 /// operator precedence.
1513 class ExpressionParser {
1515 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1516 AnnotatedLine &Line)
1517 : Style(Style), Keywords(Keywords), Current(Line.First) {}
1519 /// \brief Parse expressions with the given operatore precedence.
1520 void parse(int Precedence = 0) {
1521 // Skip 'return' and ObjC selector colons as they are not part of a binary
1523 while (Current && (Current->is(tok::kw_return) ||
1524 (Current->is(tok::colon) &&
1525 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1528 if (!Current || Precedence > PrecedenceArrowAndPeriod)
1531 // Conditional expressions need to be parsed separately for proper nesting.
1532 if (Precedence == prec::Conditional) {
1533 parseConditionalExpr();
1537 // Parse unary operators, which all have a higher precedence than binary
1539 if (Precedence == PrecedenceUnaryOperator) {
1540 parseUnaryOperator();
1544 FormatToken *Start = Current;
1545 FormatToken *LatestOperator = nullptr;
1546 unsigned OperatorIndex = 0;
1549 // Consume operators with higher precedence.
1550 parse(Precedence + 1);
1552 int CurrentPrecedence = getCurrentPrecedence();
1554 if (Current && Current->is(TT_SelectorName) &&
1555 Precedence == CurrentPrecedence) {
1557 addFakeParenthesis(Start, prec::Level(Precedence));
1561 // At the end of the line or when an operator with higher precedence is
1562 // found, insert fake parenthesis and return.
1564 (Current->closesScope() &&
1565 (Current->MatchingParen || Current->is(TT_TemplateString))) ||
1566 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1567 (CurrentPrecedence == prec::Conditional &&
1568 Precedence == prec::Assignment && Current->is(tok::colon))) {
1572 // Consume scopes: (), [], <> and {}
1573 if (Current->opensScope()) {
1574 // In fragment of a JavaScript template string can look like '}..${' and
1575 // thus close a scope and open a new one at the same time.
1576 while (Current && (!Current->closesScope() || Current->opensScope())) {
1583 if (CurrentPrecedence == Precedence) {
1585 LatestOperator->NextOperator = Current;
1586 LatestOperator = Current;
1587 Current->OperatorIndex = OperatorIndex;
1590 next(/*SkipPastLeadingComments=*/Precedence > 0);
1594 if (LatestOperator && (Current || Precedence > 0)) {
1595 // LatestOperator->LastOperator = true;
1596 if (Precedence == PrecedenceArrowAndPeriod) {
1597 // Call expressions don't have a binary operator precedence.
1598 addFakeParenthesis(Start, prec::Unknown);
1600 addFakeParenthesis(Start, prec::Level(Precedence));
1606 /// \brief Gets the precedence (+1) of the given token for binary operators
1607 /// and other tokens that we treat like binary operators.
1608 int getCurrentPrecedence() {
1610 const FormatToken *NextNonComment = Current->getNextNonComment();
1611 if (Current->is(TT_ConditionalExpr))
1612 return prec::Conditional;
1613 if (NextNonComment && Current->is(TT_SelectorName) &&
1614 (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
1615 ((Style.Language == FormatStyle::LK_Proto ||
1616 Style.Language == FormatStyle::LK_TextProto) &&
1617 NextNonComment->is(tok::less))))
1618 return prec::Assignment;
1619 if (Current->is(TT_JsComputedPropertyName))
1620 return prec::Assignment;
1621 if (Current->is(TT_LambdaArrow))
1623 if (Current->is(TT_JsFatArrow))
1624 return prec::Assignment;
1625 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
1626 (Current->is(tok::comment) && NextNonComment &&
1627 NextNonComment->is(TT_SelectorName)))
1629 if (Current->is(TT_RangeBasedForLoopColon))
1631 if ((Style.Language == FormatStyle::LK_Java ||
1632 Style.Language == FormatStyle::LK_JavaScript) &&
1633 Current->is(Keywords.kw_instanceof))
1634 return prec::Relational;
1635 if (Style.Language == FormatStyle::LK_JavaScript &&
1636 Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
1637 return prec::Relational;
1638 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1639 return Current->getPrecedence();
1640 if (Current->isOneOf(tok::period, tok::arrow))
1641 return PrecedenceArrowAndPeriod;
1642 if ((Style.Language == FormatStyle::LK_Java ||
1643 Style.Language == FormatStyle::LK_JavaScript) &&
1644 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1645 Keywords.kw_throws))
1651 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1652 Start->FakeLParens.push_back(Precedence);
1653 if (Precedence > prec::Unknown)
1654 Start->StartsBinaryExpression = true;
1656 FormatToken *Previous = Current->Previous;
1657 while (Previous->is(tok::comment) && Previous->Previous)
1658 Previous = Previous->Previous;
1659 ++Previous->FakeRParens;
1660 if (Precedence > prec::Unknown)
1661 Previous->EndsBinaryExpression = true;
1665 /// \brief Parse unary operator expressions and surround them with fake
1666 /// parentheses if appropriate.
1667 void parseUnaryOperator() {
1668 llvm::SmallVector<FormatToken *, 2> Tokens;
1669 while (Current && Current->is(TT_UnaryOperator)) {
1670 Tokens.push_back(Current);
1673 parse(PrecedenceArrowAndPeriod);
1674 for (FormatToken *Token : llvm::reverse(Tokens))
1675 // The actual precedence doesn't matter.
1676 addFakeParenthesis(Token, prec::Unknown);
1679 void parseConditionalExpr() {
1680 while (Current && Current->isTrailingComment()) {
1683 FormatToken *Start = Current;
1684 parse(prec::LogicalOr);
1685 if (!Current || !Current->is(tok::question))
1688 parse(prec::Assignment);
1689 if (!Current || Current->isNot(TT_ConditionalExpr))
1692 parse(prec::Assignment);
1693 addFakeParenthesis(Start, prec::Conditional);
1696 void next(bool SkipPastLeadingComments = true) {
1698 Current = Current->Next;
1700 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1701 Current->isTrailingComment())
1702 Current = Current->Next;
1705 const FormatStyle &Style;
1706 const AdditionalKeywords &Keywords;
1707 FormatToken *Current;
1710 } // end anonymous namespace
1712 void TokenAnnotator::setCommentLineLevels(
1713 SmallVectorImpl<AnnotatedLine *> &Lines) {
1714 const AnnotatedLine *NextNonCommentLine = nullptr;
1715 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1718 bool CommentLine = true;
1719 for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
1720 if (!Tok->is(tok::comment)) {
1721 CommentLine = false;
1726 // If the comment is currently aligned with the line immediately following
1727 // it, that's probably intentional and we should keep it.
1728 if (NextNonCommentLine && CommentLine &&
1729 NextNonCommentLine->First->NewlinesBefore <= 1 &&
1730 NextNonCommentLine->First->OriginalColumn ==
1731 (*I)->First->OriginalColumn) {
1732 // Align comments for preprocessor lines with the # in column 0.
1733 // Otherwise, align with the next line.
1734 (*I)->Level = (NextNonCommentLine->Type == LT_PreprocessorDirective ||
1735 NextNonCommentLine->Type == LT_ImportStatement)
1737 : NextNonCommentLine->Level;
1739 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1742 setCommentLineLevels((*I)->Children);
1746 static unsigned maxNestingDepth(const AnnotatedLine &Line) {
1747 unsigned Result = 0;
1748 for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
1749 Result = std::max(Result, Tok->NestingLevel);
1753 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1754 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1755 E = Line.Children.end();
1759 AnnotatingParser Parser(Style, Line, Keywords);
1760 Line.Type = Parser.parseLine();
1762 // With very deep nesting, ExpressionParser uses lots of stack and the
1763 // formatting algorithm is very slow. We're not going to do a good job here
1764 // anyway - it's probably generated code being formatted by mistake.
1765 // Just skip the whole line.
1766 if (maxNestingDepth(Line) > 50)
1767 Line.Type = LT_Invalid;
1769 if (Line.Type == LT_Invalid)
1772 ExpressionParser ExprParser(Style, Keywords, Line);
1775 if (Line.startsWith(TT_ObjCMethodSpecifier))
1776 Line.Type = LT_ObjCMethodDecl;
1777 else if (Line.startsWith(TT_ObjCDecl))
1778 Line.Type = LT_ObjCDecl;
1779 else if (Line.startsWith(TT_ObjCProperty))
1780 Line.Type = LT_ObjCProperty;
1782 Line.First->SpacesRequiredBefore = 1;
1783 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1786 // This function heuristically determines whether 'Current' starts the name of a
1787 // function declaration.
1788 static bool isFunctionDeclarationName(const FormatToken &Current,
1789 const AnnotatedLine &Line) {
1790 auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
1791 for (; Next; Next = Next->Next) {
1792 if (Next->is(TT_OverloadedOperatorLParen))
1794 if (Next->is(TT_OverloadedOperator))
1796 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1797 // For 'new[]' and 'delete[]'.
1798 if (Next->Next && Next->Next->is(tok::l_square) && Next->Next->Next &&
1799 Next->Next->Next->is(tok::r_square))
1800 Next = Next->Next->Next;
1809 // Find parentheses of parameter list.
1810 const FormatToken *Next = Current.Next;
1811 if (Current.is(tok::kw_operator)) {
1812 if (Current.Previous && Current.Previous->is(tok::coloncolon))
1814 Next = skipOperatorName(Next);
1816 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1818 for (; Next; Next = Next->Next) {
1819 if (Next->is(TT_TemplateOpener)) {
1820 Next = Next->MatchingParen;
1821 } else if (Next->is(tok::coloncolon)) {
1825 if (Next->is(tok::kw_operator)) {
1826 Next = skipOperatorName(Next->Next);
1829 if (!Next->is(tok::identifier))
1831 } else if (Next->is(tok::l_paren)) {
1839 // Check whether parameter list can belong to a function declaration.
1840 if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
1842 // If the lines ends with "{", this is likely an function definition.
1843 if (Line.Last->is(tok::l_brace))
1845 if (Next->Next == Next->MatchingParen)
1846 return true; // Empty parentheses.
1847 // If there is an &/&& after the r_paren, this is likely a function.
1848 if (Next->MatchingParen->Next &&
1849 Next->MatchingParen->Next->is(TT_PointerOrReference))
1851 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1853 if (Tok->is(tok::l_paren) && Tok->MatchingParen) {
1854 Tok = Tok->MatchingParen;
1857 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1858 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
1860 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1861 Tok->Tok.isLiteral())
1867 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
1868 assert(Line.MightBeFunctionDecl);
1870 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
1871 Style.AlwaysBreakAfterReturnType ==
1872 FormatStyle::RTBS_TopLevelDefinitions) &&
1876 switch (Style.AlwaysBreakAfterReturnType) {
1877 case FormatStyle::RTBS_None:
1879 case FormatStyle::RTBS_All:
1880 case FormatStyle::RTBS_TopLevel:
1882 case FormatStyle::RTBS_AllDefinitions:
1883 case FormatStyle::RTBS_TopLevelDefinitions:
1884 return Line.mightBeFunctionDefinition();
1890 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1891 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1892 E = Line.Children.end();
1894 calculateFormattingInformation(**I);
1897 Line.First->TotalLength =
1898 Line.First->IsMultiline ? Style.ColumnLimit
1899 : Line.FirstStartColumn + Line.First->ColumnWidth;
1900 FormatToken *Current = Line.First->Next;
1901 bool InFunctionDecl = Line.MightBeFunctionDecl;
1903 if (isFunctionDeclarationName(*Current, Line))
1904 Current->Type = TT_FunctionDeclarationName;
1905 if (Current->is(TT_LineComment)) {
1906 if (Current->Previous->BlockKind == BK_BracedInit &&
1907 Current->Previous->opensScope())
1908 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1910 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1912 // If we find a trailing comment, iterate backwards to determine whether
1913 // it seems to relate to a specific parameter. If so, break before that
1914 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1915 // to the previous line in:
1919 if (!Current->HasUnescapedNewline) {
1920 for (FormatToken *Parameter = Current->Previous; Parameter;
1921 Parameter = Parameter->Previous) {
1922 if (Parameter->isOneOf(tok::comment, tok::r_brace))
1924 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1925 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1926 Parameter->HasUnescapedNewline)
1927 Parameter->MustBreakBefore = true;
1932 } else if (Current->SpacesRequiredBefore == 0 &&
1933 spaceRequiredBefore(Line, *Current)) {
1934 Current->SpacesRequiredBefore = 1;
1937 Current->MustBreakBefore =
1938 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1940 if (!Current->MustBreakBefore && InFunctionDecl &&
1941 Current->is(TT_FunctionDeclarationName))
1942 Current->MustBreakBefore = mustBreakForReturnType(Line);
1944 Current->CanBreakBefore =
1945 Current->MustBreakBefore || canBreakBefore(Line, *Current);
1946 unsigned ChildSize = 0;
1947 if (Current->Previous->Children.size() == 1) {
1948 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1949 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1950 : LastOfChild.TotalLength + 1;
1952 const FormatToken *Prev = Current->Previous;
1953 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1954 (Prev->Children.size() == 1 &&
1955 Prev->Children[0]->First->MustBreakBefore) ||
1956 Current->IsMultiline)
1957 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1959 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1960 ChildSize + Current->SpacesRequiredBefore;
1962 if (Current->is(TT_CtorInitializerColon))
1963 InFunctionDecl = false;
1965 // FIXME: Only calculate this if CanBreakBefore is true once static
1966 // initializers etc. are sorted out.
1967 // FIXME: Move magic numbers to a better place.
1968 Current->SplitPenalty = 20 * Current->BindingStrength +
1969 splitPenalty(Line, *Current, InFunctionDecl);
1971 Current = Current->Next;
1974 calculateUnbreakableTailLengths(Line);
1975 unsigned IndentLevel = Line.Level;
1976 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1978 Current->Role->precomputeFormattingInfos(Current);
1979 if (Current->MatchingParen &&
1980 Current->MatchingParen->opensBlockOrBlockTypeList(Style)) {
1981 assert(IndentLevel > 0);
1984 Current->IndentLevel = IndentLevel;
1985 if (Current->opensBlockOrBlockTypeList(Style))
1989 DEBUG({ printDebugInfo(Line); });
1992 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1993 unsigned UnbreakableTailLength = 0;
1994 FormatToken *Current = Line.Last;
1996 Current->UnbreakableTailLength = UnbreakableTailLength;
1997 if (Current->CanBreakBefore ||
1998 Current->isOneOf(tok::comment, tok::string_literal)) {
1999 UnbreakableTailLength = 0;
2001 UnbreakableTailLength +=
2002 Current->ColumnWidth + Current->SpacesRequiredBefore;
2004 Current = Current->Previous;
2008 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
2009 const FormatToken &Tok,
2010 bool InFunctionDecl) {
2011 const FormatToken &Left = *Tok.Previous;
2012 const FormatToken &Right = Tok;
2014 if (Left.is(tok::semi))
2017 if (Style.Language == FormatStyle::LK_Java) {
2018 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
2020 if (Right.is(Keywords.kw_implements))
2022 if (Left.is(tok::comma) && Left.NestingLevel == 0)
2024 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2025 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
2027 if (Left.is(TT_JsTypeColon))
2029 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2030 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2032 // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
2033 if (Left.opensScope() && Right.closesScope())
2037 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2039 if (Right.is(tok::l_square)) {
2040 if (Style.Language == FormatStyle::LK_Proto)
2042 if (Left.is(tok::r_square))
2044 // Slightly prefer formatting local lambda definitions like functions.
2045 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
2047 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2048 TT_ArrayInitializerLSquare,
2049 TT_DesignatedInitializerLSquare))
2053 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2054 Right.is(tok::kw_operator)) {
2055 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
2057 if (Left.is(TT_StartOfName))
2059 if (InFunctionDecl && Right.NestingLevel == 0)
2060 return Style.PenaltyReturnTypeOnItsOwnLine;
2063 if (Right.is(TT_PointerOrReference))
2065 if (Right.is(TT_LambdaArrow))
2067 if (Left.is(tok::equal) && Right.is(tok::l_brace))
2069 if (Left.is(TT_CastRParen))
2071 if (Left.is(tok::coloncolon) ||
2072 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
2074 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
2076 if (Left.is(tok::comment))
2079 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
2080 TT_CtorInitializerColon))
2083 if (Right.isMemberAccess()) {
2084 // Breaking before the "./->" of a chained call/member access is reasonably
2085 // cheap, as formatting those with one call per line is generally
2086 // desirable. In particular, it should be cheaper to break before the call
2087 // than it is to break inside a call's parameters, which could lead to weird
2088 // "hanging" indents. The exception is the very last "./->" to support this
2089 // frequent pattern:
2091 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
2094 // which might otherwise be blown up onto many lines. Here, clang-format
2095 // won't produce "hanging" indents anyway as there is no other trailing
2098 // Also apply higher penalty is not a call as that might lead to a wrapping
2102 // .aaaaaaaaa.bbbbbbbb(cccccccc);
2103 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
2108 if (Right.is(TT_TrailingAnnotation) &&
2109 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
2110 // Moving trailing annotations to the next line is fine for ObjC method
2112 if (Line.startsWith(TT_ObjCMethodSpecifier))
2114 // Generally, breaking before a trailing annotation is bad unless it is
2115 // function-like. It seems to be especially preferable to keep standard
2116 // annotations (i.e. "const", "final" and "override") on the same line.
2117 // Use a slightly higher penalty after ")" so that annotations like
2118 // "const override" are kept together.
2119 bool is_short_annotation = Right.TokenText.size() < 10;
2120 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
2123 // In for-loops, prefer breaking at ',' and ';'.
2124 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
2127 // In Objective-C method expressions, prefer breaking before "param:" over
2128 // breaking after it.
2129 if (Right.is(TT_SelectorName))
2131 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
2132 return Line.MightBeFunctionDecl ? 50 : 500;
2134 if (Left.is(tok::l_paren) && InFunctionDecl &&
2135 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
2137 if (Left.is(tok::l_paren) && Left.Previous &&
2138 (Left.Previous->isOneOf(tok::kw_if, tok::kw_for) ||
2139 Left.Previous->endsSequence(tok::kw_constexpr, tok::kw_if)))
2141 if (Left.is(tok::equal) && InFunctionDecl)
2143 if (Right.is(tok::r_brace))
2145 if (Left.is(TT_TemplateOpener))
2147 if (Left.opensScope()) {
2148 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
2150 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
2153 if (Left.is(TT_JavaAnnotation))
2156 if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
2157 Left.Previous->isLabelString() &&
2158 (Left.NextOperator || Left.OperatorIndex != 0))
2160 if (Right.is(tok::plus) && Left.isLabelString() &&
2161 (Right.NextOperator || Right.OperatorIndex != 0))
2163 if (Left.is(tok::comma))
2165 if (Right.is(tok::lessless) && Left.isLabelString() &&
2166 (Right.NextOperator || Right.OperatorIndex != 1))
2168 if (Right.is(tok::lessless)) {
2169 // Breaking at a << is really cheap.
2170 if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
2171 // Slightly prefer to break before the first one in log-like statements.
2175 if (Left.is(TT_ConditionalExpr))
2176 return prec::Conditional;
2177 prec::Level Level = Left.getPrecedence();
2178 if (Level == prec::Unknown)
2179 Level = Right.getPrecedence();
2180 if (Level == prec::Assignment)
2181 return Style.PenaltyBreakAssignment;
2182 if (Level != prec::Unknown)
2188 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
2189 const FormatToken &Left,
2190 const FormatToken &Right) {
2191 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
2193 if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java)
2195 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
2196 Left.Tok.getObjCKeywordID() == tok::objc_property)
2198 if (Right.is(tok::hashhash))
2199 return Left.is(tok::hash);
2200 if (Left.isOneOf(tok::hashhash, tok::hash))
2201 return Right.is(tok::hash);
2202 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
2203 return Style.SpaceInEmptyParentheses;
2204 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
2205 return (Right.is(TT_CastRParen) ||
2206 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
2207 ? Style.SpacesInCStyleCastParentheses
2208 : Style.SpacesInParentheses;
2209 if (Right.isOneOf(tok::semi, tok::comma))
2211 if (Right.is(tok::less) && Line.Type == LT_ObjCDecl &&
2212 Style.ObjCSpaceBeforeProtocolList)
2214 if (Right.is(tok::less) && Left.is(tok::kw_template))
2215 return Style.SpaceAfterTemplateKeyword;
2216 if (Left.isOneOf(tok::exclaim, tok::tilde))
2218 if (Left.is(tok::at) &&
2219 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
2220 tok::numeric_constant, tok::l_paren, tok::l_brace,
2221 tok::kw_true, tok::kw_false))
2223 if (Left.is(tok::colon))
2224 return !Left.is(TT_ObjCMethodExpr);
2225 if (Left.is(tok::coloncolon))
2227 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
2229 if (Right.is(tok::ellipsis))
2230 return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
2231 Left.Previous->is(tok::kw_case));
2232 if (Left.is(tok::l_square) && Right.is(tok::amp))
2234 if (Right.is(TT_PointerOrReference)) {
2235 if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
2236 if (!Left.MatchingParen)
2238 FormatToken *TokenBeforeMatchingParen =
2239 Left.MatchingParen->getPreviousNonComment();
2240 if (!TokenBeforeMatchingParen ||
2241 !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
2244 return (Left.Tok.isLiteral() ||
2245 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
2246 (Style.PointerAlignment != FormatStyle::PAS_Left ||
2247 (Line.IsMultiVariableDeclStmt &&
2248 (Left.NestingLevel == 0 ||
2249 (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
2251 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
2252 (!Left.is(TT_PointerOrReference) ||
2253 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2254 !Line.IsMultiVariableDeclStmt)))
2256 if (Left.is(TT_PointerOrReference))
2257 return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
2258 (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
2259 !Right.is(TT_StartOfName)) ||
2260 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
2261 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
2263 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2264 !Line.IsMultiVariableDeclStmt) &&
2266 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
2267 if (Right.is(tok::star) && Left.is(tok::l_paren))
2269 if (Left.is(tok::l_square))
2270 return (Left.is(TT_ArrayInitializerLSquare) &&
2271 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
2272 (Left.isOneOf(TT_ArraySubscriptLSquare,
2273 TT_StructuredBindingLSquare) &&
2274 Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
2275 if (Right.is(tok::r_square))
2276 return Right.MatchingParen &&
2277 ((Style.SpacesInContainerLiterals &&
2278 Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
2279 (Style.SpacesInSquareBrackets &&
2280 Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
2281 TT_StructuredBindingLSquare)));
2282 if (Right.is(tok::l_square) &&
2283 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
2284 TT_DesignatedInitializerLSquare,
2285 TT_StructuredBindingLSquare) &&
2286 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
2288 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
2289 return !Left.Children.empty(); // No spaces in "{}".
2290 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
2291 (Right.is(tok::r_brace) && Right.MatchingParen &&
2292 Right.MatchingParen->BlockKind != BK_Block))
2293 return !Style.Cpp11BracedListStyle;
2294 if (Left.is(TT_BlockComment))
2295 return !Left.TokenText.endswith("=*/");
2296 if (Right.is(tok::l_paren)) {
2297 if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
2299 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
2300 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
2301 (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
2302 tok::kw_switch, tok::kw_case, TT_ForEachMacro,
2304 Left.endsSequence(tok::kw_constexpr, tok::kw_if) ||
2305 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
2306 tok::kw_new, tok::kw_delete) &&
2307 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
2308 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
2309 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
2310 Left.is(tok::r_paren)) &&
2311 Line.Type != LT_PreprocessorDirective);
2313 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
2315 if (Right.is(TT_UnaryOperator))
2316 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
2317 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
2318 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
2320 Left.isSimpleTypeSpecifier()) &&
2321 Right.is(tok::l_brace) && Right.getNextNonComment() &&
2322 Right.BlockKind != BK_Block)
2324 if (Left.is(tok::period) || Right.is(tok::period))
2326 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
2328 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
2329 Left.MatchingParen->Previous &&
2330 Left.MatchingParen->Previous->is(tok::period))
2331 // A.<B<C<...>>>DoSomething();
2333 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
2338 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
2339 const FormatToken &Right) {
2340 const FormatToken &Left = *Right.Previous;
2341 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
2342 return true; // Never ever merge two identifiers.
2343 if (Style.isCpp()) {
2344 if (Left.is(tok::kw_operator))
2345 return Right.is(tok::coloncolon);
2346 } else if (Style.Language == FormatStyle::LK_Proto ||
2347 Style.Language == FormatStyle::LK_TextProto) {
2348 if (Right.is(tok::period) &&
2349 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2350 Keywords.kw_repeated, Keywords.kw_extend))
2352 if (Right.is(tok::l_paren) &&
2353 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2355 if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
2357 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2358 if (Left.is(TT_JsFatArrow))
2361 if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
2362 Left.Previous->is(tok::kw_for))
2364 if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
2365 Right.MatchingParen) {
2366 const FormatToken *Next = Right.MatchingParen->getNextNonComment();
2367 // An async arrow function, for example: `x = async () => foo();`,
2368 // as opposed to calling a function called async: `x = async();`
2369 if (Next && Next->is(TT_JsFatArrow))
2372 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2373 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2375 // In tagged template literals ("html`bar baz`"), there is no space between
2376 // the tag identifier and the template string. getIdentifierInfo makes sure
2377 // that the identifier is not a pseudo keyword like `yield`, either.
2378 if (Left.is(tok::identifier) && Keywords.IsJavaScriptIdentifier(Left) &&
2379 Right.is(TT_TemplateString))
2381 if (Right.is(tok::star) &&
2382 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2384 if (Right.isOneOf(tok::l_brace, tok::l_square) &&
2385 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
2386 Keywords.kw_extends, Keywords.kw_implements))
2388 if (Right.is(tok::l_paren)) {
2389 // JS methods can use some keywords as names (e.g. `delete()`).
2390 if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
2392 // Valid JS method names can include keywords, e.g. `foo.delete()` or
2393 // `bar.instanceof()`. Recognize call positions by preceding period.
2394 if (Left.Previous && Left.Previous->is(tok::period) &&
2395 Left.Tok.getIdentifierInfo())
2397 // Additional unary JavaScript operators that need a space after.
2398 if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
2402 if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
2404 // "of" is only a keyword if it appears after another identifier
2405 // (e.g. as "const x of y" in a for loop), or after a destructuring
2406 // operation (const [x, y] of z, const {a, b} of c).
2407 (Left.is(Keywords.kw_of) && Left.Previous &&
2408 (Left.Previous->Tok.getIdentifierInfo() ||
2409 Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) &&
2410 (!Left.Previous || !Left.Previous->is(tok::period)))
2412 if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
2413 Left.Previous->is(tok::period) && Right.is(tok::l_paren))
2415 if (Left.is(Keywords.kw_as) &&
2416 Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
2418 if (Left.is(tok::kw_default) && Left.Previous &&
2419 Left.Previous->is(tok::kw_export))
2421 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2423 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2425 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
2427 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2428 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2430 if (Left.is(tok::ellipsis))
2432 if (Left.is(TT_TemplateCloser) &&
2433 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2434 Keywords.kw_implements, Keywords.kw_extends))
2435 // Type assertions ('<type>expr') are not followed by whitespace. Other
2436 // locations that should have whitespace following are identified by the
2437 // above set of follower tokens.
2439 if (Right.is(TT_JsNonNullAssertion))
2441 if (Left.is(TT_JsNonNullAssertion) &&
2442 Right.isOneOf(Keywords.kw_as, Keywords.kw_in))
2443 return true; // "x! as string", "x! in y"
2444 } else if (Style.Language == FormatStyle::LK_Java) {
2445 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2447 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2448 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2449 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2450 tok::kw_protected) ||
2451 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2452 Keywords.kw_native)) &&
2453 Right.is(TT_TemplateOpener))
2456 if (Left.is(TT_ImplicitStringLiteral))
2457 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2458 if (Line.Type == LT_ObjCMethodDecl) {
2459 if (Left.is(TT_ObjCMethodSpecifier))
2461 if (Left.is(tok::r_paren) && Right.is(tok::identifier))
2462 // Don't space between ')' and <id>
2465 if (Line.Type == LT_ObjCProperty &&
2466 (Right.is(tok::equal) || Left.is(tok::equal)))
2469 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2470 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2472 if (Right.is(TT_OverloadedOperatorLParen))
2473 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2474 if (Left.is(tok::comma))
2476 if (Right.is(tok::comma))
2478 if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
2480 if (Right.is(tok::colon)) {
2481 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2482 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2484 if (Right.is(TT_ObjCMethodExpr))
2486 if (Left.is(tok::question))
2488 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2490 if (Right.is(TT_DictLiteral))
2491 return Style.SpacesInContainerLiterals;
2494 if (Left.is(TT_UnaryOperator))
2495 return Right.is(TT_BinaryOperator);
2497 // If the next token is a binary operator or a selector name, we have
2498 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2499 if (Left.is(TT_CastRParen))
2500 return Style.SpaceAfterCStyleCast ||
2501 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2503 if (Left.is(tok::greater) && Right.is(tok::greater))
2504 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2505 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2506 if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
2507 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2508 (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod)))
2510 if (!Style.SpaceBeforeAssignmentOperators &&
2511 Right.getPrecedence() == prec::Assignment)
2513 if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
2514 // Generally don't remove existing spaces between an identifier and "::".
2515 // The identifier might actually be a macro name such as ALWAYS_INLINE. If
2516 // this turns out to be too lenient, add analysis of the identifier itself.
2517 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2518 if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
2519 return (Left.is(TT_TemplateOpener) &&
2520 Style.Standard == FormatStyle::LS_Cpp03) ||
2521 !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
2522 tok::kw___super, TT_TemplateCloser,
2523 TT_TemplateOpener));
2524 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2525 return Style.SpacesInAngles;
2526 // Space before TT_StructuredBindingLSquare.
2527 if (Right.is(TT_StructuredBindingLSquare))
2528 return !Left.isOneOf(tok::amp, tok::ampamp) ||
2529 Style.PointerAlignment != FormatStyle::PAS_Right;
2530 // Space before & or && following a TT_StructuredBindingLSquare.
2531 if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
2532 Right.isOneOf(tok::amp, tok::ampamp))
2533 return Style.PointerAlignment != FormatStyle::PAS_Left;
2534 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2535 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2536 !Right.is(tok::r_paren)))
2538 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2539 Right.isNot(TT_FunctionTypeLParen))
2540 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2541 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2542 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2544 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2545 Line.startsWith(tok::hash))
2547 if (Right.is(TT_TrailingUnaryOperator))
2549 if (Left.is(TT_RegexLiteral))
2551 return spaceRequiredBetween(Line, Left, Right);
2554 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2555 static bool isAllmanBrace(const FormatToken &Tok) {
2556 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2557 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2560 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2561 const FormatToken &Right) {
2562 const FormatToken &Left = *Right.Previous;
2563 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2566 if (Style.Language == FormatStyle::LK_JavaScript) {
2567 // FIXME: This might apply to other languages and token kinds.
2568 if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
2569 Left.Previous->is(tok::string_literal))
2571 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2572 Left.Previous && Left.Previous->is(tok::equal) &&
2573 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2575 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2577 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2578 // Object literals on the top level of a file are treated as "enum-style".
2579 // Each key/value pair is put on a separate line, instead of bin-packing.
2581 if (Left.is(tok::l_brace) && Line.Level == 0 &&
2582 (Line.startsWith(tok::kw_enum) ||
2583 Line.startsWith(tok::kw_const, tok::kw_enum) ||
2584 Line.startsWith(tok::kw_export, tok::kw_enum) ||
2585 Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
2586 // JavaScript top-level enum key/value pairs are put on separate lines
2587 // instead of bin-packing.
2589 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2590 !Left.Children.empty())
2591 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2592 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2593 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2594 (Left.NestingLevel == 0 && Line.Level == 0 &&
2595 Style.AllowShortFunctionsOnASingleLine &
2596 FormatStyle::SFS_InlineOnly);
2597 } else if (Style.Language == FormatStyle::LK_Java) {
2598 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2599 Right.Next->is(tok::string_literal))
2601 } else if (Style.Language == FormatStyle::LK_Cpp ||
2602 Style.Language == FormatStyle::LK_ObjC ||
2603 Style.Language == FormatStyle::LK_Proto) {
2604 if (Left.isStringLiteral() && Right.isStringLiteral())
2608 // If the last token before a '}', ']', or ')' is a comma or a trailing
2609 // comment, the intention is to insert a line break after it in order to make
2610 // shuffling around entries easier. Import statements, especially in
2611 // JavaScript, can be an exception to this rule.
2612 if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
2613 const FormatToken *BeforeClosingBrace = nullptr;
2614 if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
2615 (Style.Language == FormatStyle::LK_JavaScript &&
2616 Left.is(tok::l_paren))) &&
2617 Left.BlockKind != BK_Block && Left.MatchingParen)
2618 BeforeClosingBrace = Left.MatchingParen->Previous;
2619 else if (Right.MatchingParen &&
2620 (Right.MatchingParen->isOneOf(tok::l_brace,
2621 TT_ArrayInitializerLSquare) ||
2622 (Style.Language == FormatStyle::LK_JavaScript &&
2623 Right.MatchingParen->is(tok::l_paren))))
2624 BeforeClosingBrace = &Left;
2625 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2626 BeforeClosingBrace->isTrailingComment()))
2630 if (Right.is(tok::comment))
2631 return Left.BlockKind != BK_BracedInit &&
2632 Left.isNot(TT_CtorInitializerColon) &&
2633 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2634 if (Left.isTrailingComment())
2636 if (Right.Previous->IsUnterminatedLiteral)
2638 if (Right.is(tok::lessless) && Right.Next &&
2639 Right.Previous->is(tok::string_literal) &&
2640 Right.Next->is(tok::string_literal))
2642 if (Right.Previous->ClosesTemplateDeclaration &&
2643 Right.Previous->MatchingParen &&
2644 Right.Previous->MatchingParen->NestingLevel == 0 &&
2645 Style.AlwaysBreakTemplateDeclarations)
2647 if (Right.is(TT_CtorInitializerComma) &&
2648 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
2649 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2651 if (Right.is(TT_CtorInitializerColon) &&
2652 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
2653 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2655 // Break only if we have multiple inheritance.
2656 if (Style.BreakBeforeInheritanceComma && Right.is(TT_InheritanceComma))
2658 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2659 // Raw string literals are special wrt. line breaks. The author has made a
2660 // deliberate choice and might have aligned the contents of the string
2661 // literal accordingly. Thus, we try keep existing line breaks.
2662 return Right.NewlinesBefore > 0;
2663 if ((Right.Previous->is(tok::l_brace) ||
2664 (Right.Previous->is(tok::less) && Right.Previous->Previous &&
2665 Right.Previous->Previous->is(tok::equal))) &&
2666 Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
2667 // Don't put enums or option definitions onto single lines in protocol
2671 if (Right.is(TT_InlineASMBrace))
2672 return Right.HasUnescapedNewline;
2673 if (isAllmanBrace(Left) || isAllmanBrace(Right))
2674 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2675 (Line.startsWith(tok::kw_typedef, tok::kw_enum) &&
2676 Style.BraceWrapping.AfterEnum) ||
2677 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2678 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2679 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2682 if ((Style.Language == FormatStyle::LK_Java ||
2683 Style.Language == FormatStyle::LK_JavaScript) &&
2684 Left.is(TT_LeadingJavaAnnotation) &&
2685 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2686 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2692 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2693 const FormatToken &Right) {
2694 const FormatToken &Left = *Right.Previous;
2696 // Language-specific stuff.
2697 if (Style.Language == FormatStyle::LK_Java) {
2698 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2699 Keywords.kw_implements))
2701 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2702 Keywords.kw_implements))
2704 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2705 const FormatToken *NonComment = Right.getPreviousNonComment();
2707 NonComment->isOneOf(
2708 tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
2709 tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
2710 tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected,
2711 Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
2712 Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
2713 return false; // Otherwise automatic semicolon insertion would trigger.
2714 if (Left.Tok.getIdentifierInfo() &&
2715 Right.startsSequence(tok::l_square, tok::r_square))
2716 return false; // breaking in "foo[]" creates illegal TS type syntax.
2717 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2719 if (Left.is(TT_JsTypeColon))
2721 if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is))
2723 if (Left.is(Keywords.kw_in))
2724 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
2725 if (Right.is(Keywords.kw_in))
2726 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
2727 if (Right.is(Keywords.kw_as))
2728 return false; // must not break before as in 'x as type' casts
2729 if (Left.is(Keywords.kw_as))
2731 if (Left.is(TT_JsNonNullAssertion))
2733 if (Left.is(Keywords.kw_declare) &&
2734 Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
2735 Keywords.kw_function, tok::kw_class, tok::kw_enum,
2736 Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
2737 Keywords.kw_let, tok::kw_const))
2738 // See grammar for 'declare' statements at:
2739 // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10
2741 if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
2742 Right.isOneOf(tok::identifier, tok::string_literal))
2743 return false; // must not break in "module foo { ...}"
2744 if (Right.is(TT_TemplateString) && Right.closesScope())
2746 if (Left.is(TT_TemplateString) && Left.opensScope())
2750 if (Left.is(tok::at))
2752 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2754 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2755 return !Right.is(tok::l_paren);
2756 if (Right.is(TT_PointerOrReference))
2757 return Line.IsMultiVariableDeclStmt ||
2758 (Style.PointerAlignment == FormatStyle::PAS_Right &&
2759 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2760 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2761 Right.is(tok::kw_operator))
2763 if (Left.is(TT_PointerOrReference))
2765 if (Right.isTrailingComment())
2766 // We rely on MustBreakBefore being set correctly here as we should not
2767 // change the "binding" behavior of a comment.
2768 // The first comment in a braced lists is always interpreted as belonging to
2769 // the first list element. Otherwise, it should be placed outside of the
2771 return Left.BlockKind == BK_BracedInit ||
2772 (Left.is(TT_CtorInitializerColon) &&
2773 Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon);
2774 if (Left.is(tok::question) && Right.is(tok::colon))
2776 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2777 return Style.BreakBeforeTernaryOperators;
2778 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2779 return !Style.BreakBeforeTernaryOperators;
2780 if (Right.is(TT_InheritanceColon))
2782 if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
2783 Left.isNot(TT_SelectorName))
2785 if (Right.is(tok::colon) &&
2786 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2788 if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr))
2790 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2791 Right.Next->is(TT_ObjCMethodExpr)))
2792 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2793 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2795 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
2797 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2798 TT_OverloadedOperator))
2800 if (Left.is(TT_RangeBasedForLoopColon))
2802 if (Right.is(TT_RangeBasedForLoopColon))
2804 if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
2806 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2807 Left.is(tok::kw_operator))
2809 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2810 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
2812 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2814 if (Left.is(tok::l_paren) && Left.Previous &&
2815 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2817 if (Right.is(TT_ImplicitStringLiteral))
2820 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2822 if (Right.is(tok::r_square) && Right.MatchingParen &&
2823 Right.MatchingParen->is(TT_LambdaLSquare))
2826 // We only break before r_brace if there was a corresponding break before
2827 // the l_brace, which is tracked by BreakBeforeClosingBrace.
2828 if (Right.is(tok::r_brace))
2829 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2831 // Allow breaking after a trailing annotation, e.g. after a method
2833 if (Left.is(TT_TrailingAnnotation))
2834 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2835 tok::less, tok::coloncolon);
2837 if (Right.is(tok::kw___attribute))
2840 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2843 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2846 if (Left.is(TT_CtorInitializerColon))
2847 return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
2848 if (Right.is(TT_CtorInitializerColon))
2849 return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon;
2850 if (Left.is(TT_CtorInitializerComma) &&
2851 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
2853 if (Right.is(TT_CtorInitializerComma) &&
2854 Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
2856 if (Left.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma)
2858 if (Right.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma)
2860 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2861 (Left.is(tok::less) && Right.is(tok::less)))
2863 if (Right.is(TT_BinaryOperator) &&
2864 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2865 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2866 Right.getPrecedence() != prec::Assignment))
2868 if (Left.is(TT_ArrayInitializerLSquare))
2870 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2872 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
2873 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2874 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2875 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2876 Left.getPrecedence() == prec::Assignment))
2878 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2879 tok::kw_class, tok::kw_struct, tok::comment) ||
2880 Right.isMemberAccess() ||
2881 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2882 tok::colon, tok::l_square, tok::at) ||
2883 (Left.is(tok::r_paren) &&
2884 Right.isOneOf(tok::identifier, tok::kw_const)) ||
2885 (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
2886 (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
2889 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2890 llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
2891 const FormatToken *Tok = Line.First;
2893 llvm::errs() << " M=" << Tok->MustBreakBefore
2894 << " C=" << Tok->CanBreakBefore
2895 << " T=" << getTokenTypeName(Tok->Type)
2896 << " S=" << Tok->SpacesRequiredBefore
2897 << " B=" << Tok->BlockParameterCount
2898 << " BK=" << Tok->BlockKind << " P=" << Tok->SplitPenalty
2899 << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
2900 << " PPK=" << Tok->PackingKind << " FakeLParens=";
2901 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2902 llvm::errs() << Tok->FakeLParens[i] << "/";
2903 llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
2904 llvm::errs() << " Text='" << Tok->TokenText << "'\n";
2906 assert(Tok == Line.Last);
2909 llvm::errs() << "----\n";
2912 } // namespace format
2913 } // namespace clang