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_decltype,
124 tok::kw_if, tok::kw_while, tok::l_paren,
126 Left->Previous->is(TT_BinaryOperator))) {
127 // static_assert, if and while usually contain expressions.
128 Contexts.back().IsExpression = true;
129 } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
130 Left->Previous->MatchingParen &&
131 Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
132 // This is a parameter list of a lambda expression.
133 Contexts.back().IsExpression = false;
134 } else if (Line.InPPDirective &&
136 !Left->Previous->isOneOf(tok::identifier,
137 TT_OverloadedOperator))) {
138 Contexts.back().IsExpression = true;
139 } else if (Contexts[Contexts.size() - 2].CaretFound) {
140 // This is the parameter list of an ObjC block.
141 Contexts.back().IsExpression = false;
142 } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
143 Left->Type = TT_AttributeParen;
144 } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
145 // The first argument to a foreach macro is a declaration.
146 Contexts.back().IsForEachMacro = true;
147 Contexts.back().IsExpression = false;
148 } else if (Left->Previous && Left->Previous->MatchingParen &&
149 Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
150 Contexts.back().IsExpression = false;
153 if (StartsObjCMethodExpr) {
154 Contexts.back().ColonIsObjCMethodExpr = true;
155 Left->Type = TT_ObjCMethodExpr;
158 bool MightBeFunctionType = CurrentToken->isOneOf(tok::star, tok::amp);
159 bool HasMultipleLines = false;
160 bool HasMultipleParametersOnALine = false;
161 bool MightBeObjCForRangeLoop =
162 Left->Previous && Left->Previous->is(tok::kw_for);
163 while (CurrentToken) {
164 // LookForDecls is set when "if (" has been seen. Check for
165 // 'identifier' '*' 'identifier' followed by not '=' -- this
166 // '*' has to be a binary operator but determineStarAmpUsage() will
167 // categorize it as an unary operator, so set the right type here.
168 if (LookForDecls && CurrentToken->Next) {
169 FormatToken *Prev = CurrentToken->getPreviousNonComment();
171 FormatToken *PrevPrev = Prev->getPreviousNonComment();
172 FormatToken *Next = CurrentToken->Next;
173 if (PrevPrev && PrevPrev->is(tok::identifier) &&
174 Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
175 CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
176 Prev->Type = TT_BinaryOperator;
177 LookForDecls = false;
182 if (CurrentToken->Previous->is(TT_PointerOrReference) &&
183 CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
185 MightBeFunctionType = true;
186 if (CurrentToken->Previous->is(TT_BinaryOperator))
187 Contexts.back().IsExpression = true;
188 if (CurrentToken->is(tok::r_paren)) {
189 if (MightBeFunctionType && CurrentToken->Next &&
190 (CurrentToken->Next->is(tok::l_paren) ||
191 (CurrentToken->Next->is(tok::l_square) &&
192 !Contexts.back().IsExpression)))
193 Left->Type = TT_FunctionTypeLParen;
194 Left->MatchingParen = CurrentToken;
195 CurrentToken->MatchingParen = Left;
197 if (StartsObjCMethodExpr) {
198 CurrentToken->Type = TT_ObjCMethodExpr;
199 if (Contexts.back().FirstObjCSelectorName) {
200 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
201 Contexts.back().LongestObjCSelectorName;
205 if (Left->is(TT_AttributeParen))
206 CurrentToken->Type = TT_AttributeParen;
207 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
208 CurrentToken->Type = TT_JavaAnnotation;
209 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
210 CurrentToken->Type = TT_LeadingJavaAnnotation;
212 if (!HasMultipleLines)
213 Left->PackingKind = PPK_Inconclusive;
214 else if (HasMultipleParametersOnALine)
215 Left->PackingKind = PPK_BinPacked;
217 Left->PackingKind = PPK_OnePerLine;
222 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
225 if (CurrentToken->is(tok::l_brace))
226 Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
227 if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
228 !CurrentToken->Next->HasUnescapedNewline &&
229 !CurrentToken->Next->isTrailingComment())
230 HasMultipleParametersOnALine = true;
231 if (CurrentToken->isOneOf(tok::kw_const, tok::kw_auto) ||
232 CurrentToken->isSimpleTypeSpecifier())
233 Contexts.back().IsExpression = false;
234 if (CurrentToken->isOneOf(tok::semi, tok::colon))
235 MightBeObjCForRangeLoop = false;
236 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
237 CurrentToken->Type = TT_ObjCForIn;
238 // When we discover a 'new', we set CanBeExpression to 'false' in order to
239 // parse the type correctly. Reset that after a comma.
240 if (CurrentToken->is(tok::comma))
241 Contexts.back().CanBeExpression = true;
243 FormatToken *Tok = CurrentToken;
246 updateParameterCount(Left, Tok);
247 if (CurrentToken && CurrentToken->HasUnescapedNewline)
248 HasMultipleLines = true;
257 // A '[' could be an index subscript (after an identifier or after
258 // ')' or ']'), it could be the start of an Objective-C method
259 // expression, or it could the start of an Objective-C array literal.
260 FormatToken *Left = CurrentToken->Previous;
261 Left->ParentBracket = Contexts.back().ContextKind;
262 FormatToken *Parent = Left->getPreviousNonComment();
263 bool StartsObjCMethodExpr =
264 Style.Language == FormatStyle::LK_Cpp &&
265 Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
266 CurrentToken->isNot(tok::l_brace) &&
268 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
269 tok::kw_return, tok::kw_throw) ||
270 Parent->isUnaryOperator() ||
271 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
272 getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
273 bool ColonFound = false;
275 unsigned BindingIncrease = 1;
276 if (Left->is(TT_Unknown)) {
277 if (StartsObjCMethodExpr) {
278 Left->Type = TT_ObjCMethodExpr;
279 } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
280 Contexts.back().ContextKind == tok::l_brace &&
281 Parent->isOneOf(tok::l_brace, tok::comma)) {
282 Left->Type = TT_JsComputedPropertyName;
284 Parent->isOneOf(tok::at, tok::equal, tok::comma, tok::l_paren,
285 tok::l_square, tok::question, tok::colon,
287 Left->Type = TT_ArrayInitializerLSquare;
289 BindingIncrease = 10;
290 Left->Type = TT_ArraySubscriptLSquare;
294 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
295 Contexts.back().IsExpression = true;
296 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
298 while (CurrentToken) {
299 if (CurrentToken->is(tok::r_square)) {
300 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
301 Left->is(TT_ObjCMethodExpr)) {
302 // An ObjC method call is rarely followed by an open parenthesis.
303 // FIXME: Do we incorrectly label ":" with this?
304 StartsObjCMethodExpr = false;
305 Left->Type = TT_Unknown;
307 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
308 CurrentToken->Type = TT_ObjCMethodExpr;
309 // determineStarAmpUsage() thinks that '*' '[' is allocating an
310 // array of pointers, but if '[' starts a selector then '*' is a
312 if (Parent && Parent->is(TT_PointerOrReference))
313 Parent->Type = TT_BinaryOperator;
315 Left->MatchingParen = CurrentToken;
316 CurrentToken->MatchingParen = Left;
317 if (Contexts.back().FirstObjCSelectorName) {
318 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
319 Contexts.back().LongestObjCSelectorName;
320 if (Left->BlockParameterCount > 1)
321 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
326 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
328 if (CurrentToken->is(tok::colon)) {
329 if (Left->is(TT_ArraySubscriptLSquare)) {
330 Left->Type = TT_ObjCMethodExpr;
331 StartsObjCMethodExpr = true;
332 Contexts.back().ColonIsObjCMethodExpr = true;
333 if (Parent && Parent->is(tok::r_paren))
334 Parent->Type = TT_CastRParen;
338 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
340 Left->Type = TT_ArrayInitializerLSquare;
341 FormatToken *Tok = CurrentToken;
344 updateParameterCount(Left, Tok);
351 FormatToken *Left = CurrentToken->Previous;
352 Left->ParentBracket = Contexts.back().ContextKind;
354 if (Contexts.back().CaretFound)
355 Left->Type = TT_ObjCBlockLBrace;
356 Contexts.back().CaretFound = false;
358 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
359 Contexts.back().ColonIsDictLiteral = true;
360 if (Left->BlockKind == BK_BracedInit)
361 Contexts.back().IsExpression = true;
363 while (CurrentToken) {
364 if (CurrentToken->is(tok::r_brace)) {
365 Left->MatchingParen = CurrentToken;
366 CurrentToken->MatchingParen = Left;
370 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
372 updateParameterCount(Left, CurrentToken);
373 if (CurrentToken->isOneOf(tok::colon, tok::l_brace)) {
374 FormatToken *Previous = CurrentToken->getPreviousNonComment();
375 if (((CurrentToken->is(tok::colon) &&
376 (!Contexts.back().ColonIsDictLiteral ||
377 Style.Language != FormatStyle::LK_Cpp)) ||
378 Style.Language == FormatStyle::LK_Proto) &&
379 Previous->Tok.getIdentifierInfo())
380 Previous->Type = TT_SelectorName;
381 if (CurrentToken->is(tok::colon) ||
382 Style.Language == FormatStyle::LK_JavaScript)
383 Left->Type = TT_DictLiteral;
392 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
393 if (Current->is(tok::l_brace) && !Current->is(TT_DictLiteral))
394 ++Left->BlockParameterCount;
395 if (Current->is(tok::comma)) {
396 ++Left->ParameterCount;
398 Left->Role.reset(new CommaSeparatedList(Style));
399 Left->Role->CommaFound(Current);
400 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
401 Left->ParameterCount = 1;
405 bool parseConditional() {
406 while (CurrentToken) {
407 if (CurrentToken->is(tok::colon)) {
408 CurrentToken->Type = TT_ConditionalExpr;
418 bool parseTemplateDeclaration() {
419 if (CurrentToken && CurrentToken->is(tok::less)) {
420 CurrentToken->Type = TT_TemplateOpener;
425 CurrentToken->Previous->ClosesTemplateDeclaration = true;
431 bool consumeToken() {
432 FormatToken *Tok = CurrentToken;
434 switch (Tok->Tok.getKind()) {
437 if (!Tok->Previous && Line.MustBeDeclaration)
438 Tok->Type = TT_ObjCMethodSpecifier;
443 // Colons from ?: are handled in parseConditional().
444 if (Style.Language == FormatStyle::LK_JavaScript) {
445 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
446 (Contexts.size() == 1 && // switch/case labels
447 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
448 Contexts.back().ContextKind == tok::l_paren || // function params
449 Contexts.back().ContextKind == tok::l_square || // array type
450 (Contexts.size() == 1 &&
451 Line.MustBeDeclaration)) { // method/property declaration
452 Tok->Type = TT_JsTypeColon;
456 if (Contexts.back().ColonIsDictLiteral) {
457 Tok->Type = TT_DictLiteral;
458 } else if (Contexts.back().ColonIsObjCMethodExpr ||
459 Line.startsWith(TT_ObjCMethodSpecifier)) {
460 Tok->Type = TT_ObjCMethodExpr;
461 Tok->Previous->Type = TT_SelectorName;
462 if (Tok->Previous->ColumnWidth >
463 Contexts.back().LongestObjCSelectorName) {
464 Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth;
466 if (!Contexts.back().FirstObjCSelectorName)
467 Contexts.back().FirstObjCSelectorName = Tok->Previous;
468 } else if (Contexts.back().ColonIsForRangeExpr) {
469 Tok->Type = TT_RangeBasedForLoopColon;
470 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
471 Tok->Type = TT_BitFieldColon;
472 } else if (Contexts.size() == 1 &&
473 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
474 if (Tok->Previous->is(tok::r_paren))
475 Tok->Type = TT_CtorInitializerColon;
477 Tok->Type = TT_InheritanceColon;
478 } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
479 Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
480 // This handles a special macro in ObjC code where selectors including
481 // the colon are passed as macro arguments.
482 Tok->Type = TT_ObjCMethodExpr;
483 } else if (Contexts.back().ContextKind == tok::l_paren) {
484 Tok->Type = TT_InlineASMColon;
489 if (CurrentToken && CurrentToken->is(tok::l_paren)) {
491 if (!parseParens(/*LookForDecls=*/true))
496 Contexts.back().ColonIsForRangeExpr = true;
502 // When faced with 'operator()()', the kw_operator handler incorrectly
503 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
504 // the first two parens OverloadedOperators and the second l_paren an
505 // OverloadedOperatorLParen.
507 Tok->Previous->is(tok::r_paren) &&
508 Tok->Previous->MatchingParen &&
509 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
510 Tok->Previous->Type = TT_OverloadedOperator;
511 Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
512 Tok->Type = TT_OverloadedOperatorLParen;
517 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
518 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
520 !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
521 TT_LeadingJavaAnnotation)))
522 Line.MightBeFunctionDecl = true;
533 if (!NonTemplateLess.count(Tok) &&
535 (!Tok->Previous->Tok.isLiteral() &&
536 !(Tok->Previous->is(tok::r_paren) && Contexts.size() > 1))) &&
538 Tok->Type = TT_TemplateOpener;
540 Tok->Type = TT_BinaryOperator;
541 NonTemplateLess.insert(Tok);
550 // Lines can start with '}'.
555 Tok->Type = TT_BinaryOperator;
557 case tok::kw_operator:
558 while (CurrentToken &&
559 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
560 if (CurrentToken->isOneOf(tok::star, tok::amp))
561 CurrentToken->Type = TT_PointerOrReference;
563 if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator))
564 CurrentToken->Previous->Type = TT_OverloadedOperator;
567 CurrentToken->Type = TT_OverloadedOperatorLParen;
568 if (CurrentToken->Previous->is(TT_BinaryOperator))
569 CurrentToken->Previous->Type = TT_OverloadedOperator;
573 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
574 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
576 // Question marks before semicolons, colons, etc. indicate optional
577 // types (fields, parameters), e.g.
578 // function(x?: string, y?) {...}
580 Tok->Type = TT_JsTypeOptionalQuestion;
583 // Declarations cannot be conditional expressions, this can only be part
584 // of a type declaration.
585 if (Line.MustBeDeclaration &&
586 Style.Language == FormatStyle::LK_JavaScript)
590 case tok::kw_template:
591 parseTemplateDeclaration();
594 if (Contexts.back().InCtorInitializer)
595 Tok->Type = TT_CtorInitializerComma;
596 else if (Contexts.back().FirstStartOfName &&
597 (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
598 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
599 Line.IsMultiVariableDeclStmt = true;
601 if (Contexts.back().IsForEachMacro)
602 Contexts.back().IsExpression = true;
610 void parseIncludeDirective() {
611 if (CurrentToken && CurrentToken->is(tok::less)) {
613 while (CurrentToken) {
614 if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
615 CurrentToken->Type = TT_ImplicitStringLiteral;
621 void parseWarningOrError() {
623 // We still want to format the whitespace left of the first token of the
626 while (CurrentToken) {
627 CurrentToken->Type = TT_ImplicitStringLiteral;
633 next(); // Consume "pragma".
635 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
636 bool IsMark = CurrentToken->is(Keywords.kw_mark);
637 next(); // Consume "mark".
638 next(); // Consume first token (so we fix leading whitespace).
639 while (CurrentToken) {
640 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
641 CurrentToken->Type = TT_ImplicitStringLiteral;
647 LineType parsePreprocessorDirective() {
648 LineType Type = LT_PreprocessorDirective;
652 if (CurrentToken->Tok.is(tok::numeric_constant)) {
653 CurrentToken->SpacesRequiredBefore = 1;
656 // Hashes in the middle of a line can lead to any strange token
658 if (!CurrentToken->Tok.getIdentifierInfo())
660 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
661 case tok::pp_include:
662 case tok::pp_include_next:
665 parseIncludeDirective();
666 Type = LT_ImportStatement;
669 case tok::pp_warning:
670 parseWarningOrError();
677 Contexts.back().IsExpression = true;
689 LineType parseLine() {
690 NonTemplateLess.clear();
691 if (CurrentToken->is(tok::hash))
692 return parsePreprocessorDirective();
694 // Directly allow to 'import <string-literal>' to support protocol buffer
695 // definitions (code.google.com/p/protobuf) or missing "#" (either way we
696 // should not break the line).
697 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
698 if ((Style.Language == FormatStyle::LK_Java &&
699 CurrentToken->is(Keywords.kw_package)) ||
700 (Info && Info->getPPKeywordID() == tok::pp_import &&
701 CurrentToken->Next &&
702 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
705 parseIncludeDirective();
706 return LT_ImportStatement;
709 // If this line starts and ends in '<' and '>', respectively, it is likely
710 // part of "#define <a/b.h>".
711 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
712 parseIncludeDirective();
713 return LT_ImportStatement;
716 // In .proto files, top-level options are very similar to import statements
717 // and should not be line-wrapped.
718 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
719 CurrentToken->is(Keywords.kw_option)) {
721 if (CurrentToken && CurrentToken->is(tok::identifier))
722 return LT_ImportStatement;
725 bool KeywordVirtualFound = false;
726 bool ImportStatement = false;
727 while (CurrentToken) {
728 if (CurrentToken->is(tok::kw_virtual))
729 KeywordVirtualFound = true;
730 if (isImportStatement(*CurrentToken))
731 ImportStatement = true;
735 if (KeywordVirtualFound)
736 return LT_VirtualFunctionDecl;
738 return LT_ImportStatement;
740 if (Line.startsWith(TT_ObjCMethodSpecifier)) {
741 if (Contexts.back().FirstObjCSelectorName)
742 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
743 Contexts.back().LongestObjCSelectorName;
744 return LT_ObjCMethodDecl;
751 bool isImportStatement(const FormatToken &Tok) {
752 // FIXME: Closure-library specific stuff should not be hard-coded but be
754 return Style.Language == FormatStyle::LK_JavaScript &&
755 Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
756 Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
757 Tok.Next->Next->TokenText == "provide" ||
758 Tok.Next->Next->TokenText == "require" ||
759 Tok.Next->Next->TokenText == "setTestOnly") &&
760 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
763 void resetTokenMetadata(FormatToken *Token) {
767 // Reset token type in case we have already looked at it and then
768 // recovered from an error (e.g. failure to find the matching >).
769 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
770 TT_FunctionLBrace, TT_ImplicitStringLiteral,
771 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
773 CurrentToken->Type = TT_Unknown;
774 CurrentToken->Role.reset();
775 CurrentToken->MatchingParen = nullptr;
776 CurrentToken->FakeLParens.clear();
777 CurrentToken->FakeRParens = 0;
782 CurrentToken->NestingLevel = Contexts.size() - 1;
783 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
784 modifyContext(*CurrentToken);
785 determineTokenType(*CurrentToken);
786 CurrentToken = CurrentToken->Next;
789 resetTokenMetadata(CurrentToken);
792 /// \brief A struct to hold information valid in a specific context, e.g.
793 /// a pair of parenthesis.
795 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
797 : ContextKind(ContextKind), BindingStrength(BindingStrength),
798 IsExpression(IsExpression) {}
800 tok::TokenKind ContextKind;
801 unsigned BindingStrength;
803 unsigned LongestObjCSelectorName = 0;
804 bool ColonIsForRangeExpr = false;
805 bool ColonIsDictLiteral = false;
806 bool ColonIsObjCMethodExpr = false;
807 FormatToken *FirstObjCSelectorName = nullptr;
808 FormatToken *FirstStartOfName = nullptr;
809 bool CanBeExpression = true;
810 bool InTemplateArgument = false;
811 bool InCtorInitializer = false;
812 bool CaretFound = false;
813 bool IsForEachMacro = false;
816 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
817 /// of each instance.
818 struct ScopedContextCreator {
821 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
824 P.Contexts.push_back(Context(ContextKind,
825 P.Contexts.back().BindingStrength + Increase,
826 P.Contexts.back().IsExpression));
829 ~ScopedContextCreator() { P.Contexts.pop_back(); }
832 void modifyContext(const FormatToken &Current) {
833 if (Current.getPrecedence() == prec::Assignment &&
834 !Line.First->isOneOf(tok::kw_template, tok::kw_using) &&
835 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
836 Contexts.back().IsExpression = true;
837 if (!Line.startsWith(TT_UnaryOperator)) {
838 for (FormatToken *Previous = Current.Previous;
839 Previous && Previous->Previous &&
840 !Previous->Previous->isOneOf(tok::comma, tok::semi);
841 Previous = Previous->Previous) {
842 if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
843 Previous = Previous->MatchingParen;
847 if (Previous->opensScope())
849 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
850 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
851 Previous->Previous && Previous->Previous->isNot(tok::equal))
852 Previous->Type = TT_PointerOrReference;
855 } else if (Current.is(tok::lessless) &&
856 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
857 Contexts.back().IsExpression = true;
858 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
859 Contexts.back().IsExpression = true;
860 } else if (Current.is(TT_TrailingReturnArrow)) {
861 Contexts.back().IsExpression = false;
862 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
863 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
864 } else if (Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
865 !Line.InPPDirective &&
866 (!Current.Previous ||
867 Current.Previous->isNot(tok::kw_decltype))) {
868 bool ParametersOfFunctionType =
869 Current.Previous && Current.Previous->is(tok::r_paren) &&
870 Current.Previous->MatchingParen &&
871 Current.Previous->MatchingParen->is(TT_FunctionTypeLParen);
872 bool IsForOrCatch = Current.Previous &&
873 Current.Previous->isOneOf(tok::kw_for, tok::kw_catch);
874 Contexts.back().IsExpression = !ParametersOfFunctionType && !IsForOrCatch;
875 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
876 for (FormatToken *Previous = Current.Previous;
877 Previous && Previous->isOneOf(tok::star, tok::amp);
878 Previous = Previous->Previous)
879 Previous->Type = TT_PointerOrReference;
880 if (Line.MustBeDeclaration)
881 Contexts.back().IsExpression = Contexts.front().InCtorInitializer;
882 } else if (Current.Previous &&
883 Current.Previous->is(TT_CtorInitializerColon)) {
884 Contexts.back().IsExpression = true;
885 Contexts.back().InCtorInitializer = true;
886 } else if (Current.is(tok::kw_new)) {
887 Contexts.back().CanBeExpression = false;
888 } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
889 // This should be the condition or increment in a for-loop.
890 Contexts.back().IsExpression = true;
894 void determineTokenType(FormatToken &Current) {
895 if (!Current.is(TT_Unknown))
896 // The token type is already known.
899 // Line.MightBeFunctionDecl can only be true after the parentheses of a
900 // function declaration have been found. In this case, 'Current' is a
901 // trailing token of this declaration and thus cannot be a name.
902 if (Current.is(Keywords.kw_instanceof)) {
903 Current.Type = TT_BinaryOperator;
904 } else if (isStartOfName(Current) &&
905 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
906 Contexts.back().FirstStartOfName = &Current;
907 Current.Type = TT_StartOfName;
908 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
910 } else if (Current.is(tok::arrow) &&
911 Style.Language == FormatStyle::LK_Java) {
912 Current.Type = TT_LambdaArrow;
913 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
914 Current.NestingLevel == 0) {
915 Current.Type = TT_TrailingReturnArrow;
916 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
918 determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
919 Contexts.back().IsExpression,
920 Contexts.back().InTemplateArgument);
921 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
922 Current.Type = determinePlusMinusCaretUsage(Current);
923 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
924 Contexts.back().CaretFound = true;
925 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
926 Current.Type = determineIncrementUsage(Current);
927 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
928 Current.Type = TT_UnaryOperator;
929 } else if (Current.is(tok::question)) {
930 if (Style.Language == FormatStyle::LK_JavaScript &&
931 Line.MustBeDeclaration) {
932 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
933 // on the interface, not a ternary expression.
934 Current.Type = TT_JsTypeOptionalQuestion;
936 Current.Type = TT_ConditionalExpr;
938 } else if (Current.isBinaryOperator() &&
939 (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
940 Current.Type = TT_BinaryOperator;
941 } else if (Current.is(tok::comment)) {
942 if (Current.TokenText.startswith("/*")) {
943 if (Current.TokenText.endswith("*/"))
944 Current.Type = TT_BlockComment;
946 // The lexer has for some reason determined a comment here. But we
947 // cannot really handle it, if it isn't properly terminated.
948 Current.Tok.setKind(tok::unknown);
950 Current.Type = TT_LineComment;
952 } else if (Current.is(tok::r_paren)) {
953 if (rParenEndsCast(Current))
954 Current.Type = TT_CastRParen;
955 if (Current.MatchingParen && Current.Next &&
956 !Current.Next->isBinaryOperator() &&
957 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace))
958 if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
959 if (BeforeParen->is(tok::identifier) &&
960 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
961 (!BeforeParen->Previous ||
962 BeforeParen->Previous->ClosesTemplateDeclaration))
963 Current.Type = TT_FunctionAnnotationRParen;
964 } else if (Current.is(tok::at) && Current.Next) {
965 if (Current.Next->isStringLiteral()) {
966 Current.Type = TT_ObjCStringLiteral;
968 switch (Current.Next->Tok.getObjCKeywordID()) {
969 case tok::objc_interface:
970 case tok::objc_implementation:
971 case tok::objc_protocol:
972 Current.Type = TT_ObjCDecl;
974 case tok::objc_property:
975 Current.Type = TT_ObjCProperty;
981 } else if (Current.is(tok::period)) {
982 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
983 if (PreviousNoComment &&
984 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
985 Current.Type = TT_DesignatedInitializerPeriod;
986 else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
987 Current.Previous->isOneOf(TT_JavaAnnotation,
988 TT_LeadingJavaAnnotation)) {
989 Current.Type = Current.Previous->Type;
991 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
993 !Current.Previous->isOneOf(tok::equal, tok::at) &&
994 Line.MightBeFunctionDecl && Contexts.size() == 1) {
995 // Line.MightBeFunctionDecl can only be true after the parentheses of a
996 // function declaration have been found.
997 Current.Type = TT_TrailingAnnotation;
998 } else if ((Style.Language == FormatStyle::LK_Java ||
999 Style.Language == FormatStyle::LK_JavaScript) &&
1001 if (Current.Previous->is(tok::at) &&
1002 Current.isNot(Keywords.kw_interface)) {
1003 const FormatToken &AtToken = *Current.Previous;
1004 const FormatToken *Previous = AtToken.getPreviousNonComment();
1005 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1006 Current.Type = TT_LeadingJavaAnnotation;
1008 Current.Type = TT_JavaAnnotation;
1009 } else if (Current.Previous->is(tok::period) &&
1010 Current.Previous->isOneOf(TT_JavaAnnotation,
1011 TT_LeadingJavaAnnotation)) {
1012 Current.Type = Current.Previous->Type;
1017 /// \brief Take a guess at whether \p Tok starts a name of a function or
1018 /// variable declaration.
1020 /// This is a heuristic based on whether \p Tok is an identifier following
1021 /// something that is likely a type.
1022 bool isStartOfName(const FormatToken &Tok) {
1023 if (Tok.isNot(tok::identifier) || !Tok.Previous)
1026 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof))
1029 // Skip "const" as it does not have an influence on whether this is a name.
1030 FormatToken *PreviousNotConst = Tok.Previous;
1031 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1032 PreviousNotConst = PreviousNotConst->Previous;
1034 if (!PreviousNotConst)
1037 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1038 PreviousNotConst->Previous &&
1039 PreviousNotConst->Previous->is(tok::hash);
1041 if (PreviousNotConst->is(TT_TemplateCloser))
1042 return PreviousNotConst && PreviousNotConst->MatchingParen &&
1043 PreviousNotConst->MatchingParen->Previous &&
1044 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1045 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1047 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1048 PreviousNotConst->MatchingParen->Previous &&
1049 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1052 return (!IsPPKeyword &&
1053 PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1054 PreviousNotConst->is(TT_PointerOrReference) ||
1055 PreviousNotConst->isSimpleTypeSpecifier();
1058 /// \brief Determine whether ')' is ending a cast.
1059 bool rParenEndsCast(const FormatToken &Tok) {
1060 // C-style casts are only used in C++ and Java.
1061 if (Style.Language != FormatStyle::LK_Cpp &&
1062 Style.Language != FormatStyle::LK_Java)
1065 // Empty parens aren't casts and there are no casts at the end of the line.
1066 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1069 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1071 // If there is an identifier (or with a few exceptions a keyword) right
1072 // before the parentheses, this is unlikely to be a cast.
1073 if (LeftOfParens->Tok.getIdentifierInfo() &&
1074 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1078 // Certain other tokens right before the parentheses are also signals that
1079 // this cannot be a cast.
1080 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1085 if (Tok.Next->is(tok::question))
1088 // As Java has no function types, a "(" after the ")" likely means that this
1090 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1093 // If a (non-string) literal follows, this is likely a cast.
1094 if (Tok.Next->isNot(tok::string_literal) &&
1095 (Tok.Next->Tok.isLiteral() ||
1096 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1099 // Heuristically try to determine whether the parentheses contain a type.
1100 bool ParensAreType =
1102 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1103 Tok.Previous->isSimpleTypeSpecifier();
1104 bool ParensCouldEndDecl =
1105 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1106 if (ParensAreType && !ParensCouldEndDecl &&
1107 (Contexts.size() > 1 && Contexts[Contexts.size() - 2].IsExpression))
1110 // At this point, we heuristically assume that there are no casts at the
1111 // start of the line. We assume that we have found most cases where there
1112 // are by the logic above, e.g. "(void)x;".
1116 // If the following token is an identifier, this is a cast. All cases where
1117 // this can be something else are handled above.
1118 if (Tok.Next->is(tok::identifier))
1121 if (!Tok.Next->Next)
1124 // If the next token after the parenthesis is a unary operator, assume
1125 // that this is cast, unless there are unexpected tokens inside the
1128 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1129 if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1130 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1132 // Search for unexpected tokens.
1133 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1134 Prev = Prev->Previous) {
1135 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1141 /// \brief Return the type of the given token assuming it is * or &.
1142 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1143 bool InTemplateArgument) {
1144 if (Style.Language == FormatStyle::LK_JavaScript)
1145 return TT_BinaryOperator;
1147 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1149 return TT_UnaryOperator;
1151 const FormatToken *NextToken = Tok.getNextNonComment();
1153 NextToken->isOneOf(tok::arrow, Keywords.kw_final,
1154 Keywords.kw_override) ||
1155 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1156 return TT_PointerOrReference;
1158 if (PrevToken->is(tok::coloncolon))
1159 return TT_PointerOrReference;
1161 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1162 tok::comma, tok::semi, tok::kw_return, tok::colon,
1163 tok::equal, tok::kw_delete, tok::kw_sizeof) ||
1164 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1165 TT_UnaryOperator, TT_CastRParen))
1166 return TT_UnaryOperator;
1168 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1169 return TT_PointerOrReference;
1170 if (NextToken->is(tok::kw_operator) && !IsExpression)
1171 return TT_PointerOrReference;
1172 if (NextToken->isOneOf(tok::comma, tok::semi))
1173 return TT_PointerOrReference;
1175 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
1176 PrevToken->MatchingParen->Previous &&
1177 PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
1179 return TT_PointerOrReference;
1181 if (PrevToken->Tok.isLiteral() ||
1182 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1183 tok::kw_false, tok::r_brace) ||
1184 NextToken->Tok.isLiteral() ||
1185 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1186 NextToken->isUnaryOperator() ||
1187 // If we know we're in a template argument, there are no named
1188 // declarations. Thus, having an identifier on the right-hand side
1189 // indicates a binary operator.
1190 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1191 return TT_BinaryOperator;
1193 // "&&(" is quite unlikely to be two successive unary "&".
1194 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1195 return TT_BinaryOperator;
1197 // This catches some cases where evaluation order is used as control flow:
1199 const FormatToken *NextNextToken = NextToken->getNextNonComment();
1200 if (NextNextToken && NextNextToken->is(tok::arrow))
1201 return TT_BinaryOperator;
1203 // It is very unlikely that we are going to find a pointer or reference type
1204 // definition on the RHS of an assignment.
1205 if (IsExpression && !Contexts.back().CaretFound)
1206 return TT_BinaryOperator;
1208 return TT_PointerOrReference;
1211 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1212 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1213 if (!PrevToken || PrevToken->is(TT_CastRParen))
1214 return TT_UnaryOperator;
1216 // Use heuristics to recognize unary operators.
1217 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1218 tok::question, tok::colon, tok::kw_return,
1219 tok::kw_case, tok::at, tok::l_brace))
1220 return TT_UnaryOperator;
1222 // There can't be two consecutive binary operators.
1223 if (PrevToken->is(TT_BinaryOperator))
1224 return TT_UnaryOperator;
1226 // Fall back to marking the token as binary operator.
1227 return TT_BinaryOperator;
1230 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1231 TokenType determineIncrementUsage(const FormatToken &Tok) {
1232 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1233 if (!PrevToken || PrevToken->is(TT_CastRParen))
1234 return TT_UnaryOperator;
1235 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1236 return TT_TrailingUnaryOperator;
1238 return TT_UnaryOperator;
1241 SmallVector<Context, 8> Contexts;
1243 const FormatStyle &Style;
1244 AnnotatedLine &Line;
1245 FormatToken *CurrentToken;
1247 const AdditionalKeywords &Keywords;
1249 // Set of "<" tokens that do not open a template parameter list. If parseAngle
1250 // determines that a specific token can't be a template opener, it will make
1251 // same decision irrespective of the decisions for tokens leading up to it.
1252 // Store this information to prevent this from causing exponential runtime.
1253 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1256 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1257 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1259 /// \brief Parses binary expressions by inserting fake parenthesis based on
1260 /// operator precedence.
1261 class ExpressionParser {
1263 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1264 AnnotatedLine &Line)
1265 : Style(Style), Keywords(Keywords), Current(Line.First) {}
1267 /// \brief Parse expressions with the given operatore precedence.
1268 void parse(int Precedence = 0) {
1269 // Skip 'return' and ObjC selector colons as they are not part of a binary
1271 while (Current && (Current->is(tok::kw_return) ||
1272 (Current->is(tok::colon) &&
1273 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1276 if (!Current || Precedence > PrecedenceArrowAndPeriod)
1279 // Conditional expressions need to be parsed separately for proper nesting.
1280 if (Precedence == prec::Conditional) {
1281 parseConditionalExpr();
1285 // Parse unary operators, which all have a higher precedence than binary
1287 if (Precedence == PrecedenceUnaryOperator) {
1288 parseUnaryOperator();
1292 FormatToken *Start = Current;
1293 FormatToken *LatestOperator = nullptr;
1294 unsigned OperatorIndex = 0;
1297 // Consume operators with higher precedence.
1298 parse(Precedence + 1);
1300 int CurrentPrecedence = getCurrentPrecedence();
1302 if (Current && Current->is(TT_SelectorName) &&
1303 Precedence == CurrentPrecedence) {
1305 addFakeParenthesis(Start, prec::Level(Precedence));
1309 // At the end of the line or when an operator with higher precedence is
1310 // found, insert fake parenthesis and return.
1311 if (!Current || (Current->closesScope() && Current->MatchingParen) ||
1312 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1313 (CurrentPrecedence == prec::Conditional &&
1314 Precedence == prec::Assignment && Current->is(tok::colon))) {
1318 // Consume scopes: (), [], <> and {}
1319 if (Current->opensScope()) {
1320 while (Current && !Current->closesScope()) {
1327 if (CurrentPrecedence == Precedence) {
1328 LatestOperator = Current;
1329 Current->OperatorIndex = OperatorIndex;
1332 next(/*SkipPastLeadingComments=*/Precedence > 0);
1336 if (LatestOperator && (Current || Precedence > 0)) {
1337 LatestOperator->LastOperator = true;
1338 if (Precedence == PrecedenceArrowAndPeriod) {
1339 // Call expressions don't have a binary operator precedence.
1340 addFakeParenthesis(Start, prec::Unknown);
1342 addFakeParenthesis(Start, prec::Level(Precedence));
1348 /// \brief Gets the precedence (+1) of the given token for binary operators
1349 /// and other tokens that we treat like binary operators.
1350 int getCurrentPrecedence() {
1352 const FormatToken *NextNonComment = Current->getNextNonComment();
1353 if (Current->is(TT_ConditionalExpr))
1354 return prec::Conditional;
1355 if (NextNonComment && NextNonComment->is(tok::colon) &&
1356 NextNonComment->is(TT_DictLiteral))
1358 if (Current->is(TT_LambdaArrow))
1360 if (Current->is(TT_JsFatArrow))
1361 return prec::Assignment;
1362 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName,
1363 TT_JsComputedPropertyName) ||
1364 (Current->is(tok::comment) && NextNonComment &&
1365 NextNonComment->is(TT_SelectorName)))
1367 if (Current->is(TT_RangeBasedForLoopColon))
1369 if ((Style.Language == FormatStyle::LK_Java ||
1370 Style.Language == FormatStyle::LK_JavaScript) &&
1371 Current->is(Keywords.kw_instanceof))
1372 return prec::Relational;
1373 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1374 return Current->getPrecedence();
1375 if (Current->isOneOf(tok::period, tok::arrow))
1376 return PrecedenceArrowAndPeriod;
1377 if (Style.Language == FormatStyle::LK_Java &&
1378 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1379 Keywords.kw_throws))
1385 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1386 Start->FakeLParens.push_back(Precedence);
1387 if (Precedence > prec::Unknown)
1388 Start->StartsBinaryExpression = true;
1390 FormatToken *Previous = Current->Previous;
1391 while (Previous->is(tok::comment) && Previous->Previous)
1392 Previous = Previous->Previous;
1393 ++Previous->FakeRParens;
1394 if (Precedence > prec::Unknown)
1395 Previous->EndsBinaryExpression = true;
1399 /// \brief Parse unary operator expressions and surround them with fake
1400 /// parentheses if appropriate.
1401 void parseUnaryOperator() {
1402 if (!Current || Current->isNot(TT_UnaryOperator)) {
1403 parse(PrecedenceArrowAndPeriod);
1407 FormatToken *Start = Current;
1409 parseUnaryOperator();
1411 // The actual precedence doesn't matter.
1412 addFakeParenthesis(Start, prec::Unknown);
1415 void parseConditionalExpr() {
1416 while (Current && Current->isTrailingComment()) {
1419 FormatToken *Start = Current;
1420 parse(prec::LogicalOr);
1421 if (!Current || !Current->is(tok::question))
1424 parse(prec::Assignment);
1425 if (!Current || Current->isNot(TT_ConditionalExpr))
1428 parse(prec::Assignment);
1429 addFakeParenthesis(Start, prec::Conditional);
1432 void next(bool SkipPastLeadingComments = true) {
1434 Current = Current->Next;
1436 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1437 Current->isTrailingComment())
1438 Current = Current->Next;
1441 const FormatStyle &Style;
1442 const AdditionalKeywords &Keywords;
1443 FormatToken *Current;
1446 } // end anonymous namespace
1448 void TokenAnnotator::setCommentLineLevels(
1449 SmallVectorImpl<AnnotatedLine *> &Lines) {
1450 const AnnotatedLine *NextNonCommentLine = nullptr;
1451 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1454 if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
1455 (*I)->First->Next == nullptr)
1456 (*I)->Level = NextNonCommentLine->Level;
1458 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1460 setCommentLineLevels((*I)->Children);
1464 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1465 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1466 E = Line.Children.end();
1470 AnnotatingParser Parser(Style, Line, Keywords);
1471 Line.Type = Parser.parseLine();
1472 if (Line.Type == LT_Invalid)
1475 ExpressionParser ExprParser(Style, Keywords, Line);
1478 if (Line.startsWith(TT_ObjCMethodSpecifier))
1479 Line.Type = LT_ObjCMethodDecl;
1480 else if (Line.startsWith(TT_ObjCDecl))
1481 Line.Type = LT_ObjCDecl;
1482 else if (Line.startsWith(TT_ObjCProperty))
1483 Line.Type = LT_ObjCProperty;
1485 Line.First->SpacesRequiredBefore = 1;
1486 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1489 // This function heuristically determines whether 'Current' starts the name of a
1490 // function declaration.
1491 static bool isFunctionDeclarationName(const FormatToken &Current) {
1492 auto skipOperatorName = [](const FormatToken* Next) -> const FormatToken* {
1493 for (; Next; Next = Next->Next) {
1494 if (Next->is(TT_OverloadedOperatorLParen))
1496 if (Next->is(TT_OverloadedOperator))
1498 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1499 // For 'new[]' and 'delete[]'.
1500 if (Next->Next && Next->Next->is(tok::l_square) &&
1501 Next->Next->Next && Next->Next->Next->is(tok::r_square))
1502 Next = Next->Next->Next;
1511 const FormatToken *Next = Current.Next;
1512 if (Current.is(tok::kw_operator)) {
1513 if (Current.Previous && Current.Previous->is(tok::coloncolon))
1515 Next = skipOperatorName(Next);
1517 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1519 for (; Next; Next = Next->Next) {
1520 if (Next->is(TT_TemplateOpener)) {
1521 Next = Next->MatchingParen;
1522 } else if (Next->is(tok::coloncolon)) {
1526 if (Next->is(tok::kw_operator)) {
1527 Next = skipOperatorName(Next->Next);
1530 if (!Next->is(tok::identifier))
1532 } else if (Next->is(tok::l_paren)) {
1540 if (!Next || !Next->is(tok::l_paren))
1542 if (Next->Next == Next->MatchingParen)
1544 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1546 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1547 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName))
1549 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1550 Tok->Tok.isLiteral())
1556 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1557 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1558 E = Line.Children.end();
1560 calculateFormattingInformation(**I);
1563 Line.First->TotalLength =
1564 Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1565 if (!Line.First->Next)
1567 FormatToken *Current = Line.First->Next;
1568 bool InFunctionDecl = Line.MightBeFunctionDecl;
1570 if (isFunctionDeclarationName(*Current))
1571 Current->Type = TT_FunctionDeclarationName;
1572 if (Current->is(TT_LineComment)) {
1573 if (Current->Previous->BlockKind == BK_BracedInit &&
1574 Current->Previous->opensScope())
1575 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1577 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1579 // If we find a trailing comment, iterate backwards to determine whether
1580 // it seems to relate to a specific parameter. If so, break before that
1581 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1582 // to the previous line in:
1586 if (!Current->HasUnescapedNewline) {
1587 for (FormatToken *Parameter = Current->Previous; Parameter;
1588 Parameter = Parameter->Previous) {
1589 if (Parameter->isOneOf(tok::comment, tok::r_brace))
1591 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1592 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1593 Parameter->HasUnescapedNewline)
1594 Parameter->MustBreakBefore = true;
1599 } else if (Current->SpacesRequiredBefore == 0 &&
1600 spaceRequiredBefore(Line, *Current)) {
1601 Current->SpacesRequiredBefore = 1;
1604 Current->MustBreakBefore =
1605 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1607 if ((Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All ||
1608 (Style.AlwaysBreakAfterDefinitionReturnType ==
1609 FormatStyle::DRTBS_TopLevel &&
1610 Line.Level == 0)) &&
1611 InFunctionDecl && Current->is(TT_FunctionDeclarationName) &&
1612 !Line.Last->isOneOf(tok::semi, tok::comment)) // Only for definitions.
1613 // FIXME: Line.Last points to other characters than tok::semi
1615 Current->MustBreakBefore = true;
1617 Current->CanBreakBefore =
1618 Current->MustBreakBefore || canBreakBefore(Line, *Current);
1619 unsigned ChildSize = 0;
1620 if (Current->Previous->Children.size() == 1) {
1621 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1622 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1623 : LastOfChild.TotalLength + 1;
1625 const FormatToken *Prev = Current->Previous;
1626 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1627 (Prev->Children.size() == 1 &&
1628 Prev->Children[0]->First->MustBreakBefore) ||
1629 Current->IsMultiline)
1630 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1632 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1633 ChildSize + Current->SpacesRequiredBefore;
1635 if (Current->is(TT_CtorInitializerColon))
1636 InFunctionDecl = false;
1638 // FIXME: Only calculate this if CanBreakBefore is true once static
1639 // initializers etc. are sorted out.
1640 // FIXME: Move magic numbers to a better place.
1641 Current->SplitPenalty = 20 * Current->BindingStrength +
1642 splitPenalty(Line, *Current, InFunctionDecl);
1644 Current = Current->Next;
1647 calculateUnbreakableTailLengths(Line);
1648 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1650 Current->Role->precomputeFormattingInfos(Current);
1653 DEBUG({ printDebugInfo(Line); });
1656 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1657 unsigned UnbreakableTailLength = 0;
1658 FormatToken *Current = Line.Last;
1660 Current->UnbreakableTailLength = UnbreakableTailLength;
1661 if (Current->CanBreakBefore ||
1662 Current->isOneOf(tok::comment, tok::string_literal)) {
1663 UnbreakableTailLength = 0;
1665 UnbreakableTailLength +=
1666 Current->ColumnWidth + Current->SpacesRequiredBefore;
1668 Current = Current->Previous;
1672 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1673 const FormatToken &Tok,
1674 bool InFunctionDecl) {
1675 const FormatToken &Left = *Tok.Previous;
1676 const FormatToken &Right = Tok;
1678 if (Left.is(tok::semi))
1681 if (Style.Language == FormatStyle::LK_Java) {
1682 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
1684 if (Right.is(Keywords.kw_implements))
1686 if (Left.is(tok::comma) && Left.NestingLevel == 0)
1688 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1689 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
1691 if (Left.is(TT_JsTypeColon))
1695 if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
1696 Right.Next->is(TT_DictLiteral)))
1698 if (Right.is(tok::l_square)) {
1699 if (Style.Language == FormatStyle::LK_Proto)
1701 // Slightly prefer formatting local lambda definitions like functions.
1702 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
1704 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
1705 TT_ArrayInitializerLSquare))
1709 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
1710 Right.is(tok::kw_operator)) {
1711 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1713 if (Left.is(TT_StartOfName))
1715 if (InFunctionDecl && Right.NestingLevel == 0)
1716 return Style.PenaltyReturnTypeOnItsOwnLine;
1719 if (Right.is(TT_PointerOrReference))
1721 if (Right.is(TT_LambdaArrow))
1723 if (Left.is(tok::equal) && Right.is(tok::l_brace))
1725 if (Left.is(TT_CastRParen))
1727 if (Left.is(tok::coloncolon) ||
1728 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1730 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1733 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
1736 if (Right.isMemberAccess()) {
1737 if (Left.is(tok::r_paren) && Left.MatchingParen &&
1738 Left.MatchingParen->ParameterCount > 0)
1739 return 20; // Should be smaller than breaking at a nested comma.
1743 if (Right.is(TT_TrailingAnnotation) &&
1744 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
1745 // Moving trailing annotations to the next line is fine for ObjC method
1747 if (Line.startsWith(TT_ObjCMethodSpecifier))
1749 // Generally, breaking before a trailing annotation is bad unless it is
1750 // function-like. It seems to be especially preferable to keep standard
1751 // annotations (i.e. "const", "final" and "override") on the same line.
1752 // Use a slightly higher penalty after ")" so that annotations like
1753 // "const override" are kept together.
1754 bool is_short_annotation = Right.TokenText.size() < 10;
1755 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
1758 // In for-loops, prefer breaking at ',' and ';'.
1759 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
1762 // In Objective-C method expressions, prefer breaking before "param:" over
1763 // breaking after it.
1764 if (Right.is(TT_SelectorName))
1766 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
1767 return Line.MightBeFunctionDecl ? 50 : 500;
1769 if (Left.is(tok::l_paren) && InFunctionDecl &&
1770 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
1772 if (Left.is(tok::l_paren) && Left.Previous &&
1773 Left.Previous->isOneOf(tok::kw_if, tok::kw_for))
1775 if (Left.is(tok::equal) && InFunctionDecl)
1777 if (Right.is(tok::r_brace))
1779 if (Left.is(TT_TemplateOpener))
1781 if (Left.opensScope()) {
1782 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
1784 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1787 if (Left.is(TT_JavaAnnotation))
1790 if (Right.is(tok::lessless)) {
1791 if (Left.is(tok::string_literal) &&
1792 (!Right.LastOperator || Right.OperatorIndex != 1)) {
1793 StringRef Content = Left.TokenText;
1794 if (Content.startswith("\""))
1795 Content = Content.drop_front(1);
1796 if (Content.endswith("\""))
1797 Content = Content.drop_back(1);
1798 Content = Content.trim();
1799 if (Content.size() > 1 &&
1800 (Content.back() == ':' || Content.back() == '='))
1803 return 1; // Breaking at a << is really cheap.
1805 if (Left.is(TT_ConditionalExpr))
1806 return prec::Conditional;
1807 prec::Level Level = Left.getPrecedence();
1808 if (Level != prec::Unknown)
1810 Level = Right.getPrecedence();
1811 if (Level != prec::Unknown)
1817 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1818 const FormatToken &Left,
1819 const FormatToken &Right) {
1820 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
1822 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1823 Left.Tok.getObjCKeywordID() == tok::objc_property)
1825 if (Right.is(tok::hashhash))
1826 return Left.is(tok::hash);
1827 if (Left.isOneOf(tok::hashhash, tok::hash))
1828 return Right.is(tok::hash);
1829 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
1830 return Style.SpaceInEmptyParentheses;
1831 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
1832 return (Right.is(TT_CastRParen) ||
1833 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
1834 ? Style.SpacesInCStyleCastParentheses
1835 : Style.SpacesInParentheses;
1836 if (Right.isOneOf(tok::semi, tok::comma))
1838 if (Right.is(tok::less) &&
1839 (Left.is(tok::kw_template) ||
1840 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1842 if (Left.isOneOf(tok::exclaim, tok::tilde))
1844 if (Left.is(tok::at) &&
1845 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1846 tok::numeric_constant, tok::l_paren, tok::l_brace,
1847 tok::kw_true, tok::kw_false))
1849 if (Left.is(tok::coloncolon))
1851 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
1853 if (Right.is(tok::ellipsis))
1854 return Left.Tok.isLiteral();
1855 if (Left.is(tok::l_square) && Right.is(tok::amp))
1857 if (Right.is(TT_PointerOrReference))
1858 return (Left.is(tok::r_paren) && Left.MatchingParen &&
1859 (Left.MatchingParen->is(TT_OverloadedOperatorLParen) ||
1860 (Left.MatchingParen->Previous &&
1861 Left.MatchingParen->Previous->is(TT_FunctionDeclarationName)))) ||
1862 (Left.Tok.isLiteral() ||
1863 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
1864 (Style.PointerAlignment != FormatStyle::PAS_Left ||
1865 Line.IsMultiVariableDeclStmt)));
1866 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
1867 (!Left.is(TT_PointerOrReference) ||
1868 (Style.PointerAlignment != FormatStyle::PAS_Right &&
1869 !Line.IsMultiVariableDeclStmt)))
1871 if (Left.is(TT_PointerOrReference))
1872 return Right.Tok.isLiteral() ||
1873 Right.isOneOf(TT_BlockComment, Keywords.kw_final,
1874 Keywords.kw_override) ||
1875 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
1876 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
1878 (Style.PointerAlignment != FormatStyle::PAS_Right &&
1879 !Line.IsMultiVariableDeclStmt) &&
1881 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
1882 if (Right.is(tok::star) && Left.is(tok::l_paren))
1884 if (Left.is(tok::l_square))
1885 return (Left.is(TT_ArrayInitializerLSquare) &&
1886 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
1887 (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
1888 Right.isNot(tok::r_square));
1889 if (Right.is(tok::r_square))
1890 return Right.MatchingParen &&
1891 ((Style.SpacesInContainerLiterals &&
1892 Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
1893 (Style.SpacesInSquareBrackets &&
1894 Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
1895 if (Right.is(tok::l_square) &&
1896 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
1897 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
1899 if (Left.is(tok::colon))
1900 return !Left.is(TT_ObjCMethodExpr);
1901 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1902 return !Left.Children.empty(); // No spaces in "{}".
1903 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
1904 (Right.is(tok::r_brace) && Right.MatchingParen &&
1905 Right.MatchingParen->BlockKind != BK_Block))
1906 return !Style.Cpp11BracedListStyle;
1907 if (Left.is(TT_BlockComment))
1908 return !Left.TokenText.endswith("=*/");
1909 if (Right.is(tok::l_paren)) {
1910 if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
1912 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
1913 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
1914 (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
1915 tok::kw_switch, tok::kw_case, TT_ForEachMacro,
1917 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
1918 tok::kw_new, tok::kw_delete) &&
1919 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
1920 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
1921 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
1922 Left.is(tok::r_paren)) &&
1923 Line.Type != LT_PreprocessorDirective);
1925 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
1927 if (Right.is(TT_UnaryOperator))
1928 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
1929 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
1930 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
1932 Left.isSimpleTypeSpecifier()) &&
1933 Right.is(tok::l_brace) && Right.getNextNonComment() &&
1934 Right.BlockKind != BK_Block)
1936 if (Left.is(tok::period) || Right.is(tok::period))
1938 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
1940 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
1941 Left.MatchingParen->Previous &&
1942 Left.MatchingParen->Previous->is(tok::period))
1943 // A.<B>DoSomething();
1945 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
1950 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
1951 const FormatToken &Right) {
1952 const FormatToken &Left = *Right.Previous;
1953 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
1954 return true; // Never ever merge two identifiers.
1955 if (Style.Language == FormatStyle::LK_Cpp) {
1956 if (Left.is(tok::kw_operator))
1957 return Right.is(tok::coloncolon);
1958 } else if (Style.Language == FormatStyle::LK_Proto) {
1959 if (Right.is(tok::period) &&
1960 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
1961 Keywords.kw_repeated, Keywords.kw_extend))
1963 if (Right.is(tok::l_paren) &&
1964 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
1966 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1967 if (Left.isOneOf(Keywords.kw_let, Keywords.kw_var, TT_JsFatArrow,
1970 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
1972 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
1973 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
1975 if (Left.is(tok::ellipsis))
1977 if (Left.is(TT_TemplateCloser) &&
1978 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
1979 Keywords.kw_implements, Keywords.kw_extends))
1980 // Type assertions ('<type>expr') are not followed by whitespace. Other
1981 // locations that should have whitespace following are identified by the
1982 // above set of follower tokens.
1984 } else if (Style.Language == FormatStyle::LK_Java) {
1985 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
1987 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
1988 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
1989 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
1990 tok::kw_protected) ||
1991 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
1992 Keywords.kw_native)) &&
1993 Right.is(TT_TemplateOpener))
1996 if (Left.is(TT_ImplicitStringLiteral))
1997 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
1998 if (Line.Type == LT_ObjCMethodDecl) {
1999 if (Left.is(TT_ObjCMethodSpecifier))
2001 if (Left.is(tok::r_paren) && Right.is(tok::identifier))
2002 // Don't space between ')' and <id>
2005 if (Line.Type == LT_ObjCProperty &&
2006 (Right.is(tok::equal) || Left.is(tok::equal)))
2009 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2010 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2012 if (Left.is(tok::comma))
2014 if (Right.is(tok::comma))
2016 if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
2018 if (Right.is(TT_OverloadedOperatorLParen))
2019 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2020 if (Right.is(tok::colon)) {
2021 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2022 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2024 if (Right.is(TT_ObjCMethodExpr))
2026 if (Left.is(tok::question))
2028 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2030 if (Right.is(TT_DictLiteral))
2031 return Style.SpacesInContainerLiterals;
2034 if (Left.is(TT_UnaryOperator))
2035 return Right.is(TT_BinaryOperator);
2037 // If the next token is a binary operator or a selector name, we have
2038 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2039 if (Left.is(TT_CastRParen))
2040 return Style.SpaceAfterCStyleCast ||
2041 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2043 if (Left.is(tok::greater) && Right.is(tok::greater))
2044 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2045 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2046 if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2047 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
2049 if (!Style.SpaceBeforeAssignmentOperators &&
2050 Right.getPrecedence() == prec::Assignment)
2052 if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
2053 return (Left.is(TT_TemplateOpener) &&
2054 Style.Standard == FormatStyle::LS_Cpp03) ||
2055 !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren) ||
2056 Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
2057 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2058 return Style.SpacesInAngles;
2059 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2060 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2061 !Right.is(tok::r_paren)))
2063 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2064 Right.isNot(TT_FunctionTypeLParen))
2065 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2066 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2067 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2069 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2070 Line.startsWith(tok::hash))
2072 if (Right.is(TT_TrailingUnaryOperator))
2074 if (Left.is(TT_RegexLiteral))
2076 return spaceRequiredBetween(Line, Left, Right);
2079 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2080 static bool isAllmanBrace(const FormatToken &Tok) {
2081 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2082 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2085 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2086 const FormatToken &Right) {
2087 const FormatToken &Left = *Right.Previous;
2088 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2091 if (Style.Language == FormatStyle::LK_JavaScript) {
2092 // FIXME: This might apply to other languages and token kinds.
2093 if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
2094 Left.Previous->is(tok::char_constant))
2096 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2097 Left.Previous && Left.Previous->is(tok::equal) &&
2098 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2100 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2102 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2103 // Object literals on the top level of a file are treated as "enum-style".
2104 // Each key/value pair is put on a separate line, instead of bin-packing.
2106 if (Left.is(tok::l_brace) && Line.Level == 0 &&
2107 (Line.startsWith(tok::kw_enum) ||
2108 Line.startsWith(tok::kw_export, tok::kw_enum)))
2109 // JavaScript top-level enum key/value pairs are put on separate lines
2110 // instead of bin-packing.
2112 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2113 !Left.Children.empty())
2114 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2115 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2116 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2117 (Left.NestingLevel == 0 && Line.Level == 0 &&
2118 Style.AllowShortFunctionsOnASingleLine ==
2119 FormatStyle::SFS_Inline);
2120 } else if (Style.Language == FormatStyle::LK_Java) {
2121 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2122 Right.Next->is(tok::string_literal))
2126 // If the last token before a '}' is a comma or a trailing comment, the
2127 // intention is to insert a line break after it in order to make shuffling
2128 // around entries easier.
2129 const FormatToken *BeforeClosingBrace = nullptr;
2130 if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
2131 Left.BlockKind != BK_Block && Left.MatchingParen)
2132 BeforeClosingBrace = Left.MatchingParen->Previous;
2133 else if (Right.MatchingParen &&
2134 Right.MatchingParen->isOneOf(tok::l_brace,
2135 TT_ArrayInitializerLSquare))
2136 BeforeClosingBrace = &Left;
2137 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2138 BeforeClosingBrace->isTrailingComment()))
2141 if (Right.is(tok::comment))
2142 return Left.BlockKind != BK_BracedInit &&
2143 Left.isNot(TT_CtorInitializerColon) &&
2144 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2145 if (Left.isTrailingComment())
2147 if (Left.isStringLiteral() &&
2148 (Right.isStringLiteral() || Right.is(TT_ObjCStringLiteral)))
2150 if (Right.Previous->IsUnterminatedLiteral)
2152 if (Right.is(tok::lessless) && Right.Next &&
2153 Right.Previous->is(tok::string_literal) &&
2154 Right.Next->is(tok::string_literal))
2156 if (Right.Previous->ClosesTemplateDeclaration &&
2157 Right.Previous->MatchingParen &&
2158 Right.Previous->MatchingParen->NestingLevel == 0 &&
2159 Style.AlwaysBreakTemplateDeclarations)
2161 if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
2162 Style.BreakConstructorInitializersBeforeComma &&
2163 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2165 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2166 // Raw string literals are special wrt. line breaks. The author has made a
2167 // deliberate choice and might have aligned the contents of the string
2168 // literal accordingly. Thus, we try keep existing line breaks.
2169 return Right.NewlinesBefore > 0;
2170 if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
2171 Style.Language == FormatStyle::LK_Proto)
2172 // Don't put enums onto single lines in protocol buffers.
2174 if (Right.is(TT_InlineASMBrace))
2175 return Right.HasUnescapedNewline;
2176 if (isAllmanBrace(Left) || isAllmanBrace(Right))
2177 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2178 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2179 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2180 if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) &&
2181 Right.is(TT_SelectorName))
2183 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2186 if ((Style.Language == FormatStyle::LK_Java ||
2187 Style.Language == FormatStyle::LK_JavaScript) &&
2188 Left.is(TT_LeadingJavaAnnotation) &&
2189 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2190 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2196 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2197 const FormatToken &Right) {
2198 const FormatToken &Left = *Right.Previous;
2200 // Language-specific stuff.
2201 if (Style.Language == FormatStyle::LK_Java) {
2202 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2203 Keywords.kw_implements))
2205 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2206 Keywords.kw_implements))
2208 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2209 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2211 if (Left.is(TT_JsTypeColon))
2215 if (Left.is(tok::at))
2217 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2219 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2220 return !Right.is(tok::l_paren);
2221 if (Right.is(TT_PointerOrReference))
2222 return Line.IsMultiVariableDeclStmt ||
2223 (Style.PointerAlignment == FormatStyle::PAS_Right &&
2224 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2225 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2226 Right.is(tok::kw_operator))
2228 if (Left.is(TT_PointerOrReference))
2230 if (Right.isTrailingComment())
2231 // We rely on MustBreakBefore being set correctly here as we should not
2232 // change the "binding" behavior of a comment.
2233 // The first comment in a braced lists is always interpreted as belonging to
2234 // the first list element. Otherwise, it should be placed outside of the
2236 return Left.BlockKind == BK_BracedInit;
2237 if (Left.is(tok::question) && Right.is(tok::colon))
2239 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2240 return Style.BreakBeforeTernaryOperators;
2241 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2242 return !Style.BreakBeforeTernaryOperators;
2243 if (Right.is(TT_InheritanceColon))
2245 if (Right.is(tok::colon) &&
2246 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2248 if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
2250 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2251 Right.Next->is(TT_ObjCMethodExpr)))
2252 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2253 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2255 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
2257 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2258 TT_OverloadedOperator))
2260 if (Left.is(TT_RangeBasedForLoopColon))
2262 if (Right.is(TT_RangeBasedForLoopColon))
2264 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2265 Left.is(tok::kw_operator))
2267 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2268 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
2270 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2272 if (Left.is(tok::l_paren) && Left.Previous &&
2273 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2275 if (Right.is(TT_ImplicitStringLiteral))
2278 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2280 if (Right.is(tok::r_square) && Right.MatchingParen &&
2281 Right.MatchingParen->is(TT_LambdaLSquare))
2284 // We only break before r_brace if there was a corresponding break before
2285 // the l_brace, which is tracked by BreakBeforeClosingBrace.
2286 if (Right.is(tok::r_brace))
2287 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2289 // Allow breaking after a trailing annotation, e.g. after a method
2291 if (Left.is(TT_TrailingAnnotation))
2292 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2293 tok::less, tok::coloncolon);
2295 if (Right.is(tok::kw___attribute))
2298 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2301 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2304 if (Left.is(TT_CtorInitializerComma) &&
2305 Style.BreakConstructorInitializersBeforeComma)
2307 if (Right.is(TT_CtorInitializerComma) &&
2308 Style.BreakConstructorInitializersBeforeComma)
2310 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2311 (Left.is(tok::less) && Right.is(tok::less)))
2313 if (Right.is(TT_BinaryOperator) &&
2314 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2315 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2316 Right.getPrecedence() != prec::Assignment))
2318 if (Left.is(TT_ArrayInitializerLSquare))
2320 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2322 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
2323 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2324 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2325 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2326 Left.getPrecedence() == prec::Assignment))
2328 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2329 tok::kw_class, tok::kw_struct) ||
2330 Right.isMemberAccess() ||
2331 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2332 tok::colon, tok::l_square, tok::at) ||
2333 (Left.is(tok::r_paren) &&
2334 Right.isOneOf(tok::identifier, tok::kw_const)) ||
2335 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
2338 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2339 llvm::errs() << "AnnotatedTokens:\n";
2340 const FormatToken *Tok = Line.First;
2342 llvm::errs() << " M=" << Tok->MustBreakBefore
2343 << " C=" << Tok->CanBreakBefore
2344 << " T=" << getTokenTypeName(Tok->Type)
2345 << " S=" << Tok->SpacesRequiredBefore
2346 << " B=" << Tok->BlockParameterCount
2347 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
2348 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
2350 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2351 llvm::errs() << Tok->FakeLParens[i] << "/";
2352 llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
2354 assert(Tok == Line.Last);
2357 llvm::errs() << "----\n";
2360 } // namespace format
2361 } // namespace clang