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;
289 Parent->isOneOf(tok::at, tok::equal, tok::comma, tok::l_paren,
290 tok::l_square, tok::question, tok::colon,
292 Left->Type = TT_ArrayInitializerLSquare;
294 BindingIncrease = 10;
295 Left->Type = TT_ArraySubscriptLSquare;
299 ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
300 Contexts.back().IsExpression = true;
301 Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
303 while (CurrentToken) {
304 if (CurrentToken->is(tok::r_square)) {
305 if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
306 Left->is(TT_ObjCMethodExpr)) {
307 // An ObjC method call is rarely followed by an open parenthesis.
308 // FIXME: Do we incorrectly label ":" with this?
309 StartsObjCMethodExpr = false;
310 Left->Type = TT_Unknown;
312 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
313 CurrentToken->Type = TT_ObjCMethodExpr;
314 // determineStarAmpUsage() thinks that '*' '[' is allocating an
315 // array of pointers, but if '[' starts a selector then '*' is a
317 if (Parent && Parent->is(TT_PointerOrReference))
318 Parent->Type = TT_BinaryOperator;
320 Left->MatchingParen = CurrentToken;
321 CurrentToken->MatchingParen = Left;
322 if (Contexts.back().FirstObjCSelectorName) {
323 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
324 Contexts.back().LongestObjCSelectorName;
325 if (Left->BlockParameterCount > 1)
326 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
331 if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
333 if (CurrentToken->is(tok::colon)) {
334 if (Left->is(TT_ArraySubscriptLSquare)) {
335 Left->Type = TT_ObjCMethodExpr;
336 StartsObjCMethodExpr = true;
337 Contexts.back().ColonIsObjCMethodExpr = true;
338 if (Parent && Parent->is(tok::r_paren))
339 Parent->Type = TT_CastRParen;
343 if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
345 Left->Type = TT_ArrayInitializerLSquare;
346 FormatToken *Tok = CurrentToken;
349 updateParameterCount(Left, Tok);
356 FormatToken *Left = CurrentToken->Previous;
357 Left->ParentBracket = Contexts.back().ContextKind;
359 if (Contexts.back().CaretFound)
360 Left->Type = TT_ObjCBlockLBrace;
361 Contexts.back().CaretFound = false;
363 ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
364 Contexts.back().ColonIsDictLiteral = true;
365 if (Left->BlockKind == BK_BracedInit)
366 Contexts.back().IsExpression = true;
368 while (CurrentToken) {
369 if (CurrentToken->is(tok::r_brace)) {
370 Left->MatchingParen = CurrentToken;
371 CurrentToken->MatchingParen = Left;
375 if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
377 updateParameterCount(Left, CurrentToken);
378 if (CurrentToken->isOneOf(tok::colon, tok::l_brace)) {
379 FormatToken *Previous = CurrentToken->getPreviousNonComment();
380 if (((CurrentToken->is(tok::colon) &&
381 (!Contexts.back().ColonIsDictLiteral ||
382 Style.Language != FormatStyle::LK_Cpp)) ||
383 Style.Language == FormatStyle::LK_Proto) &&
384 Previous->Tok.getIdentifierInfo())
385 Previous->Type = TT_SelectorName;
386 if (CurrentToken->is(tok::colon) ||
387 Style.Language == FormatStyle::LK_JavaScript)
388 Left->Type = TT_DictLiteral;
397 void updateParameterCount(FormatToken *Left, FormatToken *Current) {
398 if (Current->is(tok::l_brace) && !Current->is(TT_DictLiteral))
399 ++Left->BlockParameterCount;
400 if (Current->is(tok::comma)) {
401 ++Left->ParameterCount;
403 Left->Role.reset(new CommaSeparatedList(Style));
404 Left->Role->CommaFound(Current);
405 } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
406 Left->ParameterCount = 1;
410 bool parseConditional() {
411 while (CurrentToken) {
412 if (CurrentToken->is(tok::colon)) {
413 CurrentToken->Type = TT_ConditionalExpr;
423 bool parseTemplateDeclaration() {
424 if (CurrentToken && CurrentToken->is(tok::less)) {
425 CurrentToken->Type = TT_TemplateOpener;
430 CurrentToken->Previous->ClosesTemplateDeclaration = true;
436 bool consumeToken() {
437 FormatToken *Tok = CurrentToken;
439 switch (Tok->Tok.getKind()) {
442 if (!Tok->Previous && Line.MustBeDeclaration)
443 Tok->Type = TT_ObjCMethodSpecifier;
448 // Colons from ?: are handled in parseConditional().
449 if (Style.Language == FormatStyle::LK_JavaScript) {
450 if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
451 (Contexts.size() == 1 && // switch/case labels
452 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
453 Contexts.back().ContextKind == tok::l_paren || // function params
454 Contexts.back().ContextKind == tok::l_square || // array type
455 (Contexts.size() == 1 &&
456 Line.MustBeDeclaration)) { // method/property declaration
457 Tok->Type = TT_JsTypeColon;
461 if (Contexts.back().ColonIsDictLiteral) {
462 Tok->Type = TT_DictLiteral;
463 } else if (Contexts.back().ColonIsObjCMethodExpr ||
464 Line.startsWith(TT_ObjCMethodSpecifier)) {
465 Tok->Type = TT_ObjCMethodExpr;
466 Tok->Previous->Type = TT_SelectorName;
467 if (Tok->Previous->ColumnWidth >
468 Contexts.back().LongestObjCSelectorName) {
469 Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth;
471 if (!Contexts.back().FirstObjCSelectorName)
472 Contexts.back().FirstObjCSelectorName = Tok->Previous;
473 } else if (Contexts.back().ColonIsForRangeExpr) {
474 Tok->Type = TT_RangeBasedForLoopColon;
475 } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
476 Tok->Type = TT_BitFieldColon;
477 } else if (Contexts.size() == 1 &&
478 !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
479 if (Tok->Previous->is(tok::r_paren))
480 Tok->Type = TT_CtorInitializerColon;
482 Tok->Type = TT_InheritanceColon;
483 } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
484 Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
485 // This handles a special macro in ObjC code where selectors including
486 // the colon are passed as macro arguments.
487 Tok->Type = TT_ObjCMethodExpr;
488 } else if (Contexts.back().ContextKind == tok::l_paren) {
489 Tok->Type = TT_InlineASMColon;
494 if (CurrentToken && CurrentToken->is(tok::l_paren)) {
496 if (!parseParens(/*LookForDecls=*/true))
501 Contexts.back().ColonIsForRangeExpr = true;
507 // When faced with 'operator()()', the kw_operator handler incorrectly
508 // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
509 // the first two parens OverloadedOperators and the second l_paren an
510 // OverloadedOperatorLParen.
512 Tok->Previous->is(tok::r_paren) &&
513 Tok->Previous->MatchingParen &&
514 Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
515 Tok->Previous->Type = TT_OverloadedOperator;
516 Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
517 Tok->Type = TT_OverloadedOperatorLParen;
522 if (Line.MustBeDeclaration && Contexts.size() == 1 &&
523 !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
525 !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
526 TT_LeadingJavaAnnotation)))
527 Line.MightBeFunctionDecl = true;
538 if (!NonTemplateLess.count(Tok) &&
540 (!Tok->Previous->Tok.isLiteral() &&
541 !(Tok->Previous->is(tok::r_paren) && Contexts.size() > 1))) &&
543 Tok->Type = TT_TemplateOpener;
545 Tok->Type = TT_BinaryOperator;
546 NonTemplateLess.insert(Tok);
555 // Lines can start with '}'.
560 Tok->Type = TT_BinaryOperator;
562 case tok::kw_operator:
563 while (CurrentToken &&
564 !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
565 if (CurrentToken->isOneOf(tok::star, tok::amp))
566 CurrentToken->Type = TT_PointerOrReference;
568 if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator))
569 CurrentToken->Previous->Type = TT_OverloadedOperator;
572 CurrentToken->Type = TT_OverloadedOperatorLParen;
573 if (CurrentToken->Previous->is(TT_BinaryOperator))
574 CurrentToken->Previous->Type = TT_OverloadedOperator;
578 if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
579 Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
581 // Question marks before semicolons, colons, etc. indicate optional
582 // types (fields, parameters), e.g.
583 // function(x?: string, y?) {...}
585 Tok->Type = TT_JsTypeOptionalQuestion;
588 // Declarations cannot be conditional expressions, this can only be part
589 // of a type declaration.
590 if (Line.MustBeDeclaration &&
591 Style.Language == FormatStyle::LK_JavaScript)
595 case tok::kw_template:
596 parseTemplateDeclaration();
599 if (Contexts.back().InCtorInitializer)
600 Tok->Type = TT_CtorInitializerComma;
601 else if (Contexts.back().FirstStartOfName &&
602 (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
603 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
604 Line.IsMultiVariableDeclStmt = true;
606 if (Contexts.back().IsForEachMacro)
607 Contexts.back().IsExpression = true;
615 void parseIncludeDirective() {
616 if (CurrentToken && CurrentToken->is(tok::less)) {
618 while (CurrentToken) {
619 if (CurrentToken->isNot(tok::comment) || CurrentToken->Next)
620 CurrentToken->Type = TT_ImplicitStringLiteral;
626 void parseWarningOrError() {
628 // We still want to format the whitespace left of the first token of the
631 while (CurrentToken) {
632 CurrentToken->Type = TT_ImplicitStringLiteral;
638 next(); // Consume "pragma".
640 CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
641 bool IsMark = CurrentToken->is(Keywords.kw_mark);
642 next(); // Consume "mark".
643 next(); // Consume first token (so we fix leading whitespace).
644 while (CurrentToken) {
645 if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
646 CurrentToken->Type = TT_ImplicitStringLiteral;
652 LineType parsePreprocessorDirective() {
653 LineType Type = LT_PreprocessorDirective;
657 if (CurrentToken->Tok.is(tok::numeric_constant)) {
658 CurrentToken->SpacesRequiredBefore = 1;
661 // Hashes in the middle of a line can lead to any strange token
663 if (!CurrentToken->Tok.getIdentifierInfo())
665 switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
666 case tok::pp_include:
667 case tok::pp_include_next:
670 parseIncludeDirective();
671 Type = LT_ImportStatement;
674 case tok::pp_warning:
675 parseWarningOrError();
682 Contexts.back().IsExpression = true;
694 LineType parseLine() {
695 NonTemplateLess.clear();
696 if (CurrentToken->is(tok::hash))
697 return parsePreprocessorDirective();
699 // Directly allow to 'import <string-literal>' to support protocol buffer
700 // definitions (code.google.com/p/protobuf) or missing "#" (either way we
701 // should not break the line).
702 IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
703 if ((Style.Language == FormatStyle::LK_Java &&
704 CurrentToken->is(Keywords.kw_package)) ||
705 (Info && Info->getPPKeywordID() == tok::pp_import &&
706 CurrentToken->Next &&
707 CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
710 parseIncludeDirective();
711 return LT_ImportStatement;
714 // If this line starts and ends in '<' and '>', respectively, it is likely
715 // part of "#define <a/b.h>".
716 if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
717 parseIncludeDirective();
718 return LT_ImportStatement;
721 // In .proto files, top-level options are very similar to import statements
722 // and should not be line-wrapped.
723 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
724 CurrentToken->is(Keywords.kw_option)) {
726 if (CurrentToken && CurrentToken->is(tok::identifier))
727 return LT_ImportStatement;
730 bool KeywordVirtualFound = false;
731 bool ImportStatement = false;
732 while (CurrentToken) {
733 if (CurrentToken->is(tok::kw_virtual))
734 KeywordVirtualFound = true;
735 if (isImportStatement(*CurrentToken))
736 ImportStatement = true;
740 if (KeywordVirtualFound)
741 return LT_VirtualFunctionDecl;
743 return LT_ImportStatement;
745 if (Line.startsWith(TT_ObjCMethodSpecifier)) {
746 if (Contexts.back().FirstObjCSelectorName)
747 Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
748 Contexts.back().LongestObjCSelectorName;
749 return LT_ObjCMethodDecl;
756 bool isImportStatement(const FormatToken &Tok) {
757 // FIXME: Closure-library specific stuff should not be hard-coded but be
759 return Style.Language == FormatStyle::LK_JavaScript &&
760 Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
761 Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
762 Tok.Next->Next->TokenText == "provide" ||
763 Tok.Next->Next->TokenText == "require" ||
764 Tok.Next->Next->TokenText == "setTestOnly") &&
765 Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
768 void resetTokenMetadata(FormatToken *Token) {
772 // Reset token type in case we have already looked at it and then
773 // recovered from an error (e.g. failure to find the matching >).
774 if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
775 TT_FunctionLBrace, TT_ImplicitStringLiteral,
776 TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
778 CurrentToken->Type = TT_Unknown;
779 CurrentToken->Role.reset();
780 CurrentToken->MatchingParen = nullptr;
781 CurrentToken->FakeLParens.clear();
782 CurrentToken->FakeRParens = 0;
787 CurrentToken->NestingLevel = Contexts.size() - 1;
788 CurrentToken->BindingStrength = Contexts.back().BindingStrength;
789 modifyContext(*CurrentToken);
790 determineTokenType(*CurrentToken);
791 CurrentToken = CurrentToken->Next;
794 resetTokenMetadata(CurrentToken);
797 /// \brief A struct to hold information valid in a specific context, e.g.
798 /// a pair of parenthesis.
800 Context(tok::TokenKind ContextKind, unsigned BindingStrength,
802 : ContextKind(ContextKind), BindingStrength(BindingStrength),
803 IsExpression(IsExpression) {}
805 tok::TokenKind ContextKind;
806 unsigned BindingStrength;
808 unsigned LongestObjCSelectorName = 0;
809 bool ColonIsForRangeExpr = false;
810 bool ColonIsDictLiteral = false;
811 bool ColonIsObjCMethodExpr = false;
812 FormatToken *FirstObjCSelectorName = nullptr;
813 FormatToken *FirstStartOfName = nullptr;
814 bool CanBeExpression = true;
815 bool InTemplateArgument = false;
816 bool InCtorInitializer = false;
817 bool CaretFound = false;
818 bool IsForEachMacro = false;
821 /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
822 /// of each instance.
823 struct ScopedContextCreator {
826 ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
829 P.Contexts.push_back(Context(ContextKind,
830 P.Contexts.back().BindingStrength + Increase,
831 P.Contexts.back().IsExpression));
834 ~ScopedContextCreator() { P.Contexts.pop_back(); }
837 void modifyContext(const FormatToken &Current) {
838 if (Current.getPrecedence() == prec::Assignment &&
839 !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
840 (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
841 Contexts.back().IsExpression = true;
842 if (!Line.startsWith(TT_UnaryOperator)) {
843 for (FormatToken *Previous = Current.Previous;
844 Previous && Previous->Previous &&
845 !Previous->Previous->isOneOf(tok::comma, tok::semi);
846 Previous = Previous->Previous) {
847 if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
848 Previous = Previous->MatchingParen;
852 if (Previous->opensScope())
854 if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
855 Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
856 Previous->Previous && Previous->Previous->isNot(tok::equal))
857 Previous->Type = TT_PointerOrReference;
860 } else if (Current.is(tok::lessless) &&
861 (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
862 Contexts.back().IsExpression = true;
863 } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
864 Contexts.back().IsExpression = true;
865 } else if (Current.is(TT_TrailingReturnArrow)) {
866 Contexts.back().IsExpression = false;
867 } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
868 Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
869 } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
870 for (FormatToken *Previous = Current.Previous;
871 Previous && Previous->isOneOf(tok::star, tok::amp);
872 Previous = Previous->Previous)
873 Previous->Type = TT_PointerOrReference;
874 if (Line.MustBeDeclaration)
875 Contexts.back().IsExpression = Contexts.front().InCtorInitializer;
876 } else if (Current.Previous &&
877 Current.Previous->is(TT_CtorInitializerColon)) {
878 Contexts.back().IsExpression = true;
879 Contexts.back().InCtorInitializer = true;
880 } else if (Current.is(tok::kw_new)) {
881 Contexts.back().CanBeExpression = false;
882 } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
883 // This should be the condition or increment in a for-loop.
884 Contexts.back().IsExpression = true;
888 void determineTokenType(FormatToken &Current) {
889 if (!Current.is(TT_Unknown))
890 // The token type is already known.
893 // Line.MightBeFunctionDecl can only be true after the parentheses of a
894 // function declaration have been found. In this case, 'Current' is a
895 // trailing token of this declaration and thus cannot be a name.
896 if (Current.is(Keywords.kw_instanceof)) {
897 Current.Type = TT_BinaryOperator;
898 } else if (isStartOfName(Current) &&
899 (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
900 Contexts.back().FirstStartOfName = &Current;
901 Current.Type = TT_StartOfName;
902 } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
904 } else if (Current.is(tok::arrow) &&
905 Style.Language == FormatStyle::LK_Java) {
906 Current.Type = TT_LambdaArrow;
907 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
908 Current.NestingLevel == 0) {
909 Current.Type = TT_TrailingReturnArrow;
910 } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
912 determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
913 Contexts.back().IsExpression,
914 Contexts.back().InTemplateArgument);
915 } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
916 Current.Type = determinePlusMinusCaretUsage(Current);
917 if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
918 Contexts.back().CaretFound = true;
919 } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
920 Current.Type = determineIncrementUsage(Current);
921 } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
922 Current.Type = TT_UnaryOperator;
923 } else if (Current.is(tok::question)) {
924 if (Style.Language == FormatStyle::LK_JavaScript &&
925 Line.MustBeDeclaration) {
926 // In JavaScript, `interface X { foo?(): bar; }` is an optional method
927 // on the interface, not a ternary expression.
928 Current.Type = TT_JsTypeOptionalQuestion;
930 Current.Type = TT_ConditionalExpr;
932 } else if (Current.isBinaryOperator() &&
933 (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
934 Current.Type = TT_BinaryOperator;
935 } else if (Current.is(tok::comment)) {
936 if (Current.TokenText.startswith("/*")) {
937 if (Current.TokenText.endswith("*/"))
938 Current.Type = TT_BlockComment;
940 // The lexer has for some reason determined a comment here. But we
941 // cannot really handle it, if it isn't properly terminated.
942 Current.Tok.setKind(tok::unknown);
944 Current.Type = TT_LineComment;
946 } else if (Current.is(tok::r_paren)) {
947 if (rParenEndsCast(Current))
948 Current.Type = TT_CastRParen;
949 if (Current.MatchingParen && Current.Next &&
950 !Current.Next->isBinaryOperator() &&
951 !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace))
952 if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
953 if (BeforeParen->is(tok::identifier) &&
954 BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
955 (!BeforeParen->Previous ||
956 BeforeParen->Previous->ClosesTemplateDeclaration))
957 Current.Type = TT_FunctionAnnotationRParen;
958 } else if (Current.is(tok::at) && Current.Next) {
959 if (Current.Next->isStringLiteral()) {
960 Current.Type = TT_ObjCStringLiteral;
962 switch (Current.Next->Tok.getObjCKeywordID()) {
963 case tok::objc_interface:
964 case tok::objc_implementation:
965 case tok::objc_protocol:
966 Current.Type = TT_ObjCDecl;
968 case tok::objc_property:
969 Current.Type = TT_ObjCProperty;
975 } else if (Current.is(tok::period)) {
976 FormatToken *PreviousNoComment = Current.getPreviousNonComment();
977 if (PreviousNoComment &&
978 PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
979 Current.Type = TT_DesignatedInitializerPeriod;
980 else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
981 Current.Previous->isOneOf(TT_JavaAnnotation,
982 TT_LeadingJavaAnnotation)) {
983 Current.Type = Current.Previous->Type;
985 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
987 !Current.Previous->isOneOf(tok::equal, tok::at) &&
988 Line.MightBeFunctionDecl && Contexts.size() == 1) {
989 // Line.MightBeFunctionDecl can only be true after the parentheses of a
990 // function declaration have been found.
991 Current.Type = TT_TrailingAnnotation;
992 } else if ((Style.Language == FormatStyle::LK_Java ||
993 Style.Language == FormatStyle::LK_JavaScript) &&
995 if (Current.Previous->is(tok::at) &&
996 Current.isNot(Keywords.kw_interface)) {
997 const FormatToken &AtToken = *Current.Previous;
998 const FormatToken *Previous = AtToken.getPreviousNonComment();
999 if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
1000 Current.Type = TT_LeadingJavaAnnotation;
1002 Current.Type = TT_JavaAnnotation;
1003 } else if (Current.Previous->is(tok::period) &&
1004 Current.Previous->isOneOf(TT_JavaAnnotation,
1005 TT_LeadingJavaAnnotation)) {
1006 Current.Type = Current.Previous->Type;
1011 /// \brief Take a guess at whether \p Tok starts a name of a function or
1012 /// variable declaration.
1014 /// This is a heuristic based on whether \p Tok is an identifier following
1015 /// something that is likely a type.
1016 bool isStartOfName(const FormatToken &Tok) {
1017 if (Tok.isNot(tok::identifier) || !Tok.Previous)
1020 if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof))
1023 // Skip "const" as it does not have an influence on whether this is a name.
1024 FormatToken *PreviousNotConst = Tok.Previous;
1025 while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
1026 PreviousNotConst = PreviousNotConst->Previous;
1028 if (!PreviousNotConst)
1031 bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
1032 PreviousNotConst->Previous &&
1033 PreviousNotConst->Previous->is(tok::hash);
1035 if (PreviousNotConst->is(TT_TemplateCloser))
1036 return PreviousNotConst && PreviousNotConst->MatchingParen &&
1037 PreviousNotConst->MatchingParen->Previous &&
1038 PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
1039 PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
1041 if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
1042 PreviousNotConst->MatchingParen->Previous &&
1043 PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
1046 return (!IsPPKeyword &&
1047 PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
1048 PreviousNotConst->is(TT_PointerOrReference) ||
1049 PreviousNotConst->isSimpleTypeSpecifier();
1052 /// \brief Determine whether ')' is ending a cast.
1053 bool rParenEndsCast(const FormatToken &Tok) {
1054 // C-style casts are only used in C++ and Java.
1055 if (Style.Language != FormatStyle::LK_Cpp &&
1056 Style.Language != FormatStyle::LK_Java)
1059 // Empty parens aren't casts and there are no casts at the end of the line.
1060 if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
1063 FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
1065 // If there is an opening parenthesis left of the current parentheses,
1066 // look past it as these might be chained casts.
1067 if (LeftOfParens->is(tok::r_paren)) {
1068 if (!LeftOfParens->MatchingParen ||
1069 !LeftOfParens->MatchingParen->Previous)
1071 LeftOfParens = LeftOfParens->MatchingParen->Previous;
1074 // If there is an identifier (or with a few exceptions a keyword) right
1075 // before the parentheses, this is unlikely to be a cast.
1076 if (LeftOfParens->Tok.getIdentifierInfo() &&
1077 !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
1081 // Certain other tokens right before the parentheses are also signals that
1082 // this cannot be a cast.
1083 if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
1088 if (Tok.Next->is(tok::question))
1091 // As Java has no function types, a "(" after the ")" likely means that this
1093 if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
1096 // If a (non-string) literal follows, this is likely a cast.
1097 if (Tok.Next->isNot(tok::string_literal) &&
1098 (Tok.Next->Tok.isLiteral() ||
1099 Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
1102 // Heuristically try to determine whether the parentheses contain a type.
1103 bool ParensAreType =
1105 Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
1106 Tok.Previous->isSimpleTypeSpecifier();
1107 bool ParensCouldEndDecl =
1108 Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
1109 if (ParensAreType && !ParensCouldEndDecl)
1112 // At this point, we heuristically assume that there are no casts at the
1113 // start of the line. We assume that we have found most cases where there
1114 // are by the logic above, e.g. "(void)x;".
1118 // If the following token is an identifier, this is a cast. All cases where
1119 // this can be something else are handled above.
1120 if (Tok.Next->is(tok::identifier))
1123 if (!Tok.Next->Next)
1126 // If the next token after the parenthesis is a unary operator, assume
1127 // that this is cast, unless there are unexpected tokens inside the
1130 Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
1131 if (!NextIsUnary || Tok.Next->is(tok::plus) ||
1132 !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
1134 // Search for unexpected tokens.
1135 for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
1136 Prev = Prev->Previous) {
1137 if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
1143 /// \brief Return the type of the given token assuming it is * or &.
1144 TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
1145 bool InTemplateArgument) {
1146 if (Style.Language == FormatStyle::LK_JavaScript)
1147 return TT_BinaryOperator;
1149 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1151 return TT_UnaryOperator;
1153 const FormatToken *NextToken = Tok.getNextNonComment();
1155 NextToken->isOneOf(tok::arrow, Keywords.kw_final,
1156 Keywords.kw_override) ||
1157 (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
1158 return TT_PointerOrReference;
1160 if (PrevToken->is(tok::coloncolon))
1161 return TT_PointerOrReference;
1163 if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
1164 tok::comma, tok::semi, tok::kw_return, tok::colon,
1165 tok::equal, tok::kw_delete, tok::kw_sizeof) ||
1166 PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
1167 TT_UnaryOperator, TT_CastRParen))
1168 return TT_UnaryOperator;
1170 if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
1171 return TT_PointerOrReference;
1172 if (NextToken->is(tok::kw_operator) && !IsExpression)
1173 return TT_PointerOrReference;
1174 if (NextToken->isOneOf(tok::comma, tok::semi))
1175 return TT_PointerOrReference;
1177 if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen &&
1178 PrevToken->MatchingParen->Previous &&
1179 PrevToken->MatchingParen->Previous->isOneOf(tok::kw_typeof,
1181 return TT_PointerOrReference;
1183 if (PrevToken->Tok.isLiteral() ||
1184 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
1185 tok::kw_false, tok::r_brace) ||
1186 NextToken->Tok.isLiteral() ||
1187 NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
1188 NextToken->isUnaryOperator() ||
1189 // If we know we're in a template argument, there are no named
1190 // declarations. Thus, having an identifier on the right-hand side
1191 // indicates a binary operator.
1192 (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
1193 return TT_BinaryOperator;
1195 // "&&(" is quite unlikely to be two successive unary "&".
1196 if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
1197 return TT_BinaryOperator;
1199 // This catches some cases where evaluation order is used as control flow:
1201 const FormatToken *NextNextToken = NextToken->getNextNonComment();
1202 if (NextNextToken && NextNextToken->is(tok::arrow))
1203 return TT_BinaryOperator;
1205 // It is very unlikely that we are going to find a pointer or reference type
1206 // definition on the RHS of an assignment.
1207 if (IsExpression && !Contexts.back().CaretFound)
1208 return TT_BinaryOperator;
1210 return TT_PointerOrReference;
1213 TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
1214 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1215 if (!PrevToken || PrevToken->is(TT_CastRParen))
1216 return TT_UnaryOperator;
1218 // Use heuristics to recognize unary operators.
1219 if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
1220 tok::question, tok::colon, tok::kw_return,
1221 tok::kw_case, tok::at, tok::l_brace))
1222 return TT_UnaryOperator;
1224 // There can't be two consecutive binary operators.
1225 if (PrevToken->is(TT_BinaryOperator))
1226 return TT_UnaryOperator;
1228 // Fall back to marking the token as binary operator.
1229 return TT_BinaryOperator;
1232 /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
1233 TokenType determineIncrementUsage(const FormatToken &Tok) {
1234 const FormatToken *PrevToken = Tok.getPreviousNonComment();
1235 if (!PrevToken || PrevToken->is(TT_CastRParen))
1236 return TT_UnaryOperator;
1237 if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
1238 return TT_TrailingUnaryOperator;
1240 return TT_UnaryOperator;
1243 SmallVector<Context, 8> Contexts;
1245 const FormatStyle &Style;
1246 AnnotatedLine &Line;
1247 FormatToken *CurrentToken;
1249 const AdditionalKeywords &Keywords;
1251 // Set of "<" tokens that do not open a template parameter list. If parseAngle
1252 // determines that a specific token can't be a template opener, it will make
1253 // same decision irrespective of the decisions for tokens leading up to it.
1254 // Store this information to prevent this from causing exponential runtime.
1255 llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
1258 static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
1259 static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
1261 /// \brief Parses binary expressions by inserting fake parenthesis based on
1262 /// operator precedence.
1263 class ExpressionParser {
1265 ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
1266 AnnotatedLine &Line)
1267 : Style(Style), Keywords(Keywords), Current(Line.First) {}
1269 /// \brief Parse expressions with the given operatore precedence.
1270 void parse(int Precedence = 0) {
1271 // Skip 'return' and ObjC selector colons as they are not part of a binary
1273 while (Current && (Current->is(tok::kw_return) ||
1274 (Current->is(tok::colon) &&
1275 Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
1278 if (!Current || Precedence > PrecedenceArrowAndPeriod)
1281 // Conditional expressions need to be parsed separately for proper nesting.
1282 if (Precedence == prec::Conditional) {
1283 parseConditionalExpr();
1287 // Parse unary operators, which all have a higher precedence than binary
1289 if (Precedence == PrecedenceUnaryOperator) {
1290 parseUnaryOperator();
1294 FormatToken *Start = Current;
1295 FormatToken *LatestOperator = nullptr;
1296 unsigned OperatorIndex = 0;
1299 // Consume operators with higher precedence.
1300 parse(Precedence + 1);
1302 int CurrentPrecedence = getCurrentPrecedence();
1304 if (Current && Current->is(TT_SelectorName) &&
1305 Precedence == CurrentPrecedence) {
1307 addFakeParenthesis(Start, prec::Level(Precedence));
1311 // At the end of the line or when an operator with higher precedence is
1312 // found, insert fake parenthesis and return.
1313 if (!Current || (Current->closesScope() && Current->MatchingParen) ||
1314 (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
1315 (CurrentPrecedence == prec::Conditional &&
1316 Precedence == prec::Assignment && Current->is(tok::colon))) {
1320 // Consume scopes: (), [], <> and {}
1321 if (Current->opensScope()) {
1322 while (Current && !Current->closesScope()) {
1329 if (CurrentPrecedence == Precedence) {
1330 LatestOperator = Current;
1331 Current->OperatorIndex = OperatorIndex;
1334 next(/*SkipPastLeadingComments=*/Precedence > 0);
1338 if (LatestOperator && (Current || Precedence > 0)) {
1339 LatestOperator->LastOperator = true;
1340 if (Precedence == PrecedenceArrowAndPeriod) {
1341 // Call expressions don't have a binary operator precedence.
1342 addFakeParenthesis(Start, prec::Unknown);
1344 addFakeParenthesis(Start, prec::Level(Precedence));
1350 /// \brief Gets the precedence (+1) of the given token for binary operators
1351 /// and other tokens that we treat like binary operators.
1352 int getCurrentPrecedence() {
1354 const FormatToken *NextNonComment = Current->getNextNonComment();
1355 if (Current->is(TT_ConditionalExpr))
1356 return prec::Conditional;
1357 if (NextNonComment && NextNonComment->is(tok::colon) &&
1358 NextNonComment->is(TT_DictLiteral))
1360 if (Current->is(TT_LambdaArrow))
1362 if (Current->is(TT_JsFatArrow))
1363 return prec::Assignment;
1364 if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName,
1365 TT_JsComputedPropertyName) ||
1366 (Current->is(tok::comment) && NextNonComment &&
1367 NextNonComment->is(TT_SelectorName)))
1369 if (Current->is(TT_RangeBasedForLoopColon))
1371 if ((Style.Language == FormatStyle::LK_Java ||
1372 Style.Language == FormatStyle::LK_JavaScript) &&
1373 Current->is(Keywords.kw_instanceof))
1374 return prec::Relational;
1375 if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
1376 return Current->getPrecedence();
1377 if (Current->isOneOf(tok::period, tok::arrow))
1378 return PrecedenceArrowAndPeriod;
1379 if (Style.Language == FormatStyle::LK_Java &&
1380 Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
1381 Keywords.kw_throws))
1387 void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
1388 Start->FakeLParens.push_back(Precedence);
1389 if (Precedence > prec::Unknown)
1390 Start->StartsBinaryExpression = true;
1392 FormatToken *Previous = Current->Previous;
1393 while (Previous->is(tok::comment) && Previous->Previous)
1394 Previous = Previous->Previous;
1395 ++Previous->FakeRParens;
1396 if (Precedence > prec::Unknown)
1397 Previous->EndsBinaryExpression = true;
1401 /// \brief Parse unary operator expressions and surround them with fake
1402 /// parentheses if appropriate.
1403 void parseUnaryOperator() {
1404 if (!Current || Current->isNot(TT_UnaryOperator)) {
1405 parse(PrecedenceArrowAndPeriod);
1409 FormatToken *Start = Current;
1411 parseUnaryOperator();
1413 // The actual precedence doesn't matter.
1414 addFakeParenthesis(Start, prec::Unknown);
1417 void parseConditionalExpr() {
1418 while (Current && Current->isTrailingComment()) {
1421 FormatToken *Start = Current;
1422 parse(prec::LogicalOr);
1423 if (!Current || !Current->is(tok::question))
1426 parse(prec::Assignment);
1427 if (!Current || Current->isNot(TT_ConditionalExpr))
1430 parse(prec::Assignment);
1431 addFakeParenthesis(Start, prec::Conditional);
1434 void next(bool SkipPastLeadingComments = true) {
1436 Current = Current->Next;
1438 (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
1439 Current->isTrailingComment())
1440 Current = Current->Next;
1443 const FormatStyle &Style;
1444 const AdditionalKeywords &Keywords;
1445 FormatToken *Current;
1448 } // end anonymous namespace
1450 void TokenAnnotator::setCommentLineLevels(
1451 SmallVectorImpl<AnnotatedLine *> &Lines) {
1452 const AnnotatedLine *NextNonCommentLine = nullptr;
1453 for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
1456 if (NextNonCommentLine && (*I)->First->is(tok::comment) &&
1457 (*I)->First->Next == nullptr)
1458 (*I)->Level = NextNonCommentLine->Level;
1460 NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
1462 setCommentLineLevels((*I)->Children);
1466 void TokenAnnotator::annotate(AnnotatedLine &Line) {
1467 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1468 E = Line.Children.end();
1472 AnnotatingParser Parser(Style, Line, Keywords);
1473 Line.Type = Parser.parseLine();
1474 if (Line.Type == LT_Invalid)
1477 ExpressionParser ExprParser(Style, Keywords, Line);
1480 if (Line.startsWith(TT_ObjCMethodSpecifier))
1481 Line.Type = LT_ObjCMethodDecl;
1482 else if (Line.startsWith(TT_ObjCDecl))
1483 Line.Type = LT_ObjCDecl;
1484 else if (Line.startsWith(TT_ObjCProperty))
1485 Line.Type = LT_ObjCProperty;
1487 Line.First->SpacesRequiredBefore = 1;
1488 Line.First->CanBreakBefore = Line.First->MustBreakBefore;
1491 // This function heuristically determines whether 'Current' starts the name of a
1492 // function declaration.
1493 static bool isFunctionDeclarationName(const FormatToken &Current) {
1494 auto skipOperatorName = [](const FormatToken* Next) -> const FormatToken* {
1495 for (; Next; Next = Next->Next) {
1496 if (Next->is(TT_OverloadedOperatorLParen))
1498 if (Next->is(TT_OverloadedOperator))
1500 if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
1501 // For 'new[]' and 'delete[]'.
1502 if (Next->Next && Next->Next->is(tok::l_square) &&
1503 Next->Next->Next && Next->Next->Next->is(tok::r_square))
1504 Next = Next->Next->Next;
1513 const FormatToken *Next = Current.Next;
1514 if (Current.is(tok::kw_operator)) {
1515 if (Current.Previous && Current.Previous->is(tok::coloncolon))
1517 Next = skipOperatorName(Next);
1519 if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
1521 for (; Next; Next = Next->Next) {
1522 if (Next->is(TT_TemplateOpener)) {
1523 Next = Next->MatchingParen;
1524 } else if (Next->is(tok::coloncolon)) {
1528 if (Next->is(tok::kw_operator)) {
1529 Next = skipOperatorName(Next->Next);
1532 if (!Next->is(tok::identifier))
1534 } else if (Next->is(tok::l_paren)) {
1542 if (!Next || !Next->is(tok::l_paren))
1544 if (Next->Next == Next->MatchingParen)
1546 for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
1548 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
1549 Tok->isOneOf(TT_PointerOrReference, TT_StartOfName))
1551 if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
1552 Tok->Tok.isLiteral())
1558 bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
1559 assert(Line.MightBeFunctionDecl);
1561 if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
1562 Style.AlwaysBreakAfterReturnType ==
1563 FormatStyle::RTBS_TopLevelDefinitions) &&
1567 switch (Style.AlwaysBreakAfterReturnType) {
1568 case FormatStyle::RTBS_None:
1570 case FormatStyle::RTBS_All:
1571 case FormatStyle::RTBS_TopLevel:
1573 case FormatStyle::RTBS_AllDefinitions:
1574 case FormatStyle::RTBS_TopLevelDefinitions:
1575 return Line.mightBeFunctionDefinition();
1581 void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
1582 for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
1583 E = Line.Children.end();
1585 calculateFormattingInformation(**I);
1588 Line.First->TotalLength =
1589 Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
1590 if (!Line.First->Next)
1592 FormatToken *Current = Line.First->Next;
1593 bool InFunctionDecl = Line.MightBeFunctionDecl;
1595 if (isFunctionDeclarationName(*Current))
1596 Current->Type = TT_FunctionDeclarationName;
1597 if (Current->is(TT_LineComment)) {
1598 if (Current->Previous->BlockKind == BK_BracedInit &&
1599 Current->Previous->opensScope())
1600 Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
1602 Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
1604 // If we find a trailing comment, iterate backwards to determine whether
1605 // it seems to relate to a specific parameter. If so, break before that
1606 // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
1607 // to the previous line in:
1611 if (!Current->HasUnescapedNewline) {
1612 for (FormatToken *Parameter = Current->Previous; Parameter;
1613 Parameter = Parameter->Previous) {
1614 if (Parameter->isOneOf(tok::comment, tok::r_brace))
1616 if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
1617 if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
1618 Parameter->HasUnescapedNewline)
1619 Parameter->MustBreakBefore = true;
1624 } else if (Current->SpacesRequiredBefore == 0 &&
1625 spaceRequiredBefore(Line, *Current)) {
1626 Current->SpacesRequiredBefore = 1;
1629 Current->MustBreakBefore =
1630 Current->MustBreakBefore || mustBreakBefore(Line, *Current);
1632 if (!Current->MustBreakBefore && InFunctionDecl &&
1633 Current->is(TT_FunctionDeclarationName))
1634 Current->MustBreakBefore = mustBreakForReturnType(Line);
1636 Current->CanBreakBefore =
1637 Current->MustBreakBefore || canBreakBefore(Line, *Current);
1638 unsigned ChildSize = 0;
1639 if (Current->Previous->Children.size() == 1) {
1640 FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
1641 ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
1642 : LastOfChild.TotalLength + 1;
1644 const FormatToken *Prev = Current->Previous;
1645 if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
1646 (Prev->Children.size() == 1 &&
1647 Prev->Children[0]->First->MustBreakBefore) ||
1648 Current->IsMultiline)
1649 Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
1651 Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
1652 ChildSize + Current->SpacesRequiredBefore;
1654 if (Current->is(TT_CtorInitializerColon))
1655 InFunctionDecl = false;
1657 // FIXME: Only calculate this if CanBreakBefore is true once static
1658 // initializers etc. are sorted out.
1659 // FIXME: Move magic numbers to a better place.
1660 Current->SplitPenalty = 20 * Current->BindingStrength +
1661 splitPenalty(Line, *Current, InFunctionDecl);
1663 Current = Current->Next;
1666 calculateUnbreakableTailLengths(Line);
1667 for (Current = Line.First; Current != nullptr; Current = Current->Next) {
1669 Current->Role->precomputeFormattingInfos(Current);
1672 DEBUG({ printDebugInfo(Line); });
1675 void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
1676 unsigned UnbreakableTailLength = 0;
1677 FormatToken *Current = Line.Last;
1679 Current->UnbreakableTailLength = UnbreakableTailLength;
1680 if (Current->CanBreakBefore ||
1681 Current->isOneOf(tok::comment, tok::string_literal)) {
1682 UnbreakableTailLength = 0;
1684 UnbreakableTailLength +=
1685 Current->ColumnWidth + Current->SpacesRequiredBefore;
1687 Current = Current->Previous;
1691 unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
1692 const FormatToken &Tok,
1693 bool InFunctionDecl) {
1694 const FormatToken &Left = *Tok.Previous;
1695 const FormatToken &Right = Tok;
1697 if (Left.is(tok::semi))
1700 if (Style.Language == FormatStyle::LK_Java) {
1701 if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
1703 if (Right.is(Keywords.kw_implements))
1705 if (Left.is(tok::comma) && Left.NestingLevel == 0)
1707 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1708 if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
1710 if (Left.is(TT_JsTypeColon))
1714 if (Left.is(tok::comma) || (Right.is(tok::identifier) && Right.Next &&
1715 Right.Next->is(TT_DictLiteral)))
1717 if (Right.is(tok::l_square)) {
1718 if (Style.Language == FormatStyle::LK_Proto || Left.is(tok::r_square))
1720 // Slightly prefer formatting local lambda definitions like functions.
1721 if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
1723 if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
1724 TT_ArrayInitializerLSquare))
1728 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
1729 Right.is(tok::kw_operator)) {
1730 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
1732 if (Left.is(TT_StartOfName))
1734 if (InFunctionDecl && Right.NestingLevel == 0)
1735 return Style.PenaltyReturnTypeOnItsOwnLine;
1738 if (Right.is(TT_PointerOrReference))
1740 if (Right.is(TT_LambdaArrow))
1742 if (Left.is(tok::equal) && Right.is(tok::l_brace))
1744 if (Left.is(TT_CastRParen))
1746 if (Left.is(tok::coloncolon) ||
1747 (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
1749 if (Left.isOneOf(tok::kw_class, tok::kw_struct))
1752 if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon))
1755 if (Right.isMemberAccess()) {
1756 // Breaking before the "./->" of a chained call/member access is reasonably
1757 // cheap, as formatting those with one call per line is generally
1758 // desirable. In particular, it should be cheaper to break before the call
1759 // than it is to break inside a call's parameters, which could lead to weird
1760 // "hanging" indents. The exception is the very last "./->" to support this
1761 // frequent pattern:
1763 // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
1766 // which might otherwise be blown up onto many lines. Here, clang-format
1767 // won't produce "hanging" indents anyway as there is no other trailing
1769 return Right.LastOperator ? 150 : 40;
1772 if (Right.is(TT_TrailingAnnotation) &&
1773 (!Right.Next || Right.Next->isNot(tok::l_paren))) {
1774 // Moving trailing annotations to the next line is fine for ObjC method
1776 if (Line.startsWith(TT_ObjCMethodSpecifier))
1778 // Generally, breaking before a trailing annotation is bad unless it is
1779 // function-like. It seems to be especially preferable to keep standard
1780 // annotations (i.e. "const", "final" and "override") on the same line.
1781 // Use a slightly higher penalty after ")" so that annotations like
1782 // "const override" are kept together.
1783 bool is_short_annotation = Right.TokenText.size() < 10;
1784 return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
1787 // In for-loops, prefer breaking at ',' and ';'.
1788 if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
1791 // In Objective-C method expressions, prefer breaking before "param:" over
1792 // breaking after it.
1793 if (Right.is(TT_SelectorName))
1795 if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
1796 return Line.MightBeFunctionDecl ? 50 : 500;
1798 if (Left.is(tok::l_paren) && InFunctionDecl &&
1799 Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
1801 if (Left.is(tok::l_paren) && Left.Previous &&
1802 Left.Previous->isOneOf(tok::kw_if, tok::kw_for))
1804 if (Left.is(tok::equal) && InFunctionDecl)
1806 if (Right.is(tok::r_brace))
1808 if (Left.is(TT_TemplateOpener))
1810 if (Left.opensScope()) {
1811 if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
1813 return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
1816 if (Left.is(TT_JavaAnnotation))
1819 if (Right.is(tok::lessless)) {
1820 if (Left.is(tok::string_literal) &&
1821 (!Right.LastOperator || Right.OperatorIndex != 1)) {
1822 StringRef Content = Left.TokenText;
1823 if (Content.startswith("\""))
1824 Content = Content.drop_front(1);
1825 if (Content.endswith("\""))
1826 Content = Content.drop_back(1);
1827 Content = Content.trim();
1828 if (Content.size() > 1 &&
1829 (Content.back() == ':' || Content.back() == '='))
1832 return 1; // Breaking at a << is really cheap.
1834 if (Left.is(TT_ConditionalExpr))
1835 return prec::Conditional;
1836 prec::Level Level = Left.getPrecedence();
1837 if (Level != prec::Unknown)
1839 Level = Right.getPrecedence();
1840 if (Level != prec::Unknown)
1846 bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
1847 const FormatToken &Left,
1848 const FormatToken &Right) {
1849 if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
1851 if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
1852 Left.Tok.getObjCKeywordID() == tok::objc_property)
1854 if (Right.is(tok::hashhash))
1855 return Left.is(tok::hash);
1856 if (Left.isOneOf(tok::hashhash, tok::hash))
1857 return Right.is(tok::hash);
1858 if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
1859 return Style.SpaceInEmptyParentheses;
1860 if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
1861 return (Right.is(TT_CastRParen) ||
1862 (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
1863 ? Style.SpacesInCStyleCastParentheses
1864 : Style.SpacesInParentheses;
1865 if (Right.isOneOf(tok::semi, tok::comma))
1867 if (Right.is(tok::less) &&
1868 (Left.is(tok::kw_template) ||
1869 (Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)))
1871 if (Left.isOneOf(tok::exclaim, tok::tilde))
1873 if (Left.is(tok::at) &&
1874 Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
1875 tok::numeric_constant, tok::l_paren, tok::l_brace,
1876 tok::kw_true, tok::kw_false))
1878 if (Left.is(tok::coloncolon))
1880 if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
1882 if (Right.is(tok::ellipsis))
1883 return Left.Tok.isLiteral();
1884 if (Left.is(tok::l_square) && Right.is(tok::amp))
1886 if (Right.is(TT_PointerOrReference))
1887 return (Left.is(tok::r_paren) && Left.MatchingParen &&
1888 (Left.MatchingParen->is(TT_OverloadedOperatorLParen) ||
1889 (Left.MatchingParen->Previous &&
1890 Left.MatchingParen->Previous->is(TT_FunctionDeclarationName)))) ||
1891 (Left.Tok.isLiteral() ||
1892 (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
1893 (Style.PointerAlignment != FormatStyle::PAS_Left ||
1894 Line.IsMultiVariableDeclStmt)));
1895 if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
1896 (!Left.is(TT_PointerOrReference) ||
1897 (Style.PointerAlignment != FormatStyle::PAS_Right &&
1898 !Line.IsMultiVariableDeclStmt)))
1900 if (Left.is(TT_PointerOrReference))
1901 return Right.Tok.isLiteral() ||
1902 Right.isOneOf(TT_BlockComment, Keywords.kw_final,
1903 Keywords.kw_override) ||
1904 (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
1905 (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
1907 (Style.PointerAlignment != FormatStyle::PAS_Right &&
1908 !Line.IsMultiVariableDeclStmt) &&
1910 !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
1911 if (Right.is(tok::star) && Left.is(tok::l_paren))
1913 if (Left.is(tok::l_square))
1914 return (Left.is(TT_ArrayInitializerLSquare) &&
1915 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
1916 (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets &&
1917 Right.isNot(tok::r_square));
1918 if (Right.is(tok::r_square))
1919 return Right.MatchingParen &&
1920 ((Style.SpacesInContainerLiterals &&
1921 Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
1922 (Style.SpacesInSquareBrackets &&
1923 Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
1924 if (Right.is(tok::l_square) &&
1925 !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare) &&
1926 !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
1928 if (Left.is(tok::colon))
1929 return !Left.is(TT_ObjCMethodExpr);
1930 if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
1931 return !Left.Children.empty(); // No spaces in "{}".
1932 if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
1933 (Right.is(tok::r_brace) && Right.MatchingParen &&
1934 Right.MatchingParen->BlockKind != BK_Block))
1935 return !Style.Cpp11BracedListStyle;
1936 if (Left.is(TT_BlockComment))
1937 return !Left.TokenText.endswith("=*/");
1938 if (Right.is(tok::l_paren)) {
1939 if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
1941 return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
1942 (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
1943 (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
1944 tok::kw_switch, tok::kw_case, TT_ForEachMacro,
1946 (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
1947 tok::kw_new, tok::kw_delete) &&
1948 (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
1949 (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
1950 (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
1951 Left.is(tok::r_paren)) &&
1952 Line.Type != LT_PreprocessorDirective);
1954 if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
1956 if (Right.is(TT_UnaryOperator))
1957 return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
1958 (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
1959 if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
1961 Left.isSimpleTypeSpecifier()) &&
1962 Right.is(tok::l_brace) && Right.getNextNonComment() &&
1963 Right.BlockKind != BK_Block)
1965 if (Left.is(tok::period) || Right.is(tok::period))
1967 if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
1969 if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
1970 Left.MatchingParen->Previous &&
1971 Left.MatchingParen->Previous->is(tok::period))
1972 // A.<B>DoSomething();
1974 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
1979 bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
1980 const FormatToken &Right) {
1981 const FormatToken &Left = *Right.Previous;
1982 if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
1983 return true; // Never ever merge two identifiers.
1984 if (Style.Language == FormatStyle::LK_Cpp) {
1985 if (Left.is(tok::kw_operator))
1986 return Right.is(tok::coloncolon);
1987 } else if (Style.Language == FormatStyle::LK_Proto) {
1988 if (Right.is(tok::period) &&
1989 Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
1990 Keywords.kw_repeated, Keywords.kw_extend))
1992 if (Right.is(tok::l_paren) &&
1993 Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
1995 } else if (Style.Language == FormatStyle::LK_JavaScript) {
1996 if (Left.isOneOf(Keywords.kw_let, Keywords.kw_var, TT_JsFatArrow,
1999 if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
2001 if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
2003 if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
2004 Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
2006 if (Left.is(tok::ellipsis))
2008 if (Left.is(TT_TemplateCloser) &&
2009 !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
2010 Keywords.kw_implements, Keywords.kw_extends))
2011 // Type assertions ('<type>expr') are not followed by whitespace. Other
2012 // locations that should have whitespace following are identified by the
2013 // above set of follower tokens.
2015 } else if (Style.Language == FormatStyle::LK_Java) {
2016 if (Left.is(tok::r_square) && Right.is(tok::l_brace))
2018 if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
2019 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
2020 if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
2021 tok::kw_protected) ||
2022 Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
2023 Keywords.kw_native)) &&
2024 Right.is(TT_TemplateOpener))
2027 if (Left.is(TT_ImplicitStringLiteral))
2028 return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
2029 if (Line.Type == LT_ObjCMethodDecl) {
2030 if (Left.is(TT_ObjCMethodSpecifier))
2032 if (Left.is(tok::r_paren) && Right.is(tok::identifier))
2033 // Don't space between ')' and <id>
2036 if (Line.Type == LT_ObjCProperty &&
2037 (Right.is(tok::equal) || Left.is(tok::equal)))
2040 if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
2041 Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
2043 if (Left.is(tok::comma))
2045 if (Right.is(tok::comma))
2047 if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
2049 if (Right.is(TT_OverloadedOperatorLParen))
2050 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2051 if (Right.is(tok::colon)) {
2052 if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
2053 !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
2055 if (Right.is(TT_ObjCMethodExpr))
2057 if (Left.is(tok::question))
2059 if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
2061 if (Right.is(TT_DictLiteral))
2062 return Style.SpacesInContainerLiterals;
2065 if (Left.is(TT_UnaryOperator))
2066 return Right.is(TT_BinaryOperator);
2068 // If the next token is a binary operator or a selector name, we have
2069 // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
2070 if (Left.is(TT_CastRParen))
2071 return Style.SpaceAfterCStyleCast ||
2072 Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
2074 if (Left.is(tok::greater) && Right.is(tok::greater))
2075 return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
2076 (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
2077 if (Right.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
2078 Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar))
2080 if (!Style.SpaceBeforeAssignmentOperators &&
2081 Right.getPrecedence() == prec::Assignment)
2083 if (Right.is(tok::coloncolon) && Left.isNot(tok::l_brace))
2084 return (Left.is(TT_TemplateOpener) &&
2085 Style.Standard == FormatStyle::LS_Cpp03) ||
2086 !(Left.isOneOf(tok::identifier, tok::l_paren, tok::r_paren) ||
2087 Left.isOneOf(TT_TemplateCloser, TT_TemplateOpener));
2088 if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
2089 return Style.SpacesInAngles;
2090 if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
2091 (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
2092 !Right.is(tok::r_paren)))
2094 if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
2095 Right.isNot(TT_FunctionTypeLParen))
2096 return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
2097 if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
2098 Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
2100 if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
2101 Line.startsWith(tok::hash))
2103 if (Right.is(TT_TrailingUnaryOperator))
2105 if (Left.is(TT_RegexLiteral))
2107 return spaceRequiredBetween(Line, Left, Right);
2110 // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
2111 static bool isAllmanBrace(const FormatToken &Tok) {
2112 return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
2113 !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
2116 bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
2117 const FormatToken &Right) {
2118 const FormatToken &Left = *Right.Previous;
2119 if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
2122 if (Style.Language == FormatStyle::LK_JavaScript) {
2123 // FIXME: This might apply to other languages and token kinds.
2124 if (Right.is(tok::char_constant) && Left.is(tok::plus) && Left.Previous &&
2125 Left.Previous->is(tok::char_constant))
2127 if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
2128 Left.Previous && Left.Previous->is(tok::equal) &&
2129 Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
2131 // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
2133 !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
2134 // Object literals on the top level of a file are treated as "enum-style".
2135 // Each key/value pair is put on a separate line, instead of bin-packing.
2137 if (Left.is(tok::l_brace) && Line.Level == 0 &&
2138 (Line.startsWith(tok::kw_enum) ||
2139 Line.startsWith(tok::kw_export, tok::kw_enum)))
2140 // JavaScript top-level enum key/value pairs are put on separate lines
2141 // instead of bin-packing.
2143 if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
2144 !Left.Children.empty())
2145 // Support AllowShortFunctionsOnASingleLine for JavaScript.
2146 return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
2147 Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
2148 (Left.NestingLevel == 0 && Line.Level == 0 &&
2149 Style.AllowShortFunctionsOnASingleLine ==
2150 FormatStyle::SFS_Inline);
2151 } else if (Style.Language == FormatStyle::LK_Java) {
2152 if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
2153 Right.Next->is(tok::string_literal))
2157 // If the last token before a '}' is a comma or a trailing comment, the
2158 // intention is to insert a line break after it in order to make shuffling
2159 // around entries easier.
2160 const FormatToken *BeforeClosingBrace = nullptr;
2161 if (Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
2162 Left.BlockKind != BK_Block && Left.MatchingParen)
2163 BeforeClosingBrace = Left.MatchingParen->Previous;
2164 else if (Right.MatchingParen &&
2165 Right.MatchingParen->isOneOf(tok::l_brace,
2166 TT_ArrayInitializerLSquare))
2167 BeforeClosingBrace = &Left;
2168 if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
2169 BeforeClosingBrace->isTrailingComment()))
2172 if (Right.is(tok::comment))
2173 return Left.BlockKind != BK_BracedInit &&
2174 Left.isNot(TT_CtorInitializerColon) &&
2175 (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
2176 if (Left.isTrailingComment())
2178 if (Left.isStringLiteral() &&
2179 (Right.isStringLiteral() || Right.is(TT_ObjCStringLiteral)))
2181 if (Right.Previous->IsUnterminatedLiteral)
2183 if (Right.is(tok::lessless) && Right.Next &&
2184 Right.Previous->is(tok::string_literal) &&
2185 Right.Next->is(tok::string_literal))
2187 if (Right.Previous->ClosesTemplateDeclaration &&
2188 Right.Previous->MatchingParen &&
2189 Right.Previous->MatchingParen->NestingLevel == 0 &&
2190 Style.AlwaysBreakTemplateDeclarations)
2192 if ((Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) &&
2193 Style.BreakConstructorInitializersBeforeComma &&
2194 !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
2196 if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
2197 // Raw string literals are special wrt. line breaks. The author has made a
2198 // deliberate choice and might have aligned the contents of the string
2199 // literal accordingly. Thus, we try keep existing line breaks.
2200 return Right.NewlinesBefore > 0;
2201 if (Right.Previous->is(tok::l_brace) && Right.NestingLevel == 1 &&
2202 Style.Language == FormatStyle::LK_Proto)
2203 // Don't put enums onto single lines in protocol buffers.
2205 if (Right.is(TT_InlineASMBrace))
2206 return Right.HasUnescapedNewline;
2207 if (isAllmanBrace(Left) || isAllmanBrace(Right))
2208 return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
2209 (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
2210 (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
2211 if (Style.Language == FormatStyle::LK_Proto && Left.isNot(tok::l_brace) &&
2212 Right.is(TT_SelectorName))
2214 if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
2217 if ((Style.Language == FormatStyle::LK_Java ||
2218 Style.Language == FormatStyle::LK_JavaScript) &&
2219 Left.is(TT_LeadingJavaAnnotation) &&
2220 Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
2221 (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
2227 bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
2228 const FormatToken &Right) {
2229 const FormatToken &Left = *Right.Previous;
2231 // Language-specific stuff.
2232 if (Style.Language == FormatStyle::LK_Java) {
2233 if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2234 Keywords.kw_implements))
2236 if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
2237 Keywords.kw_implements))
2239 } else if (Style.Language == FormatStyle::LK_JavaScript) {
2240 if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
2242 if (Left.is(TT_JsTypeColon))
2244 if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is))
2248 if (Left.is(tok::at))
2250 if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
2252 if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
2253 return !Right.is(tok::l_paren);
2254 if (Right.is(TT_PointerOrReference))
2255 return Line.IsMultiVariableDeclStmt ||
2256 (Style.PointerAlignment == FormatStyle::PAS_Right &&
2257 (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
2258 if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
2259 Right.is(tok::kw_operator))
2261 if (Left.is(TT_PointerOrReference))
2263 if (Right.isTrailingComment())
2264 // We rely on MustBreakBefore being set correctly here as we should not
2265 // change the "binding" behavior of a comment.
2266 // The first comment in a braced lists is always interpreted as belonging to
2267 // the first list element. Otherwise, it should be placed outside of the
2269 return Left.BlockKind == BK_BracedInit;
2270 if (Left.is(tok::question) && Right.is(tok::colon))
2272 if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
2273 return Style.BreakBeforeTernaryOperators;
2274 if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
2275 return !Style.BreakBeforeTernaryOperators;
2276 if (Right.is(TT_InheritanceColon))
2278 if (Right.is(tok::colon) &&
2279 !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
2281 if (Left.is(tok::colon) && (Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)))
2283 if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
2284 Right.Next->is(TT_ObjCMethodExpr)))
2285 return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
2286 if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
2288 if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
2290 if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
2291 TT_OverloadedOperator))
2293 if (Left.is(TT_RangeBasedForLoopColon))
2295 if (Right.is(TT_RangeBasedForLoopColon))
2297 if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
2298 Left.is(tok::kw_operator))
2300 if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
2301 Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
2303 if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
2305 if (Left.is(tok::l_paren) && Left.Previous &&
2306 (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
2308 if (Right.is(TT_ImplicitStringLiteral))
2311 if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
2313 if (Right.is(tok::r_square) && Right.MatchingParen &&
2314 Right.MatchingParen->is(TT_LambdaLSquare))
2317 // We only break before r_brace if there was a corresponding break before
2318 // the l_brace, which is tracked by BreakBeforeClosingBrace.
2319 if (Right.is(tok::r_brace))
2320 return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
2322 // Allow breaking after a trailing annotation, e.g. after a method
2324 if (Left.is(TT_TrailingAnnotation))
2325 return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
2326 tok::less, tok::coloncolon);
2328 if (Right.is(tok::kw___attribute))
2331 if (Left.is(tok::identifier) && Right.is(tok::string_literal))
2334 if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
2337 if (Left.is(TT_CtorInitializerComma) &&
2338 Style.BreakConstructorInitializersBeforeComma)
2340 if (Right.is(TT_CtorInitializerComma) &&
2341 Style.BreakConstructorInitializersBeforeComma)
2343 if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
2344 (Left.is(tok::less) && Right.is(tok::less)))
2346 if (Right.is(TT_BinaryOperator) &&
2347 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
2348 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
2349 Right.getPrecedence() != prec::Assignment))
2351 if (Left.is(TT_ArrayInitializerLSquare))
2353 if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
2355 if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
2356 !Left.isOneOf(tok::arrowstar, tok::lessless) &&
2357 Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
2358 (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
2359 Left.getPrecedence() == prec::Assignment))
2361 return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
2362 tok::kw_class, tok::kw_struct) ||
2363 Right.isMemberAccess() ||
2364 Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
2365 tok::colon, tok::l_square, tok::at) ||
2366 (Left.is(tok::r_paren) &&
2367 Right.isOneOf(tok::identifier, tok::kw_const)) ||
2368 (Left.is(tok::l_paren) && !Right.is(tok::r_paren));
2371 void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
2372 llvm::errs() << "AnnotatedTokens:\n";
2373 const FormatToken *Tok = Line.First;
2375 llvm::errs() << " M=" << Tok->MustBreakBefore
2376 << " C=" << Tok->CanBreakBefore
2377 << " T=" << getTokenTypeName(Tok->Type)
2378 << " S=" << Tok->SpacesRequiredBefore
2379 << " B=" << Tok->BlockParameterCount
2380 << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
2381 << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
2383 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
2384 llvm::errs() << Tok->FakeLParens[i] << "/";
2385 llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
2387 assert(Tok == Line.Last);
2390 llvm::errs() << "----\n";
2393 } // namespace format
2394 } // namespace clang