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 = CurrentToken->isOneOf(tok::star, tok::amp) &&
182 !Contexts[Contexts.size() - 2].IsExpression;
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 MightBeFunctionType = true;
210 if (CurrentToken->Previous->is(TT_BinaryOperator))
211 Contexts.back().IsExpression = true;
212 if (CurrentToken->is(tok::r_paren)) {
213 if (MightBeFunctionType && CurrentToken->Next &&
214 (CurrentToken->Next->is(tok::l_paren) ||
215 (CurrentToken->Next->is(tok::l_square) &&
216 Line.MustBeDeclaration)))
217 Left->Type = TT_FunctionTypeLParen;
218 Left->MatchingParen = CurrentToken;
219 CurrentToken->MatchingParen = Left;
221 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
222 Left->Previous && Left->Previous->is(tok::l_paren)) {
223 // Detect the case where macros are used to generate lambdas or
224 // function bodies, e.g.:
225 // auto my_lambda = MARCO((Type *type, int i) { .. body .. });
226 for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
227 if (Tok->is(TT_BinaryOperator) &&
228 Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
229 Tok->Type = TT_PointerOrReference;
233 if (StartsObjCMethodExpr) {
234 CurrentToken->Type = TT_ObjCMethodExpr;
235 if (Contexts.back().FirstObjCSelectorName) {
236 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
237 Contexts.back().LongestObjCSelectorName;
241 if (Left->is(TT_AttributeParen))
242 CurrentToken->Type = TT_AttributeParen;
243 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
244 CurrentToken->Type = TT_JavaAnnotation;
245 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
246 CurrentToken->Type = TT_LeadingJavaAnnotation;
248 if (!HasMultipleLines)
249 Left->PackingKind = PPK_Inconclusive;
250 else if (HasMultipleParametersOnALine)
251 Left->PackingKind = PPK_BinPacked;
253 Left->PackingKind = PPK_OnePerLine;
258 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
261 if (CurrentToken->is(tok::l_brace))
262 Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
263 if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
264 !CurrentToken->Next->HasUnescapedNewline &&
265 !CurrentToken->Next->isTrailingComment())
266 HasMultipleParametersOnALine = true;
267 if (CurrentToken->isOneOf(tok::kw_const, tok::kw_auto) ||
268 CurrentToken->isSimpleTypeSpecifier())
269 Contexts.back().IsExpression = false;
270 if (CurrentToken->isOneOf(tok::semi, tok::colon))
271 MightBeObjCForRangeLoop = false;
272 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
273 CurrentToken->Type = TT_ObjCForIn;
274 // When we discover a 'new', we set CanBeExpression to 'false' in order to
275 // parse the type correctly. Reset that after a comma.
276 if (CurrentToken->is(tok::comma))
277 Contexts.back().CanBeExpression = true;
279 FormatToken *Tok = CurrentToken;
282 updateParameterCount(Left, Tok);
283 if (CurrentToken && CurrentToken->HasUnescapedNewline)
284 HasMultipleLines = true;
293 // A '[' could be an index subscript (after an identifier or after
294 // ')' or ']'), it could be the start of an Objective-C method
295 // expression, or it could the start of an Objective-C array literal.
296 FormatToken *Left = CurrentToken->Previous;
297 Left->ParentBracket = Contexts.back().ContextKind;
298 FormatToken *Parent = Left->getPreviousNonComment();
299 bool StartsObjCMethodExpr =
300 Style.Language == FormatStyle::LK_Cpp &&
301 Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
302 CurrentToken->isNot(tok::l_brace) &&
304 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
305 tok::kw_return, tok::kw_throw) ||
306 Parent->isUnaryOperator() ||
307 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
308 getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
309 bool ColonFound = false;
311 unsigned BindingIncrease = 1;
312 if (Left->is(TT_Unknown)) {
313 if (StartsObjCMethodExpr) {
314 Left->Type = TT_ObjCMethodExpr;
315 } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
316 Contexts.back().ContextKind == tok::l_brace &&
317 Parent->isOneOf(tok::l_brace, tok::comma)) {
318 Left->Type = TT_JsComputedPropertyName;
319 } else if (Style.Language == FormatStyle::LK_Proto ||
321 Parent->isOneOf(TT_BinaryOperator, tok::at, tok::comma,
322 tok::l_paren, tok::l_square, tok::question,
323 tok::colon, tok::kw_return,
324 // Should only be relevant to JavaScript:
326 Left->Type = TT_ArrayInitializerLSquare;
328 BindingIncrease = 10;
329 Left->Type = TT_ArraySubscriptLSquare;
333 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
334 Contexts.back().IsExpression = true;
335 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
337 while (CurrentToken) {
338 if (CurrentToken->is(tok::r_square)) {
339 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
340 Left->is(TT_ObjCMethodExpr)) {
341 // An ObjC method call is rarely followed by an open parenthesis.
342 // FIXME: Do we incorrectly label ":" with this?
343 StartsObjCMethodExpr = false;
344 Left->Type = TT_Unknown;
346 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
347 CurrentToken->Type = TT_ObjCMethodExpr;
348 // determineStarAmpUsage() thinks that '*' '[' is allocating an
349 // array of pointers, but if '[' starts a selector then '*' is a
351 if (Parent && Parent->is(TT_PointerOrReference))
352 Parent->Type = TT_BinaryOperator;
354 Left->MatchingParen = CurrentToken;
355 CurrentToken->MatchingParen = Left;
356 if (Contexts.back().FirstObjCSelectorName) {
357 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
358 Contexts.back().LongestObjCSelectorName;
359 if (Left->BlockParameterCount > 1)
360 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
365 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
367 if (CurrentToken->is(tok::colon)) {
368 if (Left->is(TT_ArraySubscriptLSquare)) {
369 Left->Type = TT_ObjCMethodExpr;
370 StartsObjCMethodExpr = true;
371 Contexts.back().ColonIsObjCMethodExpr = true;
372 if (Parent && Parent->is(tok::r_paren))
373 Parent->Type = TT_CastRParen;
377 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
379 Left->Type = TT_ArrayInitializerLSquare;
380 FormatToken *Tok = CurrentToken;
383 updateParameterCount(Left, Tok);
390 FormatToken *Left = CurrentToken->Previous;
391 Left->ParentBracket = Contexts.back().ContextKind;
393 if (Contexts.back().CaretFound)
394 Left->Type = TT_ObjCBlockLBrace;
395 Contexts.back().CaretFound = false;
397 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
398 Contexts.back().ColonIsDictLiteral = true;
399 if (Left->BlockKind == BK_BracedInit)
400 Contexts.back().IsExpression = true;
402 while (CurrentToken) {
403 if (CurrentToken->is(tok::r_brace)) {
404 Left->MatchingParen = CurrentToken;
405 CurrentToken->MatchingParen = Left;
409 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
411 updateParameterCount(Left, CurrentToken);
412 if (CurrentToken->isOneOf(tok::colon, tok::l_brace)) {
413 FormatToken *Previous = CurrentToken->getPreviousNonComment();
414 if (((CurrentToken->is(tok::colon) &&
415 (!Contexts.back().ColonIsDictLiteral ||
416 Style.Language != FormatStyle::LK_Cpp)) ||
417 Style.Language == FormatStyle::LK_Proto) &&
418 (Previous->Tok.getIdentifierInfo() ||
419 Previous->is(tok::string_literal)))
420 Previous->Type = TT_SelectorName;
421 if (CurrentToken->is(tok::colon) ||
422 Style.Language == FormatStyle::LK_JavaScript)
423 Left->Type = TT_DictLiteral;
432 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
433 if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
434 ++Left->BlockParameterCount;
435 if (Current->is(tok::comma)) {
436 ++Left->ParameterCount;
438 Left->Role.reset(new CommaSeparatedList(Style));
439 Left->Role->CommaFound(Current);
440 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
441 Left->ParameterCount = 1;
445 bool parseConditional() {
446 while (CurrentToken) {
447 if (CurrentToken->is(tok::colon)) {
448 CurrentToken->Type = TT_ConditionalExpr;
458 bool parseTemplateDeclaration() {
459 if (CurrentToken && CurrentToken->is(tok::less)) {
460 CurrentToken->Type = TT_TemplateOpener;
465 CurrentToken->Previous->ClosesTemplateDeclaration = true;
471 bool consumeToken() {
472 FormatToken *Tok = CurrentToken;
474 switch (Tok->Tok.getKind()) {
477 if (!Tok->Previous && Line.MustBeDeclaration)
478 Tok->Type = TT_ObjCMethodSpecifier;
483 // Colons from ?: are handled in parseConditional().
484 if (Style.Language == FormatStyle::LK_JavaScript) {
485 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
486 (Contexts.size() == 1 && // switch/case labels
487 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
488 Contexts.back().ContextKind == tok::l_paren || // function params
489 Contexts.back().ContextKind == tok::l_square || // array type
490 (Contexts.size() == 1 &&
491 Line.MustBeDeclaration)) { // method/property declaration
492 Tok->Type = TT_JsTypeColon;
496 if (Contexts.back().ColonIsDictLiteral ||
497 Style.Language == FormatStyle::LK_Proto) {
498 Tok->Type = TT_DictLiteral;
499 } else if (Contexts.back().ColonIsObjCMethodExpr ||
500 Line.startsWith(TT_ObjCMethodSpecifier)) {
501 Tok->Type = TT_ObjCMethodExpr;
502 Tok->Previous->Type = TT_SelectorName;
503 if (Tok->Previous->ColumnWidth >
504 Contexts.back().LongestObjCSelectorName)
505 Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth;
506 if (!Contexts.back().FirstObjCSelectorName)
507 Contexts.back().FirstObjCSelectorName = Tok->Previous;
508 } else if (Contexts.back().ColonIsForRangeExpr) {
509 Tok->Type = TT_RangeBasedForLoopColon;
510 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
511 Tok->Type = TT_BitFieldColon;
512 } else if (Contexts.size() == 1 &&
513 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
514 if (Tok->Previous->isOneOf(tok::r_paren, tok::kw_noexcept))
515 Tok->Type = TT_CtorInitializerColon;
517 Tok->Type = TT_InheritanceColon;
518 } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
519 Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
520 // This handles a special macro in ObjC code where selectors including
521 // the colon are passed as macro arguments.
522 Tok->Type = TT_ObjCMethodExpr;
523 } else if (Contexts.back().ContextKind == tok::l_paren) {
524 Tok->Type = TT_InlineASMColon;
529 // | and & in declarations/type expressions represent union and
530 // intersection types, respectively.
531 if (Style.Language == FormatStyle::LK_JavaScript &&
532 !Contexts.back().IsExpression)
533 Tok->Type = TT_JsTypeOperator;
537 if (CurrentToken && CurrentToken->is(tok::l_paren)) {
539 if (!parseParens(/*LookForDecls=*/true))
544 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Previous &&
545 Tok->Previous->is(tok::period))
547 Contexts.back().ColonIsForRangeExpr = true;
553 // When faced with 'operator()()', the kw_operator handler incorrectly
554 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
555 // the first two parens OverloadedOperators and the second l_paren an
556 // OverloadedOperatorLParen.
558 Tok->Previous->is(tok::r_paren) &&
559 Tok->Previous->MatchingParen &&
560 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
561 Tok->Previous->Type = TT_OverloadedOperator;
562 Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
563 Tok->Type = TT_OverloadedOperatorLParen;
568 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
569 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
571 !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
572 TT_LeadingJavaAnnotation)))
573 Line.MightBeFunctionDecl = true;
585 Tok->Type = TT_TemplateOpener;
587 Tok->Type = TT_BinaryOperator;
588 NonTemplateLess.insert(Tok);
597 // Lines can start with '}'.
602 Tok->Type = TT_BinaryOperator;
604 case tok::kw_operator:
605 while (CurrentToken &&
606 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
607 if (CurrentToken->isOneOf(tok::star, tok::amp))
608 CurrentToken->Type = TT_PointerOrReference;
611 CurrentToken->Previous->isOneOf(TT_BinaryOperator, tok::comma))
612 CurrentToken->Previous->Type = TT_OverloadedOperator;
615 CurrentToken->Type = TT_OverloadedOperatorLParen;
616 if (CurrentToken->Previous->is(TT_BinaryOperator))
617 CurrentToken->Previous->Type = TT_OverloadedOperator;
621 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
622 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
624 // Question marks before semicolons, colons, etc. indicate optional
625 // types (fields, parameters), e.g.
626 // function(x?: string, y?) {...}
628 Tok->Type = TT_JsTypeOptionalQuestion;
631 // Declarations cannot be conditional expressions, this can only be part
632 // of a type declaration.
633 if (Line.MustBeDeclaration &&
634 Style.Language == FormatStyle::LK_JavaScript)
638 case tok::kw_template:
639 parseTemplateDeclaration();
642 if (Contexts.back().InCtorInitializer)
643 Tok->Type = TT_CtorInitializerComma;
644 else if (Contexts.back().FirstStartOfName &&
645 (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
646 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
647 Line.IsMultiVariableDeclStmt = true;
649 if (Contexts.back().IsForEachMacro)
650 Contexts.back().IsExpression = true;
658 void parseIncludeDirective() {
659 if (CurrentToken && CurrentToken->is(tok::less)) {
661 while (CurrentToken) {
662 if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
663 CurrentToken->Type = TT_ImplicitStringLiteral;
669 void parseWarningOrError() {
671 // We still want to format the whitespace left of the first token of the
674 while (CurrentToken) {
675 CurrentToken->Type = TT_ImplicitStringLiteral;
681 next(); // Consume "pragma".
683 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
684 bool IsMark = CurrentToken->is(Keywords.kw_mark);
685 next(); // Consume "mark".
686 next(); // Consume first token (so we fix leading whitespace).
687 while (CurrentToken) {
688 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
689 CurrentToken->Type = TT_ImplicitStringLiteral;
695 LineType parsePreprocessorDirective() {
696 bool IsFirstToken = CurrentToken->IsFirst;
697 LineType Type = LT_PreprocessorDirective;
702 if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
703 // JavaScript files can contain shebang lines of the form:
704 // #!/usr/bin/env node
705 // Treat these like C++ #include directives.
706 while (CurrentToken) {
707 // Tokens cannot be comments here.
708 CurrentToken->Type = TT_ImplicitStringLiteral;
711 return LT_ImportStatement;
714 if (CurrentToken->Tok.is(tok::numeric_constant)) {
715 CurrentToken->SpacesRequiredBefore = 1;
718 // Hashes in the middle of a line can lead to any strange token
720 if (!CurrentToken->Tok.getIdentifierInfo())
722 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
723 case tok::pp_include:
724 case tok::pp_include_next:
727 parseIncludeDirective();
728 Type = LT_ImportStatement;
731 case tok::pp_warning:
732 parseWarningOrError();
739 Contexts.back().IsExpression = true;
751 LineType parseLine() {
752 NonTemplateLess.clear();
753 if (CurrentToken->is(tok::hash))
754 return parsePreprocessorDirective();
756 // Directly allow to 'import <string-literal>' to support protocol buffer
757 // definitions (code.google.com/p/protobuf) or missing "#" (either way we
758 // should not break the line).
759 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
760 if ((Style.Language == FormatStyle::LK_Java &&
761 CurrentToken->is(Keywords.kw_package)) ||
762 (Info && Info->getPPKeywordID() == tok::pp_import &&
763 CurrentToken->Next &&
764 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
767 parseIncludeDirective();
768 return LT_ImportStatement;
771 // If this line starts and ends in '<' and '>', respectively, it is likely
772 // part of "#define <a/b.h>".
773 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
774 parseIncludeDirective();
775 return LT_ImportStatement;
778 // In .proto files, top-level options are very similar to import statements
779 // and should not be line-wrapped.
780 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
781 CurrentToken->is(Keywords.kw_option)) {
783 if (CurrentToken && CurrentToken->is(tok::identifier))
784 return LT_ImportStatement;
787 // import {...} from '...';
788 if (Style.Language == FormatStyle::LK_JavaScript &&
789 CurrentToken->is(Keywords.kw_import))
790 return LT_ImportStatement;
792 bool KeywordVirtualFound = false;
793 bool ImportStatement = false;
794 while (CurrentToken) {
795 if (CurrentToken->is(tok::kw_virtual))
796 KeywordVirtualFound = true;
797 if (Style.Language == FormatStyle::LK_JavaScript) {
798 // export {...} from '...';
799 // An export followed by "from 'some string';" is a re-export from
800 // another module identified by a URI and is treated as a
801 // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
802 // Just "export {...};" or "export class ..." should not be treated as
803 // an import in this sense.
804 if (Line.First->is(tok::kw_export) &&
805 CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
806 CurrentToken->Next->isStringLiteral())
807 ImportStatement = true;
808 if (isClosureImportStatement(*CurrentToken))
809 ImportStatement = true;
814 if (KeywordVirtualFound)
815 return LT_VirtualFunctionDecl;
817 return LT_ImportStatement;
819 if (Line.startsWith(TT_ObjCMethodSpecifier)) {
820 if (Contexts.back().FirstObjCSelectorName)
821 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
822 Contexts.back().LongestObjCSelectorName;
823 return LT_ObjCMethodDecl;
830 bool isClosureImportStatement(const FormatToken &Tok) {
831 // FIXME: Closure-library specific stuff should not be hard-coded but be
833 return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
834 Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
835 Tok.Next->Next->TokenText == "provide" ||
836 Tok.Next->Next->TokenText == "require" ||
837 Tok.Next->Next->TokenText == "setTestOnly" ||
838 Tok.Next->Next->TokenText == "forwardDeclare") &&
839 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
842 void resetTokenMetadata(FormatToken *Token) {
846 // Reset token type in case we have already looked at it and then
847 // recovered from an error (e.g. failure to find the matching >).
848 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
849 TT_FunctionLBrace, TT_ImplicitStringLiteral,
850 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
852 CurrentToken->Type = TT_Unknown;
853 CurrentToken->Role.reset();
854 CurrentToken->MatchingParen = nullptr;
855 CurrentToken->FakeLParens.clear();
856 CurrentToken->FakeRParens = 0;
861 CurrentToken->NestingLevel = Contexts.size() - 1;
862 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
863 modifyContext(*CurrentToken);
864 determineTokenType(*CurrentToken);
865 CurrentToken = CurrentToken->Next;
868 resetTokenMetadata(CurrentToken);
871 /// \brief A struct to hold information valid in a specific context, e.g.
872 /// a pair of parenthesis.
874 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
876 : ContextKind(ContextKind), BindingStrength(BindingStrength),
877 IsExpression(IsExpression) {}
879 tok::TokenKind ContextKind;
880 unsigned BindingStrength;
882 unsigned LongestObjCSelectorName = 0;
883 bool ColonIsForRangeExpr = false;
884 bool ColonIsDictLiteral = false;
885 bool ColonIsObjCMethodExpr = false;
886 FormatToken *FirstObjCSelectorName = nullptr;
887 FormatToken *FirstStartOfName = nullptr;
888 bool CanBeExpression = true;
889 bool InTemplateArgument = false;
890 bool InCtorInitializer = false;
891 bool CaretFound = false;
892 bool IsForEachMacro = false;
895 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
896 /// of each instance.
897 struct ScopedContextCreator {
900 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
903 P.Contexts.push_back(Context(ContextKind,
904 P.Contexts.back().BindingStrength + Increase,
905 P.Contexts.back().IsExpression));
908 ~ScopedContextCreator() { P.Contexts.pop_back(); }
911 void modifyContext(const FormatToken &Current) {
912 if (Current.getPrecedence() == prec::Assignment &&
913 !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
914 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
915 Contexts.back().IsExpression = true;
916 if (!Line.startsWith(TT_UnaryOperator)) {
917 for (FormatToken *Previous = Current.Previous;
918 Previous && Previous->Previous &&
919 !Previous->Previous->isOneOf(tok::comma, tok::semi);
920 Previous = Previous->Previous) {
921 if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
922 Previous = Previous->MatchingParen;
926 if (Previous->opensScope())
928 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
929 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
930 Previous->Previous && Previous->Previous->isNot(tok::equal))
931 Previous->Type = TT_PointerOrReference;
934 } else if (Current.is(tok::lessless) &&
935 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
936 Contexts.back().IsExpression = true;
937 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
938 Contexts.back().IsExpression = true;
939 } else if (Current.is(TT_TrailingReturnArrow)) {
940 Contexts.back().IsExpression = false;
941 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
942 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
943 } else if (Current.Previous &&
944 Current.Previous->is(TT_CtorInitializerColon)) {
945 Contexts.back().IsExpression = true;
946 Contexts.back().InCtorInitializer = true;
947 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
948 for (FormatToken *Previous = Current.Previous;
949 Previous && Previous->isOneOf(tok::star, tok::amp);
950 Previous = Previous->Previous)
951 Previous->Type = TT_PointerOrReference;
952 if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
953 Contexts.back().IsExpression = false;
954 } else if (Current.is(tok::kw_new)) {
955 Contexts.back().CanBeExpression = false;
956 } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
957 // This should be the condition or increment in a for-loop.
958 Contexts.back().IsExpression = true;
962 void determineTokenType(FormatToken &Current) {
963 if (!Current.is(TT_Unknown))
964 // The token type is already known.
967 // Line.MightBeFunctionDecl can only be true after the parentheses of a
968 // function declaration have been found. In this case, 'Current' is a
969 // trailing token of this declaration and thus cannot be a name.
970 if (Current.is(Keywords.kw_instanceof)) {
971 Current.Type = TT_BinaryOperator;
972 } else if (isStartOfName(Current) &&
973 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
974 Contexts.back().FirstStartOfName = &Current;
975 Current.Type = TT_StartOfName;
976 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
978 } else if (Current.is(tok::arrow) &&
979 Style.Language == FormatStyle::LK_Java) {
980 Current.Type = TT_LambdaArrow;
981 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
982 Current.NestingLevel == 0) {
983 Current.Type = TT_TrailingReturnArrow;
984 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
986 determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
987 Contexts.back().IsExpression,
988 Contexts.back().InTemplateArgument);
989 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
990 Current.Type = determinePlusMinusCaretUsage(Current);
991 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
992 Contexts.back().CaretFound = true;
993 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
994 Current.Type = determineIncrementUsage(Current);
995 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
996 Current.Type = TT_UnaryOperator;
997 } else if (Current.is(tok::question)) {
998 if (Style.Language == FormatStyle::LK_JavaScript &&
999 Line.MustBeDeclaration) {
1000 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
1001 // on the interface, not a ternary expression.
1002 Current.Type = TT_JsTypeOptionalQuestion;
1004 Current.Type = TT_ConditionalExpr;
1006 } else if (Current.isBinaryOperator() &&
1007 (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
1008 Current.Type = TT_BinaryOperator;
1009 } else if (Current.is(tok::comment)) {
1010 if (Current.TokenText.startswith("/*")) {
1011 if (Current.TokenText.endswith("*/"))
1012 Current.Type = TT_BlockComment;
1014 // The lexer has for some reason determined a comment here. But we
1015 // cannot really handle it, if it isn't properly terminated.
1016 Current.Tok.setKind(tok::unknown);
1018 Current.Type = TT_LineComment;
1020 } else if (Current.is(tok::r_paren)) {
1021 if (rParenEndsCast(Current))
1022 Current.Type = TT_CastRParen;
1023 if (Current.MatchingParen && Current.Next &&
1024 !Current.Next->isBinaryOperator() &&
1025 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1026 tok::period, tok::arrow, tok::coloncolon))
1027 if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1028 if (BeforeParen->is(tok::identifier) &&
1029 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1030 (!BeforeParen->Previous ||
1031 BeforeParen->Previous->ClosesTemplateDeclaration))
1032 Current.Type = TT_FunctionAnnotationRParen;
1033 } else if (Current.is(tok::at) && Current.Next) {
1034 if (Current.Next->isStringLiteral()) {
1035 Current.Type = TT_ObjCStringLiteral;
1037 switch (Current.Next->Tok.getObjCKeywordID()) {
1038 case tok::objc_interface:
1039 case tok::objc_implementation:
1040 case tok::objc_protocol:
1041 Current.Type = TT_ObjCDecl;
1043 case tok::objc_property:
1044 Current.Type = TT_ObjCProperty;
1050 } else if (Current.is(tok::period)) {
1051 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1052 if (PreviousNoComment &&
1053 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1054 Current.Type = TT_DesignatedInitializerPeriod;
1055 else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1056 Current.Previous->isOneOf(TT_JavaAnnotation,
1057 TT_LeadingJavaAnnotation)) {
1058 Current.Type = Current.Previous->Type;
1060 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
1062 !Current.Previous->isOneOf(tok::equal, tok::at) &&
1063 Line.MightBeFunctionDecl && Contexts.size() == 1) {
1064 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1065 // function declaration have been found.
1066 Current.Type = TT_TrailingAnnotation;
1067 } else if ((Style.Language == FormatStyle::LK_Java ||
1068 Style.Language == FormatStyle::LK_JavaScript) &&
1070 if (Current.Previous->is(tok::at) &&
1071 Current.isNot(Keywords.kw_interface)) {
1072 const FormatToken &AtToken = *Current.Previous;
1073 const FormatToken *Previous = AtToken.getPreviousNonComment();
1074 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1075 Current.Type = TT_LeadingJavaAnnotation;
1077 Current.Type = TT_JavaAnnotation;
1078 } else if (Current.Previous->is(tok::period) &&
1079 Current.Previous->isOneOf(TT_JavaAnnotation,
1080 TT_LeadingJavaAnnotation)) {
1081 Current.Type = Current.Previous->Type;
1086 /// \brief Take a guess at whether \p Tok starts a name of a function or
1087 /// variable declaration.
1089 /// This is a heuristic based on whether \p Tok is an identifier following
1090 /// something that is likely a type.
1091 bool isStartOfName(const FormatToken &Tok) {
1092 if (Tok.isNot(tok::identifier) || !Tok.Previous)
1095 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof))
1097 if (Style.Language == FormatStyle::LK_JavaScript &&
1098 Tok.Previous->is(Keywords.kw_in))
1101 // Skip "const" as it does not have an influence on whether this is a name.
1102 FormatToken *PreviousNotConst = Tok.Previous;
1103 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1104 PreviousNotConst = PreviousNotConst->Previous;
1106 if (!PreviousNotConst)
1109 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1110 PreviousNotConst->Previous &&
1111 PreviousNotConst->Previous->is(tok::hash);
1113 if (PreviousNotConst->is(TT_TemplateCloser))
1114 return PreviousNotConst && PreviousNotConst->MatchingParen &&
1115 PreviousNotConst->MatchingParen->Previous &&
1116 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1117 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1119 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1120 PreviousNotConst->MatchingParen->Previous &&
1121 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1124 return (!IsPPKeyword &&
1125 PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1126 PreviousNotConst->is(TT_PointerOrReference) ||
1127 PreviousNotConst->isSimpleTypeSpecifier();
1130 /// \brief Determine whether ')' is ending a cast.
1131 bool rParenEndsCast(const FormatToken &Tok) {
1132 // C-style casts are only used in C++ and Java.
1133 if (Style.Language != FormatStyle::LK_Cpp &&
1134 Style.Language != FormatStyle::LK_Java)
1137 // Empty parens aren't casts and there are no casts at the end of the line.
1138 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1141 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1143 // If there is a closing parenthesis left of the current parentheses,
1144 // look past it as these might be chained casts.
1145 if (LeftOfParens->is(tok::r_paren)) {
1146 if (!LeftOfParens->MatchingParen ||
1147 !LeftOfParens->MatchingParen->Previous)
1149 LeftOfParens = LeftOfParens->MatchingParen->Previous;
1152 // If there is an identifier (or with a few exceptions a keyword) right
1153 // before the parentheses, this is unlikely to be a cast.
1154 if (LeftOfParens->Tok.getIdentifierInfo() &&
1155 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1159 // Certain other tokens right before the parentheses are also signals that
1160 // this cannot be a cast.
1161 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1162 TT_TemplateCloser, tok::ellipsis))
1166 if (Tok.Next->is(tok::question))
1169 // As Java has no function types, a "(" after the ")" likely means that this
1171 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1174 // If a (non-string) literal follows, this is likely a cast.
1175 if (Tok.Next->isNot(tok::string_literal) &&
1176 (Tok.Next->Tok.isLiteral() ||
1177 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1180 // Heuristically try to determine whether the parentheses contain a type.
1181 bool ParensAreType =
1183 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1184 Tok.Previous->isSimpleTypeSpecifier();
1185 bool ParensCouldEndDecl =
1186 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1187 if (ParensAreType && !ParensCouldEndDecl)
1190 // At this point, we heuristically assume that there are no casts at the
1191 // start of the line. We assume that we have found most cases where there
1192 // are by the logic above, e.g. "(void)x;".
1196 // If the following token is an identifier or 'this', this is a cast. All
1197 // cases where this can be something else are handled above.
1198 if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
1201 if (!Tok.Next->Next)
1204 // If the next token after the parenthesis is a unary operator, assume
1205 // that this is cast, unless there are unexpected tokens inside the
1208 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1209 if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1210 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1212 // Search for unexpected tokens.
1213 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1214 Prev = Prev->Previous) {
1215 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1221 /// \brief Return the type of the given token assuming it is * or &.
1222 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1223 bool InTemplateArgument) {
1224 if (Style.Language == FormatStyle::LK_JavaScript)
1225 return TT_BinaryOperator;
1227 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1229 return TT_UnaryOperator;
1231 const FormatToken *NextToken = Tok.getNextNonComment();
1233 NextToken->isOneOf(tok::arrow, Keywords.kw_final,
1234 Keywords.kw_override) ||
1235 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1236 return TT_PointerOrReference;
1238 if (PrevToken->is(tok::coloncolon))
1239 return TT_PointerOrReference;
1241 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1242 tok::comma, tok::semi, tok::kw_return, tok::colon,
1243 tok::equal, tok::kw_delete, tok::kw_sizeof) ||
1244 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1245 TT_UnaryOperator, TT_CastRParen))
1246 return TT_UnaryOperator;
1248 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1249 return TT_PointerOrReference;
1250 if (NextToken->is(tok::kw_operator) && !IsExpression)
1251 return TT_PointerOrReference;
1252 if (NextToken->isOneOf(tok::comma, tok::semi))
1253 return TT_PointerOrReference;
1255 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
1256 PrevToken->MatchingParen->Previous &&
1257 PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
1259 return TT_PointerOrReference;
1261 if (PrevToken->Tok.isLiteral() ||
1262 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1263 tok::kw_false, tok::r_brace) ||
1264 NextToken->Tok.isLiteral() ||
1265 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1266 NextToken->isUnaryOperator() ||
1267 // If we know we're in a template argument, there are no named
1268 // declarations. Thus, having an identifier on the right-hand side
1269 // indicates a binary operator.
1270 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1271 return TT_BinaryOperator;
1273 // "&&(" is quite unlikely to be two successive unary "&".
1274 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1275 return TT_BinaryOperator;
1277 // This catches some cases where evaluation order is used as control flow:
1279 const FormatToken *NextNextToken = NextToken->getNextNonComment();
1280 if (NextNextToken && NextNextToken->is(tok::arrow))
1281 return TT_BinaryOperator;
1283 // It is very unlikely that we are going to find a pointer or reference type
1284 // definition on the RHS of an assignment.
1285 if (IsExpression && !Contexts.back().CaretFound)
1286 return TT_BinaryOperator;
1288 return TT_PointerOrReference;
1291 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1292 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1293 if (!PrevToken || PrevToken->is(TT_CastRParen))
1294 return TT_UnaryOperator;
1296 // Use heuristics to recognize unary operators.
1297 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1298 tok::question, tok::colon, tok::kw_return,
1299 tok::kw_case, tok::at, tok::l_brace))
1300 return TT_UnaryOperator;
1302 // There can't be two consecutive binary operators.
1303 if (PrevToken->is(TT_BinaryOperator))
1304 return TT_UnaryOperator;
1306 // Fall back to marking the token as binary operator.
1307 return TT_BinaryOperator;
1310 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1311 TokenType determineIncrementUsage(const FormatToken &Tok) {
1312 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1313 if (!PrevToken || PrevToken->is(TT_CastRParen))
1314 return TT_UnaryOperator;
1315 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1316 return TT_TrailingUnaryOperator;
1318 return TT_UnaryOperator;
1321 SmallVector<Context, 8> Contexts;
1323 const FormatStyle &Style;
1324 AnnotatedLine &Line;
1325 FormatToken *CurrentToken;
1327 const AdditionalKeywords &Keywords;
1329 // Set of "<" tokens that do not open a template parameter list. If parseAngle
1330 // determines that a specific token can't be a template opener, it will make
1331 // same decision irrespective of the decisions for tokens leading up to it.
1332 // Store this information to prevent this from causing exponential runtime.
1333 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1336 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1337 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1339 /// \brief Parses binary expressions by inserting fake parenthesis based on
1340 /// operator precedence.
1341 class ExpressionParser {
1343 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1344 AnnotatedLine &Line)
1345 : Style(Style), Keywords(Keywords), Current(Line.First) {}
1347 /// \brief Parse expressions with the given operatore precedence.
1348 void parse(int Precedence = 0) {
1349 // Skip 'return' and ObjC selector colons as they are not part of a binary
1351 while (Current && (Current->is(tok::kw_return) ||
1352 (Current->is(tok::colon) &&
1353 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1356 if (!Current || Precedence > PrecedenceArrowAndPeriod)
1359 // Conditional expressions need to be parsed separately for proper nesting.
1360 if (Precedence == prec::Conditional) {
1361 parseConditionalExpr();
1365 // Parse unary operators, which all have a higher precedence than binary
1367 if (Precedence == PrecedenceUnaryOperator) {
1368 parseUnaryOperator();
1372 FormatToken *Start = Current;
1373 FormatToken *LatestOperator = nullptr;
1374 unsigned OperatorIndex = 0;
1377 // Consume operators with higher precedence.
1378 parse(Precedence + 1);
1380 int CurrentPrecedence = getCurrentPrecedence();
1382 if (Current && Current->is(TT_SelectorName) &&
1383 Precedence == CurrentPrecedence) {
1385 addFakeParenthesis(Start, prec::Level(Precedence));
1389 // At the end of the line or when an operator with higher precedence is
1390 // found, insert fake parenthesis and return.
1391 if (!Current || (Current->closesScope() && Current->MatchingParen) ||
1392 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1393 (CurrentPrecedence == prec::Conditional &&
1394 Precedence == prec::Assignment && Current->is(tok::colon))) {
1398 // Consume scopes: (), [], <> and {}
1399 if (Current->opensScope()) {
1400 while (Current && !Current->closesScope()) {
1407 if (CurrentPrecedence == Precedence) {
1409 LatestOperator->NextOperator = Current;
1410 LatestOperator = Current;
1411 Current->OperatorIndex = OperatorIndex;
1414 next(/*SkipPastLeadingComments=*/Precedence > 0);
1418 if (LatestOperator && (Current || Precedence > 0)) {
1419 // LatestOperator->LastOperator = true;
1420 if (Precedence == PrecedenceArrowAndPeriod) {
1421 // Call expressions don't have a binary operator precedence.
1422 addFakeParenthesis(Start, prec::Unknown);
1424 addFakeParenthesis(Start, prec::Level(Precedence));
1430 /// \brief Gets the precedence (+1) of the given token for binary operators
1431 /// and other tokens that we treat like binary operators.
1432 int getCurrentPrecedence() {
1434 const FormatToken *NextNonComment = Current->getNextNonComment();
1435 if (Current->is(TT_ConditionalExpr))
1436 return prec::Conditional;
1437 if (NextNonComment && NextNonComment->is(tok::colon) &&
1438 NextNonComment->is(TT_DictLiteral))
1440 if (Current->is(TT_LambdaArrow))
1442 if (Current->is(TT_JsFatArrow))
1443 return prec::Assignment;
1444 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName,
1445 TT_JsComputedPropertyName) ||
1446 (Current->is(tok::comment) && NextNonComment &&
1447 NextNonComment->is(TT_SelectorName)))
1449 if (Current->is(TT_RangeBasedForLoopColon))
1451 if ((Style.Language == FormatStyle::LK_Java ||
1452 Style.Language == FormatStyle::LK_JavaScript) &&
1453 Current->is(Keywords.kw_instanceof))
1454 return prec::Relational;
1455 if (Style.Language == FormatStyle::LK_JavaScript &&
1456 Current->is(Keywords.kw_in))
1457 return prec::Relational;
1458 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1459 return Current->getPrecedence();
1460 if (Current->isOneOf(tok::period, tok::arrow))
1461 return PrecedenceArrowAndPeriod;
1462 if (Style.Language == FormatStyle::LK_Java &&
1463 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1464 Keywords.kw_throws))
1470 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1471 Start->FakeLParens.push_back(Precedence);
1472 if (Precedence > prec::Unknown)
1473 Start->StartsBinaryExpression = true;
1475 FormatToken *Previous = Current->Previous;
1476 while (Previous->is(tok::comment) && Previous->Previous)
1477 Previous = Previous->Previous;
1478 ++Previous->FakeRParens;
1479 if (Precedence > prec::Unknown)
1480 Previous->EndsBinaryExpression = true;
1484 /// \brief Parse unary operator expressions and surround them with fake
1485 /// parentheses if appropriate.
1486 void parseUnaryOperator() {
1487 if (!Current || Current->isNot(TT_UnaryOperator)) {
1488 parse(PrecedenceArrowAndPeriod);
1492 FormatToken *Start = Current;
1494 parseUnaryOperator();
1496 // The actual precedence doesn't matter.
1497 addFakeParenthesis(Start, prec::Unknown);
1500 void parseConditionalExpr() {
1501 while (Current && Current->isTrailingComment()) {
1504 FormatToken *Start = Current;
1505 parse(prec::LogicalOr);
1506 if (!Current || !Current->is(tok::question))
1509 parse(prec::Assignment);
1510 if (!Current || Current->isNot(TT_ConditionalExpr))
1513 parse(prec::Assignment);
1514 addFakeParenthesis(Start, prec::Conditional);
1517 void next(bool SkipPastLeadingComments = true) {
1519 Current = Current->Next;
1521 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1522 Current->isTrailingComment())
1523 Current = Current->Next;
1526 const FormatStyle &Style;
1527 const AdditionalKeywords &Keywords;
1528 FormatToken *Current;
1531 } // end anonymous namespace
1533 void TokenAnnotator::setCommentLineLevels(
1534 SmallVectorImpl<AnnotatedLine *> &Lines) {
1535 const AnnotatedLine *NextNonCommentLine = nullptr;
1536 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1539 if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
1540 (*I)->First->Next == nullptr)
1541 (*I)->Level = NextNonCommentLine->Level;
1543 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1545 setCommentLineLevels((*I)->Children);
1549 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1550 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1551 E = Line.Children.end();
1555 AnnotatingParser Parser(Style, Line, Keywords);
1556 Line.Type = Parser.parseLine();
1557 if (Line.Type == LT_Invalid)
1560 ExpressionParser ExprParser(Style, Keywords, Line);
1563 if (Line.startsWith(TT_ObjCMethodSpecifier))
1564 Line.Type = LT_ObjCMethodDecl;
1565 else if (Line.startsWith(TT_ObjCDecl))
1566 Line.Type = LT_ObjCDecl;
1567 else if (Line.startsWith(TT_ObjCProperty))
1568 Line.Type = LT_ObjCProperty;
1570 Line.First->SpacesRequiredBefore = 1;
1571 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1574 // This function heuristically determines whether 'Current' starts the name of a
1575 // function declaration.
1576 static bool isFunctionDeclarationName(const FormatToken &Current,
1577 const AnnotatedLine &Line) {
1578 auto skipOperatorName = [](const FormatToken* Next) -> const FormatToken* {
1579 for (; Next; Next = Next->Next) {
1580 if (Next->is(TT_OverloadedOperatorLParen))
1582 if (Next->is(TT_OverloadedOperator))
1584 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1585 // For 'new[]' and 'delete[]'.
1586 if (Next->Next && Next->Next->is(tok::l_square) &&
1587 Next->Next->Next && Next->Next->Next->is(tok::r_square))
1588 Next = Next->Next->Next;
1597 // Find parentheses of parameter list.
1598 const FormatToken *Next = Current.Next;
1599 if (Current.is(tok::kw_operator)) {
1600 if (Current.Previous && Current.Previous->is(tok::coloncolon))
1602 Next = skipOperatorName(Next);
1604 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1606 for (; Next; Next = Next->Next) {
1607 if (Next->is(TT_TemplateOpener)) {
1608 Next = Next->MatchingParen;
1609 } else if (Next->is(tok::coloncolon)) {
1613 if (Next->is(tok::kw_operator)) {
1614 Next = skipOperatorName(Next->Next);
1617 if (!Next->is(tok::identifier))
1619 } else if (Next->is(tok::l_paren)) {
1627 // Check whether parameter list can be long to a function declaration.
1628 if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
1630 // If the lines ends with "{", this is likely an function definition.
1631 if (Line.Last->is(tok::l_brace))
1633 if (Next->Next == Next->MatchingParen)
1634 return true; // Empty parentheses.
1635 // If there is an &/&& after the r_paren, this is likely a function.
1636 if (Next->MatchingParen->Next &&
1637 Next->MatchingParen->Next->is(TT_PointerOrReference))
1639 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1641 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1642 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
1644 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1645 Tok->Tok.isLiteral())
1651 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
1652 assert(Line.MightBeFunctionDecl);
1654 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
1655 Style.AlwaysBreakAfterReturnType ==
1656 FormatStyle::RTBS_TopLevelDefinitions) &&
1660 switch (Style.AlwaysBreakAfterReturnType) {
1661 case FormatStyle::RTBS_None:
1663 case FormatStyle::RTBS_All:
1664 case FormatStyle::RTBS_TopLevel:
1666 case FormatStyle::RTBS_AllDefinitions:
1667 case FormatStyle::RTBS_TopLevelDefinitions:
1668 return Line.mightBeFunctionDefinition();
1674 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1675 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1676 E = Line.Children.end();
1678 calculateFormattingInformation(**I);
1681 Line.First->TotalLength =
1682 Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1683 if (!Line.First->Next)
1685 FormatToken *Current = Line.First->Next;
1686 bool InFunctionDecl = Line.MightBeFunctionDecl;
1688 if (isFunctionDeclarationName(*Current, Line))
1689 Current->Type = TT_FunctionDeclarationName;
1690 if (Current->is(TT_LineComment)) {
1691 if (Current->Previous->BlockKind == BK_BracedInit &&
1692 Current->Previous->opensScope())
1693 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1695 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1697 // If we find a trailing comment, iterate backwards to determine whether
1698 // it seems to relate to a specific parameter. If so, break before that
1699 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1700 // to the previous line in:
1704 if (!Current->HasUnescapedNewline) {
1705 for (FormatToken *Parameter = Current->Previous; Parameter;
1706 Parameter = Parameter->Previous) {
1707 if (Parameter->isOneOf(tok::comment, tok::r_brace))
1709 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1710 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1711 Parameter->HasUnescapedNewline)
1712 Parameter->MustBreakBefore = true;
1717 } else if (Current->SpacesRequiredBefore == 0 &&
1718 spaceRequiredBefore(Line, *Current)) {
1719 Current->SpacesRequiredBefore = 1;
1722 Current->MustBreakBefore =
1723 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1725 if (!Current->MustBreakBefore && InFunctionDecl &&
1726 Current->is(TT_FunctionDeclarationName))
1727 Current->MustBreakBefore = mustBreakForReturnType(Line);
1729 Current->CanBreakBefore =
1730 Current->MustBreakBefore || canBreakBefore(Line, *Current);
1731 unsigned ChildSize = 0;
1732 if (Current->Previous->Children.size() == 1) {
1733 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1734 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1735 : LastOfChild.TotalLength + 1;
1737 const FormatToken *Prev = Current->Previous;
1738 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1739 (Prev->Children.size() == 1 &&
1740 Prev->Children[0]->First->MustBreakBefore) ||
1741 Current->IsMultiline)
1742 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1744 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1745 ChildSize + Current->SpacesRequiredBefore;
1747 if (Current->is(TT_CtorInitializerColon))
1748 InFunctionDecl = false;
1750 // FIXME: Only calculate this if CanBreakBefore is true once static
1751 // initializers etc. are sorted out.
1752 // FIXME: Move magic numbers to a better place.
1753 Current->SplitPenalty = 20 * Current->BindingStrength +
1754 splitPenalty(Line, *Current, InFunctionDecl);
1756 Current = Current->Next;
1759 calculateUnbreakableTailLengths(Line);
1760 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1762 Current->Role->precomputeFormattingInfos(Current);
1765 DEBUG({ printDebugInfo(Line); });
1768 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1769 unsigned UnbreakableTailLength = 0;
1770 FormatToken *Current = Line.Last;
1772 Current->UnbreakableTailLength = UnbreakableTailLength;
1773 if (Current->CanBreakBefore ||
1774 Current->isOneOf(tok::comment, tok::string_literal)) {
1775 UnbreakableTailLength = 0;
1777 UnbreakableTailLength +=
1778 Current->ColumnWidth + Current->SpacesRequiredBefore;
1780 Current = Current->Previous;
1784 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1785 const FormatToken &Tok,
1786 bool InFunctionDecl) {
1787 const FormatToken &Left = *Tok.Previous;
1788 const FormatToken &Right = Tok;
1790 if (Left.is(tok::semi))
1793 if (Style.Language == FormatStyle::LK_Java) {
1794 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
1796 if (Right.is(Keywords.kw_implements))
1798 if (Left.is(tok::comma) && Left.NestingLevel == 0)
1800 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1801 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
1803 if (Left.is(TT_JsTypeColon))
1807 if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
1808 Right.Next->is(TT_DictLiteral)))
1810 if (Right.is(tok::l_square)) {
1811 if (Style.Language == FormatStyle::LK_Proto)
1813 if (Left.is(tok::r_square))
1815 // Slightly prefer formatting local lambda definitions like functions.
1816 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
1818 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
1819 TT_ArrayInitializerLSquare))
1823 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
1824 Right.is(tok::kw_operator)) {
1825 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1827 if (Left.is(TT_StartOfName))
1829 if (InFunctionDecl && Right.NestingLevel == 0)
1830 return Style.PenaltyReturnTypeOnItsOwnLine;
1833 if (Right.is(TT_PointerOrReference))
1835 if (Right.is(TT_LambdaArrow))
1837 if (Left.is(tok::equal) && Right.is(tok::l_brace))
1839 if (Left.is(TT_CastRParen))
1841 if (Left.is(tok::coloncolon) ||
1842 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1844 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1846 if (Left.is(tok::comment))
1849 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
1852 if (Right.isMemberAccess()) {
1853 // Breaking before the "./->" of a chained call/member access is reasonably
1854 // cheap, as formatting those with one call per line is generally
1855 // desirable. In particular, it should be cheaper to break before the call
1856 // than it is to break inside a call's parameters, which could lead to weird
1857 // "hanging" indents. The exception is the very last "./->" to support this
1858 // frequent pattern:
1860 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
1863 // which might otherwise be blown up onto many lines. Here, clang-format
1864 // won't produce "hanging" indents anyway as there is no other trailing
1867 // Also apply higher penalty is not a call as that might lead to a wrapping
1871 // .aaaaaaaaa.bbbbbbbb(cccccccc);
1872 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
1877 if (Right.is(TT_TrailingAnnotation) &&
1878 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
1879 // Moving trailing annotations to the next line is fine for ObjC method
1881 if (Line.startsWith(TT_ObjCMethodSpecifier))
1883 // Generally, breaking before a trailing annotation is bad unless it is
1884 // function-like. It seems to be especially preferable to keep standard
1885 // annotations (i.e. "const", "final" and "override") on the same line.
1886 // Use a slightly higher penalty after ")" so that annotations like
1887 // "const override" are kept together.
1888 bool is_short_annotation = Right.TokenText.size() < 10;
1889 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
1892 // In for-loops, prefer breaking at ',' and ';'.
1893 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
1896 // In Objective-C method expressions, prefer breaking before "param:" over
1897 // breaking after it.
1898 if (Right.is(TT_SelectorName))
1900 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
1901 return Line.MightBeFunctionDecl ? 50 : 500;
1903 if (Left.is(tok::l_paren) && InFunctionDecl &&
1904 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
1906 if (Left.is(tok::l_paren) && Left.Previous &&
1907 Left.Previous->isOneOf(tok::kw_if, tok::kw_for))
1909 if (Left.is(tok::equal) && InFunctionDecl)
1911 if (Right.is(tok::r_brace))
1913 if (Left.is(TT_TemplateOpener))
1915 if (Left.opensScope()) {
1916 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
1918 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1921 if (Left.is(TT_JavaAnnotation))
1924 if (Right.is(tok::lessless)) {
1925 if (Left.is(tok::string_literal) &&
1926 (Right.NextOperator || Right.OperatorIndex != 1)) {
1927 StringRef Content = Left.TokenText;
1928 if (Content.startswith("\""))
1929 Content = Content.drop_front(1);
1930 if (Content.endswith("\""))
1931 Content = Content.drop_back(1);
1932 Content = Content.trim();
1933 if (Content.size() > 1 &&
1934 (Content.back() == ':' || Content.back() == '='))
1937 return 1; // Breaking at a << is really cheap.
1939 if (Left.is(TT_ConditionalExpr))
1940 return prec::Conditional;
1941 prec::Level Level = Left.getPrecedence();
1942 if (Level != prec::Unknown)
1944 Level = Right.getPrecedence();
1945 if (Level != prec::Unknown)
1951 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1952 const FormatToken &Left,
1953 const FormatToken &Right) {
1954 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
1956 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1957 Left.Tok.getObjCKeywordID() == tok::objc_property)
1959 if (Right.is(tok::hashhash))
1960 return Left.is(tok::hash);
1961 if (Left.isOneOf(tok::hashhash, tok::hash))
1962 return Right.is(tok::hash);
1963 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
1964 return Style.SpaceInEmptyParentheses;
1965 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
1966 return (Right.is(TT_CastRParen) ||
1967 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
1968 ? Style.SpacesInCStyleCastParentheses
1969 : Style.SpacesInParentheses;
1970 if (Right.isOneOf(tok::semi, tok::comma))
1972 if (Right.is(tok::less) &&
1973 (Left.is(tok::kw_template) ||
1974 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1976 if (Left.isOneOf(tok::exclaim, tok::tilde))
1978 if (Left.is(tok::at) &&
1979 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1980 tok::numeric_constant, tok::l_paren, tok::l_brace,
1981 tok::kw_true, tok::kw_false))
1983 if (Left.is(tok::colon))
1984 return !Left.is(TT_ObjCMethodExpr);
1985 if (Left.is(tok::coloncolon))
1987 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
1989 if (Right.is(tok::ellipsis))
1990 return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
1991 Left.Previous->is(tok::kw_case));
1992 if (Left.is(tok::l_square) && Right.is(tok::amp))
1994 if (Right.is(TT_PointerOrReference))
1995 return (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) ||
1996 (Left.Tok.isLiteral() || Left.is(tok::kw_const) ||
1997 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
1998 (Style.PointerAlignment != FormatStyle::PAS_Left ||
1999 Line.IsMultiVariableDeclStmt)));
2000 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
2001 (!Left.is(TT_PointerOrReference) ||
2002 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2003 !Line.IsMultiVariableDeclStmt)))
2005 if (Left.is(TT_PointerOrReference))
2006 return Right.Tok.isLiteral() ||
2007 Right.isOneOf(TT_BlockComment, Keywords.kw_final,
2008 Keywords.kw_override) ||
2009 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
2010 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
2012 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2013 !Line.IsMultiVariableDeclStmt) &&
2015 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
2016 if (Right.is(tok::star) && Left.is(tok::l_paren))
2018 if (Left.is(tok::l_square))
2019 return (Left.is(TT_ArrayInitializerLSquare) &&
2020 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
2021 (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
2022 Right.isNot(tok::r_square));
2023 if (Right.is(tok::r_square))
2024 return Right.MatchingParen &&
2025 ((Style.SpacesInContainerLiterals &&
2026 Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
2027 (Style.SpacesInSquareBrackets &&
2028 Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
2029 if (Right.is(tok::l_square) &&
2030 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
2031 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
2033 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
2034 return !Left.Children.empty(); // No spaces in "{}".
2035 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
2036 (Right.is(tok::r_brace) && Right.MatchingParen &&
2037 Right.MatchingParen->BlockKind != BK_Block))
2038 return !Style.Cpp11BracedListStyle;
2039 if (Left.is(TT_BlockComment))
2040 return !Left.TokenText.endswith("=*/");
2041 if (Right.is(tok::l_paren)) {
2042 if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
2044 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
2045 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
2046 (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
2047 tok::kw_switch, tok::kw_case, TT_ForEachMacro,
2049 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
2050 tok::kw_new, tok::kw_delete) &&
2051 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
2052 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
2053 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
2054 Left.is(tok::r_paren)) &&
2055 Line.Type != LT_PreprocessorDirective);
2057 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
2059 if (Right.is(TT_UnaryOperator))
2060 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
2061 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
2062 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
2064 Left.isSimpleTypeSpecifier()) &&
2065 Right.is(tok::l_brace) && Right.getNextNonComment() &&
2066 Right.BlockKind != BK_Block)
2068 if (Left.is(tok::period) || Right.is(tok::period))
2070 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
2072 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
2073 Left.MatchingParen->Previous &&
2074 Left.MatchingParen->Previous->is(tok::period))
2075 // A.<B>DoSomething();
2077 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
2082 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
2083 const FormatToken &Right) {
2084 const FormatToken &Left = *Right.Previous;
2085 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
2086 return true; // Never ever merge two identifiers.
2087 if (Style.Language == FormatStyle::LK_Cpp) {
2088 if (Left.is(tok::kw_operator))
2089 return Right.is(tok::coloncolon);
2090 } else if (Style.Language == FormatStyle::LK_Proto) {
2091 if (Right.is(tok::period) &&
2092 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2093 Keywords.kw_repeated, Keywords.kw_extend))
2095 if (Right.is(tok::l_paren) &&
2096 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2098 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2099 if (Left.is(TT_JsFatArrow))
2101 if (Right.is(tok::star) &&
2102 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2104 if (Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
2105 Keywords.kw_of, tok::kw_const) &&
2106 (!Left.Previous || !Left.Previous->is(tok::period)))
2108 if (Left.is(tok::kw_default) && Left.Previous &&
2109 Left.Previous->is(tok::kw_export))
2111 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2113 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2115 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
2117 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2118 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2120 if (Left.is(tok::ellipsis))
2122 if (Left.is(TT_TemplateCloser) &&
2123 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2124 Keywords.kw_implements, Keywords.kw_extends))
2125 // Type assertions ('<type>expr') are not followed by whitespace. Other
2126 // locations that should have whitespace following are identified by the
2127 // above set of follower tokens.
2129 // Postfix non-null assertion operator, as in `foo!.bar()`.
2130 if (Right.is(tok::exclaim) && (Left.isOneOf(tok::identifier, tok::r_paren,
2131 tok::r_square, tok::r_brace) ||
2132 Left.Tok.isLiteral()))
2134 } else if (Style.Language == FormatStyle::LK_Java) {
2135 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2137 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2138 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2139 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2140 tok::kw_protected) ||
2141 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2142 Keywords.kw_native)) &&
2143 Right.is(TT_TemplateOpener))
2146 if (Left.is(TT_ImplicitStringLiteral))
2147 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2148 if (Line.Type == LT_ObjCMethodDecl) {
2149 if (Left.is(TT_ObjCMethodSpecifier))
2151 if (Left.is(tok::r_paren) && Right.is(tok::identifier))
2152 // Don't space between ')' and <id>
2155 if (Line.Type == LT_ObjCProperty &&
2156 (Right.is(tok::equal) || Left.is(tok::equal)))
2159 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2160 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2162 if (Right.is(TT_OverloadedOperatorLParen))
2163 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2164 if (Left.is(tok::comma))
2166 if (Right.is(tok::comma))
2168 if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
2170 if (Right.is(tok::colon)) {
2171 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2172 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2174 if (Right.is(TT_ObjCMethodExpr))
2176 if (Left.is(tok::question))
2178 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2180 if (Right.is(TT_DictLiteral))
2181 return Style.SpacesInContainerLiterals;
2184 if (Left.is(TT_UnaryOperator))
2185 return Right.is(TT_BinaryOperator);
2187 // If the next token is a binary operator or a selector name, we have
2188 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2189 if (Left.is(TT_CastRParen))
2190 return Style.SpaceAfterCStyleCast ||
2191 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2193 if (Left.is(tok::greater) && Right.is(tok::greater))
2194 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2195 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2196 if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2197 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
2199 if (!Style.SpaceBeforeAssignmentOperators &&
2200 Right.getPrecedence() == prec::Assignment)
2202 if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
2203 return (Left.is(TT_TemplateOpener) &&
2204 Style.Standard == FormatStyle::LS_Cpp03) ||
2205 !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren,
2207 Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
2208 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2209 return Style.SpacesInAngles;
2210 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2211 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2212 !Right.is(tok::r_paren)))
2214 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2215 Right.isNot(TT_FunctionTypeLParen))
2216 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2217 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2218 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2220 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2221 Line.startsWith(tok::hash))
2223 if (Right.is(TT_TrailingUnaryOperator))
2225 if (Left.is(TT_RegexLiteral))
2227 return spaceRequiredBetween(Line, Left, Right);
2230 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2231 static bool isAllmanBrace(const FormatToken &Tok) {
2232 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2233 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2236 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2237 const FormatToken &Right) {
2238 const FormatToken &Left = *Right.Previous;
2239 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2242 if (Style.Language == FormatStyle::LK_JavaScript) {
2243 // FIXME: This might apply to other languages and token kinds.
2244 if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
2245 Left.Previous->is(tok::string_literal))
2247 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2248 Left.Previous && Left.Previous->is(tok::equal) &&
2249 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2251 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2253 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2254 // Object literals on the top level of a file are treated as "enum-style".
2255 // Each key/value pair is put on a separate line, instead of bin-packing.
2257 if (Left.is(tok::l_brace) && Line.Level == 0 &&
2258 (Line.startsWith(tok::kw_enum) ||
2259 Line.startsWith(tok::kw_export, tok::kw_enum)))
2260 // JavaScript top-level enum key/value pairs are put on separate lines
2261 // instead of bin-packing.
2263 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2264 !Left.Children.empty())
2265 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2266 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2267 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2268 (Left.NestingLevel == 0 && Line.Level == 0 &&
2269 Style.AllowShortFunctionsOnASingleLine ==
2270 FormatStyle::SFS_Inline);
2271 } else if (Style.Language == FormatStyle::LK_Java) {
2272 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2273 Right.Next->is(tok::string_literal))
2277 // If the last token before a '}' is a comma or a trailing comment, the
2278 // intention is to insert a line break after it in order to make shuffling
2279 // around entries easier.
2280 const FormatToken *BeforeClosingBrace = nullptr;
2281 if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
2282 Left.BlockKind != BK_Block && Left.MatchingParen)
2283 BeforeClosingBrace = Left.MatchingParen->Previous;
2284 else if (Right.MatchingParen &&
2285 Right.MatchingParen->isOneOf(tok::l_brace,
2286 TT_ArrayInitializerLSquare))
2287 BeforeClosingBrace = &Left;
2288 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2289 BeforeClosingBrace->isTrailingComment()))
2292 if (Right.is(tok::comment))
2293 return Left.BlockKind != BK_BracedInit &&
2294 Left.isNot(TT_CtorInitializerColon) &&
2295 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2296 if (Left.isTrailingComment())
2298 if (Left.isStringLiteral() &&
2299 (Right.isStringLiteral() || Right.is(TT_ObjCStringLiteral)))
2301 if (Right.Previous->IsUnterminatedLiteral)
2303 if (Right.is(tok::lessless) && Right.Next &&
2304 Right.Previous->is(tok::string_literal) &&
2305 Right.Next->is(tok::string_literal))
2307 if (Right.Previous->ClosesTemplateDeclaration &&
2308 Right.Previous->MatchingParen &&
2309 Right.Previous->MatchingParen->NestingLevel == 0 &&
2310 Style.AlwaysBreakTemplateDeclarations)
2312 if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
2313 Style.BreakConstructorInitializersBeforeComma &&
2314 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2316 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2317 // Raw string literals are special wrt. line breaks. The author has made a
2318 // deliberate choice and might have aligned the contents of the string
2319 // literal accordingly. Thus, we try keep existing line breaks.
2320 return Right.NewlinesBefore > 0;
2321 if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
2322 Style.Language == FormatStyle::LK_Proto)
2323 // Don't put enums onto single lines in protocol buffers.
2325 if (Right.is(TT_InlineASMBrace))
2326 return Right.HasUnescapedNewline;
2327 if (isAllmanBrace(Left) || isAllmanBrace(Right))
2328 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2329 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2330 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2331 if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) &&
2332 Right.is(TT_SelectorName))
2334 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2337 if ((Style.Language == FormatStyle::LK_Java ||
2338 Style.Language == FormatStyle::LK_JavaScript) &&
2339 Left.is(TT_LeadingJavaAnnotation) &&
2340 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2341 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2347 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2348 const FormatToken &Right) {
2349 const FormatToken &Left = *Right.Previous;
2351 // Language-specific stuff.
2352 if (Style.Language == FormatStyle::LK_Java) {
2353 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2354 Keywords.kw_implements))
2356 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2357 Keywords.kw_implements))
2359 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2360 if (Left.is(tok::kw_return))
2361 return false; // Otherwise a semicolon is inserted.
2362 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2364 if (Left.is(TT_JsTypeColon))
2366 if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is))
2368 if (Left.is(Keywords.kw_in))
2369 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
2370 if (Right.is(Keywords.kw_in))
2371 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
2374 if (Left.is(tok::at))
2376 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2378 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2379 return !Right.is(tok::l_paren);
2380 if (Right.is(TT_PointerOrReference))
2381 return Line.IsMultiVariableDeclStmt ||
2382 (Style.PointerAlignment == FormatStyle::PAS_Right &&
2383 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2384 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2385 Right.is(tok::kw_operator))
2387 if (Left.is(TT_PointerOrReference))
2389 if (Right.isTrailingComment())
2390 // We rely on MustBreakBefore being set correctly here as we should not
2391 // change the "binding" behavior of a comment.
2392 // The first comment in a braced lists is always interpreted as belonging to
2393 // the first list element. Otherwise, it should be placed outside of the
2395 return Left.BlockKind == BK_BracedInit;
2396 if (Left.is(tok::question) && Right.is(tok::colon))
2398 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2399 return Style.BreakBeforeTernaryOperators;
2400 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2401 return !Style.BreakBeforeTernaryOperators;
2402 if (Right.is(TT_InheritanceColon))
2404 if (Right.is(tok::colon) &&
2405 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2407 if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
2409 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2410 Right.Next->is(TT_ObjCMethodExpr)))
2411 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2412 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2414 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
2416 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2417 TT_OverloadedOperator))
2419 if (Left.is(TT_RangeBasedForLoopColon))
2421 if (Right.is(TT_RangeBasedForLoopColon))
2423 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2424 Left.is(tok::kw_operator))
2426 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2427 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
2429 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2431 if (Left.is(tok::l_paren) && Left.Previous &&
2432 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2434 if (Right.is(TT_ImplicitStringLiteral))
2437 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2439 if (Right.is(tok::r_square) && Right.MatchingParen &&
2440 Right.MatchingParen->is(TT_LambdaLSquare))
2443 // We only break before r_brace if there was a corresponding break before
2444 // the l_brace, which is tracked by BreakBeforeClosingBrace.
2445 if (Right.is(tok::r_brace))
2446 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2448 // Allow breaking after a trailing annotation, e.g. after a method
2450 if (Left.is(TT_TrailingAnnotation))
2451 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2452 tok::less, tok::coloncolon);
2454 if (Right.is(tok::kw___attribute))
2457 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2460 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2463 if (Left.is(TT_CtorInitializerComma) &&
2464 Style.BreakConstructorInitializersBeforeComma)
2466 if (Right.is(TT_CtorInitializerComma) &&
2467 Style.BreakConstructorInitializersBeforeComma)
2469 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2470 (Left.is(tok::less) && Right.is(tok::less)))
2472 if (Right.is(TT_BinaryOperator) &&
2473 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2474 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2475 Right.getPrecedence() != prec::Assignment))
2477 if (Left.is(TT_ArrayInitializerLSquare))
2479 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2481 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
2482 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2483 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2484 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2485 Left.getPrecedence() == prec::Assignment))
2487 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2488 tok::kw_class, tok::kw_struct, tok::comment) ||
2489 Right.isMemberAccess() ||
2490 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2491 tok::colon, tok::l_square, tok::at) ||
2492 (Left.is(tok::r_paren) &&
2493 Right.isOneOf(tok::identifier, tok::kw_const)) ||
2494 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
2497 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2498 llvm::errs() << "AnnotatedTokens:\n";
2499 const FormatToken *Tok = Line.First;
2501 llvm::errs() << " M=" << Tok->MustBreakBefore
2502 << " C=" << Tok->CanBreakBefore
2503 << " T=" << getTokenTypeName(Tok->Type)
2504 << " S=" << Tok->SpacesRequiredBefore
2505 << " B=" << Tok->BlockParameterCount
2506 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
2507 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
2509 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2510 llvm::errs() << Tok->FakeLParens[i] << "/";
2511 llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
2513 assert(Tok == Line.Last);
2516 llvm::errs() << "----\n";
2519 } // namespace format
2520 } // namespace clang