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);
47 FormatToken *Left = CurrentToken->Previous;
48 Left->ParentBracket = Contexts.back().ContextKind;
49 ScopedContextCreator ContextCreator(*this, tok::less, 10);
51 // If this angle is in the context of an expression, we need to be more
52 // hesitant to detect it as opening template parameters.
53 bool InExprContext = Contexts.back().IsExpression;
55 Contexts.back().IsExpression = false;
56 // If there's a template keyword before the opening angle bracket, this is a
57 // template parameter, not an argument.
58 Contexts.back().InTemplateArgument =
59 Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);
61 if (Style.Language == FormatStyle::LK_Java &&
62 CurrentToken->is(tok::question))
65 while (CurrentToken) {
66 if (CurrentToken->is(tok::greater)) {
67 Left->MatchingParen = CurrentToken;
68 CurrentToken->MatchingParen = Left;
69 CurrentToken->Type = TT_TemplateCloser;
73 if (CurrentToken->is(tok::question) &&
74 Style.Language == FormatStyle::LK_Java) {
78 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) ||
79 (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext))
81 // If a && or || is found and interpreted as a binary operator, this set
82 // of angles is likely part of something like "a < b && c > d". If the
83 // angles are inside an expression, the ||/&& might also be a binary
84 // operator that was misinterpreted because we are parsing template
86 // FIXME: This is getting out of hand, write a decent parser.
87 if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
88 CurrentToken->Previous->is(TT_BinaryOperator) &&
89 Contexts[Contexts.size() - 2].IsExpression &&
90 Line.First->isNot(tok::kw_template))
92 updateParameterCount(Left, CurrentToken);
99 bool parseParens(bool LookForDecls = false) {
102 FormatToken *Left = CurrentToken->Previous;
103 Left->ParentBracket = Contexts.back().ContextKind;
104 ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
106 // FIXME: This is a bit of a hack. Do better.
107 Contexts.back().ColonIsForRangeExpr =
108 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
110 bool StartsObjCMethodExpr = false;
111 if (CurrentToken->is(tok::caret)) {
112 // (^ can start a block type.
113 Left->Type = TT_ObjCBlockLParen;
114 } else if (FormatToken *MaybeSel = Left->Previous) {
115 // @selector( starts a selector.
116 if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
117 MaybeSel->Previous->is(tok::at)) {
118 StartsObjCMethodExpr = true;
122 if (Left->Previous &&
123 (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_if,
124 tok::kw_while, tok::l_paren, tok::comma) ||
125 Left->Previous->is(TT_BinaryOperator))) {
126 // static_assert, if and while usually contain expressions.
127 Contexts.back().IsExpression = true;
128 } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
129 Left->Previous->MatchingParen &&
130 Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
131 // This is a parameter list of a lambda expression.
132 Contexts.back().IsExpression = false;
133 } else if (Line.InPPDirective &&
135 !Left->Previous->isOneOf(tok::identifier,
136 TT_OverloadedOperator))) {
137 Contexts.back().IsExpression = true;
138 } else if (Contexts[Contexts.size() - 2].CaretFound) {
139 // This is the parameter list of an ObjC block.
140 Contexts.back().IsExpression = false;
141 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
142 Left->Type = TT_AttributeParen;
143 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
144 // The first argument to a foreach macro is a declaration.
145 Contexts.back().IsForEachMacro = true;
146 Contexts.back().IsExpression = false;
147 } else if (Left->Previous && Left->Previous->MatchingParen &&
148 Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
149 Contexts.back().IsExpression = false;
152 if (StartsObjCMethodExpr) {
153 Contexts.back().ColonIsObjCMethodExpr = true;
154 Left->Type = TT_ObjCMethodExpr;
157 bool MightBeFunctionType = CurrentToken->is(tok::star);
158 bool HasMultipleLines = false;
159 bool HasMultipleParametersOnALine = false;
160 bool MightBeObjCForRangeLoop =
161 Left->Previous && Left->Previous->is(tok::kw_for);
162 while (CurrentToken) {
163 // LookForDecls is set when "if (" has been seen. Check for
164 // 'identifier' '*' 'identifier' followed by not '=' -- this
165 // '*' has to be a binary operator but determineStarAmpUsage() will
166 // categorize it as an unary operator, so set the right type here.
167 if (LookForDecls && CurrentToken->Next) {
168 FormatToken *Prev = CurrentToken->getPreviousNonComment();
170 FormatToken *PrevPrev = Prev->getPreviousNonComment();
171 FormatToken *Next = CurrentToken->Next;
172 if (PrevPrev && PrevPrev->is(tok::identifier) &&
173 Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
174 CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
175 Prev->Type = TT_BinaryOperator;
176 LookForDecls = false;
181 if (CurrentToken->Previous->is(TT_PointerOrReference) &&
182 CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
184 MightBeFunctionType = true;
185 if (CurrentToken->Previous->is(TT_BinaryOperator))
186 Contexts.back().IsExpression = true;
187 if (CurrentToken->is(tok::r_paren)) {
188 if (MightBeFunctionType && CurrentToken->Next &&
189 (CurrentToken->Next->is(tok::l_paren) ||
190 (CurrentToken->Next->is(tok::l_square) &&
191 !Contexts.back().IsExpression)))
192 Left->Type = TT_FunctionTypeLParen;
193 Left->MatchingParen = CurrentToken;
194 CurrentToken->MatchingParen = Left;
196 if (StartsObjCMethodExpr) {
197 CurrentToken->Type = TT_ObjCMethodExpr;
198 if (Contexts.back().FirstObjCSelectorName) {
199 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
200 Contexts.back().LongestObjCSelectorName;
204 if (Left->is(TT_AttributeParen))
205 CurrentToken->Type = TT_AttributeParen;
206 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
207 CurrentToken->Type = TT_JavaAnnotation;
208 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
209 CurrentToken->Type = TT_LeadingJavaAnnotation;
211 if (!HasMultipleLines)
212 Left->PackingKind = PPK_Inconclusive;
213 else if (HasMultipleParametersOnALine)
214 Left->PackingKind = PPK_BinPacked;
216 Left->PackingKind = PPK_OnePerLine;
221 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
224 if (CurrentToken->is(tok::l_brace))
225 Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
226 if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
227 !CurrentToken->Next->HasUnescapedNewline &&
228 !CurrentToken->Next->isTrailingComment())
229 HasMultipleParametersOnALine = true;
230 if (CurrentToken->isOneOf(tok::kw_const, tok::kw_auto) ||
231 CurrentToken->isSimpleTypeSpecifier())
232 Contexts.back().IsExpression = false;
233 if (CurrentToken->isOneOf(tok::semi, tok::colon))
234 MightBeObjCForRangeLoop = false;
235 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
236 CurrentToken->Type = TT_ObjCForIn;
237 // When we discover a 'new', we set CanBeExpression to 'false' in order to
238 // parse the type correctly. Reset that after a comma.
239 if (CurrentToken->is(tok::comma))
240 Contexts.back().CanBeExpression = true;
242 FormatToken *Tok = CurrentToken;
245 updateParameterCount(Left, Tok);
246 if (CurrentToken && CurrentToken->HasUnescapedNewline)
247 HasMultipleLines = true;
256 // A '[' could be an index subscript (after an identifier or after
257 // ')' or ']'), it could be the start of an Objective-C method
258 // expression, or it could the the start of an Objective-C array literal.
259 FormatToken *Left = CurrentToken->Previous;
260 Left->ParentBracket = Contexts.back().ContextKind;
261 FormatToken *Parent = Left->getPreviousNonComment();
262 bool StartsObjCMethodExpr =
263 Style.Language == FormatStyle::LK_Cpp &&
264 Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
265 CurrentToken->isNot(tok::l_brace) &&
267 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
268 tok::kw_return, tok::kw_throw) ||
269 Parent->isUnaryOperator() ||
270 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
271 getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
272 bool ColonFound = false;
274 unsigned BindingIncrease = 1;
275 if (Left->is(TT_Unknown)) {
276 if (StartsObjCMethodExpr) {
277 Left->Type = TT_ObjCMethodExpr;
278 } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
279 Contexts.back().ContextKind == tok::l_brace &&
280 Parent->isOneOf(tok::l_brace, tok::comma)) {
281 Left->Type = TT_JsComputedPropertyName;
283 Parent->isOneOf(tok::at, tok::equal, tok::comma, tok::l_paren,
284 tok::l_square, tok::question, tok::colon,
286 Left->Type = TT_ArrayInitializerLSquare;
288 BindingIncrease = 10;
289 Left->Type = TT_ArraySubscriptLSquare;
293 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
294 Contexts.back().IsExpression = true;
295 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
297 while (CurrentToken) {
298 if (CurrentToken->is(tok::r_square)) {
299 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
300 Left->is(TT_ObjCMethodExpr)) {
301 // An ObjC method call is rarely followed by an open parenthesis.
302 // FIXME: Do we incorrectly label ":" with this?
303 StartsObjCMethodExpr = false;
304 Left->Type = TT_Unknown;
306 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
307 CurrentToken->Type = TT_ObjCMethodExpr;
308 // determineStarAmpUsage() thinks that '*' '[' is allocating an
309 // array of pointers, but if '[' starts a selector then '*' is a
311 if (Parent && Parent->is(TT_PointerOrReference))
312 Parent->Type = TT_BinaryOperator;
314 Left->MatchingParen = CurrentToken;
315 CurrentToken->MatchingParen = Left;
316 if (Contexts.back().FirstObjCSelectorName) {
317 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
318 Contexts.back().LongestObjCSelectorName;
319 if (Left->BlockParameterCount > 1)
320 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
325 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
327 if (CurrentToken->is(tok::colon)) {
328 if (Left->is(TT_ArraySubscriptLSquare)) {
329 Left->Type = TT_ObjCMethodExpr;
330 StartsObjCMethodExpr = true;
331 Contexts.back().ColonIsObjCMethodExpr = true;
332 if (Parent && Parent->is(tok::r_paren))
333 Parent->Type = TT_CastRParen;
337 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
339 Left->Type = TT_ArrayInitializerLSquare;
340 FormatToken *Tok = CurrentToken;
343 updateParameterCount(Left, Tok);
350 FormatToken *Left = CurrentToken->Previous;
351 Left->ParentBracket = Contexts.back().ContextKind;
353 if (Contexts.back().CaretFound)
354 Left->Type = TT_ObjCBlockLBrace;
355 Contexts.back().CaretFound = false;
357 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
358 Contexts.back().ColonIsDictLiteral = true;
359 if (Left->BlockKind == BK_BracedInit)
360 Contexts.back().IsExpression = true;
362 while (CurrentToken) {
363 if (CurrentToken->is(tok::r_brace)) {
364 Left->MatchingParen = CurrentToken;
365 CurrentToken->MatchingParen = Left;
369 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
371 updateParameterCount(Left, CurrentToken);
372 if (CurrentToken->isOneOf(tok::colon, tok::l_brace)) {
373 FormatToken *Previous = CurrentToken->getPreviousNonComment();
374 if ((CurrentToken->is(tok::colon) ||
375 Style.Language == FormatStyle::LK_Proto) &&
376 Previous->is(tok::identifier))
377 Previous->Type = TT_SelectorName;
378 if (CurrentToken->is(tok::colon) ||
379 Style.Language == FormatStyle::LK_JavaScript)
380 Left->Type = TT_DictLiteral;
389 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
390 if (Current->is(TT_LambdaLSquare) ||
391 (Current->is(tok::caret) && Current->is(TT_UnaryOperator)) ||
392 (Style.Language == FormatStyle::LK_JavaScript &&
393 Current->is(Keywords.kw_function))) {
394 ++Left->BlockParameterCount;
396 if (Current->is(tok::comma)) {
397 ++Left->ParameterCount;
399 Left->Role.reset(new CommaSeparatedList(Style));
400 Left->Role->CommaFound(Current);
401 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
402 Left->ParameterCount = 1;
406 bool parseConditional() {
407 while (CurrentToken) {
408 if (CurrentToken->is(tok::colon)) {
409 CurrentToken->Type = TT_ConditionalExpr;
419 bool parseTemplateDeclaration() {
420 if (CurrentToken && CurrentToken->is(tok::less)) {
421 CurrentToken->Type = TT_TemplateOpener;
426 CurrentToken->Previous->ClosesTemplateDeclaration = true;
432 bool consumeToken() {
433 FormatToken *Tok = CurrentToken;
435 switch (Tok->Tok.getKind()) {
438 if (!Tok->Previous && Line.MustBeDeclaration)
439 Tok->Type = TT_ObjCMethodSpecifier;
444 // Colons from ?: are handled in parseConditional().
445 if (Style.Language == FormatStyle::LK_JavaScript) {
446 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
447 (Contexts.size() == 1 && // switch/case labels
448 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
449 Contexts.back().ContextKind == tok::l_paren || // function params
450 Contexts.back().ContextKind == tok::l_square || // array type
451 (Contexts.size() == 1 &&
452 Line.MustBeDeclaration)) { // method/property declaration
453 Tok->Type = TT_JsTypeColon;
457 if (Contexts.back().ColonIsDictLiteral) {
458 Tok->Type = TT_DictLiteral;
459 } else if (Contexts.back().ColonIsObjCMethodExpr ||
460 Line.First->is(TT_ObjCMethodSpecifier)) {
461 Tok->Type = TT_ObjCMethodExpr;
462 Tok->Previous->Type = TT_SelectorName;
463 if (Tok->Previous->ColumnWidth >
464 Contexts.back().LongestObjCSelectorName) {
465 Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth;
467 if (!Contexts.back().FirstObjCSelectorName)
468 Contexts.back().FirstObjCSelectorName = Tok->Previous;
469 } else if (Contexts.back().ColonIsForRangeExpr) {
470 Tok->Type = TT_RangeBasedForLoopColon;
471 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
472 Tok->Type = TT_BitFieldColon;
473 } else if (Contexts.size() == 1 &&
474 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
475 if (Tok->Previous->is(tok::r_paren))
476 Tok->Type = TT_CtorInitializerColon;
478 Tok->Type = TT_InheritanceColon;
479 } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
480 Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
481 // This handles a special macro in ObjC code where selectors including
482 // the colon are passed as macro arguments.
483 Tok->Type = TT_ObjCMethodExpr;
484 } else if (Contexts.back().ContextKind == tok::l_paren) {
485 Tok->Type = TT_InlineASMColon;
490 if (CurrentToken && CurrentToken->is(tok::l_paren)) {
492 if (!parseParens(/*LookForDecls=*/true))
497 Contexts.back().ColonIsForRangeExpr = true;
505 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
506 !Contexts.back().IsExpression && Line.First->isNot(TT_ObjCProperty) &&
508 !Tok->Previous->isOneOf(tok::kw_decltype, TT_LeadingJavaAnnotation)))
509 Line.MightBeFunctionDecl = true;
520 if (!NonTemplateLess.count(Tok) &&
522 (!Tok->Previous->Tok.isLiteral() &&
523 !(Tok->Previous->is(tok::r_paren) && Contexts.size() > 1))) &&
525 Tok->Type = TT_TemplateOpener;
527 Tok->Type = TT_BinaryOperator;
528 NonTemplateLess.insert(Tok);
537 // Lines can start with '}'.
542 Tok->Type = TT_BinaryOperator;
544 case tok::kw_operator:
545 while (CurrentToken &&
546 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
547 if (CurrentToken->isOneOf(tok::star, tok::amp))
548 CurrentToken->Type = TT_PointerOrReference;
550 if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator))
551 CurrentToken->Previous->Type = TT_OverloadedOperator;
554 CurrentToken->Type = TT_OverloadedOperatorLParen;
555 if (CurrentToken->Previous->is(TT_BinaryOperator))
556 CurrentToken->Previous->Type = TT_OverloadedOperator;
560 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
561 Tok->Next->isOneOf(tok::semi, tok::colon, tok::r_paren,
563 // Question marks before semicolons, colons, etc. indicate optional
564 // types (fields, parameters), e.g.
565 // function(x?: string, y?) {...}
567 Tok->Type = TT_JsTypeOptionalQuestion;
570 // Declarations cannot be conditional expressions, this can only be part
571 // of a type declaration.
572 if (Line.MustBeDeclaration &&
573 Style.Language == FormatStyle::LK_JavaScript)
577 case tok::kw_template:
578 parseTemplateDeclaration();
581 if (Contexts.back().InCtorInitializer)
582 Tok->Type = TT_CtorInitializerComma;
583 else if (Contexts.back().FirstStartOfName &&
584 (Contexts.size() == 1 || Line.First->is(tok::kw_for))) {
585 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
586 Line.IsMultiVariableDeclStmt = true;
588 if (Contexts.back().IsForEachMacro)
589 Contexts.back().IsExpression = true;
597 void parseIncludeDirective() {
598 if (CurrentToken && CurrentToken->is(tok::less)) {
600 while (CurrentToken) {
601 if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
602 CurrentToken->Type = TT_ImplicitStringLiteral;
608 void parseWarningOrError() {
610 // We still want to format the whitespace left of the first token of the
613 while (CurrentToken) {
614 CurrentToken->Type = TT_ImplicitStringLiteral;
620 next(); // Consume "pragma".
622 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
623 bool IsMark = CurrentToken->is(Keywords.kw_mark);
624 next(); // Consume "mark".
625 next(); // Consume first token (so we fix leading whitespace).
626 while (CurrentToken) {
627 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
628 CurrentToken->Type = TT_ImplicitStringLiteral;
634 LineType parsePreprocessorDirective() {
635 LineType Type = LT_PreprocessorDirective;
639 if (CurrentToken->Tok.is(tok::numeric_constant)) {
640 CurrentToken->SpacesRequiredBefore = 1;
643 // Hashes in the middle of a line can lead to any strange token
645 if (!CurrentToken->Tok.getIdentifierInfo())
647 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
648 case tok::pp_include:
649 case tok::pp_include_next:
652 parseIncludeDirective();
653 Type = LT_ImportStatement;
656 case tok::pp_warning:
657 parseWarningOrError();
664 Contexts.back().IsExpression = true;
676 LineType parseLine() {
677 NonTemplateLess.clear();
678 if (CurrentToken->is(tok::hash))
679 return parsePreprocessorDirective();
681 // Directly allow to 'import <string-literal>' to support protocol buffer
682 // definitions (code.google.com/p/protobuf) or missing "#" (either way we
683 // should not break the line).
684 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
685 if ((Style.Language == FormatStyle::LK_Java &&
686 CurrentToken->is(Keywords.kw_package)) ||
687 (Info && Info->getPPKeywordID() == tok::pp_import &&
688 CurrentToken->Next &&
689 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
692 parseIncludeDirective();
693 return LT_ImportStatement;
696 // If this line starts and ends in '<' and '>', respectively, it is likely
697 // part of "#define <a/b.h>".
698 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
699 parseIncludeDirective();
700 return LT_ImportStatement;
703 // In .proto files, top-level options are very similar to import statements
704 // and should not be line-wrapped.
705 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
706 CurrentToken->is(Keywords.kw_option)) {
708 if (CurrentToken && CurrentToken->is(tok::identifier))
709 return LT_ImportStatement;
712 bool KeywordVirtualFound = false;
713 bool ImportStatement = false;
714 while (CurrentToken) {
715 if (CurrentToken->is(tok::kw_virtual))
716 KeywordVirtualFound = true;
717 if (IsImportStatement(*CurrentToken))
718 ImportStatement = true;
722 if (KeywordVirtualFound)
723 return LT_VirtualFunctionDecl;
725 return LT_ImportStatement;
727 if (Line.First->is(TT_ObjCMethodSpecifier)) {
728 if (Contexts.back().FirstObjCSelectorName)
729 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
730 Contexts.back().LongestObjCSelectorName;
731 return LT_ObjCMethodDecl;
738 bool IsImportStatement(const FormatToken &Tok) {
739 // FIXME: Closure-library specific stuff should not be hard-coded but be
741 return Style.Language == FormatStyle::LK_JavaScript &&
742 Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
743 Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
744 Tok.Next->Next->TokenText == "require" ||
745 Tok.Next->Next->TokenText == "provide") &&
746 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
749 void resetTokenMetadata(FormatToken *Token) {
753 // Reset token type in case we have already looked at it and then
754 // recovered from an error (e.g. failure to find the matching >).
755 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
756 TT_FunctionLBrace, TT_ImplicitStringLiteral,
757 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
759 CurrentToken->Type = TT_Unknown;
760 CurrentToken->Role.reset();
761 CurrentToken->MatchingParen = nullptr;
762 CurrentToken->FakeLParens.clear();
763 CurrentToken->FakeRParens = 0;
768 CurrentToken->NestingLevel = Contexts.size() - 1;
769 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
770 modifyContext(*CurrentToken);
771 determineTokenType(*CurrentToken);
772 CurrentToken = CurrentToken->Next;
775 resetTokenMetadata(CurrentToken);
778 /// \brief A struct to hold information valid in a specific context, e.g.
779 /// a pair of parenthesis.
781 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
783 : ContextKind(ContextKind), BindingStrength(BindingStrength),
784 IsExpression(IsExpression) {}
786 tok::TokenKind ContextKind;
787 unsigned BindingStrength;
789 unsigned LongestObjCSelectorName = 0;
790 bool ColonIsForRangeExpr = false;
791 bool ColonIsDictLiteral = false;
792 bool ColonIsObjCMethodExpr = false;
793 FormatToken *FirstObjCSelectorName = nullptr;
794 FormatToken *FirstStartOfName = nullptr;
795 bool CanBeExpression = true;
796 bool InTemplateArgument = false;
797 bool InCtorInitializer = false;
798 bool CaretFound = false;
799 bool IsForEachMacro = false;
802 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
803 /// of each instance.
804 struct ScopedContextCreator {
807 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
810 P.Contexts.push_back(Context(ContextKind,
811 P.Contexts.back().BindingStrength + Increase,
812 P.Contexts.back().IsExpression));
815 ~ScopedContextCreator() { P.Contexts.pop_back(); }
818 void modifyContext(const FormatToken &Current) {
819 if (Current.getPrecedence() == prec::Assignment &&
820 !Line.First->isOneOf(tok::kw_template, tok::kw_using) &&
821 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
822 Contexts.back().IsExpression = true;
823 if (!Line.First->is(TT_UnaryOperator)) {
824 for (FormatToken *Previous = Current.Previous;
825 Previous && !Previous->isOneOf(tok::comma, tok::semi);
826 Previous = Previous->Previous) {
827 if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
828 Previous = Previous->MatchingParen;
832 if (Previous->opensScope())
834 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
835 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
836 Previous->Previous && Previous->Previous->isNot(tok::equal))
837 Previous->Type = TT_PointerOrReference;
840 } else if (Current.is(tok::lessless) &&
841 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
842 Contexts.back().IsExpression = true;
843 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
844 Contexts.back().IsExpression = true;
845 } else if (Current.is(TT_TrailingReturnArrow)) {
846 Contexts.back().IsExpression = false;
847 } else if (Current.is(TT_LambdaArrow)) {
848 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
849 } else if (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
850 !Line.InPPDirective &&
851 (!Current.Previous ||
852 Current.Previous->isNot(tok::kw_decltype))) {
853 bool ParametersOfFunctionType =
854 Current.Previous && Current.Previous->is(tok::r_paren) &&
855 Current.Previous->MatchingParen &&
856 Current.Previous->MatchingParen->is(TT_FunctionTypeLParen);
857 bool IsForOrCatch = Current.Previous &&
858 Current.Previous->isOneOf(tok::kw_for, tok::kw_catch);
859 Contexts.back().IsExpression = !ParametersOfFunctionType && !IsForOrCatch;
860 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
861 for (FormatToken *Previous = Current.Previous;
862 Previous && Previous->isOneOf(tok::star, tok::amp);
863 Previous = Previous->Previous)
864 Previous->Type = TT_PointerOrReference;
865 if (Line.MustBeDeclaration)
866 Contexts.back().IsExpression = Contexts.front().InCtorInitializer;
867 } else if (Current.Previous &&
868 Current.Previous->is(TT_CtorInitializerColon)) {
869 Contexts.back().IsExpression = true;
870 Contexts.back().InCtorInitializer = true;
871 } else if (Current.is(tok::kw_new)) {
872 Contexts.back().CanBeExpression = false;
873 } else if (Current.is(tok::semi) || Current.is(tok::exclaim)) {
874 // This should be the condition or increment in a for-loop.
875 Contexts.back().IsExpression = true;
879 void determineTokenType(FormatToken &Current) {
880 if (!Current.is(TT_Unknown))
881 // The token type is already known.
884 // Line.MightBeFunctionDecl can only be true after the parentheses of a
885 // function declaration have been found. In this case, 'Current' is a
886 // trailing token of this declaration and thus cannot be a name.
887 if (Current.is(Keywords.kw_instanceof)) {
888 Current.Type = TT_BinaryOperator;
889 } else if (isStartOfName(Current) &&
890 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
891 Contexts.back().FirstStartOfName = &Current;
892 Current.Type = TT_StartOfName;
893 } else if (Current.is(tok::kw_auto)) {
895 } else if (Current.is(tok::arrow) &&
896 Style.Language == FormatStyle::LK_Java) {
897 Current.Type = TT_LambdaArrow;
898 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
899 Current.NestingLevel == 0) {
900 Current.Type = TT_TrailingReturnArrow;
901 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
903 determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
904 Contexts.back().IsExpression,
905 Contexts.back().InTemplateArgument);
906 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
907 Current.Type = determinePlusMinusCaretUsage(Current);
908 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
909 Contexts.back().CaretFound = true;
910 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
911 Current.Type = determineIncrementUsage(Current);
912 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
913 Current.Type = TT_UnaryOperator;
914 } else if (Current.is(tok::question)) {
915 if (Style.Language == FormatStyle::LK_JavaScript &&
916 Line.MustBeDeclaration) {
917 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
918 // on the interface, not a ternary expression.
919 Current.Type = TT_JsTypeOptionalQuestion;
921 Current.Type = TT_ConditionalExpr;
923 } else if (Current.isBinaryOperator() &&
924 (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
925 Current.Type = TT_BinaryOperator;
926 } else if (Current.is(tok::comment)) {
927 if (Current.TokenText.startswith("/*")) {
928 if (Current.TokenText.endswith("*/"))
929 Current.Type = TT_BlockComment;
931 // The lexer has for some reason determined a comment here. But we
932 // cannot really handle it, if it isn't properly terminated.
933 Current.Tok.setKind(tok::unknown);
935 Current.Type = TT_LineComment;
937 } else if (Current.is(tok::r_paren)) {
938 if (rParenEndsCast(Current))
939 Current.Type = TT_CastRParen;
940 if (Current.MatchingParen && Current.Next &&
941 !Current.Next->isBinaryOperator() &&
942 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace))
943 if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
944 if (BeforeParen->is(tok::identifier) &&
945 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
946 (!BeforeParen->Previous ||
947 BeforeParen->Previous->ClosesTemplateDeclaration))
948 Current.Type = TT_FunctionAnnotationRParen;
949 } else if (Current.is(tok::at) && Current.Next) {
950 if (Current.Next->isStringLiteral()) {
951 Current.Type = TT_ObjCStringLiteral;
953 switch (Current.Next->Tok.getObjCKeywordID()) {
954 case tok::objc_interface:
955 case tok::objc_implementation:
956 case tok::objc_protocol:
957 Current.Type = TT_ObjCDecl;
959 case tok::objc_property:
960 Current.Type = TT_ObjCProperty;
966 } else if (Current.is(tok::period)) {
967 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
968 if (PreviousNoComment &&
969 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
970 Current.Type = TT_DesignatedInitializerPeriod;
971 else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
972 Current.Previous->isOneOf(TT_JavaAnnotation,
973 TT_LeadingJavaAnnotation)) {
974 Current.Type = Current.Previous->Type;
976 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
978 !Current.Previous->isOneOf(tok::equal, tok::at) &&
979 Line.MightBeFunctionDecl && Contexts.size() == 1) {
980 // Line.MightBeFunctionDecl can only be true after the parentheses of a
981 // function declaration have been found.
982 Current.Type = TT_TrailingAnnotation;
983 } else if ((Style.Language == FormatStyle::LK_Java ||
984 Style.Language == FormatStyle::LK_JavaScript) &&
986 if (Current.Previous->is(tok::at) &&
987 Current.isNot(Keywords.kw_interface)) {
988 const FormatToken &AtToken = *Current.Previous;
989 const FormatToken *Previous = AtToken.getPreviousNonComment();
990 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
991 Current.Type = TT_LeadingJavaAnnotation;
993 Current.Type = TT_JavaAnnotation;
994 } else if (Current.Previous->is(tok::period) &&
995 Current.Previous->isOneOf(TT_JavaAnnotation,
996 TT_LeadingJavaAnnotation)) {
997 Current.Type = Current.Previous->Type;
1002 /// \brief Take a guess at whether \p Tok starts a name of a function or
1003 /// variable declaration.
1005 /// This is a heuristic based on whether \p Tok is an identifier following
1006 /// something that is likely a type.
1007 bool isStartOfName(const FormatToken &Tok) {
1008 if (Tok.isNot(tok::identifier) || !Tok.Previous)
1011 if (Tok.Previous->is(TT_LeadingJavaAnnotation))
1014 // Skip "const" as it does not have an influence on whether this is a name.
1015 FormatToken *PreviousNotConst = Tok.Previous;
1016 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1017 PreviousNotConst = PreviousNotConst->Previous;
1019 if (!PreviousNotConst)
1022 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1023 PreviousNotConst->Previous &&
1024 PreviousNotConst->Previous->is(tok::hash);
1026 if (PreviousNotConst->is(TT_TemplateCloser))
1027 return PreviousNotConst && PreviousNotConst->MatchingParen &&
1028 PreviousNotConst->MatchingParen->Previous &&
1029 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1030 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1032 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1033 PreviousNotConst->MatchingParen->Previous &&
1034 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1037 return (!IsPPKeyword && PreviousNotConst->is(tok::identifier)) ||
1038 PreviousNotConst->is(TT_PointerOrReference) ||
1039 PreviousNotConst->isSimpleTypeSpecifier();
1042 /// \brief Determine whether ')' is ending a cast.
1043 bool rParenEndsCast(const FormatToken &Tok) {
1044 FormatToken *LeftOfParens = nullptr;
1045 if (Tok.MatchingParen)
1046 LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1047 if (LeftOfParens && LeftOfParens->is(tok::r_paren) &&
1048 LeftOfParens->MatchingParen)
1049 LeftOfParens = LeftOfParens->MatchingParen->Previous;
1050 if (LeftOfParens && LeftOfParens->is(tok::r_square) &&
1051 LeftOfParens->MatchingParen &&
1052 LeftOfParens->MatchingParen->is(TT_LambdaLSquare))
1055 if (Tok.Next->is(tok::question))
1057 if (Style.Language == FormatStyle::LK_JavaScript &&
1058 Tok.Next->is(Keywords.kw_in))
1060 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1063 bool IsCast = false;
1064 bool ParensAreEmpty = Tok.Previous == Tok.MatchingParen;
1065 bool ParensAreType =
1067 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1068 Tok.Previous->isSimpleTypeSpecifier();
1069 bool ParensCouldEndDecl =
1070 Tok.Next && Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace);
1071 bool IsSizeOfOrAlignOf =
1072 LeftOfParens && LeftOfParens->isOneOf(tok::kw_sizeof, tok::kw_alignof);
1073 if (ParensAreType && !ParensCouldEndDecl && !IsSizeOfOrAlignOf &&
1074 (Contexts.size() > 1 && Contexts[Contexts.size() - 2].IsExpression))
1076 else if (Tok.Next && Tok.Next->isNot(tok::string_literal) &&
1077 (Tok.Next->Tok.isLiteral() ||
1078 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1080 // If there is an identifier after the (), it is likely a cast, unless
1081 // there is also an identifier before the ().
1082 else if (LeftOfParens && Tok.Next &&
1083 (LeftOfParens->Tok.getIdentifierInfo() == nullptr ||
1084 LeftOfParens->is(tok::kw_return)) &&
1085 !LeftOfParens->isOneOf(TT_OverloadedOperator, tok::at,
1086 TT_TemplateCloser)) {
1087 if (Tok.Next->isOneOf(tok::identifier, tok::numeric_constant)) {
1090 // Use heuristics to recognize c style casting.
1091 FormatToken *Prev = Tok.Previous;
1092 if (Prev && Prev->isOneOf(tok::amp, tok::star))
1093 Prev = Prev->Previous;
1095 if (Prev && Tok.Next && Tok.Next->Next) {
1096 bool NextIsUnary = Tok.Next->isUnaryOperator() ||
1097 Tok.Next->isOneOf(tok::amp, tok::star);
1099 NextIsUnary && !Tok.Next->is(tok::plus) &&
1100 Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant);
1103 for (; Prev != Tok.MatchingParen; Prev = Prev->Previous) {
1105 !Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon)) {
1112 return IsCast && !ParensAreEmpty;
1115 /// \brief Return the type of the given token assuming it is * or &.
1116 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1117 bool InTemplateArgument) {
1118 if (Style.Language == FormatStyle::LK_JavaScript)
1119 return TT_BinaryOperator;
1121 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1123 return TT_UnaryOperator;
1125 const FormatToken *NextToken = Tok.getNextNonComment();
1127 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1130 if (PrevToken->is(tok::coloncolon))
1131 return TT_PointerOrReference;
1133 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1134 tok::comma, tok::semi, tok::kw_return, tok::colon,
1135 tok::equal, tok::kw_delete, tok::kw_sizeof) ||
1136 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1137 TT_UnaryOperator, TT_CastRParen))
1138 return TT_UnaryOperator;
1140 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1141 return TT_PointerOrReference;
1142 if (NextToken->isOneOf(tok::kw_operator, tok::comma, tok::semi))
1143 return TT_PointerOrReference;
1145 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
1146 PrevToken->MatchingParen->Previous &&
1147 PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
1149 return TT_PointerOrReference;
1151 if (PrevToken->Tok.isLiteral() ||
1152 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1153 tok::kw_false, tok::r_brace) ||
1154 NextToken->Tok.isLiteral() ||
1155 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1156 NextToken->isUnaryOperator() ||
1157 // If we know we're in a template argument, there are no named
1158 // declarations. Thus, having an identifier on the right-hand side
1159 // indicates a binary operator.
1160 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1161 return TT_BinaryOperator;
1163 // "&&(" is quite unlikely to be two successive unary "&".
1164 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1165 return TT_BinaryOperator;
1167 // This catches some cases where evaluation order is used as control flow:
1169 const FormatToken *NextNextToken = NextToken->getNextNonComment();
1170 if (NextNextToken && NextNextToken->is(tok::arrow))
1171 return TT_BinaryOperator;
1173 // It is very unlikely that we are going to find a pointer or reference type
1174 // definition on the RHS of an assignment.
1175 if (IsExpression && !Contexts.back().CaretFound)
1176 return TT_BinaryOperator;
1178 return TT_PointerOrReference;
1181 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1182 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1183 if (!PrevToken || PrevToken->is(TT_CastRParen))
1184 return TT_UnaryOperator;
1186 // Use heuristics to recognize unary operators.
1187 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1188 tok::question, tok::colon, tok::kw_return,
1189 tok::kw_case, tok::at, tok::l_brace))
1190 return TT_UnaryOperator;
1192 // There can't be two consecutive binary operators.
1193 if (PrevToken->is(TT_BinaryOperator))
1194 return TT_UnaryOperator;
1196 // Fall back to marking the token as binary operator.
1197 return TT_BinaryOperator;
1200 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1201 TokenType determineIncrementUsage(const FormatToken &Tok) {
1202 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1203 if (!PrevToken || PrevToken->is(TT_CastRParen))
1204 return TT_UnaryOperator;
1205 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1206 return TT_TrailingUnaryOperator;
1208 return TT_UnaryOperator;
1211 SmallVector<Context, 8> Contexts;
1213 const FormatStyle &Style;
1214 AnnotatedLine &Line;
1215 FormatToken *CurrentToken;
1217 const AdditionalKeywords &Keywords;
1219 // Set of "<" tokens that do not open a template parameter list. If parseAngle
1220 // determines that a specific token can't be a template opener, it will make
1221 // same decision irrespective of the decisions for tokens leading up to it.
1222 // Store this information to prevent this from causing exponential runtime.
1223 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1226 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1227 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1229 /// \brief Parses binary expressions by inserting fake parenthesis based on
1230 /// operator precedence.
1231 class ExpressionParser {
1233 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1234 AnnotatedLine &Line)
1235 : Style(Style), Keywords(Keywords), Current(Line.First) {}
1237 /// \brief Parse expressions with the given operatore precedence.
1238 void parse(int Precedence = 0) {
1239 // Skip 'return' and ObjC selector colons as they are not part of a binary
1241 while (Current && (Current->is(tok::kw_return) ||
1242 (Current->is(tok::colon) &&
1243 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1246 if (!Current || Precedence > PrecedenceArrowAndPeriod)
1249 // Conditional expressions need to be parsed separately for proper nesting.
1250 if (Precedence == prec::Conditional) {
1251 parseConditionalExpr();
1255 // Parse unary operators, which all have a higher precedence than binary
1257 if (Precedence == PrecedenceUnaryOperator) {
1258 parseUnaryOperator();
1262 FormatToken *Start = Current;
1263 FormatToken *LatestOperator = nullptr;
1264 unsigned OperatorIndex = 0;
1267 // Consume operators with higher precedence.
1268 parse(Precedence + 1);
1270 int CurrentPrecedence = getCurrentPrecedence();
1272 if (Current && Current->is(TT_SelectorName) &&
1273 Precedence == CurrentPrecedence) {
1275 addFakeParenthesis(Start, prec::Level(Precedence));
1279 // At the end of the line or when an operator with higher precedence is
1280 // found, insert fake parenthesis and return.
1281 if (!Current || (Current->closesScope() && Current->MatchingParen) ||
1282 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1283 (CurrentPrecedence == prec::Conditional &&
1284 Precedence == prec::Assignment && Current->is(tok::colon))) {
1288 // Consume scopes: (), [], <> and {}
1289 if (Current->opensScope()) {
1290 while (Current && !Current->closesScope()) {
1297 if (CurrentPrecedence == Precedence) {
1298 LatestOperator = Current;
1299 Current->OperatorIndex = OperatorIndex;
1302 next(/*SkipPastLeadingComments=*/Precedence > 0);
1306 if (LatestOperator && (Current || Precedence > 0)) {
1307 LatestOperator->LastOperator = true;
1308 if (Precedence == PrecedenceArrowAndPeriod) {
1309 // Call expressions don't have a binary operator precedence.
1310 addFakeParenthesis(Start, prec::Unknown);
1312 addFakeParenthesis(Start, prec::Level(Precedence));
1318 /// \brief Gets the precedence (+1) of the given token for binary operators
1319 /// and other tokens that we treat like binary operators.
1320 int getCurrentPrecedence() {
1322 const FormatToken *NextNonComment = Current->getNextNonComment();
1323 if (Current->is(TT_ConditionalExpr))
1324 return prec::Conditional;
1325 if (NextNonComment && NextNonComment->is(tok::colon) &&
1326 NextNonComment->is(TT_DictLiteral))
1328 if (Current->is(TT_LambdaArrow))
1330 if (Current->is(TT_JsFatArrow))
1331 return prec::Assignment;
1332 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName,
1333 TT_JsComputedPropertyName) ||
1334 (Current->is(tok::comment) && NextNonComment &&
1335 NextNonComment->is(TT_SelectorName)))
1337 if (Current->is(TT_RangeBasedForLoopColon))
1339 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1340 return Current->getPrecedence();
1341 if (Current->isOneOf(tok::period, tok::arrow))
1342 return PrecedenceArrowAndPeriod;
1343 if (Style.Language == FormatStyle::LK_Java &&
1344 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1345 Keywords.kw_throws))
1351 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1352 Start->FakeLParens.push_back(Precedence);
1353 if (Precedence > prec::Unknown)
1354 Start->StartsBinaryExpression = true;
1356 FormatToken *Previous = Current->Previous;
1357 while (Previous->is(tok::comment) && Previous->Previous)
1358 Previous = Previous->Previous;
1359 ++Previous->FakeRParens;
1360 if (Precedence > prec::Unknown)
1361 Previous->EndsBinaryExpression = true;
1365 /// \brief Parse unary operator expressions and surround them with fake
1366 /// parentheses if appropriate.
1367 void parseUnaryOperator() {
1368 if (!Current || Current->isNot(TT_UnaryOperator)) {
1369 parse(PrecedenceArrowAndPeriod);
1373 FormatToken *Start = Current;
1375 parseUnaryOperator();
1377 // The actual precedence doesn't matter.
1378 addFakeParenthesis(Start, prec::Unknown);
1381 void parseConditionalExpr() {
1382 while (Current && Current->isTrailingComment()) {
1385 FormatToken *Start = Current;
1386 parse(prec::LogicalOr);
1387 if (!Current || !Current->is(tok::question))
1390 parse(prec::Assignment);
1391 if (!Current || Current->isNot(TT_ConditionalExpr))
1394 parse(prec::Assignment);
1395 addFakeParenthesis(Start, prec::Conditional);
1398 void next(bool SkipPastLeadingComments = true) {
1400 Current = Current->Next;
1402 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1403 Current->isTrailingComment())
1404 Current = Current->Next;
1407 const FormatStyle &Style;
1408 const AdditionalKeywords &Keywords;
1409 FormatToken *Current;
1412 } // end anonymous namespace
1414 void TokenAnnotator::setCommentLineLevels(
1415 SmallVectorImpl<AnnotatedLine *> &Lines) {
1416 const AnnotatedLine *NextNonCommentLine = nullptr;
1417 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1420 if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
1421 (*I)->First->Next == nullptr)
1422 (*I)->Level = NextNonCommentLine->Level;
1424 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1426 setCommentLineLevels((*I)->Children);
1430 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1431 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1432 E = Line.Children.end();
1436 AnnotatingParser Parser(Style, Line, Keywords);
1437 Line.Type = Parser.parseLine();
1438 if (Line.Type == LT_Invalid)
1441 ExpressionParser ExprParser(Style, Keywords, Line);
1444 if (Line.First->is(TT_ObjCMethodSpecifier))
1445 Line.Type = LT_ObjCMethodDecl;
1446 else if (Line.First->is(TT_ObjCDecl))
1447 Line.Type = LT_ObjCDecl;
1448 else if (Line.First->is(TT_ObjCProperty))
1449 Line.Type = LT_ObjCProperty;
1451 Line.First->SpacesRequiredBefore = 1;
1452 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1455 // This function heuristically determines whether 'Current' starts the name of a
1456 // function declaration.
1457 static bool isFunctionDeclarationName(const FormatToken &Current) {
1458 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1460 const FormatToken *Next = Current.Next;
1461 for (; Next; Next = Next->Next) {
1462 if (Next->is(TT_TemplateOpener)) {
1463 Next = Next->MatchingParen;
1464 } else if (Next->is(tok::coloncolon)) {
1466 if (!Next || !Next->is(tok::identifier))
1468 } else if (Next->is(tok::l_paren)) {
1476 assert(Next->is(tok::l_paren));
1477 if (Next->Next == Next->MatchingParen)
1479 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1481 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1482 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName))
1484 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1485 Tok->Tok.isLiteral())
1491 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1492 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1493 E = Line.Children.end();
1495 calculateFormattingInformation(**I);
1498 Line.First->TotalLength =
1499 Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1500 if (!Line.First->Next)
1502 FormatToken *Current = Line.First->Next;
1503 bool InFunctionDecl = Line.MightBeFunctionDecl;
1505 if (isFunctionDeclarationName(*Current))
1506 Current->Type = TT_FunctionDeclarationName;
1507 if (Current->is(TT_LineComment)) {
1508 if (Current->Previous->BlockKind == BK_BracedInit &&
1509 Current->Previous->opensScope())
1510 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1512 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1514 // If we find a trailing comment, iterate backwards to determine whether
1515 // it seems to relate to a specific parameter. If so, break before that
1516 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1517 // to the previous line in:
1521 if (!Current->HasUnescapedNewline) {
1522 for (FormatToken *Parameter = Current->Previous; Parameter;
1523 Parameter = Parameter->Previous) {
1524 if (Parameter->isOneOf(tok::comment, tok::r_brace))
1526 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1527 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1528 Parameter->HasUnescapedNewline)
1529 Parameter->MustBreakBefore = true;
1534 } else if (Current->SpacesRequiredBefore == 0 &&
1535 spaceRequiredBefore(Line, *Current)) {
1536 Current->SpacesRequiredBefore = 1;
1539 Current->MustBreakBefore =
1540 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1542 if (Style.AlwaysBreakAfterDefinitionReturnType && InFunctionDecl &&
1543 Current->is(TT_FunctionDeclarationName) &&
1544 !Line.Last->isOneOf(tok::semi, tok::comment)) // Only for definitions.
1545 // FIXME: Line.Last points to other characters than tok::semi
1547 Current->MustBreakBefore = true;
1549 Current->CanBreakBefore =
1550 Current->MustBreakBefore || canBreakBefore(Line, *Current);
1551 unsigned ChildSize = 0;
1552 if (Current->Previous->Children.size() == 1) {
1553 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1554 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1555 : LastOfChild.TotalLength + 1;
1557 const FormatToken *Prev = Current->Previous;
1558 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1559 (Prev->Children.size() == 1 &&
1560 Prev->Children[0]->First->MustBreakBefore) ||
1561 Current->IsMultiline)
1562 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1564 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1565 ChildSize + Current->SpacesRequiredBefore;
1567 if (Current->is(TT_CtorInitializerColon))
1568 InFunctionDecl = false;
1570 // FIXME: Only calculate this if CanBreakBefore is true once static
1571 // initializers etc. are sorted out.
1572 // FIXME: Move magic numbers to a better place.
1573 Current->SplitPenalty = 20 * Current->BindingStrength +
1574 splitPenalty(Line, *Current, InFunctionDecl);
1576 Current = Current->Next;
1579 calculateUnbreakableTailLengths(Line);
1580 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1582 Current->Role->precomputeFormattingInfos(Current);
1585 DEBUG({ printDebugInfo(Line); });
1588 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1589 unsigned UnbreakableTailLength = 0;
1590 FormatToken *Current = Line.Last;
1592 Current->UnbreakableTailLength = UnbreakableTailLength;
1593 if (Current->CanBreakBefore ||
1594 Current->isOneOf(tok::comment, tok::string_literal)) {
1595 UnbreakableTailLength = 0;
1597 UnbreakableTailLength +=
1598 Current->ColumnWidth + Current->SpacesRequiredBefore;
1600 Current = Current->Previous;
1604 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1605 const FormatToken &Tok,
1606 bool InFunctionDecl) {
1607 const FormatToken &Left = *Tok.Previous;
1608 const FormatToken &Right = Tok;
1610 if (Left.is(tok::semi))
1613 if (Style.Language == FormatStyle::LK_Java) {
1614 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
1616 if (Right.is(Keywords.kw_implements))
1618 if (Left.is(tok::comma) && Left.NestingLevel == 0)
1620 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1621 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
1625 if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
1626 Right.Next->is(TT_DictLiteral)))
1628 if (Right.is(tok::l_square)) {
1629 if (Style.Language == FormatStyle::LK_Proto)
1631 // Slightly prefer formatting local lambda definitions like functions.
1632 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
1634 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
1635 TT_ArrayInitializerLSquare))
1639 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
1640 Right.is(tok::kw_operator)) {
1641 if (Line.First->is(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1643 if (Left.is(TT_StartOfName))
1645 if (InFunctionDecl && Right.NestingLevel == 0)
1646 return Style.PenaltyReturnTypeOnItsOwnLine;
1649 if (Right.is(TT_PointerOrReference))
1651 if (Right.is(TT_LambdaArrow))
1653 if (Left.is(tok::equal) && Right.is(tok::l_brace))
1655 if (Left.is(TT_CastRParen))
1657 if (Left.is(tok::coloncolon) ||
1658 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1660 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1663 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
1666 if (Right.isMemberAccess()) {
1667 if (Left.is(tok::r_paren) && Left.MatchingParen &&
1668 Left.MatchingParen->ParameterCount > 0)
1669 return 20; // Should be smaller than breaking at a nested comma.
1673 if (Right.is(TT_TrailingAnnotation) &&
1674 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
1675 // Moving trailing annotations to the next line is fine for ObjC method
1677 if (Line.First->is(TT_ObjCMethodSpecifier))
1680 // Generally, breaking before a trailing annotation is bad unless it is
1681 // function-like. It seems to be especially preferable to keep standard
1682 // annotations (i.e. "const", "final" and "override") on the same line.
1683 // Use a slightly higher penalty after ")" so that annotations like
1684 // "const override" are kept together.
1685 bool is_short_annotation = Right.TokenText.size() < 10;
1686 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
1689 // In for-loops, prefer breaking at ',' and ';'.
1690 if (Line.First->is(tok::kw_for) && Left.is(tok::equal))
1693 // In Objective-C method expressions, prefer breaking before "param:" over
1694 // breaking after it.
1695 if (Right.is(TT_SelectorName))
1697 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
1698 return Line.MightBeFunctionDecl ? 50 : 500;
1700 if (Left.is(tok::l_paren) && InFunctionDecl && Style.AlignAfterOpenBracket)
1702 if (Left.is(tok::l_paren) && Left.Previous && Left.Previous->is(tok::kw_if))
1704 if (Left.is(tok::equal) && InFunctionDecl)
1706 if (Right.is(tok::r_brace))
1708 if (Left.is(TT_TemplateOpener))
1710 if (Left.opensScope()) {
1711 if (!Style.AlignAfterOpenBracket)
1713 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1716 if (Left.is(TT_JavaAnnotation))
1719 if (Right.is(tok::lessless)) {
1720 if (Left.is(tok::string_literal) &&
1721 (!Right.LastOperator || Right.OperatorIndex != 1)) {
1722 StringRef Content = Left.TokenText;
1723 if (Content.startswith("\""))
1724 Content = Content.drop_front(1);
1725 if (Content.endswith("\""))
1726 Content = Content.drop_back(1);
1727 Content = Content.trim();
1728 if (Content.size() > 1 &&
1729 (Content.back() == ':' || Content.back() == '='))
1732 return 1; // Breaking at a << is really cheap.
1734 if (Left.is(TT_ConditionalExpr))
1735 return prec::Conditional;
1736 prec::Level Level = Left.getPrecedence();
1737 if (Level != prec::Unknown)
1739 Level = Right.getPrecedence();
1740 if (Level != prec::Unknown)
1746 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1747 const FormatToken &Left,
1748 const FormatToken &Right) {
1749 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
1751 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1752 Left.Tok.getObjCKeywordID() == tok::objc_property)
1754 if (Right.is(tok::hashhash))
1755 return Left.is(tok::hash);
1756 if (Left.isOneOf(tok::hashhash, tok::hash))
1757 return Right.is(tok::hash);
1758 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
1759 return Style.SpaceInEmptyParentheses;
1760 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
1761 return (Right.is(TT_CastRParen) ||
1762 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
1763 ? Style.SpacesInCStyleCastParentheses
1764 : Style.SpacesInParentheses;
1765 if (Right.isOneOf(tok::semi, tok::comma))
1767 if (Right.is(tok::less) &&
1768 (Left.is(tok::kw_template) ||
1769 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1771 if (Left.isOneOf(tok::exclaim, tok::tilde))
1773 if (Left.is(tok::at) &&
1774 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1775 tok::numeric_constant, tok::l_paren, tok::l_brace,
1776 tok::kw_true, tok::kw_false))
1778 if (Left.is(tok::coloncolon))
1780 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
1782 if (Right.is(tok::ellipsis))
1783 return Left.Tok.isLiteral();
1784 if (Left.is(tok::l_square) && Right.is(tok::amp))
1786 if (Right.is(TT_PointerOrReference))
1787 return !(Left.is(tok::r_paren) && Left.MatchingParen &&
1788 (Left.MatchingParen->is(TT_OverloadedOperatorLParen) ||
1789 (Left.MatchingParen->Previous &&
1790 Left.MatchingParen->Previous->is(
1791 TT_FunctionDeclarationName)))) &&
1792 (Left.Tok.isLiteral() ||
1793 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
1794 (Style.PointerAlignment != FormatStyle::PAS_Left ||
1795 Line.IsMultiVariableDeclStmt)));
1796 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
1797 (!Left.is(TT_PointerOrReference) ||
1798 (Style.PointerAlignment != FormatStyle::PAS_Right &&
1799 !Line.IsMultiVariableDeclStmt)))
1801 if (Left.is(TT_PointerOrReference))
1802 return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
1803 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
1805 (Style.PointerAlignment != FormatStyle::PAS_Right &&
1806 !Line.IsMultiVariableDeclStmt) &&
1808 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
1809 if (Right.is(tok::star) && Left.is(tok::l_paren))
1811 if (Left.is(tok::l_square))
1812 return (Left.is(TT_ArrayInitializerLSquare) &&
1813 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
1814 (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
1815 Right.isNot(tok::r_square));
1816 if (Right.is(tok::r_square))
1817 return Right.MatchingParen &&
1818 ((Style.SpacesInContainerLiterals &&
1819 Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
1820 (Style.SpacesInSquareBrackets &&
1821 Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
1822 if (Right.is(tok::l_square) &&
1823 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
1824 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
1826 if (Left.is(tok::colon))
1827 return !Left.is(TT_ObjCMethodExpr);
1828 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1829 return !Left.Children.empty(); // No spaces in "{}".
1830 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
1831 (Right.is(tok::r_brace) && Right.MatchingParen &&
1832 Right.MatchingParen->BlockKind != BK_Block))
1833 return !Style.Cpp11BracedListStyle;
1834 if (Left.is(TT_BlockComment))
1835 return !Left.TokenText.endswith("=*/");
1836 if (Right.is(tok::l_paren)) {
1837 if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
1839 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
1840 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
1841 (Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while,
1842 tok::kw_switch, tok::kw_case, TT_ForEachMacro) ||
1843 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
1844 tok::kw_new, tok::kw_delete) &&
1845 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
1846 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
1847 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() || Left.is(tok::r_paren)) &&
1848 Line.Type != LT_PreprocessorDirective);
1850 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
1852 if (Right.is(TT_UnaryOperator))
1853 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
1854 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
1855 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
1857 Left.isSimpleTypeSpecifier()) &&
1858 Right.is(tok::l_brace) && Right.getNextNonComment() &&
1859 Right.BlockKind != BK_Block)
1861 if (Left.is(tok::period) || Right.is(tok::period))
1863 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
1865 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
1866 Left.MatchingParen->Previous &&
1867 Left.MatchingParen->Previous->is(tok::period))
1868 // A.<B>DoSomething();
1870 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
1875 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
1876 const FormatToken &Right) {
1877 const FormatToken &Left = *Right.Previous;
1878 if (Style.Language == FormatStyle::LK_Proto) {
1879 if (Right.is(tok::period) &&
1880 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
1881 Keywords.kw_repeated))
1883 if (Right.is(tok::l_paren) &&
1884 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
1886 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1887 if (Left.isOneOf(Keywords.kw_var, TT_JsFatArrow))
1889 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
1891 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
1892 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
1894 if (Left.is(tok::ellipsis))
1896 if (Left.is(TT_TemplateCloser) &&
1897 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
1898 Keywords.kw_implements, Keywords.kw_extends))
1899 // Type assertions ('<type>expr') are not followed by whitespace. Other
1900 // locations that should have whitespace following are identified by the
1901 // above set of follower tokens.
1903 } else if (Style.Language == FormatStyle::LK_Java) {
1904 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
1906 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
1907 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
1908 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
1909 tok::kw_protected) ||
1910 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
1911 Keywords.kw_native)) &&
1912 Right.is(TT_TemplateOpener))
1915 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
1916 return true; // Never ever merge two identifiers.
1917 if (Left.is(TT_ImplicitStringLiteral))
1918 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
1919 if (Line.Type == LT_ObjCMethodDecl) {
1920 if (Left.is(TT_ObjCMethodSpecifier))
1922 if (Left.is(tok::r_paren) && Right.is(tok::identifier))
1923 // Don't space between ')' and <id>
1926 if (Line.Type == LT_ObjCProperty &&
1927 (Right.is(tok::equal) || Left.is(tok::equal)))
1930 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
1931 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
1933 if (Left.is(tok::comma))
1935 if (Right.is(tok::comma))
1937 if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
1939 if (Left.is(tok::kw_operator))
1940 return Right.is(tok::coloncolon);
1941 if (Right.is(TT_OverloadedOperatorLParen))
1943 if (Right.is(tok::colon)) {
1944 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
1945 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
1947 if (Right.is(TT_ObjCMethodExpr))
1949 if (Left.is(tok::question))
1951 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
1953 if (Right.is(TT_DictLiteral))
1954 return Style.SpacesInContainerLiterals;
1957 if (Left.is(TT_UnaryOperator))
1958 return Right.is(TT_BinaryOperator);
1960 // If the next token is a binary operator or a selector name, we have
1961 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
1962 if (Left.is(TT_CastRParen))
1963 return Style.SpaceAfterCStyleCast ||
1964 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
1966 if (Left.is(tok::greater) && Right.is(tok::greater))
1967 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
1968 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
1969 if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
1970 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
1972 if (!Style.SpaceBeforeAssignmentOperators &&
1973 Right.getPrecedence() == prec::Assignment)
1975 if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
1976 return (Left.is(TT_TemplateOpener) &&
1977 Style.Standard == FormatStyle::LS_Cpp03) ||
1978 !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren) ||
1979 Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
1980 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
1981 return Style.SpacesInAngles;
1982 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
1983 Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr))
1985 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
1986 Right.isNot(TT_FunctionTypeLParen))
1987 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
1988 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
1989 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
1991 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
1992 Line.First->is(tok::hash))
1994 if (Right.is(TT_TrailingUnaryOperator))
1996 if (Left.is(TT_RegexLiteral))
1998 return spaceRequiredBetween(Line, Left, Right);
2001 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2002 static bool isAllmanBrace(const FormatToken &Tok) {
2003 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2004 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2007 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2008 const FormatToken &Right) {
2009 const FormatToken &Left = *Right.Previous;
2010 if (Right.NewlinesBefore > 1)
2013 // If the last token before a '}' is a comma or a trailing comment, the
2014 // intention is to insert a line break after it in order to make shuffling
2015 // around entries easier.
2016 const FormatToken *BeforeClosingBrace = nullptr;
2017 if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
2018 Left.BlockKind != BK_Block && Left.MatchingParen)
2019 BeforeClosingBrace = Left.MatchingParen->Previous;
2020 else if (Right.MatchingParen &&
2021 Right.MatchingParen->isOneOf(tok::l_brace,
2022 TT_ArrayInitializerLSquare))
2023 BeforeClosingBrace = &Left;
2024 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2025 BeforeClosingBrace->isTrailingComment()))
2028 if (Right.is(tok::comment))
2029 return Left.BlockKind != BK_BracedInit &&
2030 Left.isNot(TT_CtorInitializerColon) &&
2031 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2032 if (Left.isTrailingComment())
2034 if (Left.isStringLiteral() &&
2035 (Right.isStringLiteral() || Right.is(TT_ObjCStringLiteral)))
2037 if (Right.Previous->IsUnterminatedLiteral)
2039 if (Right.is(tok::lessless) && Right.Next &&
2040 Right.Previous->is(tok::string_literal) &&
2041 Right.Next->is(tok::string_literal))
2043 if (Right.Previous->ClosesTemplateDeclaration &&
2044 Right.Previous->MatchingParen &&
2045 Right.Previous->MatchingParen->NestingLevel == 0 &&
2046 Style.AlwaysBreakTemplateDeclarations)
2048 if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
2049 Style.BreakConstructorInitializersBeforeComma &&
2050 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2052 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2053 // Raw string literals are special wrt. line breaks. The author has made a
2054 // deliberate choice and might have aligned the contents of the string
2055 // literal accordingly. Thus, we try keep existing line breaks.
2056 return Right.NewlinesBefore > 0;
2057 if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
2058 Style.Language == FormatStyle::LK_Proto)
2059 // Don't put enums onto single lines in protocol buffers.
2061 if (Right.is(TT_InlineASMBrace))
2062 return Right.HasUnescapedNewline;
2063 if (Style.Language == FormatStyle::LK_JavaScript && Right.is(tok::r_brace) &&
2064 Left.is(tok::l_brace) && !Left.Children.empty())
2065 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2066 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2067 (Left.NestingLevel == 0 && Line.Level == 0 &&
2068 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline);
2069 if (isAllmanBrace(Left) || isAllmanBrace(Right))
2070 return Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
2071 Style.BreakBeforeBraces == FormatStyle::BS_GNU;
2072 if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) &&
2073 Right.is(TT_SelectorName))
2075 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2078 if ((Style.Language == FormatStyle::LK_Java ||
2079 Style.Language == FormatStyle::LK_JavaScript) &&
2080 Left.is(TT_LeadingJavaAnnotation) &&
2081 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2082 Line.Last->is(tok::l_brace))
2085 if (Style.Language == FormatStyle::LK_JavaScript) {
2086 // FIXME: This might apply to other languages and token kinds.
2087 if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
2088 Left.Previous->is(tok::char_constant))
2090 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) &&
2091 Left.NestingLevel == 0 && Left.Previous &&
2092 Left.Previous->is(tok::equal) &&
2093 Line.First->isOneOf(tok::identifier, Keywords.kw_import,
2095 // kw_var is a pseudo-token that's a tok::identifier, so matches above.
2096 !Line.First->is(Keywords.kw_var))
2097 // Enum style object literal.
2099 } else if (Style.Language == FormatStyle::LK_Java) {
2100 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2101 Right.Next->is(tok::string_literal))
2108 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2109 const FormatToken &Right) {
2110 const FormatToken &Left = *Right.Previous;
2112 // Language-specific stuff.
2113 if (Style.Language == FormatStyle::LK_Java) {
2114 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2115 Keywords.kw_implements))
2117 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2118 Keywords.kw_implements))
2120 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2121 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2125 if (Left.is(tok::at))
2127 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2129 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2130 return !Right.is(tok::l_paren);
2131 if (Right.is(TT_PointerOrReference))
2132 return Line.IsMultiVariableDeclStmt ||
2133 (Style.PointerAlignment == FormatStyle::PAS_Right &&
2134 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2135 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2136 Right.is(tok::kw_operator))
2138 if (Left.is(TT_PointerOrReference))
2140 if (Right.isTrailingComment())
2141 // We rely on MustBreakBefore being set correctly here as we should not
2142 // change the "binding" behavior of a comment.
2143 // The first comment in a braced lists is always interpreted as belonging to
2144 // the first list element. Otherwise, it should be placed outside of the
2146 return Left.BlockKind == BK_BracedInit;
2147 if (Left.is(tok::question) && Right.is(tok::colon))
2149 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2150 return Style.BreakBeforeTernaryOperators;
2151 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2152 return !Style.BreakBeforeTernaryOperators;
2153 if (Right.is(TT_InheritanceColon))
2155 if (Right.is(tok::colon) &&
2156 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2158 if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
2160 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2161 Right.Next->is(TT_ObjCMethodExpr)))
2162 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2163 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2165 if (Left.ClosesTemplateDeclaration)
2167 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2168 TT_OverloadedOperator))
2170 if (Left.is(TT_RangeBasedForLoopColon))
2172 if (Right.is(TT_RangeBasedForLoopColon))
2174 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2175 Left.is(tok::kw_operator))
2177 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2178 Line.Type == LT_VirtualFunctionDecl)
2180 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2182 if (Left.is(tok::l_paren) && Left.Previous &&
2183 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2185 if (Right.is(TT_ImplicitStringLiteral))
2188 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2191 // We only break before r_brace if there was a corresponding break before
2192 // the l_brace, which is tracked by BreakBeforeClosingBrace.
2193 if (Right.is(tok::r_brace))
2194 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2196 // Allow breaking after a trailing annotation, e.g. after a method
2198 if (Left.is(TT_TrailingAnnotation))
2199 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2200 tok::less, tok::coloncolon);
2202 if (Right.is(tok::kw___attribute))
2205 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2208 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2211 if (Left.is(TT_CtorInitializerComma) &&
2212 Style.BreakConstructorInitializersBeforeComma)
2214 if (Right.is(TT_CtorInitializerComma) &&
2215 Style.BreakConstructorInitializersBeforeComma)
2217 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2218 (Left.is(tok::less) && Right.is(tok::less)))
2220 if (Right.is(TT_BinaryOperator) &&
2221 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2222 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2223 Right.getPrecedence() != prec::Assignment))
2225 if (Left.is(TT_ArrayInitializerLSquare))
2227 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2229 if (Left.isBinaryOperator() && !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2230 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2231 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2232 Left.getPrecedence() == prec::Assignment))
2234 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2235 tok::kw_class, tok::kw_struct) ||
2236 Right.isMemberAccess() ||
2237 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2238 tok::colon, tok::l_square, tok::at) ||
2239 (Left.is(tok::r_paren) &&
2240 Right.isOneOf(tok::identifier, tok::kw_const)) ||
2241 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
2244 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2245 llvm::errs() << "AnnotatedTokens:\n";
2246 const FormatToken *Tok = Line.First;
2248 llvm::errs() << " M=" << Tok->MustBreakBefore
2249 << " C=" << Tok->CanBreakBefore << " T=" << Tok->Type
2250 << " S=" << Tok->SpacesRequiredBefore
2251 << " B=" << Tok->BlockParameterCount
2252 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
2253 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
2255 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2256 llvm::errs() << Tok->FakeLParens[i] << "/";
2257 llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
2259 assert(Tok == Line.Last);
2262 llvm::errs() << "----\n";
2265 } // namespace format
2266 } // namespace clang