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.startsWith(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 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.startsWith(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.startsWith(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::comma, 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.startsWith(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.startsWith(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.startsWith(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.isOneOf(tok::semi, 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->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof))
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->isOneOf(tok::kw_return, tok::kw_case)) &&
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();
1126 if (!NextToken || NextToken->is(tok::arrow) ||
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 ((Style.Language == FormatStyle::LK_Java ||
1340 Style.Language == FormatStyle::LK_JavaScript) &&
1341 Current->is(Keywords.kw_instanceof))
1342 return prec::Relational;
1343 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1344 return Current->getPrecedence();
1345 if (Current->isOneOf(tok::period, tok::arrow))
1346 return PrecedenceArrowAndPeriod;
1347 if (Style.Language == FormatStyle::LK_Java &&
1348 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1349 Keywords.kw_throws))
1355 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1356 Start->FakeLParens.push_back(Precedence);
1357 if (Precedence > prec::Unknown)
1358 Start->StartsBinaryExpression = true;
1360 FormatToken *Previous = Current->Previous;
1361 while (Previous->is(tok::comment) && Previous->Previous)
1362 Previous = Previous->Previous;
1363 ++Previous->FakeRParens;
1364 if (Precedence > prec::Unknown)
1365 Previous->EndsBinaryExpression = true;
1369 /// \brief Parse unary operator expressions and surround them with fake
1370 /// parentheses if appropriate.
1371 void parseUnaryOperator() {
1372 if (!Current || Current->isNot(TT_UnaryOperator)) {
1373 parse(PrecedenceArrowAndPeriod);
1377 FormatToken *Start = Current;
1379 parseUnaryOperator();
1381 // The actual precedence doesn't matter.
1382 addFakeParenthesis(Start, prec::Unknown);
1385 void parseConditionalExpr() {
1386 while (Current && Current->isTrailingComment()) {
1389 FormatToken *Start = Current;
1390 parse(prec::LogicalOr);
1391 if (!Current || !Current->is(tok::question))
1394 parse(prec::Assignment);
1395 if (!Current || Current->isNot(TT_ConditionalExpr))
1398 parse(prec::Assignment);
1399 addFakeParenthesis(Start, prec::Conditional);
1402 void next(bool SkipPastLeadingComments = true) {
1404 Current = Current->Next;
1406 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1407 Current->isTrailingComment())
1408 Current = Current->Next;
1411 const FormatStyle &Style;
1412 const AdditionalKeywords &Keywords;
1413 FormatToken *Current;
1416 } // end anonymous namespace
1418 void TokenAnnotator::setCommentLineLevels(
1419 SmallVectorImpl<AnnotatedLine *> &Lines) {
1420 const AnnotatedLine *NextNonCommentLine = nullptr;
1421 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1424 if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
1425 (*I)->First->Next == nullptr)
1426 (*I)->Level = NextNonCommentLine->Level;
1428 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1430 setCommentLineLevels((*I)->Children);
1434 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1435 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1436 E = Line.Children.end();
1440 AnnotatingParser Parser(Style, Line, Keywords);
1441 Line.Type = Parser.parseLine();
1442 if (Line.Type == LT_Invalid)
1445 ExpressionParser ExprParser(Style, Keywords, Line);
1448 if (Line.startsWith(TT_ObjCMethodSpecifier))
1449 Line.Type = LT_ObjCMethodDecl;
1450 else if (Line.startsWith(TT_ObjCDecl))
1451 Line.Type = LT_ObjCDecl;
1452 else if (Line.startsWith(TT_ObjCProperty))
1453 Line.Type = LT_ObjCProperty;
1455 Line.First->SpacesRequiredBefore = 1;
1456 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1459 // This function heuristically determines whether 'Current' starts the name of a
1460 // function declaration.
1461 static bool isFunctionDeclarationName(const FormatToken &Current) {
1462 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1464 const FormatToken *Next = Current.Next;
1465 for (; Next; Next = Next->Next) {
1466 if (Next->is(TT_TemplateOpener)) {
1467 Next = Next->MatchingParen;
1468 } else if (Next->is(tok::coloncolon)) {
1470 if (!Next || !Next->is(tok::identifier))
1472 } else if (Next->is(tok::l_paren)) {
1480 assert(Next->is(tok::l_paren));
1481 if (Next->Next == Next->MatchingParen)
1483 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1485 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1486 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName))
1488 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1489 Tok->Tok.isLiteral())
1495 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1496 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1497 E = Line.Children.end();
1499 calculateFormattingInformation(**I);
1502 Line.First->TotalLength =
1503 Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1504 if (!Line.First->Next)
1506 FormatToken *Current = Line.First->Next;
1507 bool InFunctionDecl = Line.MightBeFunctionDecl;
1509 if (isFunctionDeclarationName(*Current))
1510 Current->Type = TT_FunctionDeclarationName;
1511 if (Current->is(TT_LineComment)) {
1512 if (Current->Previous->BlockKind == BK_BracedInit &&
1513 Current->Previous->opensScope())
1514 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1516 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1518 // If we find a trailing comment, iterate backwards to determine whether
1519 // it seems to relate to a specific parameter. If so, break before that
1520 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1521 // to the previous line in:
1525 if (!Current->HasUnescapedNewline) {
1526 for (FormatToken *Parameter = Current->Previous; Parameter;
1527 Parameter = Parameter->Previous) {
1528 if (Parameter->isOneOf(tok::comment, tok::r_brace))
1530 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1531 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1532 Parameter->HasUnescapedNewline)
1533 Parameter->MustBreakBefore = true;
1538 } else if (Current->SpacesRequiredBefore == 0 &&
1539 spaceRequiredBefore(Line, *Current)) {
1540 Current->SpacesRequiredBefore = 1;
1543 Current->MustBreakBefore =
1544 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1546 if ((Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All ||
1547 (Style.AlwaysBreakAfterDefinitionReturnType ==
1548 FormatStyle::DRTBS_TopLevel &&
1549 Line.Level == 0)) &&
1550 InFunctionDecl && Current->is(TT_FunctionDeclarationName) &&
1551 !Line.Last->isOneOf(tok::semi, tok::comment)) // Only for definitions.
1552 // FIXME: Line.Last points to other characters than tok::semi
1554 Current->MustBreakBefore = true;
1556 Current->CanBreakBefore =
1557 Current->MustBreakBefore || canBreakBefore(Line, *Current);
1558 unsigned ChildSize = 0;
1559 if (Current->Previous->Children.size() == 1) {
1560 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1561 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1562 : LastOfChild.TotalLength + 1;
1564 const FormatToken *Prev = Current->Previous;
1565 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1566 (Prev->Children.size() == 1 &&
1567 Prev->Children[0]->First->MustBreakBefore) ||
1568 Current->IsMultiline)
1569 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1571 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1572 ChildSize + Current->SpacesRequiredBefore;
1574 if (Current->is(TT_CtorInitializerColon))
1575 InFunctionDecl = false;
1577 // FIXME: Only calculate this if CanBreakBefore is true once static
1578 // initializers etc. are sorted out.
1579 // FIXME: Move magic numbers to a better place.
1580 Current->SplitPenalty = 20 * Current->BindingStrength +
1581 splitPenalty(Line, *Current, InFunctionDecl);
1583 Current = Current->Next;
1586 calculateUnbreakableTailLengths(Line);
1587 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1589 Current->Role->precomputeFormattingInfos(Current);
1592 DEBUG({ printDebugInfo(Line); });
1595 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1596 unsigned UnbreakableTailLength = 0;
1597 FormatToken *Current = Line.Last;
1599 Current->UnbreakableTailLength = UnbreakableTailLength;
1600 if (Current->CanBreakBefore ||
1601 Current->isOneOf(tok::comment, tok::string_literal)) {
1602 UnbreakableTailLength = 0;
1604 UnbreakableTailLength +=
1605 Current->ColumnWidth + Current->SpacesRequiredBefore;
1607 Current = Current->Previous;
1611 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1612 const FormatToken &Tok,
1613 bool InFunctionDecl) {
1614 const FormatToken &Left = *Tok.Previous;
1615 const FormatToken &Right = Tok;
1617 if (Left.is(tok::semi))
1620 if (Style.Language == FormatStyle::LK_Java) {
1621 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
1623 if (Right.is(Keywords.kw_implements))
1625 if (Left.is(tok::comma) && Left.NestingLevel == 0)
1627 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1628 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
1632 if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
1633 Right.Next->is(TT_DictLiteral)))
1635 if (Right.is(tok::l_square)) {
1636 if (Style.Language == FormatStyle::LK_Proto)
1638 // Slightly prefer formatting local lambda definitions like functions.
1639 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
1641 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
1642 TT_ArrayInitializerLSquare))
1646 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
1647 Right.is(tok::kw_operator)) {
1648 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1650 if (Left.is(TT_StartOfName))
1652 if (InFunctionDecl && Right.NestingLevel == 0)
1653 return Style.PenaltyReturnTypeOnItsOwnLine;
1656 if (Right.is(TT_PointerOrReference))
1658 if (Right.is(TT_LambdaArrow))
1660 if (Left.is(tok::equal) && Right.is(tok::l_brace))
1662 if (Left.is(TT_CastRParen))
1664 if (Left.is(tok::coloncolon) ||
1665 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1667 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1670 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
1673 if (Right.isMemberAccess()) {
1674 if (Left.is(tok::r_paren) && Left.MatchingParen &&
1675 Left.MatchingParen->ParameterCount > 0)
1676 return 20; // Should be smaller than breaking at a nested comma.
1680 if (Right.is(TT_TrailingAnnotation) &&
1681 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
1682 // Moving trailing annotations to the next line is fine for ObjC method
1684 if (Line.startsWith(TT_ObjCMethodSpecifier))
1686 // Generally, breaking before a trailing annotation is bad unless it is
1687 // function-like. It seems to be especially preferable to keep standard
1688 // annotations (i.e. "const", "final" and "override") on the same line.
1689 // Use a slightly higher penalty after ")" so that annotations like
1690 // "const override" are kept together.
1691 bool is_short_annotation = Right.TokenText.size() < 10;
1692 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
1695 // In for-loops, prefer breaking at ',' and ';'.
1696 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
1699 // In Objective-C method expressions, prefer breaking before "param:" over
1700 // breaking after it.
1701 if (Right.is(TT_SelectorName))
1703 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
1704 return Line.MightBeFunctionDecl ? 50 : 500;
1706 if (Left.is(tok::l_paren) && InFunctionDecl && Style.AlignAfterOpenBracket)
1708 if (Left.is(tok::l_paren) && Left.Previous && Left.Previous->is(tok::kw_if))
1710 if (Left.is(tok::equal) && InFunctionDecl)
1712 if (Right.is(tok::r_brace))
1714 if (Left.is(TT_TemplateOpener))
1716 if (Left.opensScope()) {
1717 if (!Style.AlignAfterOpenBracket)
1719 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1722 if (Left.is(TT_JavaAnnotation))
1725 if (Right.is(tok::lessless)) {
1726 if (Left.is(tok::string_literal) &&
1727 (!Right.LastOperator || Right.OperatorIndex != 1)) {
1728 StringRef Content = Left.TokenText;
1729 if (Content.startswith("\""))
1730 Content = Content.drop_front(1);
1731 if (Content.endswith("\""))
1732 Content = Content.drop_back(1);
1733 Content = Content.trim();
1734 if (Content.size() > 1 &&
1735 (Content.back() == ':' || Content.back() == '='))
1738 return 1; // Breaking at a << is really cheap.
1740 if (Left.is(TT_ConditionalExpr))
1741 return prec::Conditional;
1742 prec::Level Level = Left.getPrecedence();
1743 if (Level != prec::Unknown)
1745 Level = Right.getPrecedence();
1746 if (Level != prec::Unknown)
1752 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1753 const FormatToken &Left,
1754 const FormatToken &Right) {
1755 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
1757 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1758 Left.Tok.getObjCKeywordID() == tok::objc_property)
1760 if (Right.is(tok::hashhash))
1761 return Left.is(tok::hash);
1762 if (Left.isOneOf(tok::hashhash, tok::hash))
1763 return Right.is(tok::hash);
1764 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
1765 return Style.SpaceInEmptyParentheses;
1766 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
1767 return (Right.is(TT_CastRParen) ||
1768 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
1769 ? Style.SpacesInCStyleCastParentheses
1770 : Style.SpacesInParentheses;
1771 if (Right.isOneOf(tok::semi, tok::comma))
1773 if (Right.is(tok::less) &&
1774 (Left.is(tok::kw_template) ||
1775 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1777 if (Left.isOneOf(tok::exclaim, tok::tilde))
1779 if (Left.is(tok::at) &&
1780 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1781 tok::numeric_constant, tok::l_paren, tok::l_brace,
1782 tok::kw_true, tok::kw_false))
1784 if (Left.is(tok::coloncolon))
1786 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
1788 if (Right.is(tok::ellipsis))
1789 return Left.Tok.isLiteral();
1790 if (Left.is(tok::l_square) && Right.is(tok::amp))
1792 if (Right.is(TT_PointerOrReference))
1793 return !(Left.is(tok::r_paren) && Left.MatchingParen &&
1794 (Left.MatchingParen->is(TT_OverloadedOperatorLParen) ||
1795 (Left.MatchingParen->Previous &&
1796 Left.MatchingParen->Previous->is(
1797 TT_FunctionDeclarationName)))) &&
1798 (Left.Tok.isLiteral() ||
1799 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
1800 (Style.PointerAlignment != FormatStyle::PAS_Left ||
1801 Line.IsMultiVariableDeclStmt)));
1802 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
1803 (!Left.is(TT_PointerOrReference) ||
1804 (Style.PointerAlignment != FormatStyle::PAS_Right &&
1805 !Line.IsMultiVariableDeclStmt)))
1807 if (Left.is(TT_PointerOrReference))
1808 return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
1809 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
1810 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
1812 (Style.PointerAlignment != FormatStyle::PAS_Right &&
1813 !Line.IsMultiVariableDeclStmt) &&
1815 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
1816 if (Right.is(tok::star) && Left.is(tok::l_paren))
1818 if (Left.is(tok::l_square))
1819 return (Left.is(TT_ArrayInitializerLSquare) &&
1820 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
1821 (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
1822 Right.isNot(tok::r_square));
1823 if (Right.is(tok::r_square))
1824 return Right.MatchingParen &&
1825 ((Style.SpacesInContainerLiterals &&
1826 Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
1827 (Style.SpacesInSquareBrackets &&
1828 Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
1829 if (Right.is(tok::l_square) &&
1830 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
1831 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
1833 if (Left.is(tok::colon))
1834 return !Left.is(TT_ObjCMethodExpr);
1835 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1836 return !Left.Children.empty(); // No spaces in "{}".
1837 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
1838 (Right.is(tok::r_brace) && Right.MatchingParen &&
1839 Right.MatchingParen->BlockKind != BK_Block))
1840 return !Style.Cpp11BracedListStyle;
1841 if (Left.is(TT_BlockComment))
1842 return !Left.TokenText.endswith("=*/");
1843 if (Right.is(tok::l_paren)) {
1844 if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
1846 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
1847 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
1848 (Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while,
1849 tok::kw_switch, tok::kw_case, TT_ForEachMacro) ||
1850 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
1851 tok::kw_new, tok::kw_delete) &&
1852 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
1853 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
1854 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
1855 Left.is(tok::r_paren)) &&
1856 Line.Type != LT_PreprocessorDirective);
1858 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
1860 if (Right.is(TT_UnaryOperator))
1861 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
1862 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
1863 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
1865 Left.isSimpleTypeSpecifier()) &&
1866 Right.is(tok::l_brace) && Right.getNextNonComment() &&
1867 Right.BlockKind != BK_Block)
1869 if (Left.is(tok::period) || Right.is(tok::period))
1871 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
1873 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
1874 Left.MatchingParen->Previous &&
1875 Left.MatchingParen->Previous->is(tok::period))
1876 // A.<B>DoSomething();
1878 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
1883 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
1884 const FormatToken &Right) {
1885 const FormatToken &Left = *Right.Previous;
1886 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
1887 return true; // Never ever merge two identifiers.
1888 if (Style.Language == FormatStyle::LK_Cpp) {
1889 if (Left.is(tok::kw_operator))
1890 return Right.is(tok::coloncolon);
1891 } else if (Style.Language == FormatStyle::LK_Proto) {
1892 if (Right.is(tok::period) &&
1893 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
1894 Keywords.kw_repeated))
1896 if (Right.is(tok::l_paren) &&
1897 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
1899 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1900 if (Left.isOneOf(Keywords.kw_var, TT_JsFatArrow))
1902 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
1904 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
1905 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
1907 if (Left.is(tok::ellipsis))
1909 if (Left.is(TT_TemplateCloser) &&
1910 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
1911 Keywords.kw_implements, Keywords.kw_extends))
1912 // Type assertions ('<type>expr') are not followed by whitespace. Other
1913 // locations that should have whitespace following are identified by the
1914 // above set of follower tokens.
1916 } else if (Style.Language == FormatStyle::LK_Java) {
1917 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
1919 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
1920 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
1921 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
1922 tok::kw_protected) ||
1923 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
1924 Keywords.kw_native)) &&
1925 Right.is(TT_TemplateOpener))
1928 if (Left.is(TT_ImplicitStringLiteral))
1929 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
1930 if (Line.Type == LT_ObjCMethodDecl) {
1931 if (Left.is(TT_ObjCMethodSpecifier))
1933 if (Left.is(tok::r_paren) && Right.is(tok::identifier))
1934 // Don't space between ')' and <id>
1937 if (Line.Type == LT_ObjCProperty &&
1938 (Right.is(tok::equal) || Left.is(tok::equal)))
1941 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
1942 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
1944 if (Left.is(tok::comma))
1946 if (Right.is(tok::comma))
1948 if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
1950 if (Right.is(TT_OverloadedOperatorLParen))
1952 if (Right.is(tok::colon)) {
1953 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
1954 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
1956 if (Right.is(TT_ObjCMethodExpr))
1958 if (Left.is(tok::question))
1960 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
1962 if (Right.is(TT_DictLiteral))
1963 return Style.SpacesInContainerLiterals;
1966 if (Left.is(TT_UnaryOperator))
1967 return Right.is(TT_BinaryOperator);
1969 // If the next token is a binary operator or a selector name, we have
1970 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
1971 if (Left.is(TT_CastRParen))
1972 return Style.SpaceAfterCStyleCast ||
1973 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
1975 if (Left.is(tok::greater) && Right.is(tok::greater))
1976 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
1977 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
1978 if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
1979 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
1981 if (!Style.SpaceBeforeAssignmentOperators &&
1982 Right.getPrecedence() == prec::Assignment)
1984 if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
1985 return (Left.is(TT_TemplateOpener) &&
1986 Style.Standard == FormatStyle::LS_Cpp03) ||
1987 !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren) ||
1988 Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
1989 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
1990 return Style.SpacesInAngles;
1991 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
1992 Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr))
1994 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
1995 Right.isNot(TT_FunctionTypeLParen))
1996 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
1997 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
1998 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2000 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2001 Line.startsWith(tok::hash))
2003 if (Right.is(TT_TrailingUnaryOperator))
2005 if (Left.is(TT_RegexLiteral))
2007 return spaceRequiredBetween(Line, Left, Right);
2010 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2011 static bool isAllmanBrace(const FormatToken &Tok) {
2012 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2013 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2016 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2017 const FormatToken &Right) {
2018 const FormatToken &Left = *Right.Previous;
2019 if (Right.NewlinesBefore > 1)
2022 if (Style.Language == FormatStyle::LK_JavaScript) {
2023 // FIXME: This might apply to other languages and token kinds.
2024 if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
2025 Left.Previous->is(tok::char_constant))
2027 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2028 Left.Previous && Left.Previous->is(tok::equal) &&
2029 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2031 // kw_var is a pseudo-token that's a tok::identifier, so matches above.
2032 !Line.startsWith(Keywords.kw_var))
2033 // Object literals on the top level of a file are treated as "enum-style".
2034 // Each key/value pair is put on a separate line, instead of bin-packing.
2036 if (Left.is(tok::l_brace) && Line.Level == 0 &&
2037 (Line.startsWith(tok::kw_enum) ||
2038 Line.startsWith(tok::kw_export, tok::kw_enum)))
2039 // JavaScript top-level enum key/value pairs are put on separate lines
2040 // instead of bin-packing.
2042 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2043 !Left.Children.empty())
2044 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2045 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2046 (Left.NestingLevel == 0 && Line.Level == 0 &&
2047 Style.AllowShortFunctionsOnASingleLine ==
2048 FormatStyle::SFS_Inline);
2049 } else if (Style.Language == FormatStyle::LK_Java) {
2050 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2051 Right.Next->is(tok::string_literal))
2055 // If the last token before a '}' is a comma or a trailing comment, the
2056 // intention is to insert a line break after it in order to make shuffling
2057 // around entries easier.
2058 const FormatToken *BeforeClosingBrace = nullptr;
2059 if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
2060 Left.BlockKind != BK_Block && Left.MatchingParen)
2061 BeforeClosingBrace = Left.MatchingParen->Previous;
2062 else if (Right.MatchingParen &&
2063 Right.MatchingParen->isOneOf(tok::l_brace,
2064 TT_ArrayInitializerLSquare))
2065 BeforeClosingBrace = &Left;
2066 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2067 BeforeClosingBrace->isTrailingComment()))
2070 if (Right.is(tok::comment))
2071 return Left.BlockKind != BK_BracedInit &&
2072 Left.isNot(TT_CtorInitializerColon) &&
2073 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2074 if (Left.isTrailingComment())
2076 if (Left.isStringLiteral() &&
2077 (Right.isStringLiteral() || Right.is(TT_ObjCStringLiteral)))
2079 if (Right.Previous->IsUnterminatedLiteral)
2081 if (Right.is(tok::lessless) && Right.Next &&
2082 Right.Previous->is(tok::string_literal) &&
2083 Right.Next->is(tok::string_literal))
2085 if (Right.Previous->ClosesTemplateDeclaration &&
2086 Right.Previous->MatchingParen &&
2087 Right.Previous->MatchingParen->NestingLevel == 0 &&
2088 Style.AlwaysBreakTemplateDeclarations)
2090 if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
2091 Style.BreakConstructorInitializersBeforeComma &&
2092 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2094 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2095 // Raw string literals are special wrt. line breaks. The author has made a
2096 // deliberate choice and might have aligned the contents of the string
2097 // literal accordingly. Thus, we try keep existing line breaks.
2098 return Right.NewlinesBefore > 0;
2099 if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
2100 Style.Language == FormatStyle::LK_Proto)
2101 // Don't put enums onto single lines in protocol buffers.
2103 if (Right.is(TT_InlineASMBrace))
2104 return Right.HasUnescapedNewline;
2105 if (isAllmanBrace(Left) || isAllmanBrace(Right))
2106 return Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
2107 Style.BreakBeforeBraces == FormatStyle::BS_GNU;
2108 if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) &&
2109 Right.is(TT_SelectorName))
2111 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2114 if ((Style.Language == FormatStyle::LK_Java ||
2115 Style.Language == FormatStyle::LK_JavaScript) &&
2116 Left.is(TT_LeadingJavaAnnotation) &&
2117 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2118 Line.Last->is(tok::l_brace))
2124 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2125 const FormatToken &Right) {
2126 const FormatToken &Left = *Right.Previous;
2128 // Language-specific stuff.
2129 if (Style.Language == FormatStyle::LK_Java) {
2130 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2131 Keywords.kw_implements))
2133 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2134 Keywords.kw_implements))
2136 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2137 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2139 if (Left.is(TT_JsTypeColon))
2143 if (Left.is(tok::at))
2145 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2147 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2148 return !Right.is(tok::l_paren);
2149 if (Right.is(TT_PointerOrReference))
2150 return Line.IsMultiVariableDeclStmt ||
2151 (Style.PointerAlignment == FormatStyle::PAS_Right &&
2152 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2153 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2154 Right.is(tok::kw_operator))
2156 if (Left.is(TT_PointerOrReference))
2158 if (Right.isTrailingComment())
2159 // We rely on MustBreakBefore being set correctly here as we should not
2160 // change the "binding" behavior of a comment.
2161 // The first comment in a braced lists is always interpreted as belonging to
2162 // the first list element. Otherwise, it should be placed outside of the
2164 return Left.BlockKind == BK_BracedInit;
2165 if (Left.is(tok::question) && Right.is(tok::colon))
2167 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2168 return Style.BreakBeforeTernaryOperators;
2169 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2170 return !Style.BreakBeforeTernaryOperators;
2171 if (Right.is(TT_InheritanceColon))
2173 if (Right.is(tok::colon) &&
2174 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2176 if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
2178 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2179 Right.Next->is(TT_ObjCMethodExpr)))
2180 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2181 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2183 if (Left.ClosesTemplateDeclaration)
2185 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2186 TT_OverloadedOperator))
2188 if (Left.is(TT_RangeBasedForLoopColon))
2190 if (Right.is(TT_RangeBasedForLoopColon))
2192 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2193 Left.is(tok::kw_operator))
2195 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2196 Line.Type == LT_VirtualFunctionDecl)
2198 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2200 if (Left.is(tok::l_paren) && Left.Previous &&
2201 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2203 if (Right.is(TT_ImplicitStringLiteral))
2206 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2209 // We only break before r_brace if there was a corresponding break before
2210 // the l_brace, which is tracked by BreakBeforeClosingBrace.
2211 if (Right.is(tok::r_brace))
2212 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2214 // Allow breaking after a trailing annotation, e.g. after a method
2216 if (Left.is(TT_TrailingAnnotation))
2217 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2218 tok::less, tok::coloncolon);
2220 if (Right.is(tok::kw___attribute))
2223 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2226 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2229 if (Left.is(TT_CtorInitializerComma) &&
2230 Style.BreakConstructorInitializersBeforeComma)
2232 if (Right.is(TT_CtorInitializerComma) &&
2233 Style.BreakConstructorInitializersBeforeComma)
2235 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2236 (Left.is(tok::less) && Right.is(tok::less)))
2238 if (Right.is(TT_BinaryOperator) &&
2239 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2240 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2241 Right.getPrecedence() != prec::Assignment))
2243 if (Left.is(TT_ArrayInitializerLSquare))
2245 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2247 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
2248 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2249 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2250 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2251 Left.getPrecedence() == prec::Assignment))
2253 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2254 tok::kw_class, tok::kw_struct) ||
2255 Right.isMemberAccess() ||
2256 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2257 tok::colon, tok::l_square, tok::at) ||
2258 (Left.is(tok::r_paren) &&
2259 Right.isOneOf(tok::identifier, tok::kw_const)) ||
2260 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
2263 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2264 llvm::errs() << "AnnotatedTokens:\n";
2265 const FormatToken *Tok = Line.First;
2267 llvm::errs() << " M=" << Tok->MustBreakBefore
2268 << " C=" << Tok->CanBreakBefore << " T=" << Tok->Type
2269 << " S=" << Tok->SpacesRequiredBefore
2270 << " B=" << Tok->BlockParameterCount
2271 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
2272 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
2274 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2275 llvm::errs() << Tok->FakeLParens[i] << "/";
2276 llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
2278 assert(Tok == Line.Last);
2281 llvm::errs() << "----\n";
2284 } // namespace format
2285 } // namespace clang