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(DesignatedInitializerPeriod) \
45 TYPE(FunctionAnnotationRParen) \
46 TYPE(FunctionDeclarationName) \
47 TYPE(FunctionLBrace) \
48 TYPE(FunctionTypeLParen) \
49 TYPE(ImplicitStringLiteral) \
50 TYPE(InheritanceColon) \
51 TYPE(InheritanceComma) \
52 TYPE(InlineASMBrace) \
53 TYPE(InlineASMColon) \
54 TYPE(JavaAnnotation) \
55 TYPE(JsComputedPropertyName) \
56 TYPE(JsExponentiation) \
57 TYPE(JsExponentiationEqual) \
59 TYPE(JsNonNullAssertion) \
61 TYPE(JsTypeOperator) \
62 TYPE(JsTypeOptionalQuestion) \
65 TYPE(LeadingJavaAnnotation) \
67 TYPE(MacroBlockBegin) \
69 TYPE(ObjCBlockLBrace) \
70 TYPE(ObjCBlockLParen) \
73 TYPE(ObjCMethodExpr) \
74 TYPE(ObjCMethodSpecifier) \
76 TYPE(ObjCStringLiteral) \
77 TYPE(OverloadedOperator) \
78 TYPE(OverloadedOperatorLParen) \
79 TYPE(PointerOrReference) \
80 TYPE(PureVirtualSpecifier) \
81 TYPE(RangeBasedForLoopColon) \
85 TYPE(TemplateCloser) \
86 TYPE(TemplateOpener) \
87 TYPE(TemplateString) \
88 TYPE(TrailingAnnotation) \
89 TYPE(TrailingReturnArrow) \
90 TYPE(TrailingUnaryOperator) \
95 #define TYPE(X) TT_##X,
101 /// \brief Determines the name of a token type.
102 const char *getTokenTypeName(TokenType Type);
104 // Represents what type of block a set of braces open.
105 enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
107 // The packing kind of a function's parameters.
108 enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
110 enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
115 /// \brief A wrapper around a \c Token storing information about the
116 /// whitespace characters preceding it.
120 /// \brief The \c Token.
123 /// \brief The number of newlines immediately before the \c Token.
125 /// This can be used to determine what the user wrote in the original code
126 /// and thereby e.g. leave an empty line between two function definitions.
127 unsigned NewlinesBefore = 0;
129 /// \brief Whether there is at least one unescaped newline before the \c
131 bool HasUnescapedNewline = false;
133 /// \brief The range of the whitespace immediately preceding the \c Token.
134 SourceRange WhitespaceRange;
136 /// \brief The offset just past the last '\n' in this token's leading
137 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
138 unsigned LastNewlineOffset = 0;
140 /// \brief The width of the non-whitespace parts of the token (or its first
141 /// line for multi-line tokens) in columns.
142 /// We need this to correctly measure number of columns a token spans.
143 unsigned ColumnWidth = 0;
145 /// \brief Contains the width in columns of the last line of a multi-line
147 unsigned LastLineColumnWidth = 0;
149 /// \brief Whether the token text contains newlines (escaped or not).
150 bool IsMultiline = false;
152 /// \brief Indicates that this is the first token of the file.
153 bool IsFirst = false;
155 /// \brief Whether there must be a line break before this token.
157 /// This happens for example when a preprocessor directive ended directly
158 /// before the token.
159 bool MustBreakBefore = false;
161 /// \brief The raw text of the token.
163 /// Contains the raw token text without leading whitespace and without leading
164 /// escaped newlines.
167 /// \brief Set to \c true if this token is an unterminated literal.
168 bool IsUnterminatedLiteral = 0;
170 /// \brief Contains the kind of block if this token is a brace.
171 BraceBlockKind BlockKind = BK_Unknown;
173 TokenType Type = TT_Unknown;
175 /// \brief The number of spaces that should be inserted before this token.
176 unsigned SpacesRequiredBefore = 0;
178 /// \brief \c true if it is allowed to break before this token.
179 bool CanBreakBefore = false;
181 /// \brief \c true if this is the ">" of "template<..>".
182 bool ClosesTemplateDeclaration = false;
184 /// \brief Number of parameters, if this is "(", "[" or "<".
186 /// This is initialized to 1 as we don't need to distinguish functions with
187 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
188 /// the number of commas.
189 unsigned ParameterCount = 0;
191 /// \brief Number of parameters that are nested blocks,
192 /// if this is "(", "[" or "<".
193 unsigned BlockParameterCount = 0;
195 /// \brief If this is a bracket ("<", "(", "[" or "{"), contains the kind of
196 /// the surrounding bracket.
197 tok::TokenKind ParentBracket = tok::unknown;
199 /// \brief A token can have a special role that can carry extra information
200 /// about the token's formatting.
201 std::unique_ptr<TokenRole> Role;
203 /// \brief If this is an opening parenthesis, how are the parameters packed?
204 ParameterPackingKind PackingKind = PPK_Inconclusive;
206 /// \brief The total length of the unwrapped line up to and including this
208 unsigned TotalLength = 0;
210 /// \brief The original 0-based column of this token, including expanded tabs.
211 /// The configured TabWidth is used as tab width.
212 unsigned OriginalColumn = 0;
214 /// \brief The length of following tokens until the next natural split point,
215 /// or the next token that can be broken.
216 unsigned UnbreakableTailLength = 0;
218 // FIXME: Come up with a 'cleaner' concept.
219 /// \brief The binding strength of a token. This is a combined value of
220 /// operator precedence, parenthesis nesting, etc.
221 unsigned BindingStrength = 0;
223 /// \brief The nesting level of this token, i.e. the number of surrounding (),
225 unsigned NestingLevel = 0;
227 /// \brief The indent level of this token. Copied from the surrounding line.
228 unsigned IndentLevel = 0;
230 /// \brief Penalty for inserting a line break before this token.
231 unsigned SplitPenalty = 0;
233 /// \brief If this is the first ObjC selector name in an ObjC method
234 /// definition or call, this contains the length of the longest name.
236 /// This being set to 0 means that the selectors should not be colon-aligned,
237 /// e.g. because several of them are block-type.
238 unsigned LongestObjCSelectorName = 0;
240 /// \brief Stores the number of required fake parentheses and the
241 /// corresponding operator precedence.
243 /// If multiple fake parentheses start at a token, this vector stores them in
244 /// reverse order, i.e. inner fake parenthesis first.
245 SmallVector<prec::Level, 4> FakeLParens;
246 /// \brief Insert this many fake ) after this token for correct indentation.
247 unsigned FakeRParens = 0;
249 /// \brief \c true if this token starts a binary expression, i.e. has at least
250 /// one fake l_paren with a precedence greater than prec::Unknown.
251 bool StartsBinaryExpression = false;
252 /// \brief \c true if this token ends a binary expression.
253 bool EndsBinaryExpression = false;
255 /// \brief Is this is an operator (or "."/"->") in a sequence of operators
256 /// with the same precedence, contains the 0-based operator index.
257 unsigned OperatorIndex = 0;
259 /// \brief If this is an operator (or "."/"->") in a sequence of operators
260 /// with the same precedence, points to the next operator.
261 FormatToken *NextOperator = nullptr;
263 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
265 /// Only set if \c Type == \c TT_StartOfName.
266 bool PartOfMultiVariableDeclStmt = false;
268 /// \brief Does this line comment continue a line comment section?
270 /// Only set to true if \c Type == \c TT_LineComment.
271 bool ContinuesLineCommentSection = false;
273 /// \brief If this is a bracket, this points to the matching one.
274 FormatToken *MatchingParen = nullptr;
276 /// \brief The previous token in the unwrapped line.
277 FormatToken *Previous = nullptr;
279 /// \brief The next token in the unwrapped line.
280 FormatToken *Next = nullptr;
282 /// \brief If this token starts a block, this contains all the unwrapped lines
284 SmallVector<AnnotatedLine *, 1> Children;
286 /// \brief Stores the formatting decision for the token once it was made.
287 FormatDecision Decision = FD_Unformatted;
289 /// \brief If \c true, this token has been fully formatted (indented and
290 /// potentially re-formatted inside), and we do not allow further formatting
292 bool Finalized = false;
294 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
295 bool is(TokenType TT) const { return Type == TT; }
296 bool is(const IdentifierInfo *II) const {
297 return II && II == Tok.getIdentifierInfo();
299 bool is(tok::PPKeywordKind Kind) const {
300 return Tok.getIdentifierInfo() &&
301 Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
303 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
304 return is(K1) || is(K2);
306 template <typename A, typename B, typename... Ts>
307 bool isOneOf(A K1, B K2, Ts... Ks) const {
308 return is(K1) || isOneOf(K2, Ks...);
310 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
312 /// \c true if this token starts a sequence with the given tokens in order,
313 /// following the ``Next`` pointers, ignoring comments.
314 template <typename A, typename... Ts>
315 bool startsSequence(A K1, Ts... Tokens) const {
316 return startsSequenceInternal(K1, Tokens...);
319 /// \c true if this token ends a sequence with the given tokens in order,
320 /// following the ``Previous`` pointers, ignoring comments.
321 template <typename A, typename... Ts>
322 bool endsSequence(A K1, Ts... Tokens) const {
323 return endsSequenceInternal(K1, Tokens...);
326 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
328 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
329 return Tok.isObjCAtKeyword(Kind);
332 bool isAccessSpecifier(bool ColonRequired = true) const {
333 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
334 (!ColonRequired || (Next && Next->is(tok::colon)));
337 /// \brief Determine whether the token is a simple-type-specifier.
338 bool isSimpleTypeSpecifier() const;
340 bool isObjCAccessSpecifier() const {
341 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
342 Next->isObjCAtKeyword(tok::objc_protected) ||
343 Next->isObjCAtKeyword(tok::objc_package) ||
344 Next->isObjCAtKeyword(tok::objc_private));
347 /// \brief Returns whether \p Tok is ([{ or a template opening <.
348 bool opensScope() const {
349 if (is(TT_TemplateString) && TokenText.endswith("${"))
351 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
354 /// \brief Returns whether \p Tok is )]} or a template closing >.
355 bool closesScope() const {
356 if (is(TT_TemplateString) && TokenText.startswith("}"))
358 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
362 /// \brief Returns \c true if this is a "." or "->" accessing a member.
363 bool isMemberAccess() const {
364 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
365 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
369 bool isUnaryOperator() const {
370 switch (Tok.getKind()) {
374 case tok::minusminus:
378 case tok::kw_alignof:
385 bool isBinaryOperator() const {
386 // Comma is a binary operator, but does not behave as such wrt. formatting.
387 return getPrecedence() > prec::Comma;
390 bool isTrailingComment() const {
391 return is(tok::comment) &&
392 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
395 /// \brief Returns \c true if this is a keyword that can be used
396 /// like a function call (e.g. sizeof, typeid, ...).
397 bool isFunctionLikeKeyword() const {
398 switch (Tok.getKind()) {
403 case tok::kw_alignof:
404 case tok::kw_alignas:
405 case tok::kw_decltype:
406 case tok::kw_noexcept:
407 case tok::kw_static_assert:
408 case tok::kw___attribute:
415 /// \brief Returns \c true if this is a string literal that's like a label,
416 /// e.g. ends with "=" or ":".
417 bool isLabelString() const {
418 if (!is(tok::string_literal))
420 StringRef Content = TokenText;
421 if (Content.startswith("\"") || Content.startswith("'"))
422 Content = Content.drop_front(1);
423 if (Content.endswith("\"") || Content.endswith("'"))
424 Content = Content.drop_back(1);
425 Content = Content.trim();
426 return Content.size() > 1 &&
427 (Content.back() == ':' || Content.back() == '=');
430 /// \brief Returns actual token start location without leading escaped
431 /// newlines and whitespace.
433 /// This can be different to Tok.getLocation(), which includes leading escaped
435 SourceLocation getStartOfNonWhitespace() const {
436 return WhitespaceRange.getEnd();
439 prec::Level getPrecedence() const {
440 return getBinOpPrecedence(Tok.getKind(), true, true);
443 /// \brief Returns the previous token ignoring comments.
444 FormatToken *getPreviousNonComment() const {
445 FormatToken *Tok = Previous;
446 while (Tok && Tok->is(tok::comment))
451 /// \brief Returns the next token ignoring comments.
452 const FormatToken *getNextNonComment() const {
453 const FormatToken *Tok = Next;
454 while (Tok && Tok->is(tok::comment))
459 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
460 /// list that should be indented with a block indent.
461 bool opensBlockOrBlockTypeList(const FormatStyle &Style) const {
462 if (is(TT_TemplateString) && opensScope())
464 return is(TT_ArrayInitializerLSquare) ||
466 (BlockKind == BK_Block || is(TT_DictLiteral) ||
467 (!Style.Cpp11BracedListStyle && NestingLevel == 0)));
470 /// \brief Same as opensBlockOrBlockTypeList, but for the closing token.
471 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
472 if (is(TT_TemplateString) && closesScope())
474 return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
479 FormatToken(const FormatToken &) = delete;
480 void operator=(const FormatToken &) = delete;
482 template <typename A, typename... Ts>
483 bool startsSequenceInternal(A K1, Ts... Tokens) const {
484 if (is(tok::comment) && Next)
485 return Next->startsSequenceInternal(K1, Tokens...);
486 return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
489 template <typename A>
490 bool startsSequenceInternal(A K1) const {
491 if (is(tok::comment) && Next)
492 return Next->startsSequenceInternal(K1);
496 template <typename A, typename... Ts>
497 bool endsSequenceInternal(A K1) const {
498 if (is(tok::comment) && Previous)
499 return Previous->endsSequenceInternal(K1);
503 template <typename A, typename... Ts>
504 bool endsSequenceInternal(A K1, Ts... Tokens) const {
505 if (is(tok::comment) && Previous)
506 return Previous->endsSequenceInternal(K1, Tokens...);
507 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
511 class ContinuationIndenter;
516 TokenRole(const FormatStyle &Style) : Style(Style) {}
517 virtual ~TokenRole();
519 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
520 /// this function precomputes required information for formatting.
521 virtual void precomputeFormattingInfos(const FormatToken *Token);
523 /// \brief Apply the special formatting that the given role demands.
525 /// Assumes that the token having this role is already formatted.
527 /// Continues formatting from \p State leaving indentation to \p Indenter and
528 /// returns the total penalty that this formatting incurs.
529 virtual unsigned formatFromToken(LineState &State,
530 ContinuationIndenter *Indenter,
535 /// \brief Same as \c formatFromToken, but assumes that the first token has
536 /// already been set thereby deciding on the first line break.
537 virtual unsigned formatAfterToken(LineState &State,
538 ContinuationIndenter *Indenter,
543 /// \brief Notifies the \c Role that a comma was found.
544 virtual void CommaFound(const FormatToken *Token) {}
547 const FormatStyle &Style;
550 class CommaSeparatedList : public TokenRole {
552 CommaSeparatedList(const FormatStyle &Style)
553 : TokenRole(Style), HasNestedBracedList(false) {}
555 void precomputeFormattingInfos(const FormatToken *Token) override;
557 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
558 bool DryRun) override;
560 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
561 bool DryRun) override;
563 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
564 void CommaFound(const FormatToken *Token) override {
565 Commas.push_back(Token);
569 /// \brief A struct that holds information on how to format a given list with
570 /// a specific number of columns.
571 struct ColumnFormat {
572 /// \brief The number of columns to use.
575 /// \brief The total width in characters.
578 /// \brief The number of lines required for this format.
581 /// \brief The size of each column in characters.
582 SmallVector<unsigned, 8> ColumnSizes;
585 /// \brief Calculate which \c ColumnFormat fits best into
586 /// \p RemainingCharacters.
587 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
589 /// \brief The ordered \c FormatTokens making up the commas of this list.
590 SmallVector<const FormatToken *, 8> Commas;
592 /// \brief The length of each of the list's items in characters including the
594 SmallVector<unsigned, 8> ItemLengths;
596 /// \brief Precomputed formats that can be used for this list.
597 SmallVector<ColumnFormat, 4> Formats;
599 bool HasNestedBracedList;
602 /// \brief Encapsulates keywords that are context sensitive or for languages not
603 /// properly supported by Clang's lexer.
604 struct AdditionalKeywords {
605 AdditionalKeywords(IdentifierTable &IdentTable) {
606 kw_final = &IdentTable.get("final");
607 kw_override = &IdentTable.get("override");
608 kw_in = &IdentTable.get("in");
609 kw_of = &IdentTable.get("of");
610 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
611 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
612 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
613 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
615 kw_as = &IdentTable.get("as");
616 kw_async = &IdentTable.get("async");
617 kw_await = &IdentTable.get("await");
618 kw_declare = &IdentTable.get("declare");
619 kw_finally = &IdentTable.get("finally");
620 kw_from = &IdentTable.get("from");
621 kw_function = &IdentTable.get("function");
622 kw_get = &IdentTable.get("get");
623 kw_import = &IdentTable.get("import");
624 kw_is = &IdentTable.get("is");
625 kw_let = &IdentTable.get("let");
626 kw_module = &IdentTable.get("module");
627 kw_set = &IdentTable.get("set");
628 kw_type = &IdentTable.get("type");
629 kw_var = &IdentTable.get("var");
630 kw_yield = &IdentTable.get("yield");
632 kw_abstract = &IdentTable.get("abstract");
633 kw_assert = &IdentTable.get("assert");
634 kw_extends = &IdentTable.get("extends");
635 kw_implements = &IdentTable.get("implements");
636 kw_instanceof = &IdentTable.get("instanceof");
637 kw_interface = &IdentTable.get("interface");
638 kw_native = &IdentTable.get("native");
639 kw_package = &IdentTable.get("package");
640 kw_synchronized = &IdentTable.get("synchronized");
641 kw_throws = &IdentTable.get("throws");
642 kw___except = &IdentTable.get("__except");
643 kw___has_include = &IdentTable.get("__has_include");
644 kw___has_include_next = &IdentTable.get("__has_include_next");
646 kw_mark = &IdentTable.get("mark");
648 kw_extend = &IdentTable.get("extend");
649 kw_option = &IdentTable.get("option");
650 kw_optional = &IdentTable.get("optional");
651 kw_repeated = &IdentTable.get("repeated");
652 kw_required = &IdentTable.get("required");
653 kw_returns = &IdentTable.get("returns");
655 kw_signals = &IdentTable.get("signals");
656 kw_qsignals = &IdentTable.get("Q_SIGNALS");
657 kw_slots = &IdentTable.get("slots");
658 kw_qslots = &IdentTable.get("Q_SLOTS");
661 // Context sensitive keywords.
662 IdentifierInfo *kw_final;
663 IdentifierInfo *kw_override;
664 IdentifierInfo *kw_in;
665 IdentifierInfo *kw_of;
666 IdentifierInfo *kw_CF_ENUM;
667 IdentifierInfo *kw_CF_OPTIONS;
668 IdentifierInfo *kw_NS_ENUM;
669 IdentifierInfo *kw_NS_OPTIONS;
670 IdentifierInfo *kw___except;
671 IdentifierInfo *kw___has_include;
672 IdentifierInfo *kw___has_include_next;
674 // JavaScript keywords.
675 IdentifierInfo *kw_as;
676 IdentifierInfo *kw_async;
677 IdentifierInfo *kw_await;
678 IdentifierInfo *kw_declare;
679 IdentifierInfo *kw_finally;
680 IdentifierInfo *kw_from;
681 IdentifierInfo *kw_function;
682 IdentifierInfo *kw_get;
683 IdentifierInfo *kw_import;
684 IdentifierInfo *kw_is;
685 IdentifierInfo *kw_let;
686 IdentifierInfo *kw_module;
687 IdentifierInfo *kw_set;
688 IdentifierInfo *kw_type;
689 IdentifierInfo *kw_var;
690 IdentifierInfo *kw_yield;
693 IdentifierInfo *kw_abstract;
694 IdentifierInfo *kw_assert;
695 IdentifierInfo *kw_extends;
696 IdentifierInfo *kw_implements;
697 IdentifierInfo *kw_instanceof;
698 IdentifierInfo *kw_interface;
699 IdentifierInfo *kw_native;
700 IdentifierInfo *kw_package;
701 IdentifierInfo *kw_synchronized;
702 IdentifierInfo *kw_throws;
705 IdentifierInfo *kw_mark;
708 IdentifierInfo *kw_extend;
709 IdentifierInfo *kw_option;
710 IdentifierInfo *kw_optional;
711 IdentifierInfo *kw_repeated;
712 IdentifierInfo *kw_required;
713 IdentifierInfo *kw_returns;
716 IdentifierInfo *kw_signals;
717 IdentifierInfo *kw_qsignals;
718 IdentifierInfo *kw_slots;
719 IdentifierInfo *kw_qslots;
722 } // namespace format