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 (Style.Language == FormatStyle::LK_JavaScript &&
138 Line.startsWith(Keywords.kw_type, tok::identifier)) {
140 Contexts.back().IsExpression = false;
141 } else if (Left->Previous &&
142 (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
143 tok::kw_if, tok::kw_while, tok::l_paren,
145 Left->Previous->is(TT_BinaryOperator))) {
146 // static_assert, if and while usually contain expressions.
147 Contexts.back().IsExpression = true;
148 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
149 (Left->Previous->is(Keywords.kw_function) ||
150 (Left->Previous->endsSequence(tok::identifier,
151 Keywords.kw_function)))) {
152 // function(...) or function f(...)
153 Contexts.back().IsExpression = false;
154 } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
155 Left->Previous->is(TT_JsTypeColon)) {
156 // let x: (SomeType);
157 Contexts.back().IsExpression = false;
158 } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
159 Left->Previous->MatchingParen &&
160 Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
161 // This is a parameter list of a lambda expression.
162 Contexts.back().IsExpression = false;
163 } else if (Line.InPPDirective &&
164 (!Left->Previous || !Left->Previous->is(tok::identifier))) {
165 Contexts.back().IsExpression = true;
166 } else if (Contexts[Contexts.size() - 2].CaretFound) {
167 // This is the parameter list of an ObjC block.
168 Contexts.back().IsExpression = false;
169 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
170 Left->Type = TT_AttributeParen;
171 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
172 // The first argument to a foreach macro is a declaration.
173 Contexts.back().IsForEachMacro = true;
174 Contexts.back().IsExpression = false;
175 } else if (Left->Previous && Left->Previous->MatchingParen &&
176 Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
177 Contexts.back().IsExpression = false;
178 } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
180 Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
181 Contexts.back().IsExpression = !IsForOrCatch;
184 if (StartsObjCMethodExpr) {
185 Contexts.back().ColonIsObjCMethodExpr = true;
186 Left->Type = TT_ObjCMethodExpr;
189 bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
190 bool ProbablyFunctionType = CurrentToken->isOneOf(tok::star, tok::amp);
191 bool HasMultipleLines = false;
192 bool HasMultipleParametersOnALine = false;
193 bool MightBeObjCForRangeLoop =
194 Left->Previous && Left->Previous->is(tok::kw_for);
195 while (CurrentToken) {
196 // LookForDecls is set when "if (" has been seen. Check for
197 // 'identifier' '*' 'identifier' followed by not '=' -- this
198 // '*' has to be a binary operator but determineStarAmpUsage() will
199 // categorize it as an unary operator, so set the right type here.
200 if (LookForDecls && CurrentToken->Next) {
201 FormatToken *Prev = CurrentToken->getPreviousNonComment();
203 FormatToken *PrevPrev = Prev->getPreviousNonComment();
204 FormatToken *Next = CurrentToken->Next;
205 if (PrevPrev && PrevPrev->is(tok::identifier) &&
206 Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
207 CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
208 Prev->Type = TT_BinaryOperator;
209 LookForDecls = false;
214 if (CurrentToken->Previous->is(TT_PointerOrReference) &&
215 CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
217 ProbablyFunctionType = true;
218 if (CurrentToken->is(tok::comma))
219 MightBeFunctionType = false;
220 if (CurrentToken->Previous->is(TT_BinaryOperator))
221 Contexts.back().IsExpression = true;
222 if (CurrentToken->is(tok::r_paren)) {
223 if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next &&
224 (CurrentToken->Next->is(tok::l_paren) ||
225 (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration)))
226 Left->Type = TT_FunctionTypeLParen;
227 Left->MatchingParen = CurrentToken;
228 CurrentToken->MatchingParen = Left;
230 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
231 Left->Previous && Left->Previous->is(tok::l_paren)) {
232 // Detect the case where macros are used to generate lambdas or
233 // function bodies, e.g.:
234 // auto my_lambda = MARCO((Type *type, int i) { .. body .. });
235 for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
236 if (Tok->is(TT_BinaryOperator) &&
237 Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
238 Tok->Type = TT_PointerOrReference;
242 if (StartsObjCMethodExpr) {
243 CurrentToken->Type = TT_ObjCMethodExpr;
244 if (Contexts.back().FirstObjCSelectorName) {
245 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
246 Contexts.back().LongestObjCSelectorName;
250 if (Left->is(TT_AttributeParen))
251 CurrentToken->Type = TT_AttributeParen;
252 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
253 CurrentToken->Type = TT_JavaAnnotation;
254 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
255 CurrentToken->Type = TT_LeadingJavaAnnotation;
257 if (!HasMultipleLines)
258 Left->PackingKind = PPK_Inconclusive;
259 else if (HasMultipleParametersOnALine)
260 Left->PackingKind = PPK_BinPacked;
262 Left->PackingKind = PPK_OnePerLine;
267 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
270 if (CurrentToken->is(tok::l_brace))
271 Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
272 if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
273 !CurrentToken->Next->HasUnescapedNewline &&
274 !CurrentToken->Next->isTrailingComment())
275 HasMultipleParametersOnALine = true;
276 if (CurrentToken->isOneOf(tok::kw_const, tok::kw_auto) ||
277 CurrentToken->isSimpleTypeSpecifier())
278 Contexts.back().IsExpression = false;
279 if (CurrentToken->isOneOf(tok::semi, tok::colon))
280 MightBeObjCForRangeLoop = false;
281 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
282 CurrentToken->Type = TT_ObjCForIn;
283 // When we discover a 'new', we set CanBeExpression to 'false' in order to
284 // parse the type correctly. Reset that after a comma.
285 if (CurrentToken->is(tok::comma))
286 Contexts.back().CanBeExpression = true;
288 FormatToken *Tok = CurrentToken;
291 updateParameterCount(Left, Tok);
292 if (CurrentToken && CurrentToken->HasUnescapedNewline)
293 HasMultipleLines = true;
302 // A '[' could be an index subscript (after an identifier or after
303 // ')' or ']'), it could be the start of an Objective-C method
304 // expression, or it could the start of an Objective-C array literal.
305 FormatToken *Left = CurrentToken->Previous;
306 Left->ParentBracket = Contexts.back().ContextKind;
307 FormatToken *Parent = Left->getPreviousNonComment();
308 bool StartsObjCMethodExpr =
309 Style.Language == FormatStyle::LK_Cpp &&
310 Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
311 CurrentToken->isNot(tok::l_brace) &&
313 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
314 tok::kw_return, tok::kw_throw) ||
315 Parent->isUnaryOperator() ||
316 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
317 getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
318 bool ColonFound = false;
320 unsigned BindingIncrease = 1;
321 if (Left->is(TT_Unknown)) {
322 if (StartsObjCMethodExpr) {
323 Left->Type = TT_ObjCMethodExpr;
324 } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
325 Contexts.back().ContextKind == tok::l_brace &&
326 Parent->isOneOf(tok::l_brace, tok::comma)) {
327 Left->Type = TT_JsComputedPropertyName;
328 } else if (Style.Language == FormatStyle::LK_Proto ||
330 Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
331 tok::comma, tok::l_paren, tok::l_square,
332 tok::question, tok::colon, tok::kw_return,
333 // Should only be relevant to JavaScript:
335 Left->Type = TT_ArrayInitializerLSquare;
337 BindingIncrease = 10;
338 Left->Type = TT_ArraySubscriptLSquare;
342 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
343 Contexts.back().IsExpression = true;
344 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
346 while (CurrentToken) {
347 if (CurrentToken->is(tok::r_square)) {
348 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
349 Left->is(TT_ObjCMethodExpr)) {
350 // An ObjC method call is rarely followed by an open parenthesis.
351 // FIXME: Do we incorrectly label ":" with this?
352 StartsObjCMethodExpr = false;
353 Left->Type = TT_Unknown;
355 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
356 CurrentToken->Type = TT_ObjCMethodExpr;
357 // determineStarAmpUsage() thinks that '*' '[' is allocating an
358 // array of pointers, but if '[' starts a selector then '*' is a
360 if (Parent && Parent->is(TT_PointerOrReference))
361 Parent->Type = TT_BinaryOperator;
363 Left->MatchingParen = CurrentToken;
364 CurrentToken->MatchingParen = Left;
365 if (Contexts.back().FirstObjCSelectorName) {
366 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
367 Contexts.back().LongestObjCSelectorName;
368 if (Left->BlockParameterCount > 1)
369 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
374 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
376 if (CurrentToken->is(tok::colon)) {
377 if (Left->is(TT_ArraySubscriptLSquare)) {
378 Left->Type = TT_ObjCMethodExpr;
379 StartsObjCMethodExpr = true;
380 Contexts.back().ColonIsObjCMethodExpr = true;
381 if (Parent && Parent->is(tok::r_paren))
382 Parent->Type = TT_CastRParen;
386 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
388 Left->Type = TT_ArrayInitializerLSquare;
389 FormatToken *Tok = CurrentToken;
392 updateParameterCount(Left, Tok);
399 FormatToken *Left = CurrentToken->Previous;
400 Left->ParentBracket = Contexts.back().ContextKind;
402 if (Contexts.back().CaretFound)
403 Left->Type = TT_ObjCBlockLBrace;
404 Contexts.back().CaretFound = false;
406 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
407 Contexts.back().ColonIsDictLiteral = true;
408 if (Left->BlockKind == BK_BracedInit)
409 Contexts.back().IsExpression = true;
411 while (CurrentToken) {
412 if (CurrentToken->is(tok::r_brace)) {
413 Left->MatchingParen = CurrentToken;
414 CurrentToken->MatchingParen = Left;
418 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
420 updateParameterCount(Left, CurrentToken);
421 if (CurrentToken->isOneOf(tok::colon, tok::l_brace)) {
422 FormatToken *Previous = CurrentToken->getPreviousNonComment();
423 if (((CurrentToken->is(tok::colon) &&
424 (!Contexts.back().ColonIsDictLiteral ||
425 Style.Language != FormatStyle::LK_Cpp)) ||
426 Style.Language == FormatStyle::LK_Proto) &&
427 (Previous->Tok.getIdentifierInfo() ||
428 Previous->is(tok::string_literal)))
429 Previous->Type = TT_SelectorName;
430 if (CurrentToken->is(tok::colon) ||
431 Style.Language == FormatStyle::LK_JavaScript)
432 Left->Type = TT_DictLiteral;
441 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
442 if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
443 ++Left->BlockParameterCount;
444 if (Current->is(tok::comma)) {
445 ++Left->ParameterCount;
447 Left->Role.reset(new CommaSeparatedList(Style));
448 Left->Role->CommaFound(Current);
449 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
450 Left->ParameterCount = 1;
454 bool parseConditional() {
455 while (CurrentToken) {
456 if (CurrentToken->is(tok::colon)) {
457 CurrentToken->Type = TT_ConditionalExpr;
467 bool parseTemplateDeclaration() {
468 if (CurrentToken && CurrentToken->is(tok::less)) {
469 CurrentToken->Type = TT_TemplateOpener;
474 CurrentToken->Previous->ClosesTemplateDeclaration = true;
480 bool consumeToken() {
481 FormatToken *Tok = CurrentToken;
483 switch (Tok->Tok.getKind()) {
486 if (!Tok->Previous && Line.MustBeDeclaration)
487 Tok->Type = TT_ObjCMethodSpecifier;
492 // Colons from ?: are handled in parseConditional().
493 if (Style.Language == FormatStyle::LK_JavaScript) {
494 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
495 (Contexts.size() == 1 && // switch/case labels
496 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
497 Contexts.back().ContextKind == tok::l_paren || // function params
498 Contexts.back().ContextKind == tok::l_square || // array type
499 (Contexts.size() == 1 &&
500 Line.MustBeDeclaration)) { // method/property declaration
501 Tok->Type = TT_JsTypeColon;
505 if (Contexts.back().ColonIsDictLiteral ||
506 Style.Language == FormatStyle::LK_Proto) {
507 Tok->Type = TT_DictLiteral;
508 } else if (Contexts.back().ColonIsObjCMethodExpr ||
509 Line.startsWith(TT_ObjCMethodSpecifier)) {
510 Tok->Type = TT_ObjCMethodExpr;
511 Tok->Previous->Type = TT_SelectorName;
512 if (Tok->Previous->ColumnWidth >
513 Contexts.back().LongestObjCSelectorName)
514 Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth;
515 if (!Contexts.back().FirstObjCSelectorName)
516 Contexts.back().FirstObjCSelectorName = Tok->Previous;
517 } else if (Contexts.back().ColonIsForRangeExpr) {
518 Tok->Type = TT_RangeBasedForLoopColon;
519 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
520 Tok->Type = TT_BitFieldColon;
521 } else if (Contexts.size() == 1 &&
522 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
523 if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren,
525 Tok->Type = TT_CtorInitializerColon;
527 Tok->Type = TT_InheritanceColon;
528 } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
529 Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
530 // This handles a special macro in ObjC code where selectors including
531 // the colon are passed as macro arguments.
532 Tok->Type = TT_ObjCMethodExpr;
533 } else if (Contexts.back().ContextKind == tok::l_paren) {
534 Tok->Type = TT_InlineASMColon;
539 // | and & in declarations/type expressions represent union and
540 // intersection types, respectively.
541 if (Style.Language == FormatStyle::LK_JavaScript &&
542 !Contexts.back().IsExpression)
543 Tok->Type = TT_JsTypeOperator;
547 if (CurrentToken && CurrentToken->is(tok::l_paren)) {
549 if (!parseParens(/*LookForDecls=*/true))
554 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Previous &&
555 Tok->Previous->is(tok::period))
557 Contexts.back().ColonIsForRangeExpr = true;
563 // When faced with 'operator()()', the kw_operator handler incorrectly
564 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
565 // the first two parens OverloadedOperators and the second l_paren an
566 // OverloadedOperatorLParen.
568 Tok->Previous->is(tok::r_paren) &&
569 Tok->Previous->MatchingParen &&
570 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
571 Tok->Previous->Type = TT_OverloadedOperator;
572 Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
573 Tok->Type = TT_OverloadedOperatorLParen;
578 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
579 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
581 !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
582 TT_LeadingJavaAnnotation)))
583 Line.MightBeFunctionDecl = true;
595 Tok->Type = TT_TemplateOpener;
597 Tok->Type = TT_BinaryOperator;
598 NonTemplateLess.insert(Tok);
607 // Lines can start with '}'.
612 Tok->Type = TT_BinaryOperator;
614 case tok::kw_operator:
615 while (CurrentToken &&
616 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
617 if (CurrentToken->isOneOf(tok::star, tok::amp))
618 CurrentToken->Type = TT_PointerOrReference;
621 CurrentToken->Previous->isOneOf(TT_BinaryOperator, tok::comma))
622 CurrentToken->Previous->Type = TT_OverloadedOperator;
625 CurrentToken->Type = TT_OverloadedOperatorLParen;
626 if (CurrentToken->Previous->is(TT_BinaryOperator))
627 CurrentToken->Previous->Type = TT_OverloadedOperator;
631 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
632 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
634 // Question marks before semicolons, colons, etc. indicate optional
635 // types (fields, parameters), e.g.
636 // function(x?: string, y?) {...}
638 Tok->Type = TT_JsTypeOptionalQuestion;
641 // Declarations cannot be conditional expressions, this can only be part
642 // of a type declaration.
643 if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
644 Style.Language == FormatStyle::LK_JavaScript)
648 case tok::kw_template:
649 parseTemplateDeclaration();
652 if (Contexts.back().InCtorInitializer)
653 Tok->Type = TT_CtorInitializerComma;
654 else if (Contexts.back().FirstStartOfName &&
655 (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
656 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
657 Line.IsMultiVariableDeclStmt = true;
659 if (Contexts.back().IsForEachMacro)
660 Contexts.back().IsExpression = true;
668 void parseIncludeDirective() {
669 if (CurrentToken && CurrentToken->is(tok::less)) {
671 while (CurrentToken) {
672 if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
673 CurrentToken->Type = TT_ImplicitStringLiteral;
679 void parseWarningOrError() {
681 // We still want to format the whitespace left of the first token of the
684 while (CurrentToken) {
685 CurrentToken->Type = TT_ImplicitStringLiteral;
691 next(); // Consume "pragma".
693 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
694 bool IsMark = CurrentToken->is(Keywords.kw_mark);
695 next(); // Consume "mark".
696 next(); // Consume first token (so we fix leading whitespace).
697 while (CurrentToken) {
698 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
699 CurrentToken->Type = TT_ImplicitStringLiteral;
705 LineType parsePreprocessorDirective() {
706 bool IsFirstToken = CurrentToken->IsFirst;
707 LineType Type = LT_PreprocessorDirective;
712 if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
713 // JavaScript files can contain shebang lines of the form:
714 // #!/usr/bin/env node
715 // Treat these like C++ #include directives.
716 while (CurrentToken) {
717 // Tokens cannot be comments here.
718 CurrentToken->Type = TT_ImplicitStringLiteral;
721 return LT_ImportStatement;
724 if (CurrentToken->Tok.is(tok::numeric_constant)) {
725 CurrentToken->SpacesRequiredBefore = 1;
728 // Hashes in the middle of a line can lead to any strange token
730 if (!CurrentToken->Tok.getIdentifierInfo())
732 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
733 case tok::pp_include:
734 case tok::pp_include_next:
737 parseIncludeDirective();
738 Type = LT_ImportStatement;
741 case tok::pp_warning:
742 parseWarningOrError();
749 Contexts.back().IsExpression = true;
761 LineType parseLine() {
762 NonTemplateLess.clear();
763 if (CurrentToken->is(tok::hash))
764 return parsePreprocessorDirective();
766 // Directly allow to 'import <string-literal>' to support protocol buffer
767 // definitions (code.google.com/p/protobuf) or missing "#" (either way we
768 // should not break the line).
769 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
770 if ((Style.Language == FormatStyle::LK_Java &&
771 CurrentToken->is(Keywords.kw_package)) ||
772 (Info && Info->getPPKeywordID() == tok::pp_import &&
773 CurrentToken->Next &&
774 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
777 parseIncludeDirective();
778 return LT_ImportStatement;
781 // If this line starts and ends in '<' and '>', respectively, it is likely
782 // part of "#define <a/b.h>".
783 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
784 parseIncludeDirective();
785 return LT_ImportStatement;
788 // In .proto files, top-level options are very similar to import statements
789 // and should not be line-wrapped.
790 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
791 CurrentToken->is(Keywords.kw_option)) {
793 if (CurrentToken && CurrentToken->is(tok::identifier))
794 return LT_ImportStatement;
797 bool KeywordVirtualFound = false;
798 bool ImportStatement = false;
800 // import {...} from '...';
801 if (Style.Language == FormatStyle::LK_JavaScript &&
802 CurrentToken->is(Keywords.kw_import))
803 ImportStatement = true;
805 while (CurrentToken) {
806 if (CurrentToken->is(tok::kw_virtual))
807 KeywordVirtualFound = true;
808 if (Style.Language == FormatStyle::LK_JavaScript) {
809 // export {...} from '...';
810 // An export followed by "from 'some string';" is a re-export from
811 // another module identified by a URI and is treated as a
812 // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
813 // Just "export {...};" or "export class ..." should not be treated as
814 // an import in this sense.
815 if (Line.First->is(tok::kw_export) &&
816 CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
817 CurrentToken->Next->isStringLiteral())
818 ImportStatement = true;
819 if (isClosureImportStatement(*CurrentToken))
820 ImportStatement = true;
825 if (KeywordVirtualFound)
826 return LT_VirtualFunctionDecl;
828 return LT_ImportStatement;
830 if (Line.startsWith(TT_ObjCMethodSpecifier)) {
831 if (Contexts.back().FirstObjCSelectorName)
832 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
833 Contexts.back().LongestObjCSelectorName;
834 return LT_ObjCMethodDecl;
841 bool isClosureImportStatement(const FormatToken &Tok) {
842 // FIXME: Closure-library specific stuff should not be hard-coded but be
844 return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
845 Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
846 Tok.Next->Next->TokenText == "provide" ||
847 Tok.Next->Next->TokenText == "require" ||
848 Tok.Next->Next->TokenText == "setTestOnly" ||
849 Tok.Next->Next->TokenText == "forwardDeclare") &&
850 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
853 void resetTokenMetadata(FormatToken *Token) {
857 // Reset token type in case we have already looked at it and then
858 // recovered from an error (e.g. failure to find the matching >).
859 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
860 TT_FunctionLBrace, TT_ImplicitStringLiteral,
861 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
862 TT_OverloadedOperator, TT_RegexLiteral,
864 CurrentToken->Type = TT_Unknown;
865 CurrentToken->Role.reset();
866 CurrentToken->MatchingParen = nullptr;
867 CurrentToken->FakeLParens.clear();
868 CurrentToken->FakeRParens = 0;
873 CurrentToken->NestingLevel = Contexts.size() - 1;
874 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
875 modifyContext(*CurrentToken);
876 determineTokenType(*CurrentToken);
877 CurrentToken = CurrentToken->Next;
880 resetTokenMetadata(CurrentToken);
883 /// \brief A struct to hold information valid in a specific context, e.g.
884 /// a pair of parenthesis.
886 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
888 : ContextKind(ContextKind), BindingStrength(BindingStrength),
889 IsExpression(IsExpression) {}
891 tok::TokenKind ContextKind;
892 unsigned BindingStrength;
894 unsigned LongestObjCSelectorName = 0;
895 bool ColonIsForRangeExpr = false;
896 bool ColonIsDictLiteral = false;
897 bool ColonIsObjCMethodExpr = false;
898 FormatToken *FirstObjCSelectorName = nullptr;
899 FormatToken *FirstStartOfName = nullptr;
900 bool CanBeExpression = true;
901 bool InTemplateArgument = false;
902 bool InCtorInitializer = false;
903 bool CaretFound = false;
904 bool IsForEachMacro = false;
907 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
908 /// of each instance.
909 struct ScopedContextCreator {
912 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
915 P.Contexts.push_back(Context(ContextKind,
916 P.Contexts.back().BindingStrength + Increase,
917 P.Contexts.back().IsExpression));
920 ~ScopedContextCreator() { P.Contexts.pop_back(); }
923 void modifyContext(const FormatToken &Current) {
924 if (Current.getPrecedence() == prec::Assignment &&
925 !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
926 // Type aliases use `type X = ...;` in TypeScript.
927 !(Style.Language == FormatStyle::LK_JavaScript &&
928 Line.startsWith(Keywords.kw_type, tok::identifier)) &&
929 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
930 Contexts.back().IsExpression = true;
931 if (!Line.startsWith(TT_UnaryOperator)) {
932 for (FormatToken *Previous = Current.Previous;
933 Previous && Previous->Previous &&
934 !Previous->Previous->isOneOf(tok::comma, tok::semi);
935 Previous = Previous->Previous) {
936 if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
937 Previous = Previous->MatchingParen;
941 if (Previous->opensScope())
943 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
944 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
945 Previous->Previous && Previous->Previous->isNot(tok::equal))
946 Previous->Type = TT_PointerOrReference;
949 } else if (Current.is(tok::lessless) &&
950 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
951 Contexts.back().IsExpression = true;
952 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
953 Contexts.back().IsExpression = true;
954 } else if (Current.is(TT_TrailingReturnArrow)) {
955 Contexts.back().IsExpression = false;
956 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
957 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
958 } else if (Current.Previous &&
959 Current.Previous->is(TT_CtorInitializerColon)) {
960 Contexts.back().IsExpression = true;
961 Contexts.back().InCtorInitializer = true;
962 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
963 for (FormatToken *Previous = Current.Previous;
964 Previous && Previous->isOneOf(tok::star, tok::amp);
965 Previous = Previous->Previous)
966 Previous->Type = TT_PointerOrReference;
967 if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
968 Contexts.back().IsExpression = false;
969 } else if (Current.is(tok::kw_new)) {
970 Contexts.back().CanBeExpression = false;
971 } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
972 // This should be the condition or increment in a for-loop.
973 Contexts.back().IsExpression = true;
977 void determineTokenType(FormatToken &Current) {
978 if (!Current.is(TT_Unknown))
979 // The token type is already known.
982 // Line.MightBeFunctionDecl can only be true after the parentheses of a
983 // function declaration have been found. In this case, 'Current' is a
984 // trailing token of this declaration and thus cannot be a name.
985 if (Current.is(Keywords.kw_instanceof)) {
986 Current.Type = TT_BinaryOperator;
987 } else if (isStartOfName(Current) &&
988 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
989 Contexts.back().FirstStartOfName = &Current;
990 Current.Type = TT_StartOfName;
991 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
993 } else if (Current.is(tok::arrow) &&
994 Style.Language == FormatStyle::LK_Java) {
995 Current.Type = TT_LambdaArrow;
996 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
997 Current.NestingLevel == 0) {
998 Current.Type = TT_TrailingReturnArrow;
999 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
1001 determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
1002 Contexts.back().IsExpression,
1003 Contexts.back().InTemplateArgument);
1004 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
1005 Current.Type = determinePlusMinusCaretUsage(Current);
1006 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
1007 Contexts.back().CaretFound = true;
1008 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
1009 Current.Type = determineIncrementUsage(Current);
1010 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
1011 Current.Type = TT_UnaryOperator;
1012 } else if (Current.is(tok::question)) {
1013 if (Style.Language == FormatStyle::LK_JavaScript &&
1014 Line.MustBeDeclaration && !Contexts.back().IsExpression) {
1015 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
1016 // on the interface, not a ternary expression.
1017 Current.Type = TT_JsTypeOptionalQuestion;
1019 Current.Type = TT_ConditionalExpr;
1021 } else if (Current.isBinaryOperator() &&
1022 (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
1023 Current.Type = TT_BinaryOperator;
1024 } else if (Current.is(tok::comment)) {
1025 if (Current.TokenText.startswith("/*")) {
1026 if (Current.TokenText.endswith("*/"))
1027 Current.Type = TT_BlockComment;
1029 // The lexer has for some reason determined a comment here. But we
1030 // cannot really handle it, if it isn't properly terminated.
1031 Current.Tok.setKind(tok::unknown);
1033 Current.Type = TT_LineComment;
1035 } else if (Current.is(tok::r_paren)) {
1036 if (rParenEndsCast(Current))
1037 Current.Type = TT_CastRParen;
1038 if (Current.MatchingParen && Current.Next &&
1039 !Current.Next->isBinaryOperator() &&
1040 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
1041 tok::period, tok::arrow, tok::coloncolon))
1042 if (FormatToken *AfterParen = Current.MatchingParen->Next) {
1043 // Make sure this isn't the return type of an Obj-C block declaration
1044 if (AfterParen->Tok.isNot(tok::caret)) {
1045 if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
1046 if (BeforeParen->is(tok::identifier) &&
1047 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
1048 (!BeforeParen->Previous ||
1049 BeforeParen->Previous->ClosesTemplateDeclaration))
1050 Current.Type = TT_FunctionAnnotationRParen;
1053 } else if (Current.is(tok::at) && Current.Next) {
1054 if (Current.Next->isStringLiteral()) {
1055 Current.Type = TT_ObjCStringLiteral;
1057 switch (Current.Next->Tok.getObjCKeywordID()) {
1058 case tok::objc_interface:
1059 case tok::objc_implementation:
1060 case tok::objc_protocol:
1061 Current.Type = TT_ObjCDecl;
1063 case tok::objc_property:
1064 Current.Type = TT_ObjCProperty;
1070 } else if (Current.is(tok::period)) {
1071 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
1072 if (PreviousNoComment &&
1073 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
1074 Current.Type = TT_DesignatedInitializerPeriod;
1075 else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
1076 Current.Previous->isOneOf(TT_JavaAnnotation,
1077 TT_LeadingJavaAnnotation)) {
1078 Current.Type = Current.Previous->Type;
1080 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
1082 !Current.Previous->isOneOf(tok::equal, tok::at) &&
1083 Line.MightBeFunctionDecl && Contexts.size() == 1) {
1084 // Line.MightBeFunctionDecl can only be true after the parentheses of a
1085 // function declaration have been found.
1086 Current.Type = TT_TrailingAnnotation;
1087 } else if ((Style.Language == FormatStyle::LK_Java ||
1088 Style.Language == FormatStyle::LK_JavaScript) &&
1090 if (Current.Previous->is(tok::at) &&
1091 Current.isNot(Keywords.kw_interface)) {
1092 const FormatToken &AtToken = *Current.Previous;
1093 const FormatToken *Previous = AtToken.getPreviousNonComment();
1094 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1095 Current.Type = TT_LeadingJavaAnnotation;
1097 Current.Type = TT_JavaAnnotation;
1098 } else if (Current.Previous->is(tok::period) &&
1099 Current.Previous->isOneOf(TT_JavaAnnotation,
1100 TT_LeadingJavaAnnotation)) {
1101 Current.Type = Current.Previous->Type;
1106 /// \brief Take a guess at whether \p Tok starts a name of a function or
1107 /// variable declaration.
1109 /// This is a heuristic based on whether \p Tok is an identifier following
1110 /// something that is likely a type.
1111 bool isStartOfName(const FormatToken &Tok) {
1112 if (Tok.isNot(tok::identifier) || !Tok.Previous)
1115 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof))
1117 if (Style.Language == FormatStyle::LK_JavaScript &&
1118 Tok.Previous->is(Keywords.kw_in))
1121 // Skip "const" as it does not have an influence on whether this is a name.
1122 FormatToken *PreviousNotConst = Tok.Previous;
1123 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1124 PreviousNotConst = PreviousNotConst->Previous;
1126 if (!PreviousNotConst)
1129 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1130 PreviousNotConst->Previous &&
1131 PreviousNotConst->Previous->is(tok::hash);
1133 if (PreviousNotConst->is(TT_TemplateCloser))
1134 return PreviousNotConst && PreviousNotConst->MatchingParen &&
1135 PreviousNotConst->MatchingParen->Previous &&
1136 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1137 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1139 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1140 PreviousNotConst->MatchingParen->Previous &&
1141 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1144 return (!IsPPKeyword &&
1145 PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1146 PreviousNotConst->is(TT_PointerOrReference) ||
1147 PreviousNotConst->isSimpleTypeSpecifier();
1150 /// \brief Determine whether ')' is ending a cast.
1151 bool rParenEndsCast(const FormatToken &Tok) {
1152 // C-style casts are only used in C++ and Java.
1153 if (Style.Language != FormatStyle::LK_Cpp &&
1154 Style.Language != FormatStyle::LK_Java)
1157 // Empty parens aren't casts and there are no casts at the end of the line.
1158 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1161 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1163 // If there is a closing parenthesis left of the current parentheses,
1164 // look past it as these might be chained casts.
1165 if (LeftOfParens->is(tok::r_paren)) {
1166 if (!LeftOfParens->MatchingParen ||
1167 !LeftOfParens->MatchingParen->Previous)
1169 LeftOfParens = LeftOfParens->MatchingParen->Previous;
1172 // If there is an identifier (or with a few exceptions a keyword) right
1173 // before the parentheses, this is unlikely to be a cast.
1174 if (LeftOfParens->Tok.getIdentifierInfo() &&
1175 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1179 // Certain other tokens right before the parentheses are also signals that
1180 // this cannot be a cast.
1181 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1182 TT_TemplateCloser, tok::ellipsis))
1186 if (Tok.Next->is(tok::question))
1189 // As Java has no function types, a "(" after the ")" likely means that this
1191 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1194 // If a (non-string) literal follows, this is likely a cast.
1195 if (Tok.Next->isNot(tok::string_literal) &&
1196 (Tok.Next->Tok.isLiteral() ||
1197 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1200 // Heuristically try to determine whether the parentheses contain a type.
1201 bool ParensAreType =
1203 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1204 Tok.Previous->isSimpleTypeSpecifier();
1205 bool ParensCouldEndDecl =
1206 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1207 if (ParensAreType && !ParensCouldEndDecl)
1210 // At this point, we heuristically assume that there are no casts at the
1211 // start of the line. We assume that we have found most cases where there
1212 // are by the logic above, e.g. "(void)x;".
1216 // If the following token is an identifier or 'this', this is a cast. All
1217 // cases where this can be something else are handled above.
1218 if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
1221 if (!Tok.Next->Next)
1224 // If the next token after the parenthesis is a unary operator, assume
1225 // that this is cast, unless there are unexpected tokens inside the
1228 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1229 if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1230 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1232 // Search for unexpected tokens.
1233 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1234 Prev = Prev->Previous) {
1235 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1241 /// \brief Return the type of the given token assuming it is * or &.
1242 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1243 bool InTemplateArgument) {
1244 if (Style.Language == FormatStyle::LK_JavaScript)
1245 return TT_BinaryOperator;
1247 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1249 return TT_UnaryOperator;
1251 const FormatToken *NextToken = Tok.getNextNonComment();
1253 NextToken->isOneOf(tok::arrow, Keywords.kw_final,
1254 Keywords.kw_override) ||
1255 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1256 return TT_PointerOrReference;
1258 if (PrevToken->is(tok::coloncolon))
1259 return TT_PointerOrReference;
1261 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1262 tok::comma, tok::semi, tok::kw_return, tok::colon,
1263 tok::equal, tok::kw_delete, tok::kw_sizeof) ||
1264 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1265 TT_UnaryOperator, TT_CastRParen))
1266 return TT_UnaryOperator;
1268 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1269 return TT_PointerOrReference;
1270 if (NextToken->is(tok::kw_operator) && !IsExpression)
1271 return TT_PointerOrReference;
1272 if (NextToken->isOneOf(tok::comma, tok::semi))
1273 return TT_PointerOrReference;
1275 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
1276 PrevToken->MatchingParen->Previous &&
1277 PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
1279 return TT_PointerOrReference;
1281 if (PrevToken->Tok.isLiteral() ||
1282 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1283 tok::kw_false, tok::r_brace) ||
1284 NextToken->Tok.isLiteral() ||
1285 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1286 NextToken->isUnaryOperator() ||
1287 // If we know we're in a template argument, there are no named
1288 // declarations. Thus, having an identifier on the right-hand side
1289 // indicates a binary operator.
1290 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1291 return TT_BinaryOperator;
1293 // "&&(" is quite unlikely to be two successive unary "&".
1294 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1295 return TT_BinaryOperator;
1297 // This catches some cases where evaluation order is used as control flow:
1299 const FormatToken *NextNextToken = NextToken->getNextNonComment();
1300 if (NextNextToken && NextNextToken->is(tok::arrow))
1301 return TT_BinaryOperator;
1303 // It is very unlikely that we are going to find a pointer or reference type
1304 // definition on the RHS of an assignment.
1305 if (IsExpression && !Contexts.back().CaretFound)
1306 return TT_BinaryOperator;
1308 return TT_PointerOrReference;
1311 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1312 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1313 if (!PrevToken || PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
1314 return TT_UnaryOperator;
1316 // Use heuristics to recognize unary operators.
1317 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1318 tok::question, tok::colon, tok::kw_return,
1319 tok::kw_case, tok::at, tok::l_brace))
1320 return TT_UnaryOperator;
1322 // There can't be two consecutive binary operators.
1323 if (PrevToken->is(TT_BinaryOperator))
1324 return TT_UnaryOperator;
1326 // Fall back to marking the token as binary operator.
1327 return TT_BinaryOperator;
1330 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1331 TokenType determineIncrementUsage(const FormatToken &Tok) {
1332 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1333 if (!PrevToken || PrevToken->is(TT_CastRParen))
1334 return TT_UnaryOperator;
1335 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1336 return TT_TrailingUnaryOperator;
1338 return TT_UnaryOperator;
1341 SmallVector<Context, 8> Contexts;
1343 const FormatStyle &Style;
1344 AnnotatedLine &Line;
1345 FormatToken *CurrentToken;
1347 const AdditionalKeywords &Keywords;
1349 // Set of "<" tokens that do not open a template parameter list. If parseAngle
1350 // determines that a specific token can't be a template opener, it will make
1351 // same decision irrespective of the decisions for tokens leading up to it.
1352 // Store this information to prevent this from causing exponential runtime.
1353 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1356 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1357 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1359 /// \brief Parses binary expressions by inserting fake parenthesis based on
1360 /// operator precedence.
1361 class ExpressionParser {
1363 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1364 AnnotatedLine &Line)
1365 : Style(Style), Keywords(Keywords), Current(Line.First) {}
1367 /// \brief Parse expressions with the given operatore precedence.
1368 void parse(int Precedence = 0) {
1369 // Skip 'return' and ObjC selector colons as they are not part of a binary
1371 while (Current && (Current->is(tok::kw_return) ||
1372 (Current->is(tok::colon) &&
1373 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1376 if (!Current || Precedence > PrecedenceArrowAndPeriod)
1379 // Conditional expressions need to be parsed separately for proper nesting.
1380 if (Precedence == prec::Conditional) {
1381 parseConditionalExpr();
1385 // Parse unary operators, which all have a higher precedence than binary
1387 if (Precedence == PrecedenceUnaryOperator) {
1388 parseUnaryOperator();
1392 FormatToken *Start = Current;
1393 FormatToken *LatestOperator = nullptr;
1394 unsigned OperatorIndex = 0;
1397 // Consume operators with higher precedence.
1398 parse(Precedence + 1);
1400 int CurrentPrecedence = getCurrentPrecedence();
1402 if (Current && Current->is(TT_SelectorName) &&
1403 Precedence == CurrentPrecedence) {
1405 addFakeParenthesis(Start, prec::Level(Precedence));
1409 // At the end of the line or when an operator with higher precedence is
1410 // found, insert fake parenthesis and return.
1411 if (!Current || (Current->closesScope() && Current->MatchingParen) ||
1412 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1413 (CurrentPrecedence == prec::Conditional &&
1414 Precedence == prec::Assignment && Current->is(tok::colon))) {
1418 // Consume scopes: (), [], <> and {}
1419 if (Current->opensScope()) {
1420 while (Current && !Current->closesScope()) {
1427 if (CurrentPrecedence == Precedence) {
1429 LatestOperator->NextOperator = Current;
1430 LatestOperator = Current;
1431 Current->OperatorIndex = OperatorIndex;
1434 next(/*SkipPastLeadingComments=*/Precedence > 0);
1438 if (LatestOperator && (Current || Precedence > 0)) {
1439 // LatestOperator->LastOperator = true;
1440 if (Precedence == PrecedenceArrowAndPeriod) {
1441 // Call expressions don't have a binary operator precedence.
1442 addFakeParenthesis(Start, prec::Unknown);
1444 addFakeParenthesis(Start, prec::Level(Precedence));
1450 /// \brief Gets the precedence (+1) of the given token for binary operators
1451 /// and other tokens that we treat like binary operators.
1452 int getCurrentPrecedence() {
1454 const FormatToken *NextNonComment = Current->getNextNonComment();
1455 if (Current->is(TT_ConditionalExpr))
1456 return prec::Conditional;
1457 if (NextNonComment && NextNonComment->is(tok::colon) &&
1458 NextNonComment->is(TT_DictLiteral))
1460 if (Current->is(TT_LambdaArrow))
1462 if (Current->is(TT_JsFatArrow))
1463 return prec::Assignment;
1464 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName,
1465 TT_JsComputedPropertyName) ||
1466 (Current->is(tok::comment) && NextNonComment &&
1467 NextNonComment->is(TT_SelectorName)))
1469 if (Current->is(TT_RangeBasedForLoopColon))
1471 if ((Style.Language == FormatStyle::LK_Java ||
1472 Style.Language == FormatStyle::LK_JavaScript) &&
1473 Current->is(Keywords.kw_instanceof))
1474 return prec::Relational;
1475 if (Style.Language == FormatStyle::LK_JavaScript &&
1476 Current->is(Keywords.kw_in))
1477 return prec::Relational;
1478 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1479 return Current->getPrecedence();
1480 if (Current->isOneOf(tok::period, tok::arrow))
1481 return PrecedenceArrowAndPeriod;
1482 if ((Style.Language == FormatStyle::LK_Java ||
1483 Style.Language == FormatStyle::LK_JavaScript) &&
1484 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1485 Keywords.kw_throws))
1491 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1492 Start->FakeLParens.push_back(Precedence);
1493 if (Precedence > prec::Unknown)
1494 Start->StartsBinaryExpression = true;
1496 FormatToken *Previous = Current->Previous;
1497 while (Previous->is(tok::comment) && Previous->Previous)
1498 Previous = Previous->Previous;
1499 ++Previous->FakeRParens;
1500 if (Precedence > prec::Unknown)
1501 Previous->EndsBinaryExpression = true;
1505 /// \brief Parse unary operator expressions and surround them with fake
1506 /// parentheses if appropriate.
1507 void parseUnaryOperator() {
1508 if (!Current || Current->isNot(TT_UnaryOperator)) {
1509 parse(PrecedenceArrowAndPeriod);
1513 FormatToken *Start = Current;
1515 parseUnaryOperator();
1517 // The actual precedence doesn't matter.
1518 addFakeParenthesis(Start, prec::Unknown);
1521 void parseConditionalExpr() {
1522 while (Current && Current->isTrailingComment()) {
1525 FormatToken *Start = Current;
1526 parse(prec::LogicalOr);
1527 if (!Current || !Current->is(tok::question))
1530 parse(prec::Assignment);
1531 if (!Current || Current->isNot(TT_ConditionalExpr))
1534 parse(prec::Assignment);
1535 addFakeParenthesis(Start, prec::Conditional);
1538 void next(bool SkipPastLeadingComments = true) {
1540 Current = Current->Next;
1542 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1543 Current->isTrailingComment())
1544 Current = Current->Next;
1547 const FormatStyle &Style;
1548 const AdditionalKeywords &Keywords;
1549 FormatToken *Current;
1552 } // end anonymous namespace
1554 void TokenAnnotator::setCommentLineLevels(
1555 SmallVectorImpl<AnnotatedLine *> &Lines) {
1556 const AnnotatedLine *NextNonCommentLine = nullptr;
1557 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1560 if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
1561 (*I)->First->Next == nullptr)
1562 (*I)->Level = NextNonCommentLine->Level;
1564 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1566 setCommentLineLevels((*I)->Children);
1570 static unsigned maxNestingDepth(const AnnotatedLine &Line) {
1571 unsigned Result = 0;
1572 for (const auto* Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
1573 Result = std::max(Result, Tok->NestingLevel);
1577 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1578 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1579 E = Line.Children.end();
1583 AnnotatingParser Parser(Style, Line, Keywords);
1584 Line.Type = Parser.parseLine();
1586 // With very deep nesting, ExpressionParser uses lots of stack and the
1587 // formatting algorithm is very slow. We're not going to do a good job here
1588 // anyway - it's probably generated code being formatted by mistake.
1589 // Just skip the whole line.
1590 if (maxNestingDepth(Line) > 50)
1591 Line.Type = LT_Invalid;
1593 if (Line.Type == LT_Invalid)
1596 ExpressionParser ExprParser(Style, Keywords, Line);
1599 if (Line.startsWith(TT_ObjCMethodSpecifier))
1600 Line.Type = LT_ObjCMethodDecl;
1601 else if (Line.startsWith(TT_ObjCDecl))
1602 Line.Type = LT_ObjCDecl;
1603 else if (Line.startsWith(TT_ObjCProperty))
1604 Line.Type = LT_ObjCProperty;
1606 Line.First->SpacesRequiredBefore = 1;
1607 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1610 // This function heuristically determines whether 'Current' starts the name of a
1611 // function declaration.
1612 static bool isFunctionDeclarationName(const FormatToken &Current,
1613 const AnnotatedLine &Line) {
1614 auto skipOperatorName = [](const FormatToken* Next) -> const FormatToken* {
1615 for (; Next; Next = Next->Next) {
1616 if (Next->is(TT_OverloadedOperatorLParen))
1618 if (Next->is(TT_OverloadedOperator))
1620 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1621 // For 'new[]' and 'delete[]'.
1622 if (Next->Next && Next->Next->is(tok::l_square) &&
1623 Next->Next->Next && Next->Next->Next->is(tok::r_square))
1624 Next = Next->Next->Next;
1633 // Find parentheses of parameter list.
1634 const FormatToken *Next = Current.Next;
1635 if (Current.is(tok::kw_operator)) {
1636 if (Current.Previous && Current.Previous->is(tok::coloncolon))
1638 Next = skipOperatorName(Next);
1640 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1642 for (; Next; Next = Next->Next) {
1643 if (Next->is(TT_TemplateOpener)) {
1644 Next = Next->MatchingParen;
1645 } else if (Next->is(tok::coloncolon)) {
1649 if (Next->is(tok::kw_operator)) {
1650 Next = skipOperatorName(Next->Next);
1653 if (!Next->is(tok::identifier))
1655 } else if (Next->is(tok::l_paren)) {
1663 // Check whether parameter list can be long to a function declaration.
1664 if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
1666 // If the lines ends with "{", this is likely an function definition.
1667 if (Line.Last->is(tok::l_brace))
1669 if (Next->Next == Next->MatchingParen)
1670 return true; // Empty parentheses.
1671 // If there is an &/&& after the r_paren, this is likely a function.
1672 if (Next->MatchingParen->Next &&
1673 Next->MatchingParen->Next->is(TT_PointerOrReference))
1675 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1677 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1678 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
1680 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1681 Tok->Tok.isLiteral())
1687 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
1688 assert(Line.MightBeFunctionDecl);
1690 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
1691 Style.AlwaysBreakAfterReturnType ==
1692 FormatStyle::RTBS_TopLevelDefinitions) &&
1696 switch (Style.AlwaysBreakAfterReturnType) {
1697 case FormatStyle::RTBS_None:
1699 case FormatStyle::RTBS_All:
1700 case FormatStyle::RTBS_TopLevel:
1702 case FormatStyle::RTBS_AllDefinitions:
1703 case FormatStyle::RTBS_TopLevelDefinitions:
1704 return Line.mightBeFunctionDefinition();
1710 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1711 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1712 E = Line.Children.end();
1714 calculateFormattingInformation(**I);
1717 Line.First->TotalLength =
1718 Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1719 if (!Line.First->Next)
1721 FormatToken *Current = Line.First->Next;
1722 bool InFunctionDecl = Line.MightBeFunctionDecl;
1724 if (isFunctionDeclarationName(*Current, Line))
1725 Current->Type = TT_FunctionDeclarationName;
1726 if (Current->is(TT_LineComment)) {
1727 if (Current->Previous->BlockKind == BK_BracedInit &&
1728 Current->Previous->opensScope())
1729 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1731 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1733 // If we find a trailing comment, iterate backwards to determine whether
1734 // it seems to relate to a specific parameter. If so, break before that
1735 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1736 // to the previous line in:
1740 if (!Current->HasUnescapedNewline) {
1741 for (FormatToken *Parameter = Current->Previous; Parameter;
1742 Parameter = Parameter->Previous) {
1743 if (Parameter->isOneOf(tok::comment, tok::r_brace))
1745 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1746 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1747 Parameter->HasUnescapedNewline)
1748 Parameter->MustBreakBefore = true;
1753 } else if (Current->SpacesRequiredBefore == 0 &&
1754 spaceRequiredBefore(Line, *Current)) {
1755 Current->SpacesRequiredBefore = 1;
1758 Current->MustBreakBefore =
1759 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1761 if (!Current->MustBreakBefore && InFunctionDecl &&
1762 Current->is(TT_FunctionDeclarationName))
1763 Current->MustBreakBefore = mustBreakForReturnType(Line);
1765 Current->CanBreakBefore =
1766 Current->MustBreakBefore || canBreakBefore(Line, *Current);
1767 unsigned ChildSize = 0;
1768 if (Current->Previous->Children.size() == 1) {
1769 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1770 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1771 : LastOfChild.TotalLength + 1;
1773 const FormatToken *Prev = Current->Previous;
1774 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1775 (Prev->Children.size() == 1 &&
1776 Prev->Children[0]->First->MustBreakBefore) ||
1777 Current->IsMultiline)
1778 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1780 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1781 ChildSize + Current->SpacesRequiredBefore;
1783 if (Current->is(TT_CtorInitializerColon))
1784 InFunctionDecl = false;
1786 // FIXME: Only calculate this if CanBreakBefore is true once static
1787 // initializers etc. are sorted out.
1788 // FIXME: Move magic numbers to a better place.
1789 Current->SplitPenalty = 20 * Current->BindingStrength +
1790 splitPenalty(Line, *Current, InFunctionDecl);
1792 Current = Current->Next;
1795 calculateUnbreakableTailLengths(Line);
1796 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1798 Current->Role->precomputeFormattingInfos(Current);
1801 DEBUG({ printDebugInfo(Line); });
1804 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1805 unsigned UnbreakableTailLength = 0;
1806 FormatToken *Current = Line.Last;
1808 Current->UnbreakableTailLength = UnbreakableTailLength;
1809 if (Current->CanBreakBefore ||
1810 Current->isOneOf(tok::comment, tok::string_literal)) {
1811 UnbreakableTailLength = 0;
1813 UnbreakableTailLength +=
1814 Current->ColumnWidth + Current->SpacesRequiredBefore;
1816 Current = Current->Previous;
1820 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1821 const FormatToken &Tok,
1822 bool InFunctionDecl) {
1823 const FormatToken &Left = *Tok.Previous;
1824 const FormatToken &Right = Tok;
1826 if (Left.is(tok::semi))
1829 if (Style.Language == FormatStyle::LK_Java) {
1830 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
1832 if (Right.is(Keywords.kw_implements))
1834 if (Left.is(tok::comma) && Left.NestingLevel == 0)
1836 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1837 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
1839 if (Left.is(TT_JsTypeColon))
1841 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
1842 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
1846 if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
1847 Right.Next->is(TT_DictLiteral)))
1849 if (Right.is(tok::l_square)) {
1850 if (Style.Language == FormatStyle::LK_Proto)
1852 if (Left.is(tok::r_square))
1854 // Slightly prefer formatting local lambda definitions like functions.
1855 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
1857 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
1858 TT_ArrayInitializerLSquare))
1862 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
1863 Right.is(tok::kw_operator)) {
1864 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1866 if (Left.is(TT_StartOfName))
1868 if (InFunctionDecl && Right.NestingLevel == 0)
1869 return Style.PenaltyReturnTypeOnItsOwnLine;
1872 if (Right.is(TT_PointerOrReference))
1874 if (Right.is(TT_LambdaArrow))
1876 if (Left.is(tok::equal) && Right.is(tok::l_brace))
1878 if (Left.is(TT_CastRParen))
1880 if (Left.is(tok::coloncolon) ||
1881 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1883 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1885 if (Left.is(tok::comment))
1888 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
1891 if (Right.isMemberAccess()) {
1892 // Breaking before the "./->" of a chained call/member access is reasonably
1893 // cheap, as formatting those with one call per line is generally
1894 // desirable. In particular, it should be cheaper to break before the call
1895 // than it is to break inside a call's parameters, which could lead to weird
1896 // "hanging" indents. The exception is the very last "./->" to support this
1897 // frequent pattern:
1899 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
1902 // which might otherwise be blown up onto many lines. Here, clang-format
1903 // won't produce "hanging" indents anyway as there is no other trailing
1906 // Also apply higher penalty is not a call as that might lead to a wrapping
1910 // .aaaaaaaaa.bbbbbbbb(cccccccc);
1911 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
1916 if (Right.is(TT_TrailingAnnotation) &&
1917 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
1918 // Moving trailing annotations to the next line is fine for ObjC method
1920 if (Line.startsWith(TT_ObjCMethodSpecifier))
1922 // Generally, breaking before a trailing annotation is bad unless it is
1923 // function-like. It seems to be especially preferable to keep standard
1924 // annotations (i.e. "const", "final" and "override") on the same line.
1925 // Use a slightly higher penalty after ")" so that annotations like
1926 // "const override" are kept together.
1927 bool is_short_annotation = Right.TokenText.size() < 10;
1928 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
1931 // In for-loops, prefer breaking at ',' and ';'.
1932 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
1935 // In Objective-C method expressions, prefer breaking before "param:" over
1936 // breaking after it.
1937 if (Right.is(TT_SelectorName))
1939 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
1940 return Line.MightBeFunctionDecl ? 50 : 500;
1942 if (Left.is(tok::l_paren) && InFunctionDecl &&
1943 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
1945 if (Left.is(tok::l_paren) && Left.Previous &&
1946 Left.Previous->isOneOf(tok::kw_if, tok::kw_for))
1948 if (Left.is(tok::equal) && InFunctionDecl)
1950 if (Right.is(tok::r_brace))
1952 if (Left.is(TT_TemplateOpener))
1954 if (Left.opensScope()) {
1955 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
1957 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1960 if (Left.is(TT_JavaAnnotation))
1963 if (Right.is(tok::lessless)) {
1964 if (Left.is(tok::string_literal) &&
1965 (Right.NextOperator || Right.OperatorIndex != 1)) {
1966 StringRef Content = Left.TokenText;
1967 if (Content.startswith("\""))
1968 Content = Content.drop_front(1);
1969 if (Content.endswith("\""))
1970 Content = Content.drop_back(1);
1971 Content = Content.trim();
1972 if (Content.size() > 1 &&
1973 (Content.back() == ':' || Content.back() == '='))
1976 return 1; // Breaking at a << is really cheap.
1978 if (Left.is(TT_ConditionalExpr))
1979 return prec::Conditional;
1980 prec::Level Level = Left.getPrecedence();
1981 if (Level != prec::Unknown)
1983 Level = Right.getPrecedence();
1984 if (Level != prec::Unknown)
1990 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1991 const FormatToken &Left,
1992 const FormatToken &Right) {
1993 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
1995 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1996 Left.Tok.getObjCKeywordID() == tok::objc_property)
1998 if (Right.is(tok::hashhash))
1999 return Left.is(tok::hash);
2000 if (Left.isOneOf(tok::hashhash, tok::hash))
2001 return Right.is(tok::hash);
2002 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
2003 return Style.SpaceInEmptyParentheses;
2004 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
2005 return (Right.is(TT_CastRParen) ||
2006 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
2007 ? Style.SpacesInCStyleCastParentheses
2008 : Style.SpacesInParentheses;
2009 if (Right.isOneOf(tok::semi, tok::comma))
2011 if (Right.is(tok::less) &&
2012 Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)
2014 if (Right.is(tok::less) && Left.is(tok::kw_template))
2015 return Style.SpaceAfterTemplateKeyword;
2016 if (Left.isOneOf(tok::exclaim, tok::tilde))
2018 if (Left.is(tok::at) &&
2019 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
2020 tok::numeric_constant, tok::l_paren, tok::l_brace,
2021 tok::kw_true, tok::kw_false))
2023 if (Left.is(tok::colon))
2024 return !Left.is(TT_ObjCMethodExpr);
2025 if (Left.is(tok::coloncolon))
2027 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
2029 if (Right.is(tok::ellipsis))
2030 return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
2031 Left.Previous->is(tok::kw_case));
2032 if (Left.is(tok::l_square) && Right.is(tok::amp))
2034 if (Right.is(TT_PointerOrReference))
2035 return (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) ||
2036 (Left.Tok.isLiteral() || (Left.is(tok::kw_const) && Left.Previous &&
2037 Left.Previous->is(tok::r_paren)) ||
2038 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
2039 (Style.PointerAlignment != FormatStyle::PAS_Left ||
2040 (Line.IsMultiVariableDeclStmt &&
2041 (Left.NestingLevel == 0 ||
2042 (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
2043 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
2044 (!Left.is(TT_PointerOrReference) ||
2045 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2046 !Line.IsMultiVariableDeclStmt)))
2048 if (Left.is(TT_PointerOrReference))
2049 return Right.Tok.isLiteral() ||
2050 Right.isOneOf(TT_BlockComment, Keywords.kw_final,
2051 Keywords.kw_override) ||
2052 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
2053 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
2055 (Style.PointerAlignment != FormatStyle::PAS_Right &&
2056 !Line.IsMultiVariableDeclStmt) &&
2058 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
2059 if (Right.is(tok::star) && Left.is(tok::l_paren))
2061 if (Left.is(tok::l_square))
2062 return (Left.is(TT_ArrayInitializerLSquare) &&
2063 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
2064 (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
2065 Right.isNot(tok::r_square));
2066 if (Right.is(tok::r_square))
2067 return Right.MatchingParen &&
2068 ((Style.SpacesInContainerLiterals &&
2069 Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
2070 (Style.SpacesInSquareBrackets &&
2071 Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
2072 if (Right.is(tok::l_square) &&
2073 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
2074 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
2076 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
2077 return !Left.Children.empty(); // No spaces in "{}".
2078 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
2079 (Right.is(tok::r_brace) && Right.MatchingParen &&
2080 Right.MatchingParen->BlockKind != BK_Block))
2081 return !Style.Cpp11BracedListStyle;
2082 if (Left.is(TT_BlockComment))
2083 return !Left.TokenText.endswith("=*/");
2084 if (Right.is(tok::l_paren)) {
2085 if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
2087 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
2088 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
2089 (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
2090 tok::kw_switch, tok::kw_case, TT_ForEachMacro,
2092 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
2093 tok::kw_new, tok::kw_delete) &&
2094 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
2095 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
2096 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
2097 Left.is(tok::r_paren)) &&
2098 Line.Type != LT_PreprocessorDirective);
2100 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
2102 if (Right.is(TT_UnaryOperator))
2103 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
2104 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
2105 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
2107 Left.isSimpleTypeSpecifier()) &&
2108 Right.is(tok::l_brace) && Right.getNextNonComment() &&
2109 Right.BlockKind != BK_Block)
2111 if (Left.is(tok::period) || Right.is(tok::period))
2113 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
2115 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
2116 Left.MatchingParen->Previous &&
2117 Left.MatchingParen->Previous->is(tok::period))
2118 // A.<B>DoSomething();
2120 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
2125 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
2126 const FormatToken &Right) {
2127 const FormatToken &Left = *Right.Previous;
2128 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
2129 return true; // Never ever merge two identifiers.
2130 if (Style.Language == FormatStyle::LK_Cpp) {
2131 if (Left.is(tok::kw_operator))
2132 return Right.is(tok::coloncolon);
2133 } else if (Style.Language == FormatStyle::LK_Proto) {
2134 if (Right.is(tok::period) &&
2135 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2136 Keywords.kw_repeated, Keywords.kw_extend))
2138 if (Right.is(tok::l_paren) &&
2139 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2141 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2142 if (Left.is(TT_JsFatArrow))
2144 if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
2145 (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
2147 if (Left.is(tok::identifier) && Right.is(TT_TemplateString))
2149 if (Right.is(tok::star) &&
2150 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2152 if (Right.isOneOf(tok::l_brace, tok::l_square) &&
2153 Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
2155 // JS methods can use some keywords as names (e.g. `delete()`).
2156 if (Right.is(tok::l_paren) && Line.MustBeDeclaration &&
2157 Left.Tok.getIdentifierInfo())
2159 if (Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
2160 Keywords.kw_of, tok::kw_const) &&
2161 (!Left.Previous || !Left.Previous->is(tok::period)))
2163 if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
2164 Left.Previous->is(tok::period) && Right.is(tok::l_paren))
2166 if (Left.is(Keywords.kw_as) &&
2167 Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
2169 if (Left.is(tok::kw_default) && Left.Previous &&
2170 Left.Previous->is(tok::kw_export))
2172 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2174 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2176 if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
2178 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2179 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2181 if (Left.is(tok::ellipsis))
2183 if (Left.is(TT_TemplateCloser) &&
2184 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2185 Keywords.kw_implements, Keywords.kw_extends))
2186 // Type assertions ('<type>expr') are not followed by whitespace. Other
2187 // locations that should have whitespace following are identified by the
2188 // above set of follower tokens.
2190 // Postfix non-null assertion operator, as in `foo!.bar()`.
2191 if (Right.is(tok::exclaim) && (Left.isOneOf(tok::identifier, tok::r_paren,
2192 tok::r_square, tok::r_brace) ||
2193 Left.Tok.isLiteral()))
2195 if (Left.is(tok::exclaim) && Right.is(Keywords.kw_as))
2196 return true; // "x! as string"
2197 } else if (Style.Language == FormatStyle::LK_Java) {
2198 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2200 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2201 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2202 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2203 tok::kw_protected) ||
2204 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2205 Keywords.kw_native)) &&
2206 Right.is(TT_TemplateOpener))
2209 if (Left.is(TT_ImplicitStringLiteral))
2210 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2211 if (Line.Type == LT_ObjCMethodDecl) {
2212 if (Left.is(TT_ObjCMethodSpecifier))
2214 if (Left.is(tok::r_paren) && Right.is(tok::identifier))
2215 // Don't space between ')' and <id>
2218 if (Line.Type == LT_ObjCProperty &&
2219 (Right.is(tok::equal) || Left.is(tok::equal)))
2222 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2223 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2225 if (Right.is(TT_OverloadedOperatorLParen))
2226 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2227 if (Left.is(tok::comma))
2229 if (Right.is(tok::comma))
2231 if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
2233 if (Right.is(tok::colon)) {
2234 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2235 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2237 if (Right.is(TT_ObjCMethodExpr))
2239 if (Left.is(tok::question))
2241 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2243 if (Right.is(TT_DictLiteral))
2244 return Style.SpacesInContainerLiterals;
2247 if (Left.is(TT_UnaryOperator))
2248 return Right.is(TT_BinaryOperator);
2250 // If the next token is a binary operator or a selector name, we have
2251 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2252 if (Left.is(TT_CastRParen))
2253 return Style.SpaceAfterCStyleCast ||
2254 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2256 if (Left.is(tok::greater) && Right.is(tok::greater))
2257 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2258 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2259 if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2260 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
2262 if (!Style.SpaceBeforeAssignmentOperators &&
2263 Right.getPrecedence() == prec::Assignment)
2265 if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
2266 return (Left.is(TT_TemplateOpener) &&
2267 Style.Standard == FormatStyle::LS_Cpp03) ||
2268 !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren,
2270 Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
2271 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2272 return Style.SpacesInAngles;
2273 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2274 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2275 !Right.is(tok::r_paren)))
2277 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2278 Right.isNot(TT_FunctionTypeLParen))
2279 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2280 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2281 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2283 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2284 Line.startsWith(tok::hash))
2286 if (Right.is(TT_TrailingUnaryOperator))
2288 if (Left.is(TT_RegexLiteral))
2290 return spaceRequiredBetween(Line, Left, Right);
2293 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2294 static bool isAllmanBrace(const FormatToken &Tok) {
2295 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2296 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2299 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2300 const FormatToken &Right) {
2301 const FormatToken &Left = *Right.Previous;
2302 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2305 if (Style.Language == FormatStyle::LK_JavaScript) {
2306 // FIXME: This might apply to other languages and token kinds.
2307 if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
2308 Left.Previous->is(tok::string_literal))
2310 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2311 Left.Previous && Left.Previous->is(tok::equal) &&
2312 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2314 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2316 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2317 // Object literals on the top level of a file are treated as "enum-style".
2318 // Each key/value pair is put on a separate line, instead of bin-packing.
2320 if (Left.is(tok::l_brace) && Line.Level == 0 &&
2321 (Line.startsWith(tok::kw_enum) ||
2322 Line.startsWith(tok::kw_export, tok::kw_enum)))
2323 // JavaScript top-level enum key/value pairs are put on separate lines
2324 // instead of bin-packing.
2326 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2327 !Left.Children.empty())
2328 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2329 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2330 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2331 (Left.NestingLevel == 0 && Line.Level == 0 &&
2332 Style.AllowShortFunctionsOnASingleLine ==
2333 FormatStyle::SFS_Inline);
2334 } else if (Style.Language == FormatStyle::LK_Java) {
2335 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2336 Right.Next->is(tok::string_literal))
2340 // If the last token before a '}' is a comma or a trailing comment, the
2341 // intention is to insert a line break after it in order to make shuffling
2342 // around entries easier.
2343 const FormatToken *BeforeClosingBrace = nullptr;
2344 if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
2345 Left.BlockKind != BK_Block && Left.MatchingParen)
2346 BeforeClosingBrace = Left.MatchingParen->Previous;
2347 else if (Right.MatchingParen &&
2348 Right.MatchingParen->isOneOf(tok::l_brace,
2349 TT_ArrayInitializerLSquare))
2350 BeforeClosingBrace = &Left;
2351 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2352 BeforeClosingBrace->isTrailingComment()))
2355 if (Right.is(tok::comment))
2356 return Left.BlockKind != BK_BracedInit &&
2357 Left.isNot(TT_CtorInitializerColon) &&
2358 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2359 if (Left.isTrailingComment())
2361 if (Left.isStringLiteral() &&
2362 (Right.isStringLiteral() || Right.is(TT_ObjCStringLiteral)))
2364 if (Right.Previous->IsUnterminatedLiteral)
2366 if (Right.is(tok::lessless) && Right.Next &&
2367 Right.Previous->is(tok::string_literal) &&
2368 Right.Next->is(tok::string_literal))
2370 if (Right.Previous->ClosesTemplateDeclaration &&
2371 Right.Previous->MatchingParen &&
2372 Right.Previous->MatchingParen->NestingLevel == 0 &&
2373 Style.AlwaysBreakTemplateDeclarations)
2375 if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
2376 Style.BreakConstructorInitializersBeforeComma &&
2377 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2379 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2380 // Raw string literals are special wrt. line breaks. The author has made a
2381 // deliberate choice and might have aligned the contents of the string
2382 // literal accordingly. Thus, we try keep existing line breaks.
2383 return Right.NewlinesBefore > 0;
2384 if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
2385 Style.Language == FormatStyle::LK_Proto)
2386 // Don't put enums onto single lines in protocol buffers.
2388 if (Right.is(TT_InlineASMBrace))
2389 return Right.HasUnescapedNewline;
2390 if (isAllmanBrace(Left) || isAllmanBrace(Right))
2391 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2392 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2393 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2394 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2397 if ((Style.Language == FormatStyle::LK_Java ||
2398 Style.Language == FormatStyle::LK_JavaScript) &&
2399 Left.is(TT_LeadingJavaAnnotation) &&
2400 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2401 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2407 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2408 const FormatToken &Right) {
2409 const FormatToken &Left = *Right.Previous;
2411 // Language-specific stuff.
2412 if (Style.Language == FormatStyle::LK_Java) {
2413 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2414 Keywords.kw_implements))
2416 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2417 Keywords.kw_implements))
2419 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2420 const FormatToken *NonComment = Right.getPreviousNonComment();
2421 if (Left.isOneOf(tok::kw_return, tok::kw_continue, tok::kw_break,
2424 NonComment->isOneOf(tok::kw_return, tok::kw_continue, tok::kw_break,
2426 return false; // Otherwise a semicolon is inserted.
2427 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2429 if (Left.is(TT_JsTypeColon))
2431 if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is))
2433 if (Left.is(Keywords.kw_in))
2434 return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
2435 if (Right.is(Keywords.kw_in))
2436 return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
2437 if (Right.is(Keywords.kw_as))
2438 return false; // must not break before as in 'x as type' casts
2441 if (Left.is(tok::at))
2443 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2445 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2446 return !Right.is(tok::l_paren);
2447 if (Right.is(TT_PointerOrReference))
2448 return Line.IsMultiVariableDeclStmt ||
2449 (Style.PointerAlignment == FormatStyle::PAS_Right &&
2450 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2451 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2452 Right.is(tok::kw_operator))
2454 if (Left.is(TT_PointerOrReference))
2456 if (Right.isTrailingComment())
2457 // We rely on MustBreakBefore being set correctly here as we should not
2458 // change the "binding" behavior of a comment.
2459 // The first comment in a braced lists is always interpreted as belonging to
2460 // the first list element. Otherwise, it should be placed outside of the
2462 return Left.BlockKind == BK_BracedInit;
2463 if (Left.is(tok::question) && Right.is(tok::colon))
2465 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2466 return Style.BreakBeforeTernaryOperators;
2467 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2468 return !Style.BreakBeforeTernaryOperators;
2469 if (Right.is(TT_InheritanceColon))
2471 if (Right.is(tok::colon) &&
2472 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2474 if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
2476 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2477 Right.Next->is(TT_ObjCMethodExpr)))
2478 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2479 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2481 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
2483 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2484 TT_OverloadedOperator))
2486 if (Left.is(TT_RangeBasedForLoopColon))
2488 if (Right.is(TT_RangeBasedForLoopColon))
2490 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2491 Left.is(tok::kw_operator))
2493 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2494 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
2496 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2498 if (Left.is(tok::l_paren) && Left.Previous &&
2499 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2501 if (Right.is(TT_ImplicitStringLiteral))
2504 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2506 if (Right.is(tok::r_square) && Right.MatchingParen &&
2507 Right.MatchingParen->is(TT_LambdaLSquare))
2510 // We only break before r_brace if there was a corresponding break before
2511 // the l_brace, which is tracked by BreakBeforeClosingBrace.
2512 if (Right.is(tok::r_brace))
2513 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2515 // Allow breaking after a trailing annotation, e.g. after a method
2517 if (Left.is(TT_TrailingAnnotation))
2518 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2519 tok::less, tok::coloncolon);
2521 if (Right.is(tok::kw___attribute))
2524 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2527 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2530 if (Left.is(TT_CtorInitializerComma) &&
2531 Style.BreakConstructorInitializersBeforeComma)
2533 if (Right.is(TT_CtorInitializerComma) &&
2534 Style.BreakConstructorInitializersBeforeComma)
2536 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2537 (Left.is(tok::less) && Right.is(tok::less)))
2539 if (Right.is(TT_BinaryOperator) &&
2540 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2541 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2542 Right.getPrecedence() != prec::Assignment))
2544 if (Left.is(TT_ArrayInitializerLSquare))
2546 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2548 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
2549 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2550 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2551 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2552 Left.getPrecedence() == prec::Assignment))
2554 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2555 tok::kw_class, tok::kw_struct, tok::comment) ||
2556 Right.isMemberAccess() ||
2557 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2558 tok::colon, tok::l_square, tok::at) ||
2559 (Left.is(tok::r_paren) &&
2560 Right.isOneOf(tok::identifier, tok::kw_const)) ||
2561 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
2564 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2565 llvm::errs() << "AnnotatedTokens:\n";
2566 const FormatToken *Tok = Line.First;
2568 llvm::errs() << " M=" << Tok->MustBreakBefore
2569 << " C=" << Tok->CanBreakBefore
2570 << " T=" << getTokenTypeName(Tok->Type)
2571 << " S=" << Tok->SpacesRequiredBefore
2572 << " B=" << Tok->BlockParameterCount
2573 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
2574 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
2576 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2577 llvm::errs() << Tok->FakeLParens[i] << "/";
2578 llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
2580 assert(Tok == Line.Last);
2583 llvm::errs() << "----\n";
2586 } // namespace format
2587 } // namespace clang