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;
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))
94 // If a && or || is found and interpreted as a binary operator, this set
95 // of angles is likely part of something like "a < b && c > d". If the
96 // angles are inside an expression, the ||/&& might also be a binary
97 // operator that was misinterpreted because we are parsing template
99 // FIXME: This is getting out of hand, write a decent parser.
100 if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
101 CurrentToken->Previous->is(TT_BinaryOperator) &&
102 Contexts[Contexts.size() - 2].IsExpression &&
103 !Line.startsWith(tok::kw_template))
105 updateParameterCount(Left, CurrentToken);
112 bool parseParens(bool LookForDecls = false) {
115 FormatToken *Left = CurrentToken->Previous;
116 Left->ParentBracket = Contexts.back().ContextKind;
117 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
119 // FIXME: This is a bit of a hack. Do better.
120 Contexts.back().ColonIsForRangeExpr =
121 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
123 bool StartsObjCMethodExpr = false;
124 if (CurrentToken->is(tok::caret)) {
125 // (^ can start a block type.
126 Left->Type = TT_ObjCBlockLParen;
127 } else if (FormatToken *MaybeSel = Left->Previous) {
128 // @selector( starts a selector.
129 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
130 MaybeSel->Previous->is(tok::at)) {
131 StartsObjCMethodExpr = true;
135 if (Left->is(TT_OverloadedOperatorLParen)) {
136 Contexts.back().IsExpression = false;
137 } else if (Left->Previous &&
138 (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
139 tok::kw_if, tok::kw_while, tok::l_paren,
141 Left->Previous->is(TT_BinaryOperator))) {
142 // static_assert, if and while usually contain expressions.
143 Contexts.back().IsExpression = true;
144 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
145 (Left->Previous->is(Keywords.kw_function) ||
146 (Left->Previous->endsSequence(tok::identifier,
147 Keywords.kw_function)))) {
148 // function(...) or function f(...)
149 Contexts.back().IsExpression = false;
150 } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
151 Left->Previous->MatchingParen &&
152 Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
153 // This is a parameter list of a lambda expression.
154 Contexts.back().IsExpression = false;
155 } else if (Line.InPPDirective &&
156 (!Left->Previous || !Left->Previous->is(tok::identifier))) {
157 Contexts.back().IsExpression = true;
158 } else if (Contexts[Contexts.size() - 2].CaretFound) {
159 // This is the parameter list of an ObjC block.
160 Contexts.back().IsExpression = false;
161 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
162 Left->Type = TT_AttributeParen;
163 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
164 // The first argument to a foreach macro is a declaration.
165 Contexts.back().IsForEachMacro = true;
166 Contexts.back().IsExpression = false;
167 } else if (Left->Previous && Left->Previous->MatchingParen &&
168 Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
169 Contexts.back().IsExpression = false;
170 } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
172 Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
173 Contexts.back().IsExpression = !IsForOrCatch;
176 if (StartsObjCMethodExpr) {
177 Contexts.back().ColonIsObjCMethodExpr = true;
178 Left->Type = TT_ObjCMethodExpr;
181 bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
182 bool ProbablyFunctionType = CurrentToken->isOneOf(tok::star, tok::amp);
183 bool HasMultipleLines = false;
184 bool HasMultipleParametersOnALine = false;
185 bool MightBeObjCForRangeLoop =
186 Left->Previous && Left->Previous->is(tok::kw_for);
187 while (CurrentToken) {
188 // LookForDecls is set when "if (" has been seen. Check for
189 // 'identifier' '*' 'identifier' followed by not '=' -- this
190 // '*' has to be a binary operator but determineStarAmpUsage() will
191 // categorize it as an unary operator, so set the right type here.
192 if (LookForDecls && CurrentToken->Next) {
193 FormatToken *Prev = CurrentToken->getPreviousNonComment();
195 FormatToken *PrevPrev = Prev->getPreviousNonComment();
196 FormatToken *Next = CurrentToken->Next;
197 if (PrevPrev && PrevPrev->is(tok::identifier) &&
198 Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
199 CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
200 Prev->Type = TT_BinaryOperator;
201 LookForDecls = false;
206 if (CurrentToken->Previous->is(TT_PointerOrReference) &&
207 CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
209 ProbablyFunctionType = true;
210 if (CurrentToken->is(tok::comma))
211 MightBeFunctionType = false;
212 if (CurrentToken->Previous->is(TT_BinaryOperator))
213 Contexts.back().IsExpression = true;
214 if (CurrentToken->is(tok::r_paren)) {
215 if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next &&
216 (CurrentToken->Next->is(tok::l_paren) ||
217 (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration)))
218 Left->Type = TT_FunctionTypeLParen;
219 Left->MatchingParen = CurrentToken;
220 CurrentToken->MatchingParen = Left;
222 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
223 Left->Previous && Left->Previous->is(tok::l_paren)) {
224 // Detect the case where macros are used to generate lambdas or
225 // function bodies, e.g.:
226 // auto my_lambda = MARCO((Type *type, int i) { .. body .. });
227 for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
228 if (Tok->is(TT_BinaryOperator) &&
229 Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
230 Tok->Type = TT_PointerOrReference;
234 if (StartsObjCMethodExpr) {
235 CurrentToken->Type = TT_ObjCMethodExpr;
236 if (Contexts.back().FirstObjCSelectorName) {
237 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
238 Contexts.back().LongestObjCSelectorName;
242 if (Left->is(TT_AttributeParen))
243 CurrentToken->Type = TT_AttributeParen;
244 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
245 CurrentToken->Type = TT_JavaAnnotation;
246 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
247 CurrentToken->Type = TT_LeadingJavaAnnotation;
249 if (!HasMultipleLines)
250 Left->PackingKind = PPK_Inconclusive;
251 else if (HasMultipleParametersOnALine)
252 Left->PackingKind = PPK_BinPacked;
254 Left->PackingKind = PPK_OnePerLine;
259 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
262 if (CurrentToken->is(tok::l_brace))
263 Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
264 if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
265 !CurrentToken->Next->HasUnescapedNewline &&
266 !CurrentToken->Next->isTrailingComment())
267 HasMultipleParametersOnALine = true;
268 if (CurrentToken->isOneOf(tok::kw_const, tok::kw_auto) ||
269 CurrentToken->isSimpleTypeSpecifier())
270 Contexts.back().IsExpression = false;
271 if (CurrentToken->isOneOf(tok::semi, tok::colon))
272 MightBeObjCForRangeLoop = false;
273 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
274 CurrentToken->Type = TT_ObjCForIn;
275 // When we discover a 'new', we set CanBeExpression to 'false' in order to
276 // parse the type correctly. Reset that after a comma.
277 if (CurrentToken->is(tok::comma))
278 Contexts.back().CanBeExpression = true;
280 FormatToken *Tok = CurrentToken;
283 updateParameterCount(Left, Tok);
284 if (CurrentToken && CurrentToken->HasUnescapedNewline)
285 HasMultipleLines = true;
294 // A '[' could be an index subscript (after an identifier or after
295 // ')' or ']'), it could be the start of an Objective-C method
296 // expression, or it could the start of an Objective-C array literal.
297 FormatToken *Left = CurrentToken->Previous;
298 Left->ParentBracket = Contexts.back().ContextKind;
299 FormatToken *Parent = Left->getPreviousNonComment();
300 bool StartsObjCMethodExpr =
301 Style.Language == FormatStyle::LK_Cpp &&
302 Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
303 CurrentToken->isNot(tok::l_brace) &&
305 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
306 tok::kw_return, tok::kw_throw) ||
307 Parent->isUnaryOperator() ||
308 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
309 getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
310 bool ColonFound = false;
312 unsigned BindingIncrease = 1;
313 if (Left->is(TT_Unknown)) {
314 if (StartsObjCMethodExpr) {
315 Left->Type = TT_ObjCMethodExpr;
316 } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
317 Contexts.back().ContextKind == tok::l_brace &&
318 Parent->isOneOf(tok::l_brace, tok::comma)) {
319 Left->Type = TT_JsComputedPropertyName;
320 } else if (Style.Language == FormatStyle::LK_Proto ||
322 Parent->isOneOf(TT_BinaryOperator, tok::at, tok::comma,
323 tok::l_paren, tok::l_square, tok::question,
324 tok::colon, tok::kw_return,
325 // Should only be relevant to JavaScript:
327 Left->Type = TT_ArrayInitializerLSquare;
329 BindingIncrease = 10;
330 Left->Type = TT_ArraySubscriptLSquare;
334 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
335 Contexts.back().IsExpression = true;
336 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
338 while (CurrentToken) {
339 if (CurrentToken->is(tok::r_square)) {
340 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
341 Left->is(TT_ObjCMethodExpr)) {
342 // An ObjC method call is rarely followed by an open parenthesis.
343 // FIXME: Do we incorrectly label ":" with this?
344 StartsObjCMethodExpr = false;
345 Left->Type = TT_Unknown;
347 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
348 CurrentToken->Type = TT_ObjCMethodExpr;
349 // determineStarAmpUsage() thinks that '*' '[' is allocating an
350 // array of pointers, but if '[' starts a selector then '*' is a
352 if (Parent && Parent->is(TT_PointerOrReference))
353 Parent->Type = TT_BinaryOperator;
355 Left->MatchingParen = CurrentToken;
356 CurrentToken->MatchingParen = Left;
357 if (Contexts.back().FirstObjCSelectorName) {
358 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
359 Contexts.back().LongestObjCSelectorName;
360 if (Left->BlockParameterCount > 1)
361 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
366 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
368 if (CurrentToken->is(tok::colon)) {
369 if (Left->is(TT_ArraySubscriptLSquare)) {
370 Left->Type = TT_ObjCMethodExpr;
371 StartsObjCMethodExpr = true;
372 Contexts.back().ColonIsObjCMethodExpr = true;
373 if (Parent && Parent->is(tok::r_paren))
374 Parent->Type = TT_CastRParen;
378 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
380 Left->Type = TT_ArrayInitializerLSquare;
381 FormatToken *Tok = CurrentToken;
384 updateParameterCount(Left, Tok);
391 FormatToken *Left = CurrentToken->Previous;
392 Left->ParentBracket = Contexts.back().ContextKind;
394 if (Contexts.back().CaretFound)
395 Left->Type = TT_ObjCBlockLBrace;
396 Contexts.back().CaretFound = false;
398 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
399 Contexts.back().ColonIsDictLiteral = true;
400 if (Left->BlockKind == BK_BracedInit)
401 Contexts.back().IsExpression = true;
403 while (CurrentToken) {
404 if (CurrentToken->is(tok::r_brace)) {
405 Left->MatchingParen = CurrentToken;
406 CurrentToken->MatchingParen = Left;
410 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
412 updateParameterCount(Left, CurrentToken);
413 if (CurrentToken->isOneOf(tok::colon, tok::l_brace)) {
414 FormatToken *Previous = CurrentToken->getPreviousNonComment();
415 if (((CurrentToken->is(tok::colon) &&
416 (!Contexts.back().ColonIsDictLiteral ||
417 Style.Language != FormatStyle::LK_Cpp)) ||
418 Style.Language == FormatStyle::LK_Proto) &&
419 (Previous->Tok.getIdentifierInfo() ||
420 Previous->is(tok::string_literal)))
421 Previous->Type = TT_SelectorName;
422 if (CurrentToken->is(tok::colon) ||
423 Style.Language == FormatStyle::LK_JavaScript)
424 Left->Type = TT_DictLiteral;
433 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
434 if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
435 ++Left->BlockParameterCount;
436 if (Current->is(tok::comma)) {
437 ++Left->ParameterCount;
439 Left->Role.reset(new CommaSeparatedList(Style));
440 Left->Role->CommaFound(Current);
441 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
442 Left->ParameterCount = 1;
446 bool parseConditional() {
447 while (CurrentToken) {
448 if (CurrentToken->is(tok::colon)) {
449 CurrentToken->Type = TT_ConditionalExpr;
459 bool parseTemplateDeclaration() {
460 if (CurrentToken && CurrentToken->is(tok::less)) {
461 CurrentToken->Type = TT_TemplateOpener;
466 CurrentToken->Previous->ClosesTemplateDeclaration = true;
472 bool consumeToken() {
473 FormatToken *Tok = CurrentToken;
475 switch (Tok->Tok.getKind()) {
478 if (!Tok->Previous && Line.MustBeDeclaration)
479 Tok->Type = TT_ObjCMethodSpecifier;
484 // Colons from ?: are handled in parseConditional().
485 if (Style.Language == FormatStyle::LK_JavaScript) {
486 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
487 (Contexts.size() == 1 && // switch/case labels
488 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
489 Contexts.back().ContextKind == tok::l_paren || // function params
490 Contexts.back().ContextKind == tok::l_square || // array type
491 (Contexts.size() == 1 &&
492 Line.MustBeDeclaration)) { // method/property declaration
493 Tok->Type = TT_JsTypeColon;
497 if (Contexts.back().ColonIsDictLiteral ||
498 Style.Language == FormatStyle::LK_Proto) {
499 Tok->Type = TT_DictLiteral;
500 } else if (Contexts.back().ColonIsObjCMethodExpr ||
501 Line.startsWith(TT_ObjCMethodSpecifier)) {
502 Tok->Type = TT_ObjCMethodExpr;
503 Tok->Previous->Type = TT_SelectorName;
504 if (Tok->Previous->ColumnWidth >
505 Contexts.back().LongestObjCSelectorName)
506 Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth;
507 if (!Contexts.back().FirstObjCSelectorName)
508 Contexts.back().FirstObjCSelectorName = Tok->Previous;
509 } else if (Contexts.back().ColonIsForRangeExpr) {
510 Tok->Type = TT_RangeBasedForLoopColon;
511 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
512 Tok->Type = TT_BitFieldColon;
513 } else if (Contexts.size() == 1 &&
514 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
515 if (Tok->Previous->isOneOf(tok::r_paren, tok::kw_noexcept))
516 Tok->Type = TT_CtorInitializerColon;
518 Tok->Type = TT_InheritanceColon;
519 } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
520 Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
521 // This handles a special macro in ObjC code where selectors including
522 // the colon are passed as macro arguments.
523 Tok->Type = TT_ObjCMethodExpr;
524 } else if (Contexts.back().ContextKind == tok::l_paren) {
525 Tok->Type = TT_InlineASMColon;
530 // | and & in declarations/type expressions represent union and
531 // intersection types, respectively.
532 if (Style.Language == FormatStyle::LK_JavaScript &&
533 !Contexts.back().IsExpression)
534 Tok->Type = TT_JsTypeOperator;
538 if (CurrentToken && CurrentToken->is(tok::l_paren)) {
540 if (!parseParens(/*LookForDecls=*/true))
545 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Previous &&
546 Tok->Previous->is(tok::period))
548 Contexts.back().ColonIsForRangeExpr = true;
554 // When faced with 'operator()()', the kw_operator handler incorrectly
555 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
556 // the first two parens OverloadedOperators and the second l_paren an
557 // OverloadedOperatorLParen.
559 Tok->Previous->is(tok::r_paren) &&
560 Tok->Previous->MatchingParen &&
561 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
562 Tok->Previous->Type = TT_OverloadedOperator;
563 Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
564 Tok->Type = TT_OverloadedOperatorLParen;
569 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
570 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
572 !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
573 TT_LeadingJavaAnnotation)))
574 Line.MightBeFunctionDecl = true;
586 Tok->Type = TT_TemplateOpener;
588 Tok->Type = TT_BinaryOperator;
589 NonTemplateLess.insert(Tok);
598 // Lines can start with '}'.
603 Tok->Type = TT_BinaryOperator;
605 case tok::kw_operator:
606 while (CurrentToken &&
607 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
608 if (CurrentToken->isOneOf(tok::star, tok::amp))
609 CurrentToken->Type = TT_PointerOrReference;
612 CurrentToken->Previous->isOneOf(TT_BinaryOperator, tok::comma))
613 CurrentToken->Previous->Type = TT_OverloadedOperator;
616 CurrentToken->Type = TT_OverloadedOperatorLParen;
617 if (CurrentToken->Previous->is(TT_BinaryOperator))
618 CurrentToken->Previous->Type = TT_OverloadedOperator;
622 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
623 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
625 // Question marks before semicolons, colons, etc. indicate optional
626 // types (fields, parameters), e.g.
627 // function(x?: string, y?) {...}
629 Tok->Type = TT_JsTypeOptionalQuestion;
632 // Declarations cannot be conditional expressions, this can only be part
633 // of a type declaration.
634 if (Line.MustBeDeclaration &&
635 Style.Language == FormatStyle::LK_JavaScript)
639 case tok::kw_template:
640 parseTemplateDeclaration();
643 if (Contexts.back().InCtorInitializer)
644 Tok->Type = TT_CtorInitializerComma;
645 else if (Contexts.back().FirstStartOfName &&
646 (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
647 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
648 Line.IsMultiVariableDeclStmt = true;
650 if (Contexts.back().IsForEachMacro)
651 Contexts.back().IsExpression = true;
659 void parseIncludeDirective() {
660 if (CurrentToken && CurrentToken->is(tok::less)) {
662 while (CurrentToken) {
663 if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
664 CurrentToken->Type = TT_ImplicitStringLiteral;
670 void parseWarningOrError() {
672 // We still want to format the whitespace left of the first token of the
675 while (CurrentToken) {
676 CurrentToken->Type = TT_ImplicitStringLiteral;
682 next(); // Consume "pragma".
684 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
685 bool IsMark = CurrentToken->is(Keywords.kw_mark);
686 next(); // Consume "mark".
687 next(); // Consume first token (so we fix leading whitespace).
688 while (CurrentToken) {
689 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
690 CurrentToken->Type = TT_ImplicitStringLiteral;
696 LineType parsePreprocessorDirective() {
697 bool IsFirstToken = CurrentToken->IsFirst;
698 LineType Type = LT_PreprocessorDirective;
703 if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
704 // JavaScript files can contain shebang lines of the form:
705 // #!/usr/bin/env node
706 // Treat these like C++ #include directives.
707 while (CurrentToken) {
708 // Tokens cannot be comments here.
709 CurrentToken->Type = TT_ImplicitStringLiteral;
712 return LT_ImportStatement;
715 if (CurrentToken->Tok.is(tok::numeric_constant)) {
716 CurrentToken->SpacesRequiredBefore = 1;
719 // Hashes in the middle of a line can lead to any strange token
721 if (!CurrentToken->Tok.getIdentifierInfo())
723 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
724 case tok::pp_include:
725 case tok::pp_include_next:
728 parseIncludeDirective();
729 Type = LT_ImportStatement;
732 case tok::pp_warning:
733 parseWarningOrError();
740 Contexts.back().IsExpression = true;
752 LineType parseLine() {
753 NonTemplateLess.clear();
754 if (CurrentToken->is(tok::hash))
755 return parsePreprocessorDirective();
757 // Directly allow to 'import <string-literal>' to support protocol buffer
758 // definitions (code.google.com/p/protobuf) or missing "#" (either way we
759 // should not break the line).
760 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
761 if ((Style.Language == FormatStyle::LK_Java &&
762 CurrentToken->is(Keywords.kw_package)) ||
763 (Info && Info->getPPKeywordID() == tok::pp_import &&
764 CurrentToken->Next &&
765 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
768 parseIncludeDirective();
769 return LT_ImportStatement;
772 // If this line starts and ends in '<' and '>', respectively, it is likely
773 // part of "#define <a/b.h>".
774 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
775 parseIncludeDirective();
776 return LT_ImportStatement;
779 // In .proto files, top-level options are very similar to import statements
780 // and should not be line-wrapped.
781 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
782 CurrentToken->is(Keywords.kw_option)) {
784 if (CurrentToken && CurrentToken->is(tok::identifier))
785 return LT_ImportStatement;
788 // import {...} from '...';
789 if (Style.Language == FormatStyle::LK_JavaScript &&
790 CurrentToken->is(Keywords.kw_import))
791 return LT_ImportStatement;
793 bool KeywordVirtualFound = false;
794 bool ImportStatement = false;
795 while (CurrentToken) {
796 if (CurrentToken->is(tok::kw_virtual))
797 KeywordVirtualFound = true;
798 if (Style.Language == FormatStyle::LK_JavaScript) {
799 // export {...} from '...';
800 // An export followed by "from 'some string';" is a re-export from
801 // another module identified by a URI and is treated as a
802 // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
803 // Just "export {...};" or "export class ..." should not be treated as
804 // an import in this sense.
805 if (Line.First->is(tok::kw_export) &&
806 CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
807 CurrentToken->Next->isStringLiteral())
808 ImportStatement = true;
809 if (isClosureImportStatement(*CurrentToken))
810 ImportStatement = true;
815 if (KeywordVirtualFound)
816 return LT_VirtualFunctionDecl;
818 return LT_ImportStatement;
820 if (Line.startsWith(TT_ObjCMethodSpecifier)) {
821 if (Contexts.back().FirstObjCSelectorName)
822 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
823 Contexts.back().LongestObjCSelectorName;
824 return LT_ObjCMethodDecl;
831 bool isClosureImportStatement(const FormatToken &Tok) {
832 // FIXME: Closure-library specific stuff should not be hard-coded but be
834 return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
835 Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
836 Tok.Next->Next->TokenText == "provide" ||
837 Tok.Next->Next->TokenText == "require" ||
838 Tok.Next->Next->TokenText == "setTestOnly" ||
839 Tok.Next->Next->TokenText == "forwardDeclare") &&
840 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
843 void resetTokenMetadata(FormatToken *Token) {
847 // Reset token type in case we have already looked at it and then
848 // recovered from an error (e.g. failure to find the matching >).
849 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
850 TT_FunctionLBrace, TT_ImplicitStringLiteral,
851 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
853 CurrentToken->Type = TT_Unknown;
854 CurrentToken->Role.reset();
855 CurrentToken->MatchingParen = nullptr;
856 CurrentToken->FakeLParens.clear();
857 CurrentToken->FakeRParens = 0;
862 CurrentToken->NestingLevel = Contexts.size() - 1;
863 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
864 modifyContext(*CurrentToken);
865 determineTokenType(*CurrentToken);
866 CurrentToken = CurrentToken->Next;
869 resetTokenMetadata(CurrentToken);
872 /// \brief A struct to hold information valid in a specific context, e.g.
873 /// a pair of parenthesis.
875 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
877 : ContextKind(ContextKind), BindingStrength(BindingStrength),
878 IsExpression(IsExpression) {}
880 tok::TokenKind ContextKind;
881 unsigned BindingStrength;
883 unsigned LongestObjCSelectorName = 0;
884 bool ColonIsForRangeExpr = false;
885 bool ColonIsDictLiteral = false;
886 bool ColonIsObjCMethodExpr = false;
887 FormatToken *FirstObjCSelectorName = nullptr;
888 FormatToken *FirstStartOfName = nullptr;
889 bool CanBeExpression = true;
890 bool InTemplateArgument = false;
891 bool InCtorInitializer = false;
892 bool CaretFound = false;
893 bool IsForEachMacro = false;
896 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
897 /// of each instance.
898 struct ScopedContextCreator {
901 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
904 P.Contexts.push_back(Context(ContextKind,
905 P.Contexts.back().BindingStrength + Increase,
906 P.Contexts.back().IsExpression));
909 ~ScopedContextCreator() { P.Contexts.pop_back(); }
912 void modifyContext(const FormatToken &Current) {
913 if (Current.getPrecedence() == prec::Assignment &&
914 !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
915 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
916 Contexts.back().IsExpression = true;
917 if (!Line.startsWith(TT_UnaryOperator)) {
918 for (FormatToken *Previous = Current.Previous;
919 Previous && Previous->Previous &&
920 !Previous->Previous->isOneOf(tok::comma, tok::semi);
921 Previous = Previous->Previous) {
922 if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
923 Previous = Previous->MatchingParen;
927 if (Previous->opensScope())
929 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
930 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
931 Previous->Previous && Previous->Previous->isNot(tok::equal))
932 Previous->Type = TT_PointerOrReference;
935 } else if (Current.is(tok::lessless) &&
936 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
937 Contexts.back().IsExpression = true;
938 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
939 Contexts.back().IsExpression = true;
940 } else if (Current.is(TT_TrailingReturnArrow)) {
941 Contexts.back().IsExpression = false;
942 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
943 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
944 } else if (Current.Previous &&
945 Current.Previous->is(TT_CtorInitializerColon)) {
946 Contexts.back().IsExpression = true;
947 Contexts.back().InCtorInitializer = true;
948 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
949 for (FormatToken *Previous = Current.Previous;
950 Previous && Previous->isOneOf(tok::star, tok::amp);
951 Previous = Previous->Previous)
952 Previous->Type = TT_PointerOrReference;
953 if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
954 Contexts.back().IsExpression = false;
955 } else if (Current.is(tok::kw_new)) {
956 Contexts.back().CanBeExpression = false;
957 } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
958 // This should be the condition or increment in a for-loop.
959 Contexts.back().IsExpression = true;
963 void determineTokenType(FormatToken &Current) {
964 if (!Current.is(TT_Unknown))
965 // The token type is already known.
968 // Line.MightBeFunctionDecl can only be true after the parentheses of a
969 // function declaration have been found. In this case, 'Current' is a
970 // trailing token of this declaration and thus cannot be a name.
971 if (Current.is(Keywords.kw_instanceof)) {
972 Current.Type = TT_BinaryOperator;
973 } else if (isStartOfName(Current) &&
974 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
975 Contexts.back().FirstStartOfName = &Current;
976 Current.Type = TT_StartOfName;
977 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
979 } else if (Current.is(tok::arrow) &&
980 Style.Language == FormatStyle::LK_Java) {
981 Current.Type = TT_LambdaArrow;
982 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
983 Current.NestingLevel == 0) {
984 Current.Type = TT_TrailingReturnArrow;
985 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
987 determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
988 Contexts.back().IsExpression,
989 Contexts.back().InTemplateArgument);
990 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
991 Current.Type = determinePlusMinusCaretUsage(Current);
992 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
993 Contexts.back().CaretFound = true;
994 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
995 Current.Type = determineIncrementUsage(Current);
996 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
997 Current.Type = TT_UnaryOperator;
998 } else if (Current.is(tok::question)) {
999 if (Style.Language == FormatStyle::LK_JavaScript &&
1000 Line.MustBeDeclaration) {
1001 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
1002 // on the interface, not a ternary expression.
1003 Current.Type = TT_JsTypeOptionalQuestion;
1005 Current.Type = TT_ConditionalExpr;
1007 } else if (Current.isBinaryOperator() &&
1008 (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
1009 Current.Type = TT_BinaryOperator;
1010 } else if (Current.is(tok::comment)) {
1011 if (Current.TokenText.startswith("/*")) {
1012 if (Current.TokenText.endswith("*/"))
1013 Current.Type = TT_BlockComment;
1015 // The lexer has for some reason determined a comment here. But we
1016 // cannot really handle it, if it isn't properly terminated.
1017 Current.Tok.setKind(tok::unknown);
1019 Current.Type = TT_LineComment;
1021 } else if (Current.is(tok::r_paren)) {
1022 if (rParenEndsCast(Current))
1023 Current.Type = TT_CastRParen;
1024 if (Current.MatchingParen && Current.Next &&
1025 !Current.Next->isBinaryOperator() &&
1026 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1027 tok::period, tok::arrow, tok::coloncolon))
1028 if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1029 if (BeforeParen->is(tok::identifier) &&
1030 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1031 (!BeforeParen->Previous ||
1032 BeforeParen->Previous->ClosesTemplateDeclaration))
1033 Current.Type = TT_FunctionAnnotationRParen;
1034 } else if (Current.is(tok::at) && Current.Next) {
1035 if (Current.Next->isStringLiteral()) {
1036 Current.Type = TT_ObjCStringLiteral;
1038 switch (Current.Next->Tok.getObjCKeywordID()) {
1039 case tok::objc_interface:
1040 case tok::objc_implementation:
1041 case tok::objc_protocol:
1042 Current.Type = TT_ObjCDecl;
1044 case tok::objc_property:
1045 Current.Type = TT_ObjCProperty;
1051 } else if (Current.is(tok::period)) {
1052 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1053 if (PreviousNoComment &&
1054 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1055 Current.Type = TT_DesignatedInitializerPeriod;
1056 else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1057 Current.Previous->isOneOf(TT_JavaAnnotation,
1058 TT_LeadingJavaAnnotation)) {
1059 Current.Type = Current.Previous->Type;
1061 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
1063 !Current.Previous->isOneOf(tok::equal, tok::at) &&
1064 Line.MightBeFunctionDecl && Contexts.size() == 1) {
1065 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1066 // function declaration have been found.
1067 Current.Type = TT_TrailingAnnotation;
1068 } else if ((Style.Language == FormatStyle::LK_Java ||
1069 Style.Language == FormatStyle::LK_JavaScript) &&
1071 if (Current.Previous->is(tok::at) &&
1072 Current.isNot(Keywords.kw_interface)) {
1073 const FormatToken &AtToken = *Current.Previous;
1074 const FormatToken *Previous = AtToken.getPreviousNonComment();
1075 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1076 Current.Type = TT_LeadingJavaAnnotation;
1078 Current.Type = TT_JavaAnnotation;
1079 } else if (Current.Previous->is(tok::period) &&
1080 Current.Previous->isOneOf(TT_JavaAnnotation,
1081 TT_LeadingJavaAnnotation)) {
1082 Current.Type = Current.Previous->Type;
1087 /// \brief Take a guess at whether \p Tok starts a name of a function or
1088 /// variable declaration.
1090 /// This is a heuristic based on whether \p Tok is an identifier following
1091 /// something that is likely a type.
1092 bool isStartOfName(const FormatToken &Tok) {
1093 if (Tok.isNot(tok::identifier) || !Tok.Previous)
1096 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof))
1098 if (Style.Language == FormatStyle::LK_JavaScript &&
1099 Tok.Previous->is(Keywords.kw_in))
1102 // Skip "const" as it does not have an influence on whether this is a name.
1103 FormatToken *PreviousNotConst = Tok.Previous;
1104 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1105 PreviousNotConst = PreviousNotConst->Previous;
1107 if (!PreviousNotConst)
1110 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1111 PreviousNotConst->Previous &&
1112 PreviousNotConst->Previous->is(tok::hash);
1114 if (PreviousNotConst->is(TT_TemplateCloser))
1115 return PreviousNotConst && PreviousNotConst->MatchingParen &&
1116 PreviousNotConst->MatchingParen->Previous &&
1117 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1118 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1120 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1121 PreviousNotConst->MatchingParen->Previous &&
1122 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1125 return (!IsPPKeyword &&
1126 PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1127 PreviousNotConst->is(TT_PointerOrReference) ||
1128 PreviousNotConst->isSimpleTypeSpecifier();
1131 /// \brief Determine whether ')' is ending a cast.
1132 bool rParenEndsCast(const FormatToken &Tok) {
1133 // C-style casts are only used in C++ and Java.
1134 if (Style.Language != FormatStyle::LK_Cpp &&
1135 Style.Language != FormatStyle::LK_Java)
1138 // Empty parens aren't casts and there are no casts at the end of the line.
1139 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1142 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1144 // If there is a closing parenthesis left of the current parentheses,
1145 // look past it as these might be chained casts.
1146 if (LeftOfParens->is(tok::r_paren)) {
1147 if (!LeftOfParens->MatchingParen ||
1148 !LeftOfParens->MatchingParen->Previous)
1150 LeftOfParens = LeftOfParens->MatchingParen->Previous;
1153 // If there is an identifier (or with a few exceptions a keyword) right
1154 // before the parentheses, this is unlikely to be a cast.
1155 if (LeftOfParens->Tok.getIdentifierInfo() &&
1156 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1160 // Certain other tokens right before the parentheses are also signals that
1161 // this cannot be a cast.
1162 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1163 TT_TemplateCloser, tok::ellipsis))
1167 if (Tok.Next->is(tok::question))
1170 // As Java has no function types, a "(" after the ")" likely means that this
1172 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1175 // If a (non-string) literal follows, this is likely a cast.
1176 if (Tok.Next->isNot(tok::string_literal) &&
1177 (Tok.Next->Tok.isLiteral() ||
1178 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1181 // Heuristically try to determine whether the parentheses contain a type.
1182 bool ParensAreType =
1184 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1185 Tok.Previous->isSimpleTypeSpecifier();
1186 bool ParensCouldEndDecl =
1187 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1188 if (ParensAreType && !ParensCouldEndDecl)
1191 // At this point, we heuristically assume that there are no casts at the
1192 // start of the line. We assume that we have found most cases where there
1193 // are by the logic above, e.g. "(void)x;".
1197 // If the following token is an identifier or 'this', this is a cast. All
1198 // cases where this can be something else are handled above.
1199 if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
1202 if (!Tok.Next->Next)
1205 // If the next token after the parenthesis is a unary operator, assume
1206 // that this is cast, unless there are unexpected tokens inside the
1209 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1210 if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1211 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1213 // Search for unexpected tokens.
1214 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1215 Prev = Prev->Previous) {
1216 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1222 /// \brief Return the type of the given token assuming it is * or &.
1223 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1224 bool InTemplateArgument) {
1225 if (Style.Language == FormatStyle::LK_JavaScript)
1226 return TT_BinaryOperator;
1228 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1230 return TT_UnaryOperator;
1232 const FormatToken *NextToken = Tok.getNextNonComment();
1234 NextToken->isOneOf(tok::arrow, Keywords.kw_final,
1235 Keywords.kw_override) ||
1236 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1237 return TT_PointerOrReference;
1239 if (PrevToken->is(tok::coloncolon))
1240 return TT_PointerOrReference;
1242 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1243 tok::comma, tok::semi, tok::kw_return, tok::colon,
1244 tok::equal, tok::kw_delete, tok::kw_sizeof) ||
1245 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1246 TT_UnaryOperator, TT_CastRParen))
1247 return TT_UnaryOperator;
1249 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1250 return TT_PointerOrReference;
1251 if (NextToken->is(tok::kw_operator) && !IsExpression)
1252 return TT_PointerOrReference;
1253 if (NextToken->isOneOf(tok::comma, tok::semi))
1254 return TT_PointerOrReference;
1256 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
1257 PrevToken->MatchingParen->Previous &&
1258 PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
1260 return TT_PointerOrReference;
1262 if (PrevToken->Tok.isLiteral() ||
1263 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1264 tok::kw_false, tok::r_brace) ||
1265 NextToken->Tok.isLiteral() ||
1266 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1267 NextToken->isUnaryOperator() ||
1268 // If we know we're in a template argument, there are no named
1269 // declarations. Thus, having an identifier on the right-hand side
1270 // indicates a binary operator.
1271 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1272 return TT_BinaryOperator;
1274 // "&&(" is quite unlikely to be two successive unary "&".
1275 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1276 return TT_BinaryOperator;
1278 // This catches some cases where evaluation order is used as control flow:
1280 const FormatToken *NextNextToken = NextToken->getNextNonComment();
1281 if (NextNextToken && NextNextToken->is(tok::arrow))
1282 return TT_BinaryOperator;
1284 // It is very unlikely that we are going to find a pointer or reference type
1285 // definition on the RHS of an assignment.
1286 if (IsExpression && !Contexts.back().CaretFound)
1287 return TT_BinaryOperator;
1289 return TT_PointerOrReference;
1292 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1293 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1294 if (!PrevToken || PrevToken->is(TT_CastRParen))
1295 return TT_UnaryOperator;
1297 // Use heuristics to recognize unary operators.
1298 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1299 tok::question, tok::colon, tok::kw_return,
1300 tok::kw_case, tok::at, tok::l_brace))
1301 return TT_UnaryOperator;
1303 // There can't be two consecutive binary operators.
1304 if (PrevToken->is(TT_BinaryOperator))
1305 return TT_UnaryOperator;
1307 // Fall back to marking the token as binary operator.
1308 return TT_BinaryOperator;
1311 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1312 TokenType determineIncrementUsage(const FormatToken &Tok) {
1313 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1314 if (!PrevToken || PrevToken->is(TT_CastRParen))
1315 return TT_UnaryOperator;
1316 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1317 return TT_TrailingUnaryOperator;
1319 return TT_UnaryOperator;
1322 SmallVector<Context, 8> Contexts;
1324 const FormatStyle &Style;
1325 AnnotatedLine &Line;
1326 FormatToken *CurrentToken;
1328 const AdditionalKeywords &Keywords;
1330 // Set of "<" tokens that do not open a template parameter list. If parseAngle
1331 // determines that a specific token can't be a template opener, it will make
1332 // same decision irrespective of the decisions for tokens leading up to it.
1333 // Store this information to prevent this from causing exponential runtime.
1334 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1337 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1338 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1340 /// \brief Parses binary expressions by inserting fake parenthesis based on
1341 /// operator precedence.
1342 class ExpressionParser {
1344 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1345 AnnotatedLine &Line)
1346 : Style(Style), Keywords(Keywords), Current(Line.First) {}
1348 /// \brief Parse expressions with the given operatore precedence.
1349 void parse(int Precedence = 0) {
1350 // Skip 'return' and ObjC selector colons as they are not part of a binary
1352 while (Current && (Current->is(tok::kw_return) ||
1353 (Current->is(tok::colon) &&
1354 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1357 if (!Current || Precedence > PrecedenceArrowAndPeriod)
1360 // Conditional expressions need to be parsed separately for proper nesting.
1361 if (Precedence == prec::Conditional) {
1362 parseConditionalExpr();
1366 // Parse unary operators, which all have a higher precedence than binary
1368 if (Precedence == PrecedenceUnaryOperator) {
1369 parseUnaryOperator();
1373 FormatToken *Start = Current;
1374 FormatToken *LatestOperator = nullptr;
1375 unsigned OperatorIndex = 0;
1378 // Consume operators with higher precedence.
1379 parse(Precedence + 1);
1381 int CurrentPrecedence = getCurrentPrecedence();
1383 if (Current && Current->is(TT_SelectorName) &&
1384 Precedence == CurrentPrecedence) {
1386 addFakeParenthesis(Start, prec::Level(Precedence));
1390 // At the end of the line or when an operator with higher precedence is
1391 // found, insert fake parenthesis and return.
1392 if (!Current || (Current->closesScope() && Current->MatchingParen) ||
1393 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1394 (CurrentPrecedence == prec::Conditional &&
1395 Precedence == prec::Assignment && Current->is(tok::colon))) {
1399 // Consume scopes: (), [], <> and {}
1400 if (Current->opensScope()) {
1401 while (Current && !Current->closesScope()) {
1408 if (CurrentPrecedence == Precedence) {
1410 LatestOperator->NextOperator = Current;
1411 LatestOperator = Current;
1412 Current->OperatorIndex = OperatorIndex;
1415 next(/*SkipPastLeadingComments=*/Precedence > 0);
1419 if (LatestOperator && (Current || Precedence > 0)) {
1420 // LatestOperator->LastOperator = true;
1421 if (Precedence == PrecedenceArrowAndPeriod) {
1422 // Call expressions don't have a binary operator precedence.
1423 addFakeParenthesis(Start, prec::Unknown);
1425 addFakeParenthesis(Start, prec::Level(Precedence));
1431 /// \brief Gets the precedence (+1) of the given token for binary operators
1432 /// and other tokens that we treat like binary operators.
1433 int getCurrentPrecedence() {
1435 const FormatToken *NextNonComment = Current->getNextNonComment();
1436 if (Current->is(TT_ConditionalExpr))
1437 return prec::Conditional;
1438 if (NextNonComment && NextNonComment->is(tok::colon) &&
1439 NextNonComment->is(TT_DictLiteral))
1441 if (Current->is(TT_LambdaArrow))
1443 if (Current->is(TT_JsFatArrow))
1444 return prec::Assignment;
1445 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName,
1446 TT_JsComputedPropertyName) ||
1447 (Current->is(tok::comment) && NextNonComment &&
1448 NextNonComment->is(TT_SelectorName)))
1450 if (Current->is(TT_RangeBasedForLoopColon))
1452 if ((Style.Language == FormatStyle::LK_Java ||
1453 Style.Language == FormatStyle::LK_JavaScript) &&
1454 Current->is(Keywords.kw_instanceof))
1455 return prec::Relational;
1456 if (Style.Language == FormatStyle::LK_JavaScript &&
1457 Current->is(Keywords.kw_in))
1458 return prec::Relational;
1459 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1460 return Current->getPrecedence();
1461 if (Current->isOneOf(tok::period, tok::arrow))
1462 return PrecedenceArrowAndPeriod;
1463 if (Style.Language == FormatStyle::LK_Java &&
1464 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1465 Keywords.kw_throws))
1471 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1472 Start->FakeLParens.push_back(Precedence);
1473 if (Precedence > prec::Unknown)
1474 Start->StartsBinaryExpression = true;
1476 FormatToken *Previous = Current->Previous;
1477 while (Previous->is(tok::comment) && Previous->Previous)
1478 Previous = Previous->Previous;
1479 ++Previous->FakeRParens;
1480 if (Precedence > prec::Unknown)
1481 Previous->EndsBinaryExpression = true;
1485 /// \brief Parse unary operator expressions and surround them with fake
1486 /// parentheses if appropriate.
1487 void parseUnaryOperator() {
1488 if (!Current || Current->isNot(TT_UnaryOperator)) {
1489 parse(PrecedenceArrowAndPeriod);
1493 FormatToken *Start = Current;
1495 parseUnaryOperator();
1497 // The actual precedence doesn't matter.
1498 addFakeParenthesis(Start, prec::Unknown);
1501 void parseConditionalExpr() {
1502 while (Current && Current->isTrailingComment()) {
1505 FormatToken *Start = Current;
1506 parse(prec::LogicalOr);
1507 if (!Current || !Current->is(tok::question))
1510 parse(prec::Assignment);
1511 if (!Current || Current->isNot(TT_ConditionalExpr))
1514 parse(prec::Assignment);
1515 addFakeParenthesis(Start, prec::Conditional);
1518 void next(bool SkipPastLeadingComments = true) {
1520 Current = Current->Next;
1522 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1523 Current->isTrailingComment())
1524 Current = Current->Next;
1527 const FormatStyle &Style;
1528 const AdditionalKeywords &Keywords;
1529 FormatToken *Current;
1532 } // end anonymous namespace
1534 void TokenAnnotator::setCommentLineLevels(
1535 SmallVectorImpl<AnnotatedLine *> &Lines) {
1536 const AnnotatedLine *NextNonCommentLine = nullptr;
1537 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1540 if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
1541 (*I)->First->Next == nullptr)
1542 (*I)->Level = NextNonCommentLine->Level;
1544 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1546 setCommentLineLevels((*I)->Children);
1550 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1551 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1552 E = Line.Children.end();
1556 AnnotatingParser Parser(Style, Line, Keywords);
1557 Line.Type = Parser.parseLine();
1558 if (Line.Type == LT_Invalid)
1561 ExpressionParser ExprParser(Style, Keywords, Line);
1564 if (Line.startsWith(TT_ObjCMethodSpecifier))
1565 Line.Type = LT_ObjCMethodDecl;
1566 else if (Line.startsWith(TT_ObjCDecl))
1567 Line.Type = LT_ObjCDecl;
1568 else if (Line.startsWith(TT_ObjCProperty))
1569 Line.Type = LT_ObjCProperty;
1571 Line.First->SpacesRequiredBefore = 1;
1572 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1575 // This function heuristically determines whether 'Current' starts the name of a
1576 // function declaration.
1577 static bool isFunctionDeclarationName(const FormatToken &Current,
1578 const AnnotatedLine &Line) {
1579 auto skipOperatorName = [](const FormatToken* Next) -> const FormatToken* {
1580 for (; Next; Next = Next->Next) {
1581 if (Next->is(TT_OverloadedOperatorLParen))
1583 if (Next->is(TT_OverloadedOperator))
1585 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1586 // For 'new[]' and 'delete[]'.
1587 if (Next->Next && Next->Next->is(tok::l_square) &&
1588 Next->Next->Next && Next->Next->Next->is(tok::r_square))
1589 Next = Next->Next->Next;
1598 // Find parentheses of parameter list.
1599 const FormatToken *Next = Current.Next;
1600 if (Current.is(tok::kw_operator)) {
1601 if (Current.Previous && Current.Previous->is(tok::coloncolon))
1603 Next = skipOperatorName(Next);
1605 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1607 for (; Next; Next = Next->Next) {
1608 if (Next->is(TT_TemplateOpener)) {
1609 Next = Next->MatchingParen;
1610 } else if (Next->is(tok::coloncolon)) {
1614 if (Next->is(tok::kw_operator)) {
1615 Next = skipOperatorName(Next->Next);
1618 if (!Next->is(tok::identifier))
1620 } else if (Next->is(tok::l_paren)) {
1628 // Check whether parameter list can be long to a function declaration.
1629 if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
1631 // If the lines ends with "{", this is likely an function definition.
1632 if (Line.Last->is(tok::l_brace))
1634 if (Next->Next == Next->MatchingParen)
1635 return true; // Empty parentheses.
1636 // If there is an &/&& after the r_paren, this is likely a function.
1637 if (Next->MatchingParen->Next &&
1638 Next->MatchingParen->Next->is(TT_PointerOrReference))
1640 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1642 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1643 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
1645 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1646 Tok->Tok.isLiteral())
1652 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
1653 assert(Line.MightBeFunctionDecl);
1655 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
1656 Style.AlwaysBreakAfterReturnType ==
1657 FormatStyle::RTBS_TopLevelDefinitions) &&
1661 switch (Style.AlwaysBreakAfterReturnType) {
1662 case FormatStyle::RTBS_None:
1664 case FormatStyle::RTBS_All:
1665 case FormatStyle::RTBS_TopLevel:
1667 case FormatStyle::RTBS_AllDefinitions:
1668 case FormatStyle::RTBS_TopLevelDefinitions:
1669 return Line.mightBeFunctionDefinition();
1675 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1676 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1677 E = Line.Children.end();
1679 calculateFormattingInformation(**I);
1682 Line.First->TotalLength =
1683 Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1684 if (!Line.First->Next)
1686 FormatToken *Current = Line.First->Next;
1687 bool InFunctionDecl = Line.MightBeFunctionDecl;
1689 if (isFunctionDeclarationName(*Current, Line))
1690 Current->Type = TT_FunctionDeclarationName;
1691 if (Current->is(TT_LineComment)) {
1692 if (Current->Previous->BlockKind == BK_BracedInit &&
1693 Current->Previous->opensScope())
1694 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1696 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1698 // If we find a trailing comment, iterate backwards to determine whether
1699 // it seems to relate to a specific parameter. If so, break before that
1700 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1701 // to the previous line in:
1705 if (!Current->HasUnescapedNewline) {
1706 for (FormatToken *Parameter = Current->Previous; Parameter;
1707 Parameter = Parameter->Previous) {
1708 if (Parameter->isOneOf(tok::comment, tok::r_brace))
1710 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1711 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1712 Parameter->HasUnescapedNewline)
1713 Parameter->MustBreakBefore = true;
1718 } else if (Current->SpacesRequiredBefore == 0 &&
1719 spaceRequiredBefore(Line, *Current)) {
1720 Current->SpacesRequiredBefore = 1;
1723 Current->MustBreakBefore =
1724 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1726 if (!Current->MustBreakBefore && InFunctionDecl &&
1727 Current->is(TT_FunctionDeclarationName))
1728 Current->MustBreakBefore = mustBreakForReturnType(Line);
1730 Current->CanBreakBefore =
1731 Current->MustBreakBefore || canBreakBefore(Line, *Current);
1732 unsigned ChildSize = 0;
1733 if (Current->Previous->Children.size() == 1) {
1734 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1735 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1736 : LastOfChild.TotalLength + 1;
1738 const FormatToken *Prev = Current->Previous;
1739 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1740 (Prev->Children.size() == 1 &&
1741 Prev->Children[0]->First->MustBreakBefore) ||
1742 Current->IsMultiline)
1743 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1745 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1746 ChildSize + Current->SpacesRequiredBefore;
1748 if (Current->is(TT_CtorInitializerColon))
1749 InFunctionDecl = false;
1751 // FIXME: Only calculate this if CanBreakBefore is true once static
1752 // initializers etc. are sorted out.
1753 // FIXME: Move magic numbers to a better place.
1754 Current->SplitPenalty = 20 * Current->BindingStrength +
1755 splitPenalty(Line, *Current, InFunctionDecl);
1757 Current = Current->Next;
1760 calculateUnbreakableTailLengths(Line);
1761 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1763 Current->Role->precomputeFormattingInfos(Current);
1766 DEBUG({ printDebugInfo(Line); });
1769 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1770 unsigned UnbreakableTailLength = 0;
1771 FormatToken *Current = Line.Last;
1773 Current->UnbreakableTailLength = UnbreakableTailLength;
1774 if (Current->CanBreakBefore ||
1775 Current->isOneOf(tok::comment, tok::string_literal)) {
1776 UnbreakableTailLength = 0;
1778 UnbreakableTailLength +=
1779 Current->ColumnWidth + Current->SpacesRequiredBefore;
1781 Current = Current->Previous;
1785 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1786 const FormatToken &Tok,
1787 bool InFunctionDecl) {
1788 const FormatToken &Left = *Tok.Previous;
1789 const FormatToken &Right = Tok;
1791 if (Left.is(tok::semi))
1794 if (Style.Language == FormatStyle::LK_Java) {
1795 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
1797 if (Right.is(Keywords.kw_implements))
1799 if (Left.is(tok::comma) && Left.NestingLevel == 0)
1801 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1802 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
1804 if (Left.is(TT_JsTypeColon))
1808 if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
1809 Right.Next->is(TT_DictLiteral)))
1811 if (Right.is(tok::l_square)) {
1812 if (Style.Language == FormatStyle::LK_Proto)
1814 if (Left.is(tok::r_square))
1816 // Slightly prefer formatting local lambda definitions like functions.
1817 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
1819 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
1820 TT_ArrayInitializerLSquare))
1824 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
1825 Right.is(tok::kw_operator)) {
1826 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1828 if (Left.is(TT_StartOfName))
1830 if (InFunctionDecl && Right.NestingLevel == 0)
1831 return Style.PenaltyReturnTypeOnItsOwnLine;
1834 if (Right.is(TT_PointerOrReference))
1836 if (Right.is(TT_LambdaArrow))
1838 if (Left.is(tok::equal) && Right.is(tok::l_brace))
1840 if (Left.is(TT_CastRParen))
1842 if (Left.is(tok::coloncolon) ||
1843 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1845 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1847 if (Left.is(tok::comment))
1850 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
1853 if (Right.isMemberAccess()) {
1854 // Breaking before the "./->" of a chained call/member access is reasonably
1855 // cheap, as formatting those with one call per line is generally
1856 // desirable. In particular, it should be cheaper to break before the call
1857 // than it is to break inside a call's parameters, which could lead to weird
1858 // "hanging" indents. The exception is the very last "./->" to support this
1859 // frequent pattern:
1861 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
1864 // which might otherwise be blown up onto many lines. Here, clang-format
1865 // won't produce "hanging" indents anyway as there is no other trailing
1868 // Also apply higher penalty is not a call as that might lead to a wrapping
1872 // .aaaaaaaaa.bbbbbbbb(cccccccc);
1873 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
1878 if (Right.is(TT_TrailingAnnotation) &&
1879 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
1880 // Moving trailing annotations to the next line is fine for ObjC method
1882 if (Line.startsWith(TT_ObjCMethodSpecifier))
1884 // Generally, breaking before a trailing annotation is bad unless it is
1885 // function-like. It seems to be especially preferable to keep standard
1886 // annotations (i.e. "const", "final" and "override") on the same line.
1887 // Use a slightly higher penalty after ")" so that annotations like
1888 // "const override" are kept together.
1889 bool is_short_annotation = Right.TokenText.size() < 10;
1890 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
1893 // In for-loops, prefer breaking at ',' and ';'.
1894 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
1897 // In Objective-C method expressions, prefer breaking before "param:" over
1898 // breaking after it.
1899 if (Right.is(TT_SelectorName))
1901 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
1902 return Line.MightBeFunctionDecl ? 50 : 500;
1904 if (Left.is(tok::l_paren) && InFunctionDecl &&
1905 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
1907 if (Left.is(tok::l_paren) && Left.Previous &&
1908 Left.Previous->isOneOf(tok::kw_if, tok::kw_for))
1910 if (Left.is(tok::equal) && InFunctionDecl)
1912 if (Right.is(tok::r_brace))
1914 if (Left.is(TT_TemplateOpener))
1916 if (Left.opensScope()) {
1917 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
1919 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1922 if (Left.is(TT_JavaAnnotation))
1925 if (Right.is(tok::lessless)) {
1926 if (Left.is(tok::string_literal) &&
1927 (Right.NextOperator || Right.OperatorIndex != 1)) {
1928 StringRef Content = Left.TokenText;
1929 if (Content.startswith("\""))
1930 Content = Content.drop_front(1);
1931 if (Content.endswith("\""))
1932 Content = Content.drop_back(1);
1933 Content = Content.trim();
1934 if (Content.size() > 1 &&
1935 (Content.back() == ':' || Content.back() == '='))
1938 return 1; // Breaking at a << is really cheap.
1940 if (Left.is(TT_ConditionalExpr))
1941 return prec::Conditional;
1942 prec::Level Level = Left.getPrecedence();
1943 if (Level != prec::Unknown)
1945 Level = Right.getPrecedence();
1946 if (Level != prec::Unknown)
1952 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1953 const FormatToken &Left,
1954 const FormatToken &Right) {
1955 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
1957 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1958 Left.Tok.getObjCKeywordID() == tok::objc_property)
1960 if (Right.is(tok::hashhash))
1961 return Left.is(tok::hash);
1962 if (Left.isOneOf(tok::hashhash, tok::hash))
1963 return Right.is(tok::hash);
1964 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
1965 return Style.SpaceInEmptyParentheses;
1966 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
1967 return (Right.is(TT_CastRParen) ||
1968 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
1969 ? Style.SpacesInCStyleCastParentheses
1970 : Style.SpacesInParentheses;
1971 if (Right.isOneOf(tok::semi, tok::comma))
1973 if (Right.is(tok::less) &&
1974 (Left.is(tok::kw_template) ||
1975 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1977 if (Left.isOneOf(tok::exclaim, tok::tilde))
1979 if (Left.is(tok::at) &&
1980 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1981 tok::numeric_constant, tok::l_paren, tok::l_brace,
1982 tok::kw_true, tok::kw_false))
1984 if (Left.is(tok::colon))
1985 return !Left.is(TT_ObjCMethodExpr);
1986 if (Left.is(tok::coloncolon))
1988 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
1990 if (Right.is(tok::ellipsis))
1991 return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
1992 Left.Previous->is(tok::kw_case));
1993 if (Left.is(tok::l_square) && Right.is(tok::amp))
1995 if (Right.is(TT_PointerOrReference))
1996 return (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) ||
1997 (Left.Tok.isLiteral() || Left.is(tok::kw_const) ||
1998 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
1999 (Style.PointerAlignment != FormatStyle::PAS_Left ||
2000 Line.IsMultiVariableDeclStmt)));
2001 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
2002 (!Left.is(TT_PointerOrReference) ||
2003 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2004 !Line.IsMultiVariableDeclStmt)))
2006 if (Left.is(TT_PointerOrReference))
2007 return Right.Tok.isLiteral() ||
2008 Right.isOneOf(TT_BlockComment, Keywords.kw_final,
2009 Keywords.kw_override) ||
2010 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
2011 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
2013 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2014 !Line.IsMultiVariableDeclStmt) &&
2016 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
2017 if (Right.is(tok::star) && Left.is(tok::l_paren))
2019 if (Left.is(tok::l_square))
2020 return (Left.is(TT_ArrayInitializerLSquare) &&
2021 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
2022 (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
2023 Right.isNot(tok::r_square));
2024 if (Right.is(tok::r_square))
2025 return Right.MatchingParen &&
2026 ((Style.SpacesInContainerLiterals &&
2027 Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
2028 (Style.SpacesInSquareBrackets &&
2029 Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
2030 if (Right.is(tok::l_square) &&
2031 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
2032 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
2034 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
2035 return !Left.Children.empty(); // No spaces in "{}".
2036 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
2037 (Right.is(tok::r_brace) && Right.MatchingParen &&
2038 Right.MatchingParen->BlockKind != BK_Block))
2039 return !Style.Cpp11BracedListStyle;
2040 if (Left.is(TT_BlockComment))
2041 return !Left.TokenText.endswith("=*/");
2042 if (Right.is(tok::l_paren)) {
2043 if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
2045 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
2046 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
2047 (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
2048 tok::kw_switch, tok::kw_case, TT_ForEachMacro,
2050 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
2051 tok::kw_new, tok::kw_delete) &&
2052 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
2053 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
2054 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
2055 Left.is(tok::r_paren)) &&
2056 Line.Type != LT_PreprocessorDirective);
2058 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
2060 if (Right.is(TT_UnaryOperator))
2061 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
2062 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
2063 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
2065 Left.isSimpleTypeSpecifier()) &&
2066 Right.is(tok::l_brace) && Right.getNextNonComment() &&
2067 Right.BlockKind != BK_Block)
2069 if (Left.is(tok::period) || Right.is(tok::period))
2071 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
2073 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
2074 Left.MatchingParen->Previous &&
2075 Left.MatchingParen->Previous->is(tok::period))
2076 // A.<B>DoSomething();
2078 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
2083 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
2084 const FormatToken &Right) {
2085 const FormatToken &Left = *Right.Previous;
2086 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
2087 return true; // Never ever merge two identifiers.
2088 if (Style.Language == FormatStyle::LK_Cpp) {
2089 if (Left.is(tok::kw_operator))
2090 return Right.is(tok::coloncolon);
2091 } else if (Style.Language == FormatStyle::LK_Proto) {
2092 if (Right.is(tok::period) &&
2093 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2094 Keywords.kw_repeated, Keywords.kw_extend))
2096 if (Right.is(tok::l_paren) &&
2097 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2099 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2100 if (Left.is(TT_JsFatArrow))
2102 if (Right.is(tok::star) &&
2103 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2105 if (Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
2106 Keywords.kw_of, tok::kw_const) &&
2107 (!Left.Previous || !Left.Previous->is(tok::period)))
2109 if (Left.is(tok::kw_default) && Left.Previous &&
2110 Left.Previous->is(tok::kw_export))
2112 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2114 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2116 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
2118 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2119 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2121 if (Left.is(tok::ellipsis))
2123 if (Left.is(TT_TemplateCloser) &&
2124 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2125 Keywords.kw_implements, Keywords.kw_extends))
2126 // Type assertions ('<type>expr') are not followed by whitespace. Other
2127 // locations that should have whitespace following are identified by the
2128 // above set of follower tokens.
2130 // Postfix non-null assertion operator, as in `foo!.bar()`.
2131 if (Right.is(tok::exclaim) && (Left.isOneOf(tok::identifier, tok::r_paren,
2132 tok::r_square, tok::r_brace) ||
2133 Left.Tok.isLiteral()))
2135 } else if (Style.Language == FormatStyle::LK_Java) {
2136 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2138 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2139 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2140 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2141 tok::kw_protected) ||
2142 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2143 Keywords.kw_native)) &&
2144 Right.is(TT_TemplateOpener))
2147 if (Left.is(TT_ImplicitStringLiteral))
2148 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2149 if (Line.Type == LT_ObjCMethodDecl) {
2150 if (Left.is(TT_ObjCMethodSpecifier))
2152 if (Left.is(tok::r_paren) && Right.is(tok::identifier))
2153 // Don't space between ')' and <id>
2156 if (Line.Type == LT_ObjCProperty &&
2157 (Right.is(tok::equal) || Left.is(tok::equal)))
2160 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2161 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2163 if (Right.is(TT_OverloadedOperatorLParen))
2164 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2165 if (Left.is(tok::comma))
2167 if (Right.is(tok::comma))
2169 if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
2171 if (Right.is(tok::colon)) {
2172 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2173 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2175 if (Right.is(TT_ObjCMethodExpr))
2177 if (Left.is(tok::question))
2179 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2181 if (Right.is(TT_DictLiteral))
2182 return Style.SpacesInContainerLiterals;
2185 if (Left.is(TT_UnaryOperator))
2186 return Right.is(TT_BinaryOperator);
2188 // If the next token is a binary operator or a selector name, we have
2189 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2190 if (Left.is(TT_CastRParen))
2191 return Style.SpaceAfterCStyleCast ||
2192 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2194 if (Left.is(tok::greater) && Right.is(tok::greater))
2195 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2196 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2197 if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2198 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
2200 if (!Style.SpaceBeforeAssignmentOperators &&
2201 Right.getPrecedence() == prec::Assignment)
2203 if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
2204 return (Left.is(TT_TemplateOpener) &&
2205 Style.Standard == FormatStyle::LS_Cpp03) ||
2206 !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren,
2208 Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
2209 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2210 return Style.SpacesInAngles;
2211 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2212 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2213 !Right.is(tok::r_paren)))
2215 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2216 Right.isNot(TT_FunctionTypeLParen))
2217 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2218 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2219 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2221 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2222 Line.startsWith(tok::hash))
2224 if (Right.is(TT_TrailingUnaryOperator))
2226 if (Left.is(TT_RegexLiteral))
2228 return spaceRequiredBetween(Line, Left, Right);
2231 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2232 static bool isAllmanBrace(const FormatToken &Tok) {
2233 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2234 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2237 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2238 const FormatToken &Right) {
2239 const FormatToken &Left = *Right.Previous;
2240 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2243 if (Style.Language == FormatStyle::LK_JavaScript) {
2244 // FIXME: This might apply to other languages and token kinds.
2245 if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
2246 Left.Previous->is(tok::string_literal))
2248 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2249 Left.Previous && Left.Previous->is(tok::equal) &&
2250 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2252 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2254 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2255 // Object literals on the top level of a file are treated as "enum-style".
2256 // Each key/value pair is put on a separate line, instead of bin-packing.
2258 if (Left.is(tok::l_brace) && Line.Level == 0 &&
2259 (Line.startsWith(tok::kw_enum) ||
2260 Line.startsWith(tok::kw_export, tok::kw_enum)))
2261 // JavaScript top-level enum key/value pairs are put on separate lines
2262 // instead of bin-packing.
2264 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2265 !Left.Children.empty())
2266 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2267 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2268 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2269 (Left.NestingLevel == 0 && Line.Level == 0 &&
2270 Style.AllowShortFunctionsOnASingleLine ==
2271 FormatStyle::SFS_Inline);
2272 } else if (Style.Language == FormatStyle::LK_Java) {
2273 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2274 Right.Next->is(tok::string_literal))
2278 // If the last token before a '}' is a comma or a trailing comment, the
2279 // intention is to insert a line break after it in order to make shuffling
2280 // around entries easier.
2281 const FormatToken *BeforeClosingBrace = nullptr;
2282 if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
2283 Left.BlockKind != BK_Block && Left.MatchingParen)
2284 BeforeClosingBrace = Left.MatchingParen->Previous;
2285 else if (Right.MatchingParen &&
2286 Right.MatchingParen->isOneOf(tok::l_brace,
2287 TT_ArrayInitializerLSquare))
2288 BeforeClosingBrace = &Left;
2289 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2290 BeforeClosingBrace->isTrailingComment()))
2293 if (Right.is(tok::comment))
2294 return Left.BlockKind != BK_BracedInit &&
2295 Left.isNot(TT_CtorInitializerColon) &&
2296 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2297 if (Left.isTrailingComment())
2299 if (Left.isStringLiteral() &&
2300 (Right.isStringLiteral() || Right.is(TT_ObjCStringLiteral)))
2302 if (Right.Previous->IsUnterminatedLiteral)
2304 if (Right.is(tok::lessless) && Right.Next &&
2305 Right.Previous->is(tok::string_literal) &&
2306 Right.Next->is(tok::string_literal))
2308 if (Right.Previous->ClosesTemplateDeclaration &&
2309 Right.Previous->MatchingParen &&
2310 Right.Previous->MatchingParen->NestingLevel == 0 &&
2311 Style.AlwaysBreakTemplateDeclarations)
2313 if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
2314 Style.BreakConstructorInitializersBeforeComma &&
2315 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2317 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2318 // Raw string literals are special wrt. line breaks. The author has made a
2319 // deliberate choice and might have aligned the contents of the string
2320 // literal accordingly. Thus, we try keep existing line breaks.
2321 return Right.NewlinesBefore > 0;
2322 if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
2323 Style.Language == FormatStyle::LK_Proto)
2324 // Don't put enums onto single lines in protocol buffers.
2326 if (Right.is(TT_InlineASMBrace))
2327 return Right.HasUnescapedNewline;
2328 if (isAllmanBrace(Left) || isAllmanBrace(Right))
2329 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2330 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2331 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2332 if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) &&
2333 Right.is(TT_SelectorName))
2335 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2338 if ((Style.Language == FormatStyle::LK_Java ||
2339 Style.Language == FormatStyle::LK_JavaScript) &&
2340 Left.is(TT_LeadingJavaAnnotation) &&
2341 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2342 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2348 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2349 const FormatToken &Right) {
2350 const FormatToken &Left = *Right.Previous;
2352 // Language-specific stuff.
2353 if (Style.Language == FormatStyle::LK_Java) {
2354 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2355 Keywords.kw_implements))
2357 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2358 Keywords.kw_implements))
2360 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2361 if (Left.is(tok::kw_return))
2362 return false; // Otherwise a semicolon is inserted.
2363 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2365 if (Left.is(TT_JsTypeColon))
2367 if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is))
2369 if (Left.is(Keywords.kw_in))
2370 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
2371 if (Right.is(Keywords.kw_in))
2372 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
2375 if (Left.is(tok::at))
2377 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2379 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2380 return !Right.is(tok::l_paren);
2381 if (Right.is(TT_PointerOrReference))
2382 return Line.IsMultiVariableDeclStmt ||
2383 (Style.PointerAlignment == FormatStyle::PAS_Right &&
2384 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2385 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2386 Right.is(tok::kw_operator))
2388 if (Left.is(TT_PointerOrReference))
2390 if (Right.isTrailingComment())
2391 // We rely on MustBreakBefore being set correctly here as we should not
2392 // change the "binding" behavior of a comment.
2393 // The first comment in a braced lists is always interpreted as belonging to
2394 // the first list element. Otherwise, it should be placed outside of the
2396 return Left.BlockKind == BK_BracedInit;
2397 if (Left.is(tok::question) && Right.is(tok::colon))
2399 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2400 return Style.BreakBeforeTernaryOperators;
2401 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2402 return !Style.BreakBeforeTernaryOperators;
2403 if (Right.is(TT_InheritanceColon))
2405 if (Right.is(tok::colon) &&
2406 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2408 if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
2410 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2411 Right.Next->is(TT_ObjCMethodExpr)))
2412 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2413 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2415 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
2417 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2418 TT_OverloadedOperator))
2420 if (Left.is(TT_RangeBasedForLoopColon))
2422 if (Right.is(TT_RangeBasedForLoopColon))
2424 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2425 Left.is(tok::kw_operator))
2427 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2428 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
2430 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2432 if (Left.is(tok::l_paren) && Left.Previous &&
2433 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2435 if (Right.is(TT_ImplicitStringLiteral))
2438 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2440 if (Right.is(tok::r_square) && Right.MatchingParen &&
2441 Right.MatchingParen->is(TT_LambdaLSquare))
2444 // We only break before r_brace if there was a corresponding break before
2445 // the l_brace, which is tracked by BreakBeforeClosingBrace.
2446 if (Right.is(tok::r_brace))
2447 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2449 // Allow breaking after a trailing annotation, e.g. after a method
2451 if (Left.is(TT_TrailingAnnotation))
2452 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2453 tok::less, tok::coloncolon);
2455 if (Right.is(tok::kw___attribute))
2458 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2461 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2464 if (Left.is(TT_CtorInitializerComma) &&
2465 Style.BreakConstructorInitializersBeforeComma)
2467 if (Right.is(TT_CtorInitializerComma) &&
2468 Style.BreakConstructorInitializersBeforeComma)
2470 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2471 (Left.is(tok::less) && Right.is(tok::less)))
2473 if (Right.is(TT_BinaryOperator) &&
2474 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2475 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2476 Right.getPrecedence() != prec::Assignment))
2478 if (Left.is(TT_ArrayInitializerLSquare))
2480 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2482 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
2483 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2484 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2485 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2486 Left.getPrecedence() == prec::Assignment))
2488 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2489 tok::kw_class, tok::kw_struct, tok::comment) ||
2490 Right.isMemberAccess() ||
2491 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2492 tok::colon, tok::l_square, tok::at) ||
2493 (Left.is(tok::r_paren) &&
2494 Right.isOneOf(tok::identifier, tok::kw_const)) ||
2495 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
2498 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2499 llvm::errs() << "AnnotatedTokens:\n";
2500 const FormatToken *Tok = Line.First;
2502 llvm::errs() << " M=" << Tok->MustBreakBefore
2503 << " C=" << Tok->CanBreakBefore
2504 << " T=" << getTokenTypeName(Tok->Type)
2505 << " S=" << Tok->SpacesRequiredBefore
2506 << " B=" << Tok->BlockParameterCount
2507 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
2508 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
2510 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2511 llvm::errs() << Tok->FakeLParens[i] << "/";
2512 llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
2514 assert(Tok == Line.Last);
2517 llvm::errs() << "----\n";
2520 } // namespace format
2521 } // namespace clang