1 //===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===//
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 contains the declaration of the FormatToken, a wrapper
12 /// around Token with additional information related to formatting.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
17 #define LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H
19 #include "clang/Basic/IdentifierTable.h"
20 #include "clang/Basic/OperatorPrecedence.h"
21 #include "clang/Format/Format.h"
22 #include "clang/Lex/Lexer.h"
28 #define LIST_TOKEN_TYPES \
29 TYPE(ArrayInitializerLSquare) \
30 TYPE(ArraySubscriptLSquare) \
31 TYPE(AttributeParen) \
32 TYPE(BinaryOperator) \
36 TYPE(ConditionalExpr) \
37 TYPE(ConflictAlternative) \
40 TYPE(CtorInitializerColon) \
41 TYPE(CtorInitializerComma) \
42 TYPE(DesignatedInitializerLSquare) \
43 TYPE(DesignatedInitializerPeriod) \
46 TYPE(FunctionAnnotationRParen) \
47 TYPE(FunctionDeclarationName) \
48 TYPE(FunctionLBrace) \
49 TYPE(FunctionTypeLParen) \
50 TYPE(ImplicitStringLiteral) \
51 TYPE(InheritanceColon) \
52 TYPE(InheritanceComma) \
53 TYPE(InlineASMBrace) \
54 TYPE(InlineASMColon) \
55 TYPE(JavaAnnotation) \
56 TYPE(JsComputedPropertyName) \
57 TYPE(JsExponentiation) \
58 TYPE(JsExponentiationEqual) \
60 TYPE(JsNonNullAssertion) \
62 TYPE(JsTypeOperator) \
63 TYPE(JsTypeOptionalQuestion) \
66 TYPE(LeadingJavaAnnotation) \
68 TYPE(MacroBlockBegin) \
70 TYPE(ObjCBlockLBrace) \
71 TYPE(ObjCBlockLParen) \
74 TYPE(ObjCMethodExpr) \
75 TYPE(ObjCMethodSpecifier) \
77 TYPE(ObjCStringLiteral) \
78 TYPE(OverloadedOperator) \
79 TYPE(OverloadedOperatorLParen) \
80 TYPE(PointerOrReference) \
81 TYPE(PureVirtualSpecifier) \
82 TYPE(RangeBasedForLoopColon) \
86 TYPE(TemplateCloser) \
87 TYPE(TemplateOpener) \
88 TYPE(TemplateString) \
89 TYPE(TrailingAnnotation) \
90 TYPE(TrailingReturnArrow) \
91 TYPE(TrailingUnaryOperator) \
96 #define TYPE(X) TT_##X,
102 /// \brief Determines the name of a token type.
103 const char *getTokenTypeName(TokenType Type);
105 // Represents what type of block a set of braces open.
106 enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
108 // The packing kind of a function's parameters.
109 enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
111 enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
116 /// \brief A wrapper around a \c Token storing information about the
117 /// whitespace characters preceding it.
121 /// \brief The \c Token.
124 /// \brief The number of newlines immediately before the \c Token.
126 /// This can be used to determine what the user wrote in the original code
127 /// and thereby e.g. leave an empty line between two function definitions.
128 unsigned NewlinesBefore = 0;
130 /// \brief Whether there is at least one unescaped newline before the \c
132 bool HasUnescapedNewline = false;
134 /// \brief The range of the whitespace immediately preceding the \c Token.
135 SourceRange WhitespaceRange;
137 /// \brief The offset just past the last '\n' in this token's leading
138 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
139 unsigned LastNewlineOffset = 0;
141 /// \brief The width of the non-whitespace parts of the token (or its first
142 /// line for multi-line tokens) in columns.
143 /// We need this to correctly measure number of columns a token spans.
144 unsigned ColumnWidth = 0;
146 /// \brief Contains the width in columns of the last line of a multi-line
148 unsigned LastLineColumnWidth = 0;
150 /// \brief Whether the token text contains newlines (escaped or not).
151 bool IsMultiline = false;
153 /// \brief Indicates that this is the first token of the file.
154 bool IsFirst = false;
156 /// \brief Whether there must be a line break before this token.
158 /// This happens for example when a preprocessor directive ended directly
159 /// before the token.
160 bool MustBreakBefore = false;
162 /// \brief The raw text of the token.
164 /// Contains the raw token text without leading whitespace and without leading
165 /// escaped newlines.
168 /// \brief Set to \c true if this token is an unterminated literal.
169 bool IsUnterminatedLiteral = 0;
171 /// \brief Contains the kind of block if this token is a brace.
172 BraceBlockKind BlockKind = BK_Unknown;
174 TokenType Type = TT_Unknown;
176 /// \brief The number of spaces that should be inserted before this token.
177 unsigned SpacesRequiredBefore = 0;
179 /// \brief \c true if it is allowed to break before this token.
180 bool CanBreakBefore = false;
182 /// \brief \c true if this is the ">" of "template<..>".
183 bool ClosesTemplateDeclaration = false;
185 /// \brief Number of parameters, if this is "(", "[" or "<".
187 /// This is initialized to 1 as we don't need to distinguish functions with
188 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
189 /// the number of commas.
190 unsigned ParameterCount = 0;
192 /// \brief Number of parameters that are nested blocks,
193 /// if this is "(", "[" or "<".
194 unsigned BlockParameterCount = 0;
196 /// \brief If this is a bracket ("<", "(", "[" or "{"), contains the kind of
197 /// the surrounding bracket.
198 tok::TokenKind ParentBracket = tok::unknown;
200 /// \brief A token can have a special role that can carry extra information
201 /// about the token's formatting.
202 std::unique_ptr<TokenRole> Role;
204 /// \brief If this is an opening parenthesis, how are the parameters packed?
205 ParameterPackingKind PackingKind = PPK_Inconclusive;
207 /// \brief The total length of the unwrapped line up to and including this
209 unsigned TotalLength = 0;
211 /// \brief The original 0-based column of this token, including expanded tabs.
212 /// The configured TabWidth is used as tab width.
213 unsigned OriginalColumn = 0;
215 /// \brief The length of following tokens until the next natural split point,
216 /// or the next token that can be broken.
217 unsigned UnbreakableTailLength = 0;
219 // FIXME: Come up with a 'cleaner' concept.
220 /// \brief The binding strength of a token. This is a combined value of
221 /// operator precedence, parenthesis nesting, etc.
222 unsigned BindingStrength = 0;
224 /// \brief The nesting level of this token, i.e. the number of surrounding (),
226 unsigned NestingLevel = 0;
228 /// \brief The indent level of this token. Copied from the surrounding line.
229 unsigned IndentLevel = 0;
231 /// \brief Penalty for inserting a line break before this token.
232 unsigned SplitPenalty = 0;
234 /// \brief If this is the first ObjC selector name in an ObjC method
235 /// definition or call, this contains the length of the longest name.
237 /// This being set to 0 means that the selectors should not be colon-aligned,
238 /// e.g. because several of them are block-type.
239 unsigned LongestObjCSelectorName = 0;
241 /// \brief Stores the number of required fake parentheses and the
242 /// corresponding operator precedence.
244 /// If multiple fake parentheses start at a token, this vector stores them in
245 /// reverse order, i.e. inner fake parenthesis first.
246 SmallVector<prec::Level, 4> FakeLParens;
247 /// \brief Insert this many fake ) after this token for correct indentation.
248 unsigned FakeRParens = 0;
250 /// \brief \c true if this token starts a binary expression, i.e. has at least
251 /// one fake l_paren with a precedence greater than prec::Unknown.
252 bool StartsBinaryExpression = false;
253 /// \brief \c true if this token ends a binary expression.
254 bool EndsBinaryExpression = false;
256 /// \brief Is this is an operator (or "."/"->") in a sequence of operators
257 /// with the same precedence, contains the 0-based operator index.
258 unsigned OperatorIndex = 0;
260 /// \brief If this is an operator (or "."/"->") in a sequence of operators
261 /// with the same precedence, points to the next operator.
262 FormatToken *NextOperator = nullptr;
264 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
266 /// Only set if \c Type == \c TT_StartOfName.
267 bool PartOfMultiVariableDeclStmt = false;
269 /// \brief Does this line comment continue a line comment section?
271 /// Only set to true if \c Type == \c TT_LineComment.
272 bool ContinuesLineCommentSection = false;
274 /// \brief If this is a bracket, this points to the matching one.
275 FormatToken *MatchingParen = nullptr;
277 /// \brief The previous token in the unwrapped line.
278 FormatToken *Previous = nullptr;
280 /// \brief The next token in the unwrapped line.
281 FormatToken *Next = nullptr;
283 /// \brief If this token starts a block, this contains all the unwrapped lines
285 SmallVector<AnnotatedLine *, 1> Children;
287 /// \brief Stores the formatting decision for the token once it was made.
288 FormatDecision Decision = FD_Unformatted;
290 /// \brief If \c true, this token has been fully formatted (indented and
291 /// potentially re-formatted inside), and we do not allow further formatting
293 bool Finalized = false;
295 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
296 bool is(TokenType TT) const { return Type == TT; }
297 bool is(const IdentifierInfo *II) const {
298 return II && II == Tok.getIdentifierInfo();
300 bool is(tok::PPKeywordKind Kind) const {
301 return Tok.getIdentifierInfo() &&
302 Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
304 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
305 return is(K1) || is(K2);
307 template <typename A, typename B, typename... Ts>
308 bool isOneOf(A K1, B K2, Ts... Ks) const {
309 return is(K1) || isOneOf(K2, Ks...);
311 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
313 /// \c true if this token starts a sequence with the given tokens in order,
314 /// following the ``Next`` pointers, ignoring comments.
315 template <typename A, typename... Ts>
316 bool startsSequence(A K1, Ts... Tokens) const {
317 return startsSequenceInternal(K1, Tokens...);
320 /// \c true if this token ends a sequence with the given tokens in order,
321 /// following the ``Previous`` pointers, ignoring comments.
322 template <typename A, typename... Ts>
323 bool endsSequence(A K1, Ts... Tokens) const {
324 return endsSequenceInternal(K1, Tokens...);
327 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
329 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
330 return Tok.isObjCAtKeyword(Kind);
333 bool isAccessSpecifier(bool ColonRequired = true) const {
334 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
335 (!ColonRequired || (Next && Next->is(tok::colon)));
338 /// \brief Determine whether the token is a simple-type-specifier.
339 bool isSimpleTypeSpecifier() const;
341 bool isObjCAccessSpecifier() const {
342 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
343 Next->isObjCAtKeyword(tok::objc_protected) ||
344 Next->isObjCAtKeyword(tok::objc_package) ||
345 Next->isObjCAtKeyword(tok::objc_private));
348 /// \brief Returns whether \p Tok is ([{ or a template opening <.
349 bool opensScope() const {
350 if (is(TT_TemplateString) && TokenText.endswith("${"))
352 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
355 /// \brief Returns whether \p Tok is )]} or a template closing >.
356 bool closesScope() const {
357 if (is(TT_TemplateString) && TokenText.startswith("}"))
359 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
363 /// \brief Returns \c true if this is a "." or "->" accessing a member.
364 bool isMemberAccess() const {
365 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
366 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
370 bool isUnaryOperator() const {
371 switch (Tok.getKind()) {
375 case tok::minusminus:
379 case tok::kw_alignof:
386 bool isBinaryOperator() const {
387 // Comma is a binary operator, but does not behave as such wrt. formatting.
388 return getPrecedence() > prec::Comma;
391 bool isTrailingComment() const {
392 return is(tok::comment) &&
393 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
396 /// \brief Returns \c true if this is a keyword that can be used
397 /// like a function call (e.g. sizeof, typeid, ...).
398 bool isFunctionLikeKeyword() const {
399 switch (Tok.getKind()) {
404 case tok::kw_alignof:
405 case tok::kw_alignas:
406 case tok::kw_decltype:
407 case tok::kw_noexcept:
408 case tok::kw_static_assert:
409 case tok::kw___attribute:
416 /// \brief Returns \c true if this is a string literal that's like a label,
417 /// e.g. ends with "=" or ":".
418 bool isLabelString() const {
419 if (!is(tok::string_literal))
421 StringRef Content = TokenText;
422 if (Content.startswith("\"") || Content.startswith("'"))
423 Content = Content.drop_front(1);
424 if (Content.endswith("\"") || Content.endswith("'"))
425 Content = Content.drop_back(1);
426 Content = Content.trim();
427 return Content.size() > 1 &&
428 (Content.back() == ':' || Content.back() == '=');
431 /// \brief Returns actual token start location without leading escaped
432 /// newlines and whitespace.
434 /// This can be different to Tok.getLocation(), which includes leading escaped
436 SourceLocation getStartOfNonWhitespace() const {
437 return WhitespaceRange.getEnd();
440 prec::Level getPrecedence() const {
441 return getBinOpPrecedence(Tok.getKind(), true, true);
444 /// \brief Returns the previous token ignoring comments.
445 FormatToken *getPreviousNonComment() const {
446 FormatToken *Tok = Previous;
447 while (Tok && Tok->is(tok::comment))
452 /// \brief Returns the next token ignoring comments.
453 const FormatToken *getNextNonComment() const {
454 const FormatToken *Tok = Next;
455 while (Tok && Tok->is(tok::comment))
460 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
461 /// list that should be indented with a block indent.
462 bool opensBlockOrBlockTypeList(const FormatStyle &Style) const {
463 if (is(TT_TemplateString) && opensScope())
465 return is(TT_ArrayInitializerLSquare) ||
467 (BlockKind == BK_Block || is(TT_DictLiteral) ||
468 (!Style.Cpp11BracedListStyle && NestingLevel == 0)));
471 /// \brief Same as opensBlockOrBlockTypeList, but for the closing token.
472 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
473 if (is(TT_TemplateString) && closesScope())
475 return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
480 FormatToken(const FormatToken &) = delete;
481 void operator=(const FormatToken &) = delete;
483 template <typename A, typename... Ts>
484 bool startsSequenceInternal(A K1, Ts... Tokens) const {
485 if (is(tok::comment) && Next)
486 return Next->startsSequenceInternal(K1, Tokens...);
487 return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
490 template <typename A>
491 bool startsSequenceInternal(A K1) const {
492 if (is(tok::comment) && Next)
493 return Next->startsSequenceInternal(K1);
497 template <typename A, typename... Ts>
498 bool endsSequenceInternal(A K1) const {
499 if (is(tok::comment) && Previous)
500 return Previous->endsSequenceInternal(K1);
504 template <typename A, typename... Ts>
505 bool endsSequenceInternal(A K1, Ts... Tokens) const {
506 if (is(tok::comment) && Previous)
507 return Previous->endsSequenceInternal(K1, Tokens...);
508 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
512 class ContinuationIndenter;
517 TokenRole(const FormatStyle &Style) : Style(Style) {}
518 virtual ~TokenRole();
520 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
521 /// this function precomputes required information for formatting.
522 virtual void precomputeFormattingInfos(const FormatToken *Token);
524 /// \brief Apply the special formatting that the given role demands.
526 /// Assumes that the token having this role is already formatted.
528 /// Continues formatting from \p State leaving indentation to \p Indenter and
529 /// returns the total penalty that this formatting incurs.
530 virtual unsigned formatFromToken(LineState &State,
531 ContinuationIndenter *Indenter,
536 /// \brief Same as \c formatFromToken, but assumes that the first token has
537 /// already been set thereby deciding on the first line break.
538 virtual unsigned formatAfterToken(LineState &State,
539 ContinuationIndenter *Indenter,
544 /// \brief Notifies the \c Role that a comma was found.
545 virtual void CommaFound(const FormatToken *Token) {}
548 const FormatStyle &Style;
551 class CommaSeparatedList : public TokenRole {
553 CommaSeparatedList(const FormatStyle &Style)
554 : TokenRole(Style), HasNestedBracedList(false) {}
556 void precomputeFormattingInfos(const FormatToken *Token) override;
558 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
559 bool DryRun) override;
561 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
562 bool DryRun) override;
564 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
565 void CommaFound(const FormatToken *Token) override {
566 Commas.push_back(Token);
570 /// \brief A struct that holds information on how to format a given list with
571 /// a specific number of columns.
572 struct ColumnFormat {
573 /// \brief The number of columns to use.
576 /// \brief The total width in characters.
579 /// \brief The number of lines required for this format.
582 /// \brief The size of each column in characters.
583 SmallVector<unsigned, 8> ColumnSizes;
586 /// \brief Calculate which \c ColumnFormat fits best into
587 /// \p RemainingCharacters.
588 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
590 /// \brief The ordered \c FormatTokens making up the commas of this list.
591 SmallVector<const FormatToken *, 8> Commas;
593 /// \brief The length of each of the list's items in characters including the
595 SmallVector<unsigned, 8> ItemLengths;
597 /// \brief Precomputed formats that can be used for this list.
598 SmallVector<ColumnFormat, 4> Formats;
600 bool HasNestedBracedList;
603 /// \brief Encapsulates keywords that are context sensitive or for languages not
604 /// properly supported by Clang's lexer.
605 struct AdditionalKeywords {
606 AdditionalKeywords(IdentifierTable &IdentTable) {
607 kw_final = &IdentTable.get("final");
608 kw_override = &IdentTable.get("override");
609 kw_in = &IdentTable.get("in");
610 kw_of = &IdentTable.get("of");
611 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
612 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
613 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
614 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
616 kw_as = &IdentTable.get("as");
617 kw_async = &IdentTable.get("async");
618 kw_await = &IdentTable.get("await");
619 kw_declare = &IdentTable.get("declare");
620 kw_finally = &IdentTable.get("finally");
621 kw_from = &IdentTable.get("from");
622 kw_function = &IdentTable.get("function");
623 kw_get = &IdentTable.get("get");
624 kw_import = &IdentTable.get("import");
625 kw_is = &IdentTable.get("is");
626 kw_let = &IdentTable.get("let");
627 kw_module = &IdentTable.get("module");
628 kw_set = &IdentTable.get("set");
629 kw_type = &IdentTable.get("type");
630 kw_var = &IdentTable.get("var");
631 kw_yield = &IdentTable.get("yield");
633 kw_abstract = &IdentTable.get("abstract");
634 kw_assert = &IdentTable.get("assert");
635 kw_extends = &IdentTable.get("extends");
636 kw_implements = &IdentTable.get("implements");
637 kw_instanceof = &IdentTable.get("instanceof");
638 kw_interface = &IdentTable.get("interface");
639 kw_native = &IdentTable.get("native");
640 kw_package = &IdentTable.get("package");
641 kw_synchronized = &IdentTable.get("synchronized");
642 kw_throws = &IdentTable.get("throws");
643 kw___except = &IdentTable.get("__except");
644 kw___has_include = &IdentTable.get("__has_include");
645 kw___has_include_next = &IdentTable.get("__has_include_next");
647 kw_mark = &IdentTable.get("mark");
649 kw_extend = &IdentTable.get("extend");
650 kw_option = &IdentTable.get("option");
651 kw_optional = &IdentTable.get("optional");
652 kw_repeated = &IdentTable.get("repeated");
653 kw_required = &IdentTable.get("required");
654 kw_returns = &IdentTable.get("returns");
656 kw_signals = &IdentTable.get("signals");
657 kw_qsignals = &IdentTable.get("Q_SIGNALS");
658 kw_slots = &IdentTable.get("slots");
659 kw_qslots = &IdentTable.get("Q_SLOTS");
662 // Context sensitive keywords.
663 IdentifierInfo *kw_final;
664 IdentifierInfo *kw_override;
665 IdentifierInfo *kw_in;
666 IdentifierInfo *kw_of;
667 IdentifierInfo *kw_CF_ENUM;
668 IdentifierInfo *kw_CF_OPTIONS;
669 IdentifierInfo *kw_NS_ENUM;
670 IdentifierInfo *kw_NS_OPTIONS;
671 IdentifierInfo *kw___except;
672 IdentifierInfo *kw___has_include;
673 IdentifierInfo *kw___has_include_next;
675 // JavaScript keywords.
676 IdentifierInfo *kw_as;
677 IdentifierInfo *kw_async;
678 IdentifierInfo *kw_await;
679 IdentifierInfo *kw_declare;
680 IdentifierInfo *kw_finally;
681 IdentifierInfo *kw_from;
682 IdentifierInfo *kw_function;
683 IdentifierInfo *kw_get;
684 IdentifierInfo *kw_import;
685 IdentifierInfo *kw_is;
686 IdentifierInfo *kw_let;
687 IdentifierInfo *kw_module;
688 IdentifierInfo *kw_set;
689 IdentifierInfo *kw_type;
690 IdentifierInfo *kw_var;
691 IdentifierInfo *kw_yield;
694 IdentifierInfo *kw_abstract;
695 IdentifierInfo *kw_assert;
696 IdentifierInfo *kw_extends;
697 IdentifierInfo *kw_implements;
698 IdentifierInfo *kw_instanceof;
699 IdentifierInfo *kw_interface;
700 IdentifierInfo *kw_native;
701 IdentifierInfo *kw_package;
702 IdentifierInfo *kw_synchronized;
703 IdentifierInfo *kw_throws;
706 IdentifierInfo *kw_mark;
709 IdentifierInfo *kw_extend;
710 IdentifierInfo *kw_option;
711 IdentifierInfo *kw_optional;
712 IdentifierInfo *kw_repeated;
713 IdentifierInfo *kw_required;
714 IdentifierInfo *kw_returns;
717 IdentifierInfo *kw_signals;
718 IdentifierInfo *kw_qsignals;
719 IdentifierInfo *kw_slots;
720 IdentifierInfo *kw_qslots;
723 } // namespace format