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;
151 } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
153 Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
154 Contexts.back().IsExpression = !IsForOrCatch;
157 if (StartsObjCMethodExpr) {
158 Contexts.back().ColonIsObjCMethodExpr = true;
159 Left->Type = TT_ObjCMethodExpr;
162 bool MightBeFunctionType = CurrentToken->isOneOf(tok::star, tok::amp) &&
163 !Contexts[Contexts.size() - 2].IsExpression;
164 bool HasMultipleLines = false;
165 bool HasMultipleParametersOnALine = false;
166 bool MightBeObjCForRangeLoop =
167 Left->Previous && Left->Previous->is(tok::kw_for);
168 while (CurrentToken) {
169 // LookForDecls is set when "if (" has been seen. Check for
170 // 'identifier' '*' 'identifier' followed by not '=' -- this
171 // '*' has to be a binary operator but determineStarAmpUsage() will
172 // categorize it as an unary operator, so set the right type here.
173 if (LookForDecls && CurrentToken->Next) {
174 FormatToken *Prev = CurrentToken->getPreviousNonComment();
176 FormatToken *PrevPrev = Prev->getPreviousNonComment();
177 FormatToken *Next = CurrentToken->Next;
178 if (PrevPrev && PrevPrev->is(tok::identifier) &&
179 Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
180 CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
181 Prev->Type = TT_BinaryOperator;
182 LookForDecls = false;
187 if (CurrentToken->Previous->is(TT_PointerOrReference) &&
188 CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
190 MightBeFunctionType = true;
191 if (CurrentToken->Previous->is(TT_BinaryOperator))
192 Contexts.back().IsExpression = true;
193 if (CurrentToken->is(tok::r_paren)) {
194 if (MightBeFunctionType && CurrentToken->Next &&
195 (CurrentToken->Next->is(tok::l_paren) ||
196 (CurrentToken->Next->is(tok::l_square) &&
197 Line.MustBeDeclaration)))
198 Left->Type = TT_FunctionTypeLParen;
199 Left->MatchingParen = CurrentToken;
200 CurrentToken->MatchingParen = Left;
202 if (StartsObjCMethodExpr) {
203 CurrentToken->Type = TT_ObjCMethodExpr;
204 if (Contexts.back().FirstObjCSelectorName) {
205 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
206 Contexts.back().LongestObjCSelectorName;
210 if (Left->is(TT_AttributeParen))
211 CurrentToken->Type = TT_AttributeParen;
212 if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
213 CurrentToken->Type = TT_JavaAnnotation;
214 if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
215 CurrentToken->Type = TT_LeadingJavaAnnotation;
217 if (!HasMultipleLines)
218 Left->PackingKind = PPK_Inconclusive;
219 else if (HasMultipleParametersOnALine)
220 Left->PackingKind = PPK_BinPacked;
222 Left->PackingKind = PPK_OnePerLine;
227 if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
230 if (CurrentToken->is(tok::l_brace))
231 Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
232 if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
233 !CurrentToken->Next->HasUnescapedNewline &&
234 !CurrentToken->Next->isTrailingComment())
235 HasMultipleParametersOnALine = true;
236 if (CurrentToken->isOneOf(tok::kw_const, tok::kw_auto) ||
237 CurrentToken->isSimpleTypeSpecifier())
238 Contexts.back().IsExpression = false;
239 if (CurrentToken->isOneOf(tok::semi, tok::colon))
240 MightBeObjCForRangeLoop = false;
241 if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
242 CurrentToken->Type = TT_ObjCForIn;
243 // When we discover a 'new', we set CanBeExpression to 'false' in order to
244 // parse the type correctly. Reset that after a comma.
245 if (CurrentToken->is(tok::comma))
246 Contexts.back().CanBeExpression = true;
248 FormatToken *Tok = CurrentToken;
251 updateParameterCount(Left, Tok);
252 if (CurrentToken && CurrentToken->HasUnescapedNewline)
253 HasMultipleLines = true;
262 // A '[' could be an index subscript (after an identifier or after
263 // ')' or ']'), it could be the start of an Objective-C method
264 // expression, or it could the start of an Objective-C array literal.
265 FormatToken *Left = CurrentToken->Previous;
266 Left->ParentBracket = Contexts.back().ContextKind;
267 FormatToken *Parent = Left->getPreviousNonComment();
268 bool StartsObjCMethodExpr =
269 Style.Language == FormatStyle::LK_Cpp &&
270 Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
271 CurrentToken->isNot(tok::l_brace) &&
273 Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
274 tok::kw_return, tok::kw_throw) ||
275 Parent->isUnaryOperator() ||
276 Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
277 getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
278 bool ColonFound = false;
280 unsigned BindingIncrease = 1;
281 if (Left->is(TT_Unknown)) {
282 if (StartsObjCMethodExpr) {
283 Left->Type = TT_ObjCMethodExpr;
284 } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
285 Contexts.back().ContextKind == tok::l_brace &&
286 Parent->isOneOf(tok::l_brace, tok::comma)) {
287 Left->Type = TT_JsComputedPropertyName;
288 } else if (Style.Language == FormatStyle::LK_Proto ||
290 Parent->isOneOf(TT_BinaryOperator, tok::at, tok::comma,
291 tok::l_paren, tok::l_square, tok::question,
292 tok::colon, tok::kw_return,
293 // Should only be relevant to JavaScript:
295 Left->Type = TT_ArrayInitializerLSquare;
297 BindingIncrease = 10;
298 Left->Type = TT_ArraySubscriptLSquare;
302 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
303 Contexts.back().IsExpression = true;
304 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
306 while (CurrentToken) {
307 if (CurrentToken->is(tok::r_square)) {
308 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
309 Left->is(TT_ObjCMethodExpr)) {
310 // An ObjC method call is rarely followed by an open parenthesis.
311 // FIXME: Do we incorrectly label ":" with this?
312 StartsObjCMethodExpr = false;
313 Left->Type = TT_Unknown;
315 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
316 CurrentToken->Type = TT_ObjCMethodExpr;
317 // determineStarAmpUsage() thinks that '*' '[' is allocating an
318 // array of pointers, but if '[' starts a selector then '*' is a
320 if (Parent && Parent->is(TT_PointerOrReference))
321 Parent->Type = TT_BinaryOperator;
323 Left->MatchingParen = CurrentToken;
324 CurrentToken->MatchingParen = Left;
325 if (Contexts.back().FirstObjCSelectorName) {
326 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
327 Contexts.back().LongestObjCSelectorName;
328 if (Left->BlockParameterCount > 1)
329 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
334 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
336 if (CurrentToken->is(tok::colon)) {
337 if (Left->is(TT_ArraySubscriptLSquare)) {
338 Left->Type = TT_ObjCMethodExpr;
339 StartsObjCMethodExpr = true;
340 Contexts.back().ColonIsObjCMethodExpr = true;
341 if (Parent && Parent->is(tok::r_paren))
342 Parent->Type = TT_CastRParen;
346 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
348 Left->Type = TT_ArrayInitializerLSquare;
349 FormatToken *Tok = CurrentToken;
352 updateParameterCount(Left, Tok);
359 FormatToken *Left = CurrentToken->Previous;
360 Left->ParentBracket = Contexts.back().ContextKind;
362 if (Contexts.back().CaretFound)
363 Left->Type = TT_ObjCBlockLBrace;
364 Contexts.back().CaretFound = false;
366 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
367 Contexts.back().ColonIsDictLiteral = true;
368 if (Left->BlockKind == BK_BracedInit)
369 Contexts.back().IsExpression = true;
371 while (CurrentToken) {
372 if (CurrentToken->is(tok::r_brace)) {
373 Left->MatchingParen = CurrentToken;
374 CurrentToken->MatchingParen = Left;
378 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
380 updateParameterCount(Left, CurrentToken);
381 if (CurrentToken->isOneOf(tok::colon, tok::l_brace)) {
382 FormatToken *Previous = CurrentToken->getPreviousNonComment();
383 if (((CurrentToken->is(tok::colon) &&
384 (!Contexts.back().ColonIsDictLiteral ||
385 Style.Language != FormatStyle::LK_Cpp)) ||
386 Style.Language == FormatStyle::LK_Proto) &&
387 Previous->Tok.getIdentifierInfo())
388 Previous->Type = TT_SelectorName;
389 if (CurrentToken->is(tok::colon) ||
390 Style.Language == FormatStyle::LK_JavaScript)
391 Left->Type = TT_DictLiteral;
400 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
401 if (Current->is(tok::l_brace) && !Current->is(TT_DictLiteral))
402 ++Left->BlockParameterCount;
403 if (Current->is(tok::comma)) {
404 ++Left->ParameterCount;
406 Left->Role.reset(new CommaSeparatedList(Style));
407 Left->Role->CommaFound(Current);
408 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
409 Left->ParameterCount = 1;
413 bool parseConditional() {
414 while (CurrentToken) {
415 if (CurrentToken->is(tok::colon)) {
416 CurrentToken->Type = TT_ConditionalExpr;
426 bool parseTemplateDeclaration() {
427 if (CurrentToken && CurrentToken->is(tok::less)) {
428 CurrentToken->Type = TT_TemplateOpener;
433 CurrentToken->Previous->ClosesTemplateDeclaration = true;
439 bool consumeToken() {
440 FormatToken *Tok = CurrentToken;
442 switch (Tok->Tok.getKind()) {
445 if (!Tok->Previous && Line.MustBeDeclaration)
446 Tok->Type = TT_ObjCMethodSpecifier;
451 // Colons from ?: are handled in parseConditional().
452 if (Style.Language == FormatStyle::LK_JavaScript) {
453 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
454 (Contexts.size() == 1 && // switch/case labels
455 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
456 Contexts.back().ContextKind == tok::l_paren || // function params
457 Contexts.back().ContextKind == tok::l_square || // array type
458 (Contexts.size() == 1 &&
459 Line.MustBeDeclaration)) { // method/property declaration
460 Tok->Type = TT_JsTypeColon;
464 if (Contexts.back().ColonIsDictLiteral ||
465 Style.Language == FormatStyle::LK_Proto) {
466 Tok->Type = TT_DictLiteral;
467 } else if (Contexts.back().ColonIsObjCMethodExpr ||
468 Line.startsWith(TT_ObjCMethodSpecifier)) {
469 Tok->Type = TT_ObjCMethodExpr;
470 Tok->Previous->Type = TT_SelectorName;
471 if (Tok->Previous->ColumnWidth >
472 Contexts.back().LongestObjCSelectorName)
473 Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth;
474 if (!Contexts.back().FirstObjCSelectorName)
475 Contexts.back().FirstObjCSelectorName = Tok->Previous;
476 } else if (Contexts.back().ColonIsForRangeExpr) {
477 Tok->Type = TT_RangeBasedForLoopColon;
478 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
479 Tok->Type = TT_BitFieldColon;
480 } else if (Contexts.size() == 1 &&
481 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
482 if (Tok->Previous->is(tok::r_paren))
483 Tok->Type = TT_CtorInitializerColon;
485 Tok->Type = TT_InheritanceColon;
486 } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
487 Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
488 // This handles a special macro in ObjC code where selectors including
489 // the colon are passed as macro arguments.
490 Tok->Type = TT_ObjCMethodExpr;
491 } else if (Contexts.back().ContextKind == tok::l_paren) {
492 Tok->Type = TT_InlineASMColon;
497 if (CurrentToken && CurrentToken->is(tok::l_paren)) {
499 if (!parseParens(/*LookForDecls=*/true))
504 Contexts.back().ColonIsForRangeExpr = true;
510 // When faced with 'operator()()', the kw_operator handler incorrectly
511 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
512 // the first two parens OverloadedOperators and the second l_paren an
513 // OverloadedOperatorLParen.
515 Tok->Previous->is(tok::r_paren) &&
516 Tok->Previous->MatchingParen &&
517 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
518 Tok->Previous->Type = TT_OverloadedOperator;
519 Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
520 Tok->Type = TT_OverloadedOperatorLParen;
525 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
526 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
528 !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
529 TT_LeadingJavaAnnotation)))
530 Line.MightBeFunctionDecl = true;
541 if (!NonTemplateLess.count(Tok) &&
543 (!Tok->Previous->Tok.isLiteral() &&
544 !(Tok->Previous->is(tok::r_paren) && Contexts.size() > 1))) &&
546 Tok->Type = TT_TemplateOpener;
548 Tok->Type = TT_BinaryOperator;
549 NonTemplateLess.insert(Tok);
558 // Lines can start with '}'.
563 Tok->Type = TT_BinaryOperator;
565 case tok::kw_operator:
566 while (CurrentToken &&
567 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
568 if (CurrentToken->isOneOf(tok::star, tok::amp))
569 CurrentToken->Type = TT_PointerOrReference;
571 if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator))
572 CurrentToken->Previous->Type = TT_OverloadedOperator;
575 CurrentToken->Type = TT_OverloadedOperatorLParen;
576 if (CurrentToken->Previous->is(TT_BinaryOperator))
577 CurrentToken->Previous->Type = TT_OverloadedOperator;
581 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
582 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
584 // Question marks before semicolons, colons, etc. indicate optional
585 // types (fields, parameters), e.g.
586 // function(x?: string, y?) {...}
588 Tok->Type = TT_JsTypeOptionalQuestion;
591 // Declarations cannot be conditional expressions, this can only be part
592 // of a type declaration.
593 if (Line.MustBeDeclaration &&
594 Style.Language == FormatStyle::LK_JavaScript)
598 case tok::kw_template:
599 parseTemplateDeclaration();
602 if (Contexts.back().InCtorInitializer)
603 Tok->Type = TT_CtorInitializerComma;
604 else if (Contexts.back().FirstStartOfName &&
605 (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
606 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
607 Line.IsMultiVariableDeclStmt = true;
609 if (Contexts.back().IsForEachMacro)
610 Contexts.back().IsExpression = true;
618 void parseIncludeDirective() {
619 if (CurrentToken && CurrentToken->is(tok::less)) {
621 while (CurrentToken) {
622 if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
623 CurrentToken->Type = TT_ImplicitStringLiteral;
629 void parseWarningOrError() {
631 // We still want to format the whitespace left of the first token of the
634 while (CurrentToken) {
635 CurrentToken->Type = TT_ImplicitStringLiteral;
641 next(); // Consume "pragma".
643 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
644 bool IsMark = CurrentToken->is(Keywords.kw_mark);
645 next(); // Consume "mark".
646 next(); // Consume first token (so we fix leading whitespace).
647 while (CurrentToken) {
648 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
649 CurrentToken->Type = TT_ImplicitStringLiteral;
655 LineType parsePreprocessorDirective() {
656 LineType Type = LT_PreprocessorDirective;
660 if (CurrentToken->Tok.is(tok::numeric_constant)) {
661 CurrentToken->SpacesRequiredBefore = 1;
664 // Hashes in the middle of a line can lead to any strange token
666 if (!CurrentToken->Tok.getIdentifierInfo())
668 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
669 case tok::pp_include:
670 case tok::pp_include_next:
673 parseIncludeDirective();
674 Type = LT_ImportStatement;
677 case tok::pp_warning:
678 parseWarningOrError();
685 Contexts.back().IsExpression = true;
697 LineType parseLine() {
698 NonTemplateLess.clear();
699 if (CurrentToken->is(tok::hash))
700 return parsePreprocessorDirective();
702 // Directly allow to 'import <string-literal>' to support protocol buffer
703 // definitions (code.google.com/p/protobuf) or missing "#" (either way we
704 // should not break the line).
705 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
706 if ((Style.Language == FormatStyle::LK_Java &&
707 CurrentToken->is(Keywords.kw_package)) ||
708 (Info && Info->getPPKeywordID() == tok::pp_import &&
709 CurrentToken->Next &&
710 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
713 parseIncludeDirective();
714 return LT_ImportStatement;
717 // If this line starts and ends in '<' and '>', respectively, it is likely
718 // part of "#define <a/b.h>".
719 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
720 parseIncludeDirective();
721 return LT_ImportStatement;
724 // In .proto files, top-level options are very similar to import statements
725 // and should not be line-wrapped.
726 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
727 CurrentToken->is(Keywords.kw_option)) {
729 if (CurrentToken && CurrentToken->is(tok::identifier))
730 return LT_ImportStatement;
733 bool KeywordVirtualFound = false;
734 bool ImportStatement = false;
735 while (CurrentToken) {
736 if (CurrentToken->is(tok::kw_virtual))
737 KeywordVirtualFound = true;
738 if (isImportStatement(*CurrentToken))
739 ImportStatement = true;
743 if (KeywordVirtualFound)
744 return LT_VirtualFunctionDecl;
746 return LT_ImportStatement;
748 if (Line.startsWith(TT_ObjCMethodSpecifier)) {
749 if (Contexts.back().FirstObjCSelectorName)
750 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
751 Contexts.back().LongestObjCSelectorName;
752 return LT_ObjCMethodDecl;
759 bool isImportStatement(const FormatToken &Tok) {
760 // FIXME: Closure-library specific stuff should not be hard-coded but be
762 return Style.Language == FormatStyle::LK_JavaScript &&
763 Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
764 Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
765 Tok.Next->Next->TokenText == "provide" ||
766 Tok.Next->Next->TokenText == "require" ||
767 Tok.Next->Next->TokenText == "setTestOnly") &&
768 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
771 void resetTokenMetadata(FormatToken *Token) {
775 // Reset token type in case we have already looked at it and then
776 // recovered from an error (e.g. failure to find the matching >).
777 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
778 TT_FunctionLBrace, TT_ImplicitStringLiteral,
779 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
781 CurrentToken->Type = TT_Unknown;
782 CurrentToken->Role.reset();
783 CurrentToken->MatchingParen = nullptr;
784 CurrentToken->FakeLParens.clear();
785 CurrentToken->FakeRParens = 0;
790 CurrentToken->NestingLevel = Contexts.size() - 1;
791 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
792 modifyContext(*CurrentToken);
793 determineTokenType(*CurrentToken);
794 CurrentToken = CurrentToken->Next;
797 resetTokenMetadata(CurrentToken);
800 /// \brief A struct to hold information valid in a specific context, e.g.
801 /// a pair of parenthesis.
803 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
805 : ContextKind(ContextKind), BindingStrength(BindingStrength),
806 IsExpression(IsExpression) {}
808 tok::TokenKind ContextKind;
809 unsigned BindingStrength;
811 unsigned LongestObjCSelectorName = 0;
812 bool ColonIsForRangeExpr = false;
813 bool ColonIsDictLiteral = false;
814 bool ColonIsObjCMethodExpr = false;
815 FormatToken *FirstObjCSelectorName = nullptr;
816 FormatToken *FirstStartOfName = nullptr;
817 bool CanBeExpression = true;
818 bool InTemplateArgument = false;
819 bool InCtorInitializer = false;
820 bool CaretFound = false;
821 bool IsForEachMacro = false;
824 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
825 /// of each instance.
826 struct ScopedContextCreator {
829 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
832 P.Contexts.push_back(Context(ContextKind,
833 P.Contexts.back().BindingStrength + Increase,
834 P.Contexts.back().IsExpression));
837 ~ScopedContextCreator() { P.Contexts.pop_back(); }
840 void modifyContext(const FormatToken &Current) {
841 if (Current.getPrecedence() == prec::Assignment &&
842 !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
843 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
844 Contexts.back().IsExpression = true;
845 if (!Line.startsWith(TT_UnaryOperator)) {
846 for (FormatToken *Previous = Current.Previous;
847 Previous && Previous->Previous &&
848 !Previous->Previous->isOneOf(tok::comma, tok::semi);
849 Previous = Previous->Previous) {
850 if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
851 Previous = Previous->MatchingParen;
855 if (Previous->opensScope())
857 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
858 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
859 Previous->Previous && Previous->Previous->isNot(tok::equal))
860 Previous->Type = TT_PointerOrReference;
863 } else if (Current.is(tok::lessless) &&
864 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
865 Contexts.back().IsExpression = true;
866 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
867 Contexts.back().IsExpression = true;
868 } else if (Current.is(TT_TrailingReturnArrow)) {
869 Contexts.back().IsExpression = false;
870 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
871 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
872 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
873 for (FormatToken *Previous = Current.Previous;
874 Previous && Previous->isOneOf(tok::star, tok::amp);
875 Previous = Previous->Previous)
876 Previous->Type = TT_PointerOrReference;
877 if (Line.MustBeDeclaration)
878 Contexts.back().IsExpression = Contexts.front().InCtorInitializer;
879 } else if (Current.Previous &&
880 Current.Previous->is(TT_CtorInitializerColon)) {
881 Contexts.back().IsExpression = true;
882 Contexts.back().InCtorInitializer = true;
883 } else if (Current.is(tok::kw_new)) {
884 Contexts.back().CanBeExpression = false;
885 } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
886 // This should be the condition or increment in a for-loop.
887 Contexts.back().IsExpression = true;
891 void determineTokenType(FormatToken &Current) {
892 if (!Current.is(TT_Unknown))
893 // The token type is already known.
896 // Line.MightBeFunctionDecl can only be true after the parentheses of a
897 // function declaration have been found. In this case, 'Current' is a
898 // trailing token of this declaration and thus cannot be a name.
899 if (Current.is(Keywords.kw_instanceof)) {
900 Current.Type = TT_BinaryOperator;
901 } else if (isStartOfName(Current) &&
902 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
903 Contexts.back().FirstStartOfName = &Current;
904 Current.Type = TT_StartOfName;
905 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
907 } else if (Current.is(tok::arrow) &&
908 Style.Language == FormatStyle::LK_Java) {
909 Current.Type = TT_LambdaArrow;
910 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
911 Current.NestingLevel == 0) {
912 Current.Type = TT_TrailingReturnArrow;
913 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
915 determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
916 Contexts.back().IsExpression,
917 Contexts.back().InTemplateArgument);
918 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
919 Current.Type = determinePlusMinusCaretUsage(Current);
920 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
921 Contexts.back().CaretFound = true;
922 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
923 Current.Type = determineIncrementUsage(Current);
924 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
925 Current.Type = TT_UnaryOperator;
926 } else if (Current.is(tok::question)) {
927 if (Style.Language == FormatStyle::LK_JavaScript &&
928 Line.MustBeDeclaration) {
929 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
930 // on the interface, not a ternary expression.
931 Current.Type = TT_JsTypeOptionalQuestion;
933 Current.Type = TT_ConditionalExpr;
935 } else if (Current.isBinaryOperator() &&
936 (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
937 Current.Type = TT_BinaryOperator;
938 } else if (Current.is(tok::comment)) {
939 if (Current.TokenText.startswith("/*")) {
940 if (Current.TokenText.endswith("*/"))
941 Current.Type = TT_BlockComment;
943 // The lexer has for some reason determined a comment here. But we
944 // cannot really handle it, if it isn't properly terminated.
945 Current.Tok.setKind(tok::unknown);
947 Current.Type = TT_LineComment;
949 } else if (Current.is(tok::r_paren)) {
950 if (rParenEndsCast(Current))
951 Current.Type = TT_CastRParen;
952 if (Current.MatchingParen && Current.Next &&
953 !Current.Next->isBinaryOperator() &&
954 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace))
955 if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
956 if (BeforeParen->is(tok::identifier) &&
957 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
958 (!BeforeParen->Previous ||
959 BeforeParen->Previous->ClosesTemplateDeclaration))
960 Current.Type = TT_FunctionAnnotationRParen;
961 } else if (Current.is(tok::at) && Current.Next) {
962 if (Current.Next->isStringLiteral()) {
963 Current.Type = TT_ObjCStringLiteral;
965 switch (Current.Next->Tok.getObjCKeywordID()) {
966 case tok::objc_interface:
967 case tok::objc_implementation:
968 case tok::objc_protocol:
969 Current.Type = TT_ObjCDecl;
971 case tok::objc_property:
972 Current.Type = TT_ObjCProperty;
978 } else if (Current.is(tok::period)) {
979 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
980 if (PreviousNoComment &&
981 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
982 Current.Type = TT_DesignatedInitializerPeriod;
983 else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
984 Current.Previous->isOneOf(TT_JavaAnnotation,
985 TT_LeadingJavaAnnotation)) {
986 Current.Type = Current.Previous->Type;
988 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
990 !Current.Previous->isOneOf(tok::equal, tok::at) &&
991 Line.MightBeFunctionDecl && Contexts.size() == 1) {
992 // Line.MightBeFunctionDecl can only be true after the parentheses of a
993 // function declaration have been found.
994 Current.Type = TT_TrailingAnnotation;
995 } else if ((Style.Language == FormatStyle::LK_Java ||
996 Style.Language == FormatStyle::LK_JavaScript) &&
998 if (Current.Previous->is(tok::at) &&
999 Current.isNot(Keywords.kw_interface)) {
1000 const FormatToken &AtToken = *Current.Previous;
1001 const FormatToken *Previous = AtToken.getPreviousNonComment();
1002 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1003 Current.Type = TT_LeadingJavaAnnotation;
1005 Current.Type = TT_JavaAnnotation;
1006 } else if (Current.Previous->is(tok::period) &&
1007 Current.Previous->isOneOf(TT_JavaAnnotation,
1008 TT_LeadingJavaAnnotation)) {
1009 Current.Type = Current.Previous->Type;
1014 /// \brief Take a guess at whether \p Tok starts a name of a function or
1015 /// variable declaration.
1017 /// This is a heuristic based on whether \p Tok is an identifier following
1018 /// something that is likely a type.
1019 bool isStartOfName(const FormatToken &Tok) {
1020 if (Tok.isNot(tok::identifier) || !Tok.Previous)
1023 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof))
1026 // Skip "const" as it does not have an influence on whether this is a name.
1027 FormatToken *PreviousNotConst = Tok.Previous;
1028 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1029 PreviousNotConst = PreviousNotConst->Previous;
1031 if (!PreviousNotConst)
1034 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1035 PreviousNotConst->Previous &&
1036 PreviousNotConst->Previous->is(tok::hash);
1038 if (PreviousNotConst->is(TT_TemplateCloser))
1039 return PreviousNotConst && PreviousNotConst->MatchingParen &&
1040 PreviousNotConst->MatchingParen->Previous &&
1041 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1042 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1044 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1045 PreviousNotConst->MatchingParen->Previous &&
1046 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1049 return (!IsPPKeyword &&
1050 PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1051 PreviousNotConst->is(TT_PointerOrReference) ||
1052 PreviousNotConst->isSimpleTypeSpecifier();
1055 /// \brief Determine whether ')' is ending a cast.
1056 bool rParenEndsCast(const FormatToken &Tok) {
1057 // C-style casts are only used in C++ and Java.
1058 if (Style.Language != FormatStyle::LK_Cpp &&
1059 Style.Language != FormatStyle::LK_Java)
1062 // Empty parens aren't casts and there are no casts at the end of the line.
1063 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1066 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1068 // If there is an opening parenthesis left of the current parentheses,
1069 // look past it as these might be chained casts.
1070 if (LeftOfParens->is(tok::r_paren)) {
1071 if (!LeftOfParens->MatchingParen ||
1072 !LeftOfParens->MatchingParen->Previous)
1074 LeftOfParens = LeftOfParens->MatchingParen->Previous;
1077 // If there is an identifier (or with a few exceptions a keyword) right
1078 // before the parentheses, this is unlikely to be a cast.
1079 if (LeftOfParens->Tok.getIdentifierInfo() &&
1080 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1084 // Certain other tokens right before the parentheses are also signals that
1085 // this cannot be a cast.
1086 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1091 if (Tok.Next->is(tok::question))
1094 // As Java has no function types, a "(" after the ")" likely means that this
1096 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1099 // If a (non-string) literal follows, this is likely a cast.
1100 if (Tok.Next->isNot(tok::string_literal) &&
1101 (Tok.Next->Tok.isLiteral() ||
1102 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1105 // Heuristically try to determine whether the parentheses contain a type.
1106 bool ParensAreType =
1108 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1109 Tok.Previous->isSimpleTypeSpecifier();
1110 bool ParensCouldEndDecl =
1111 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1112 if (ParensAreType && !ParensCouldEndDecl)
1115 // At this point, we heuristically assume that there are no casts at the
1116 // start of the line. We assume that we have found most cases where there
1117 // are by the logic above, e.g. "(void)x;".
1121 // If the following token is an identifier, this is a cast. All cases where
1122 // this can be something else are handled above.
1123 if (Tok.Next->is(tok::identifier))
1126 if (!Tok.Next->Next)
1129 // If the next token after the parenthesis is a unary operator, assume
1130 // that this is cast, unless there are unexpected tokens inside the
1133 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1134 if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1135 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1137 // Search for unexpected tokens.
1138 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1139 Prev = Prev->Previous) {
1140 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1146 /// \brief Return the type of the given token assuming it is * or &.
1147 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1148 bool InTemplateArgument) {
1149 if (Style.Language == FormatStyle::LK_JavaScript)
1150 return TT_BinaryOperator;
1152 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1154 return TT_UnaryOperator;
1156 const FormatToken *NextToken = Tok.getNextNonComment();
1158 NextToken->isOneOf(tok::arrow, Keywords.kw_final,
1159 Keywords.kw_override) ||
1160 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1161 return TT_PointerOrReference;
1163 if (PrevToken->is(tok::coloncolon))
1164 return TT_PointerOrReference;
1166 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1167 tok::comma, tok::semi, tok::kw_return, tok::colon,
1168 tok::equal, tok::kw_delete, tok::kw_sizeof) ||
1169 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1170 TT_UnaryOperator, TT_CastRParen))
1171 return TT_UnaryOperator;
1173 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1174 return TT_PointerOrReference;
1175 if (NextToken->is(tok::kw_operator) && !IsExpression)
1176 return TT_PointerOrReference;
1177 if (NextToken->isOneOf(tok::comma, tok::semi))
1178 return TT_PointerOrReference;
1180 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
1181 PrevToken->MatchingParen->Previous &&
1182 PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
1184 return TT_PointerOrReference;
1186 if (PrevToken->Tok.isLiteral() ||
1187 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1188 tok::kw_false, tok::r_brace) ||
1189 NextToken->Tok.isLiteral() ||
1190 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1191 NextToken->isUnaryOperator() ||
1192 // If we know we're in a template argument, there are no named
1193 // declarations. Thus, having an identifier on the right-hand side
1194 // indicates a binary operator.
1195 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1196 return TT_BinaryOperator;
1198 // "&&(" is quite unlikely to be two successive unary "&".
1199 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1200 return TT_BinaryOperator;
1202 // This catches some cases where evaluation order is used as control flow:
1204 const FormatToken *NextNextToken = NextToken->getNextNonComment();
1205 if (NextNextToken && NextNextToken->is(tok::arrow))
1206 return TT_BinaryOperator;
1208 // It is very unlikely that we are going to find a pointer or reference type
1209 // definition on the RHS of an assignment.
1210 if (IsExpression && !Contexts.back().CaretFound)
1211 return TT_BinaryOperator;
1213 return TT_PointerOrReference;
1216 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1217 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1218 if (!PrevToken || PrevToken->is(TT_CastRParen))
1219 return TT_UnaryOperator;
1221 // Use heuristics to recognize unary operators.
1222 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1223 tok::question, tok::colon, tok::kw_return,
1224 tok::kw_case, tok::at, tok::l_brace))
1225 return TT_UnaryOperator;
1227 // There can't be two consecutive binary operators.
1228 if (PrevToken->is(TT_BinaryOperator))
1229 return TT_UnaryOperator;
1231 // Fall back to marking the token as binary operator.
1232 return TT_BinaryOperator;
1235 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1236 TokenType determineIncrementUsage(const FormatToken &Tok) {
1237 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1238 if (!PrevToken || PrevToken->is(TT_CastRParen))
1239 return TT_UnaryOperator;
1240 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1241 return TT_TrailingUnaryOperator;
1243 return TT_UnaryOperator;
1246 SmallVector<Context, 8> Contexts;
1248 const FormatStyle &Style;
1249 AnnotatedLine &Line;
1250 FormatToken *CurrentToken;
1252 const AdditionalKeywords &Keywords;
1254 // Set of "<" tokens that do not open a template parameter list. If parseAngle
1255 // determines that a specific token can't be a template opener, it will make
1256 // same decision irrespective of the decisions for tokens leading up to it.
1257 // Store this information to prevent this from causing exponential runtime.
1258 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1261 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1262 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1264 /// \brief Parses binary expressions by inserting fake parenthesis based on
1265 /// operator precedence.
1266 class ExpressionParser {
1268 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1269 AnnotatedLine &Line)
1270 : Style(Style), Keywords(Keywords), Current(Line.First) {}
1272 /// \brief Parse expressions with the given operatore precedence.
1273 void parse(int Precedence = 0) {
1274 // Skip 'return' and ObjC selector colons as they are not part of a binary
1276 while (Current && (Current->is(tok::kw_return) ||
1277 (Current->is(tok::colon) &&
1278 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1281 if (!Current || Precedence > PrecedenceArrowAndPeriod)
1284 // Conditional expressions need to be parsed separately for proper nesting.
1285 if (Precedence == prec::Conditional) {
1286 parseConditionalExpr();
1290 // Parse unary operators, which all have a higher precedence than binary
1292 if (Precedence == PrecedenceUnaryOperator) {
1293 parseUnaryOperator();
1297 FormatToken *Start = Current;
1298 FormatToken *LatestOperator = nullptr;
1299 unsigned OperatorIndex = 0;
1302 // Consume operators with higher precedence.
1303 parse(Precedence + 1);
1305 int CurrentPrecedence = getCurrentPrecedence();
1307 if (Current && Current->is(TT_SelectorName) &&
1308 Precedence == CurrentPrecedence) {
1310 addFakeParenthesis(Start, prec::Level(Precedence));
1314 // At the end of the line or when an operator with higher precedence is
1315 // found, insert fake parenthesis and return.
1316 if (!Current || (Current->closesScope() && Current->MatchingParen) ||
1317 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1318 (CurrentPrecedence == prec::Conditional &&
1319 Precedence == prec::Assignment && Current->is(tok::colon))) {
1323 // Consume scopes: (), [], <> and {}
1324 if (Current->opensScope()) {
1325 while (Current && !Current->closesScope()) {
1332 if (CurrentPrecedence == Precedence) {
1334 LatestOperator->NextOperator = Current;
1335 LatestOperator = Current;
1336 Current->OperatorIndex = OperatorIndex;
1339 next(/*SkipPastLeadingComments=*/Precedence > 0);
1343 if (LatestOperator && (Current || Precedence > 0)) {
1344 // LatestOperator->LastOperator = true;
1345 if (Precedence == PrecedenceArrowAndPeriod) {
1346 // Call expressions don't have a binary operator precedence.
1347 addFakeParenthesis(Start, prec::Unknown);
1349 addFakeParenthesis(Start, prec::Level(Precedence));
1355 /// \brief Gets the precedence (+1) of the given token for binary operators
1356 /// and other tokens that we treat like binary operators.
1357 int getCurrentPrecedence() {
1359 const FormatToken *NextNonComment = Current->getNextNonComment();
1360 if (Current->is(TT_ConditionalExpr))
1361 return prec::Conditional;
1362 if (NextNonComment && NextNonComment->is(tok::colon) &&
1363 NextNonComment->is(TT_DictLiteral))
1365 if (Current->is(TT_LambdaArrow))
1367 if (Current->is(TT_JsFatArrow))
1368 return prec::Assignment;
1369 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName,
1370 TT_JsComputedPropertyName) ||
1371 (Current->is(tok::comment) && NextNonComment &&
1372 NextNonComment->is(TT_SelectorName)))
1374 if (Current->is(TT_RangeBasedForLoopColon))
1376 if ((Style.Language == FormatStyle::LK_Java ||
1377 Style.Language == FormatStyle::LK_JavaScript) &&
1378 Current->is(Keywords.kw_instanceof))
1379 return prec::Relational;
1380 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1381 return Current->getPrecedence();
1382 if (Current->isOneOf(tok::period, tok::arrow))
1383 return PrecedenceArrowAndPeriod;
1384 if (Style.Language == FormatStyle::LK_Java &&
1385 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1386 Keywords.kw_throws))
1392 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1393 Start->FakeLParens.push_back(Precedence);
1394 if (Precedence > prec::Unknown)
1395 Start->StartsBinaryExpression = true;
1397 FormatToken *Previous = Current->Previous;
1398 while (Previous->is(tok::comment) && Previous->Previous)
1399 Previous = Previous->Previous;
1400 ++Previous->FakeRParens;
1401 if (Precedence > prec::Unknown)
1402 Previous->EndsBinaryExpression = true;
1406 /// \brief Parse unary operator expressions and surround them with fake
1407 /// parentheses if appropriate.
1408 void parseUnaryOperator() {
1409 if (!Current || Current->isNot(TT_UnaryOperator)) {
1410 parse(PrecedenceArrowAndPeriod);
1414 FormatToken *Start = Current;
1416 parseUnaryOperator();
1418 // The actual precedence doesn't matter.
1419 addFakeParenthesis(Start, prec::Unknown);
1422 void parseConditionalExpr() {
1423 while (Current && Current->isTrailingComment()) {
1426 FormatToken *Start = Current;
1427 parse(prec::LogicalOr);
1428 if (!Current || !Current->is(tok::question))
1431 parse(prec::Assignment);
1432 if (!Current || Current->isNot(TT_ConditionalExpr))
1435 parse(prec::Assignment);
1436 addFakeParenthesis(Start, prec::Conditional);
1439 void next(bool SkipPastLeadingComments = true) {
1441 Current = Current->Next;
1443 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1444 Current->isTrailingComment())
1445 Current = Current->Next;
1448 const FormatStyle &Style;
1449 const AdditionalKeywords &Keywords;
1450 FormatToken *Current;
1453 } // end anonymous namespace
1455 void TokenAnnotator::setCommentLineLevels(
1456 SmallVectorImpl<AnnotatedLine *> &Lines) {
1457 const AnnotatedLine *NextNonCommentLine = nullptr;
1458 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1461 if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
1462 (*I)->First->Next == nullptr)
1463 (*I)->Level = NextNonCommentLine->Level;
1465 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1467 setCommentLineLevels((*I)->Children);
1471 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1472 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1473 E = Line.Children.end();
1477 AnnotatingParser Parser(Style, Line, Keywords);
1478 Line.Type = Parser.parseLine();
1479 if (Line.Type == LT_Invalid)
1482 ExpressionParser ExprParser(Style, Keywords, Line);
1485 if (Line.startsWith(TT_ObjCMethodSpecifier))
1486 Line.Type = LT_ObjCMethodDecl;
1487 else if (Line.startsWith(TT_ObjCDecl))
1488 Line.Type = LT_ObjCDecl;
1489 else if (Line.startsWith(TT_ObjCProperty))
1490 Line.Type = LT_ObjCProperty;
1492 Line.First->SpacesRequiredBefore = 1;
1493 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1496 // This function heuristically determines whether 'Current' starts the name of a
1497 // function declaration.
1498 static bool isFunctionDeclarationName(const FormatToken &Current) {
1499 auto skipOperatorName = [](const FormatToken* Next) -> const FormatToken* {
1500 for (; Next; Next = Next->Next) {
1501 if (Next->is(TT_OverloadedOperatorLParen))
1503 if (Next->is(TT_OverloadedOperator))
1505 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1506 // For 'new[]' and 'delete[]'.
1507 if (Next->Next && Next->Next->is(tok::l_square) &&
1508 Next->Next->Next && Next->Next->Next->is(tok::r_square))
1509 Next = Next->Next->Next;
1518 const FormatToken *Next = Current.Next;
1519 if (Current.is(tok::kw_operator)) {
1520 if (Current.Previous && Current.Previous->is(tok::coloncolon))
1522 Next = skipOperatorName(Next);
1524 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1526 for (; Next; Next = Next->Next) {
1527 if (Next->is(TT_TemplateOpener)) {
1528 Next = Next->MatchingParen;
1529 } else if (Next->is(tok::coloncolon)) {
1533 if (Next->is(tok::kw_operator)) {
1534 Next = skipOperatorName(Next->Next);
1537 if (!Next->is(tok::identifier))
1539 } else if (Next->is(tok::l_paren)) {
1547 if (!Next || !Next->is(tok::l_paren))
1549 if (Next->Next == Next->MatchingParen)
1551 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1553 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1554 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName))
1556 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1557 Tok->Tok.isLiteral())
1563 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
1564 assert(Line.MightBeFunctionDecl);
1566 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
1567 Style.AlwaysBreakAfterReturnType ==
1568 FormatStyle::RTBS_TopLevelDefinitions) &&
1572 switch (Style.AlwaysBreakAfterReturnType) {
1573 case FormatStyle::RTBS_None:
1575 case FormatStyle::RTBS_All:
1576 case FormatStyle::RTBS_TopLevel:
1578 case FormatStyle::RTBS_AllDefinitions:
1579 case FormatStyle::RTBS_TopLevelDefinitions:
1580 return Line.mightBeFunctionDefinition();
1586 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1587 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1588 E = Line.Children.end();
1590 calculateFormattingInformation(**I);
1593 Line.First->TotalLength =
1594 Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1595 if (!Line.First->Next)
1597 FormatToken *Current = Line.First->Next;
1598 bool InFunctionDecl = Line.MightBeFunctionDecl;
1600 if (isFunctionDeclarationName(*Current))
1601 Current->Type = TT_FunctionDeclarationName;
1602 if (Current->is(TT_LineComment)) {
1603 if (Current->Previous->BlockKind == BK_BracedInit &&
1604 Current->Previous->opensScope())
1605 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1607 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1609 // If we find a trailing comment, iterate backwards to determine whether
1610 // it seems to relate to a specific parameter. If so, break before that
1611 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1612 // to the previous line in:
1616 if (!Current->HasUnescapedNewline) {
1617 for (FormatToken *Parameter = Current->Previous; Parameter;
1618 Parameter = Parameter->Previous) {
1619 if (Parameter->isOneOf(tok::comment, tok::r_brace))
1621 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1622 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1623 Parameter->HasUnescapedNewline)
1624 Parameter->MustBreakBefore = true;
1629 } else if (Current->SpacesRequiredBefore == 0 &&
1630 spaceRequiredBefore(Line, *Current)) {
1631 Current->SpacesRequiredBefore = 1;
1634 Current->MustBreakBefore =
1635 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1637 if (!Current->MustBreakBefore && InFunctionDecl &&
1638 Current->is(TT_FunctionDeclarationName))
1639 Current->MustBreakBefore = mustBreakForReturnType(Line);
1641 Current->CanBreakBefore =
1642 Current->MustBreakBefore || canBreakBefore(Line, *Current);
1643 unsigned ChildSize = 0;
1644 if (Current->Previous->Children.size() == 1) {
1645 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1646 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1647 : LastOfChild.TotalLength + 1;
1649 const FormatToken *Prev = Current->Previous;
1650 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1651 (Prev->Children.size() == 1 &&
1652 Prev->Children[0]->First->MustBreakBefore) ||
1653 Current->IsMultiline)
1654 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1656 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1657 ChildSize + Current->SpacesRequiredBefore;
1659 if (Current->is(TT_CtorInitializerColon))
1660 InFunctionDecl = false;
1662 // FIXME: Only calculate this if CanBreakBefore is true once static
1663 // initializers etc. are sorted out.
1664 // FIXME: Move magic numbers to a better place.
1665 Current->SplitPenalty = 20 * Current->BindingStrength +
1666 splitPenalty(Line, *Current, InFunctionDecl);
1668 Current = Current->Next;
1671 calculateUnbreakableTailLengths(Line);
1672 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1674 Current->Role->precomputeFormattingInfos(Current);
1677 DEBUG({ printDebugInfo(Line); });
1680 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1681 unsigned UnbreakableTailLength = 0;
1682 FormatToken *Current = Line.Last;
1684 Current->UnbreakableTailLength = UnbreakableTailLength;
1685 if (Current->CanBreakBefore ||
1686 Current->isOneOf(tok::comment, tok::string_literal)) {
1687 UnbreakableTailLength = 0;
1689 UnbreakableTailLength +=
1690 Current->ColumnWidth + Current->SpacesRequiredBefore;
1692 Current = Current->Previous;
1696 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1697 const FormatToken &Tok,
1698 bool InFunctionDecl) {
1699 const FormatToken &Left = *Tok.Previous;
1700 const FormatToken &Right = Tok;
1702 if (Left.is(tok::semi))
1705 if (Style.Language == FormatStyle::LK_Java) {
1706 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
1708 if (Right.is(Keywords.kw_implements))
1710 if (Left.is(tok::comma) && Left.NestingLevel == 0)
1712 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1713 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
1715 if (Left.is(TT_JsTypeColon))
1719 if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
1720 Right.Next->is(TT_DictLiteral)))
1722 if (Right.is(tok::l_square)) {
1723 if (Style.Language == FormatStyle::LK_Proto)
1725 if (Left.is(tok::r_square))
1727 // Slightly prefer formatting local lambda definitions like functions.
1728 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
1730 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
1731 TT_ArrayInitializerLSquare))
1735 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
1736 Right.is(tok::kw_operator)) {
1737 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1739 if (Left.is(TT_StartOfName))
1741 if (InFunctionDecl && Right.NestingLevel == 0)
1742 return Style.PenaltyReturnTypeOnItsOwnLine;
1745 if (Right.is(TT_PointerOrReference))
1747 if (Right.is(TT_LambdaArrow))
1749 if (Left.is(tok::equal) && Right.is(tok::l_brace))
1751 if (Left.is(TT_CastRParen))
1753 if (Left.is(tok::coloncolon) ||
1754 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1756 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1759 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
1762 if (Right.isMemberAccess()) {
1763 // Breaking before the "./->" of a chained call/member access is reasonably
1764 // cheap, as formatting those with one call per line is generally
1765 // desirable. In particular, it should be cheaper to break before the call
1766 // than it is to break inside a call's parameters, which could lead to weird
1767 // "hanging" indents. The exception is the very last "./->" to support this
1768 // frequent pattern:
1770 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
1773 // which might otherwise be blown up onto many lines. Here, clang-format
1774 // won't produce "hanging" indents anyway as there is no other trailing
1777 // Also apply higher penalty is not a call as that might lead to a wrapping
1781 // .aaaaaaaaa.bbbbbbbb(cccccccc);
1782 return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
1787 if (Right.is(TT_TrailingAnnotation) &&
1788 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
1789 // Moving trailing annotations to the next line is fine for ObjC method
1791 if (Line.startsWith(TT_ObjCMethodSpecifier))
1793 // Generally, breaking before a trailing annotation is bad unless it is
1794 // function-like. It seems to be especially preferable to keep standard
1795 // annotations (i.e. "const", "final" and "override") on the same line.
1796 // Use a slightly higher penalty after ")" so that annotations like
1797 // "const override" are kept together.
1798 bool is_short_annotation = Right.TokenText.size() < 10;
1799 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
1802 // In for-loops, prefer breaking at ',' and ';'.
1803 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
1806 // In Objective-C method expressions, prefer breaking before "param:" over
1807 // breaking after it.
1808 if (Right.is(TT_SelectorName))
1810 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
1811 return Line.MightBeFunctionDecl ? 50 : 500;
1813 if (Left.is(tok::l_paren) && InFunctionDecl &&
1814 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
1816 if (Left.is(tok::l_paren) && Left.Previous &&
1817 Left.Previous->isOneOf(tok::kw_if, tok::kw_for))
1819 if (Left.is(tok::equal) && InFunctionDecl)
1821 if (Right.is(tok::r_brace))
1823 if (Left.is(TT_TemplateOpener))
1825 if (Left.opensScope()) {
1826 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
1828 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1831 if (Left.is(TT_JavaAnnotation))
1834 if (Right.is(tok::lessless)) {
1835 if (Left.is(tok::string_literal) &&
1836 (Right.NextOperator || Right.OperatorIndex != 1)) {
1837 StringRef Content = Left.TokenText;
1838 if (Content.startswith("\""))
1839 Content = Content.drop_front(1);
1840 if (Content.endswith("\""))
1841 Content = Content.drop_back(1);
1842 Content = Content.trim();
1843 if (Content.size() > 1 &&
1844 (Content.back() == ':' || Content.back() == '='))
1847 return 1; // Breaking at a << is really cheap.
1849 if (Left.is(TT_ConditionalExpr))
1850 return prec::Conditional;
1851 prec::Level Level = Left.getPrecedence();
1852 if (Level != prec::Unknown)
1854 Level = Right.getPrecedence();
1855 if (Level != prec::Unknown)
1861 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1862 const FormatToken &Left,
1863 const FormatToken &Right) {
1864 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
1866 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1867 Left.Tok.getObjCKeywordID() == tok::objc_property)
1869 if (Right.is(tok::hashhash))
1870 return Left.is(tok::hash);
1871 if (Left.isOneOf(tok::hashhash, tok::hash))
1872 return Right.is(tok::hash);
1873 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
1874 return Style.SpaceInEmptyParentheses;
1875 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
1876 return (Right.is(TT_CastRParen) ||
1877 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
1878 ? Style.SpacesInCStyleCastParentheses
1879 : Style.SpacesInParentheses;
1880 if (Right.isOneOf(tok::semi, tok::comma))
1882 if (Right.is(tok::less) &&
1883 (Left.is(tok::kw_template) ||
1884 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1886 if (Left.isOneOf(tok::exclaim, tok::tilde))
1888 if (Left.is(tok::at) &&
1889 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1890 tok::numeric_constant, tok::l_paren, tok::l_brace,
1891 tok::kw_true, tok::kw_false))
1893 if (Left.is(tok::colon))
1894 return !Left.is(TT_ObjCMethodExpr);
1895 if (Left.is(tok::coloncolon))
1897 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
1899 if (Right.is(tok::ellipsis))
1900 return Left.Tok.isLiteral();
1901 if (Left.is(tok::l_square) && Right.is(tok::amp))
1903 if (Right.is(TT_PointerOrReference))
1904 return (Left.is(tok::r_paren) && Left.MatchingParen &&
1905 (Left.MatchingParen->is(TT_OverloadedOperatorLParen) ||
1906 (Left.MatchingParen->Previous &&
1907 Left.MatchingParen->Previous->is(TT_FunctionDeclarationName)))) ||
1908 (Left.Tok.isLiteral() ||
1909 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
1910 (Style.PointerAlignment != FormatStyle::PAS_Left ||
1911 Line.IsMultiVariableDeclStmt)));
1912 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
1913 (!Left.is(TT_PointerOrReference) ||
1914 (Style.PointerAlignment != FormatStyle::PAS_Right &&
1915 !Line.IsMultiVariableDeclStmt)))
1917 if (Left.is(TT_PointerOrReference))
1918 return Right.Tok.isLiteral() ||
1919 Right.isOneOf(TT_BlockComment, Keywords.kw_final,
1920 Keywords.kw_override) ||
1921 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
1922 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
1924 (Style.PointerAlignment != FormatStyle::PAS_Right &&
1925 !Line.IsMultiVariableDeclStmt) &&
1927 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
1928 if (Right.is(tok::star) && Left.is(tok::l_paren))
1930 if (Left.is(tok::l_square))
1931 return (Left.is(TT_ArrayInitializerLSquare) &&
1932 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
1933 (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
1934 Right.isNot(tok::r_square));
1935 if (Right.is(tok::r_square))
1936 return Right.MatchingParen &&
1937 ((Style.SpacesInContainerLiterals &&
1938 Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
1939 (Style.SpacesInSquareBrackets &&
1940 Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
1941 if (Right.is(tok::l_square) &&
1942 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
1943 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
1945 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1946 return !Left.Children.empty(); // No spaces in "{}".
1947 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
1948 (Right.is(tok::r_brace) && Right.MatchingParen &&
1949 Right.MatchingParen->BlockKind != BK_Block))
1950 return !Style.Cpp11BracedListStyle;
1951 if (Left.is(TT_BlockComment))
1952 return !Left.TokenText.endswith("=*/");
1953 if (Right.is(tok::l_paren)) {
1954 if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
1956 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
1957 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
1958 (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
1959 tok::kw_switch, tok::kw_case, TT_ForEachMacro,
1961 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
1962 tok::kw_new, tok::kw_delete) &&
1963 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
1964 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
1965 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
1966 Left.is(tok::r_paren)) &&
1967 Line.Type != LT_PreprocessorDirective);
1969 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
1971 if (Right.is(TT_UnaryOperator))
1972 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
1973 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
1974 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
1976 Left.isSimpleTypeSpecifier()) &&
1977 Right.is(tok::l_brace) && Right.getNextNonComment() &&
1978 Right.BlockKind != BK_Block)
1980 if (Left.is(tok::period) || Right.is(tok::period))
1982 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
1984 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
1985 Left.MatchingParen->Previous &&
1986 Left.MatchingParen->Previous->is(tok::period))
1987 // A.<B>DoSomething();
1989 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
1994 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
1995 const FormatToken &Right) {
1996 const FormatToken &Left = *Right.Previous;
1997 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
1998 return true; // Never ever merge two identifiers.
1999 if (Style.Language == FormatStyle::LK_Cpp) {
2000 if (Left.is(tok::kw_operator))
2001 return Right.is(tok::coloncolon);
2002 } else if (Style.Language == FormatStyle::LK_Proto) {
2003 if (Right.is(tok::period) &&
2004 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
2005 Keywords.kw_repeated, Keywords.kw_extend))
2007 if (Right.is(tok::l_paren) &&
2008 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
2010 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2011 if (Left.isOneOf(Keywords.kw_let, Keywords.kw_var, TT_JsFatArrow,
2014 if (Left.is(tok::kw_default) && Left.Previous &&
2015 Left.Previous->is(tok::kw_export))
2017 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2019 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2021 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2022 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2024 if (Left.is(tok::ellipsis))
2026 if (Left.is(TT_TemplateCloser) &&
2027 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2028 Keywords.kw_implements, Keywords.kw_extends))
2029 // Type assertions ('<type>expr') are not followed by whitespace. Other
2030 // locations that should have whitespace following are identified by the
2031 // above set of follower tokens.
2033 } else if (Style.Language == FormatStyle::LK_Java) {
2034 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2036 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2037 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2038 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2039 tok::kw_protected) ||
2040 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2041 Keywords.kw_native)) &&
2042 Right.is(TT_TemplateOpener))
2045 if (Left.is(TT_ImplicitStringLiteral))
2046 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2047 if (Line.Type == LT_ObjCMethodDecl) {
2048 if (Left.is(TT_ObjCMethodSpecifier))
2050 if (Left.is(tok::r_paren) && Right.is(tok::identifier))
2051 // Don't space between ')' and <id>
2054 if (Line.Type == LT_ObjCProperty &&
2055 (Right.is(tok::equal) || Left.is(tok::equal)))
2058 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2059 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2061 if (Left.is(tok::comma))
2063 if (Right.is(tok::comma))
2065 if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
2067 if (Right.is(TT_OverloadedOperatorLParen))
2068 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2069 if (Right.is(tok::colon)) {
2070 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2071 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2073 if (Right.is(TT_ObjCMethodExpr))
2075 if (Left.is(tok::question))
2077 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2079 if (Right.is(TT_DictLiteral))
2080 return Style.SpacesInContainerLiterals;
2083 if (Left.is(TT_UnaryOperator))
2084 return Right.is(TT_BinaryOperator);
2086 // If the next token is a binary operator or a selector name, we have
2087 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2088 if (Left.is(TT_CastRParen))
2089 return Style.SpaceAfterCStyleCast ||
2090 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2092 if (Left.is(tok::greater) && Right.is(tok::greater))
2093 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2094 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2095 if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2096 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
2098 if (!Style.SpaceBeforeAssignmentOperators &&
2099 Right.getPrecedence() == prec::Assignment)
2101 if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
2102 return (Left.is(TT_TemplateOpener) &&
2103 Style.Standard == FormatStyle::LS_Cpp03) ||
2104 !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren) ||
2105 Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
2106 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2107 return Style.SpacesInAngles;
2108 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2109 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2110 !Right.is(tok::r_paren)))
2112 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2113 Right.isNot(TT_FunctionTypeLParen))
2114 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2115 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2116 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2118 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2119 Line.startsWith(tok::hash))
2121 if (Right.is(TT_TrailingUnaryOperator))
2123 if (Left.is(TT_RegexLiteral))
2125 return spaceRequiredBetween(Line, Left, Right);
2128 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2129 static bool isAllmanBrace(const FormatToken &Tok) {
2130 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2131 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2134 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2135 const FormatToken &Right) {
2136 const FormatToken &Left = *Right.Previous;
2137 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2140 if (Style.Language == FormatStyle::LK_JavaScript) {
2141 // FIXME: This might apply to other languages and token kinds.
2142 if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
2143 Left.Previous->is(tok::char_constant))
2145 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2146 Left.Previous && Left.Previous->is(tok::equal) &&
2147 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2149 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2151 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2152 // Object literals on the top level of a file are treated as "enum-style".
2153 // Each key/value pair is put on a separate line, instead of bin-packing.
2155 if (Left.is(tok::l_brace) && Line.Level == 0 &&
2156 (Line.startsWith(tok::kw_enum) ||
2157 Line.startsWith(tok::kw_export, tok::kw_enum)))
2158 // JavaScript top-level enum key/value pairs are put on separate lines
2159 // instead of bin-packing.
2161 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2162 !Left.Children.empty())
2163 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2164 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2165 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2166 (Left.NestingLevel == 0 && Line.Level == 0 &&
2167 Style.AllowShortFunctionsOnASingleLine ==
2168 FormatStyle::SFS_Inline);
2169 } else if (Style.Language == FormatStyle::LK_Java) {
2170 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2171 Right.Next->is(tok::string_literal))
2175 // If the last token before a '}' is a comma or a trailing comment, the
2176 // intention is to insert a line break after it in order to make shuffling
2177 // around entries easier.
2178 const FormatToken *BeforeClosingBrace = nullptr;
2179 if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
2180 Left.BlockKind != BK_Block && Left.MatchingParen)
2181 BeforeClosingBrace = Left.MatchingParen->Previous;
2182 else if (Right.MatchingParen &&
2183 Right.MatchingParen->isOneOf(tok::l_brace,
2184 TT_ArrayInitializerLSquare))
2185 BeforeClosingBrace = &Left;
2186 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2187 BeforeClosingBrace->isTrailingComment()))
2190 if (Right.is(tok::comment))
2191 return Left.BlockKind != BK_BracedInit &&
2192 Left.isNot(TT_CtorInitializerColon) &&
2193 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2194 if (Left.isTrailingComment())
2196 if (Left.isStringLiteral() &&
2197 (Right.isStringLiteral() || Right.is(TT_ObjCStringLiteral)))
2199 if (Right.Previous->IsUnterminatedLiteral)
2201 if (Right.is(tok::lessless) && Right.Next &&
2202 Right.Previous->is(tok::string_literal) &&
2203 Right.Next->is(tok::string_literal))
2205 if (Right.Previous->ClosesTemplateDeclaration &&
2206 Right.Previous->MatchingParen &&
2207 Right.Previous->MatchingParen->NestingLevel == 0 &&
2208 Style.AlwaysBreakTemplateDeclarations)
2210 if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
2211 Style.BreakConstructorInitializersBeforeComma &&
2212 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2214 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2215 // Raw string literals are special wrt. line breaks. The author has made a
2216 // deliberate choice and might have aligned the contents of the string
2217 // literal accordingly. Thus, we try keep existing line breaks.
2218 return Right.NewlinesBefore > 0;
2219 if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
2220 Style.Language == FormatStyle::LK_Proto)
2221 // Don't put enums onto single lines in protocol buffers.
2223 if (Right.is(TT_InlineASMBrace))
2224 return Right.HasUnescapedNewline;
2225 if (isAllmanBrace(Left) || isAllmanBrace(Right))
2226 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2227 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2228 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2229 if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) &&
2230 Right.is(TT_SelectorName))
2232 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2235 if ((Style.Language == FormatStyle::LK_Java ||
2236 Style.Language == FormatStyle::LK_JavaScript) &&
2237 Left.is(TT_LeadingJavaAnnotation) &&
2238 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2239 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2245 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2246 const FormatToken &Right) {
2247 const FormatToken &Left = *Right.Previous;
2249 // Language-specific stuff.
2250 if (Style.Language == FormatStyle::LK_Java) {
2251 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2252 Keywords.kw_implements))
2254 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2255 Keywords.kw_implements))
2257 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2258 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2260 if (Left.is(TT_JsTypeColon))
2262 if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is))
2266 if (Left.is(tok::at))
2268 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2270 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2271 return !Right.is(tok::l_paren);
2272 if (Right.is(TT_PointerOrReference))
2273 return Line.IsMultiVariableDeclStmt ||
2274 (Style.PointerAlignment == FormatStyle::PAS_Right &&
2275 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2276 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2277 Right.is(tok::kw_operator))
2279 if (Left.is(TT_PointerOrReference))
2281 if (Right.isTrailingComment())
2282 // We rely on MustBreakBefore being set correctly here as we should not
2283 // change the "binding" behavior of a comment.
2284 // The first comment in a braced lists is always interpreted as belonging to
2285 // the first list element. Otherwise, it should be placed outside of the
2287 return Left.BlockKind == BK_BracedInit;
2288 if (Left.is(tok::question) && Right.is(tok::colon))
2290 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2291 return Style.BreakBeforeTernaryOperators;
2292 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2293 return !Style.BreakBeforeTernaryOperators;
2294 if (Right.is(TT_InheritanceColon))
2296 if (Right.is(tok::colon) &&
2297 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2299 if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
2301 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2302 Right.Next->is(TT_ObjCMethodExpr)))
2303 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2304 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2306 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
2308 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2309 TT_OverloadedOperator))
2311 if (Left.is(TT_RangeBasedForLoopColon))
2313 if (Right.is(TT_RangeBasedForLoopColon))
2315 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2316 Left.is(tok::kw_operator))
2318 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2319 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
2321 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2323 if (Left.is(tok::l_paren) && Left.Previous &&
2324 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2326 if (Right.is(TT_ImplicitStringLiteral))
2329 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2331 if (Right.is(tok::r_square) && Right.MatchingParen &&
2332 Right.MatchingParen->is(TT_LambdaLSquare))
2335 // We only break before r_brace if there was a corresponding break before
2336 // the l_brace, which is tracked by BreakBeforeClosingBrace.
2337 if (Right.is(tok::r_brace))
2338 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2340 // Allow breaking after a trailing annotation, e.g. after a method
2342 if (Left.is(TT_TrailingAnnotation))
2343 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2344 tok::less, tok::coloncolon);
2346 if (Right.is(tok::kw___attribute))
2349 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2352 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2355 if (Left.is(TT_CtorInitializerComma) &&
2356 Style.BreakConstructorInitializersBeforeComma)
2358 if (Right.is(TT_CtorInitializerComma) &&
2359 Style.BreakConstructorInitializersBeforeComma)
2361 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2362 (Left.is(tok::less) && Right.is(tok::less)))
2364 if (Right.is(TT_BinaryOperator) &&
2365 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2366 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2367 Right.getPrecedence() != prec::Assignment))
2369 if (Left.is(TT_ArrayInitializerLSquare))
2371 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2373 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
2374 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2375 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2376 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2377 Left.getPrecedence() == prec::Assignment))
2379 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2380 tok::kw_class, tok::kw_struct) ||
2381 Right.isMemberAccess() ||
2382 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2383 tok::colon, tok::l_square, tok::at) ||
2384 (Left.is(tok::r_paren) &&
2385 Right.isOneOf(tok::identifier, tok::kw_const)) ||
2386 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
2389 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2390 llvm::errs() << "AnnotatedTokens:\n";
2391 const FormatToken *Tok = Line.First;
2393 llvm::errs() << " M=" << Tok->MustBreakBefore
2394 << " C=" << Tok->CanBreakBefore
2395 << " T=" << getTokenTypeName(Tok->Type)
2396 << " S=" << Tok->SpacesRequiredBefore
2397 << " B=" << Tok->BlockParameterCount
2398 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
2399 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
2401 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2402 llvm::errs() << Tok->FakeLParens[i] << "/";
2403 llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
2405 assert(Tok == Line.Last);
2408 llvm::errs() << "----\n";
2411 } // namespace format
2412 } // namespace clang