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(InlineASMBrace) \
52 TYPE(InlineASMColon) \
53 TYPE(JavaAnnotation) \
54 TYPE(JsComputedPropertyName) \
57 TYPE(JsTypeOperator) \
58 TYPE(JsTypeOptionalQuestion) \
61 TYPE(LeadingJavaAnnotation) \
63 TYPE(MacroBlockBegin) \
65 TYPE(ObjCBlockLBrace) \
66 TYPE(ObjCBlockLParen) \
69 TYPE(ObjCMethodExpr) \
70 TYPE(ObjCMethodSpecifier) \
72 TYPE(ObjCStringLiteral) \
73 TYPE(OverloadedOperator) \
74 TYPE(OverloadedOperatorLParen) \
75 TYPE(PointerOrReference) \
76 TYPE(PureVirtualSpecifier) \
77 TYPE(RangeBasedForLoopColon) \
81 TYPE(TemplateCloser) \
82 TYPE(TemplateOpener) \
83 TYPE(TemplateString) \
84 TYPE(TrailingAnnotation) \
85 TYPE(TrailingReturnArrow) \
86 TYPE(TrailingUnaryOperator) \
91 #define TYPE(X) TT_##X,
97 /// \brief Determines the name of a token type.
98 const char *getTokenTypeName(TokenType Type);
100 // Represents what type of block a set of braces open.
101 enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
103 // The packing kind of a function's parameters.
104 enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
106 enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
111 /// \brief A wrapper around a \c Token storing information about the
112 /// whitespace characters preceding it.
116 /// \brief The \c Token.
119 /// \brief The number of newlines immediately before the \c Token.
121 /// This can be used to determine what the user wrote in the original code
122 /// and thereby e.g. leave an empty line between two function definitions.
123 unsigned NewlinesBefore = 0;
125 /// \brief Whether there is at least one unescaped newline before the \c
127 bool HasUnescapedNewline = false;
129 /// \brief The range of the whitespace immediately preceding the \c Token.
130 SourceRange WhitespaceRange;
132 /// \brief The offset just past the last '\n' in this token's leading
133 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
134 unsigned LastNewlineOffset = 0;
136 /// \brief The width of the non-whitespace parts of the token (or its first
137 /// line for multi-line tokens) in columns.
138 /// We need this to correctly measure number of columns a token spans.
139 unsigned ColumnWidth = 0;
141 /// \brief Contains the width in columns of the last line of a multi-line
143 unsigned LastLineColumnWidth = 0;
145 /// \brief Whether the token text contains newlines (escaped or not).
146 bool IsMultiline = false;
148 /// \brief Indicates that this is the first token of the file.
149 bool IsFirst = false;
151 /// \brief Whether there must be a line break before this token.
153 /// This happens for example when a preprocessor directive ended directly
154 /// before the token.
155 bool MustBreakBefore = false;
157 /// \brief The raw text of the token.
159 /// Contains the raw token text without leading whitespace and without leading
160 /// escaped newlines.
163 /// \brief Set to \c true if this token is an unterminated literal.
164 bool IsUnterminatedLiteral = 0;
166 /// \brief Contains the kind of block if this token is a brace.
167 BraceBlockKind BlockKind = BK_Unknown;
169 TokenType Type = TT_Unknown;
171 /// \brief The number of spaces that should be inserted before this token.
172 unsigned SpacesRequiredBefore = 0;
174 /// \brief \c true if it is allowed to break before this token.
175 bool CanBreakBefore = false;
177 /// \brief \c true if this is the ">" of "template<..>".
178 bool ClosesTemplateDeclaration = false;
180 /// \brief Number of parameters, if this is "(", "[" or "<".
182 /// This is initialized to 1 as we don't need to distinguish functions with
183 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
184 /// the number of commas.
185 unsigned ParameterCount = 0;
187 /// \brief Number of parameters that are nested blocks,
188 /// if this is "(", "[" or "<".
189 unsigned BlockParameterCount = 0;
191 /// \brief If this is a bracket ("<", "(", "[" or "{"), contains the kind of
192 /// the surrounding bracket.
193 tok::TokenKind ParentBracket = tok::unknown;
195 /// \brief A token can have a special role that can carry extra information
196 /// about the token's formatting.
197 std::unique_ptr<TokenRole> Role;
199 /// \brief If this is an opening parenthesis, how are the parameters packed?
200 ParameterPackingKind PackingKind = PPK_Inconclusive;
202 /// \brief The total length of the unwrapped line up to and including this
204 unsigned TotalLength = 0;
206 /// \brief The original 0-based column of this token, including expanded tabs.
207 /// The configured TabWidth is used as tab width.
208 unsigned OriginalColumn = 0;
210 /// \brief The length of following tokens until the next natural split point,
211 /// or the next token that can be broken.
212 unsigned UnbreakableTailLength = 0;
214 // FIXME: Come up with a 'cleaner' concept.
215 /// \brief The binding strength of a token. This is a combined value of
216 /// operator precedence, parenthesis nesting, etc.
217 unsigned BindingStrength = 0;
219 /// \brief The nesting level of this token, i.e. the number of surrounding (),
221 unsigned NestingLevel = 0;
223 /// \brief Penalty for inserting a line break before this token.
224 unsigned SplitPenalty = 0;
226 /// \brief If this is the first ObjC selector name in an ObjC method
227 /// definition or call, this contains the length of the longest name.
229 /// This being set to 0 means that the selectors should not be colon-aligned,
230 /// e.g. because several of them are block-type.
231 unsigned LongestObjCSelectorName = 0;
233 /// \brief Stores the number of required fake parentheses and the
234 /// corresponding operator precedence.
236 /// If multiple fake parentheses start at a token, this vector stores them in
237 /// reverse order, i.e. inner fake parenthesis first.
238 SmallVector<prec::Level, 4> FakeLParens;
239 /// \brief Insert this many fake ) after this token for correct indentation.
240 unsigned FakeRParens = 0;
242 /// \brief \c true if this token starts a binary expression, i.e. has at least
243 /// one fake l_paren with a precedence greater than prec::Unknown.
244 bool StartsBinaryExpression = false;
245 /// \brief \c true if this token ends a binary expression.
246 bool EndsBinaryExpression = false;
248 /// \brief Is this is an operator (or "."/"->") in a sequence of operators
249 /// with the same precedence, contains the 0-based operator index.
250 unsigned OperatorIndex = 0;
252 /// \brief If this is an operator (or "."/"->") in a sequence of operators
253 /// with the same precedence, points to the next operator.
254 FormatToken *NextOperator = nullptr;
256 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
258 /// Only set if \c Type == \c TT_StartOfName.
259 bool PartOfMultiVariableDeclStmt = false;
261 /// \brief If this is a bracket, this points to the matching one.
262 FormatToken *MatchingParen = nullptr;
264 /// \brief The previous token in the unwrapped line.
265 FormatToken *Previous = nullptr;
267 /// \brief The next token in the unwrapped line.
268 FormatToken *Next = nullptr;
270 /// \brief If this token starts a block, this contains all the unwrapped lines
272 SmallVector<AnnotatedLine *, 1> Children;
274 /// \brief Stores the formatting decision for the token once it was made.
275 FormatDecision Decision = FD_Unformatted;
277 /// \brief If \c true, this token has been fully formatted (indented and
278 /// potentially re-formatted inside), and we do not allow further formatting
280 bool Finalized = false;
282 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
283 bool is(TokenType TT) const { return Type == TT; }
284 bool is(const IdentifierInfo *II) const {
285 return II && II == Tok.getIdentifierInfo();
287 bool is(tok::PPKeywordKind Kind) const {
288 return Tok.getIdentifierInfo() &&
289 Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
291 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
292 return is(K1) || is(K2);
294 template <typename A, typename B, typename... Ts>
295 bool isOneOf(A K1, B K2, Ts... Ks) const {
296 return is(K1) || isOneOf(K2, Ks...);
298 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
300 /// \c true if this token starts a sequence with the given tokens in order,
301 /// following the ``Next`` pointers, ignoring comments.
302 template <typename A, typename... Ts>
303 bool startsSequence(A K1, Ts... Tokens) const {
304 return startsSequenceInternal(K1, Tokens...);
307 /// \c true if this token ends a sequence with the given tokens in order,
308 /// following the ``Previous`` pointers, ignoring comments.
309 template <typename A, typename... Ts>
310 bool endsSequence(A K1, Ts... Tokens) const {
311 return endsSequenceInternal(K1, Tokens...);
314 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
316 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
317 return Tok.isObjCAtKeyword(Kind);
320 bool isAccessSpecifier(bool ColonRequired = true) const {
321 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
322 (!ColonRequired || (Next && Next->is(tok::colon)));
325 /// \brief Determine whether the token is a simple-type-specifier.
326 bool isSimpleTypeSpecifier() const;
328 bool isObjCAccessSpecifier() const {
329 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
330 Next->isObjCAtKeyword(tok::objc_protected) ||
331 Next->isObjCAtKeyword(tok::objc_package) ||
332 Next->isObjCAtKeyword(tok::objc_private));
335 /// \brief Returns whether \p Tok is ([{ or a template opening <.
336 bool opensScope() const {
337 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
340 /// \brief Returns whether \p Tok is )]} or a template closing >.
341 bool closesScope() const {
342 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
346 /// \brief Returns \c true if this is a "." or "->" accessing a member.
347 bool isMemberAccess() const {
348 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
349 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
353 bool isUnaryOperator() const {
354 switch (Tok.getKind()) {
358 case tok::minusminus:
362 case tok::kw_alignof:
369 bool isBinaryOperator() const {
370 // Comma is a binary operator, but does not behave as such wrt. formatting.
371 return getPrecedence() > prec::Comma;
374 bool isTrailingComment() const {
375 return is(tok::comment) &&
376 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
379 /// \brief Returns \c true if this is a keyword that can be used
380 /// like a function call (e.g. sizeof, typeid, ...).
381 bool isFunctionLikeKeyword() const {
382 switch (Tok.getKind()) {
387 case tok::kw_alignof:
388 case tok::kw_alignas:
389 case tok::kw_decltype:
390 case tok::kw_noexcept:
391 case tok::kw_static_assert:
392 case tok::kw___attribute:
399 /// \brief Returns \c true if this is a string literal that's like a label,
400 /// e.g. ends with "=" or ":".
401 bool isLabelString() const {
402 if (!is(tok::string_literal))
404 StringRef Content = TokenText;
405 if (Content.startswith("\"") || Content.startswith("'"))
406 Content = Content.drop_front(1);
407 if (Content.endswith("\"") || Content.endswith("'"))
408 Content = Content.drop_back(1);
409 Content = Content.trim();
410 return Content.size() > 1 &&
411 (Content.back() == ':' || Content.back() == '=');
414 /// \brief Returns actual token start location without leading escaped
415 /// newlines and whitespace.
417 /// This can be different to Tok.getLocation(), which includes leading escaped
419 SourceLocation getStartOfNonWhitespace() const {
420 return WhitespaceRange.getEnd();
423 prec::Level getPrecedence() const {
424 return getBinOpPrecedence(Tok.getKind(), true, true);
427 /// \brief Returns the previous token ignoring comments.
428 FormatToken *getPreviousNonComment() const {
429 FormatToken *Tok = Previous;
430 while (Tok && Tok->is(tok::comment))
435 /// \brief Returns the next token ignoring comments.
436 const FormatToken *getNextNonComment() const {
437 const FormatToken *Tok = Next;
438 while (Tok && Tok->is(tok::comment))
443 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
444 /// list that should be indented with a block indent.
445 bool opensBlockOrBlockTypeList(const FormatStyle &Style) const {
446 return is(TT_ArrayInitializerLSquare) ||
448 (BlockKind == BK_Block || is(TT_DictLiteral) ||
449 (!Style.Cpp11BracedListStyle && NestingLevel == 0)));
452 /// \brief Same as opensBlockOrBlockTypeList, but for the closing token.
453 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
454 return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
459 FormatToken(const FormatToken &) = delete;
460 void operator=(const FormatToken &) = delete;
462 template <typename A, typename... Ts>
463 bool startsSequenceInternal(A K1, Ts... Tokens) const {
464 if (is(tok::comment) && Next)
465 return Next->startsSequenceInternal(K1, Tokens...);
466 return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
469 template <typename A>
470 bool startsSequenceInternal(A K1) const {
471 if (is(tok::comment) && Next)
472 return Next->startsSequenceInternal(K1);
476 template <typename A, typename... Ts>
477 bool endsSequenceInternal(A K1) const {
478 if (is(tok::comment) && Previous)
479 return Previous->endsSequenceInternal(K1);
483 template <typename A, typename... Ts>
484 bool endsSequenceInternal(A K1, Ts... Tokens) const {
485 if (is(tok::comment) && Previous)
486 return Previous->endsSequenceInternal(K1, Tokens...);
487 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
491 class ContinuationIndenter;
496 TokenRole(const FormatStyle &Style) : Style(Style) {}
497 virtual ~TokenRole();
499 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
500 /// this function precomputes required information for formatting.
501 virtual void precomputeFormattingInfos(const FormatToken *Token);
503 /// \brief Apply the special formatting that the given role demands.
505 /// Assumes that the token having this role is already formatted.
507 /// Continues formatting from \p State leaving indentation to \p Indenter and
508 /// returns the total penalty that this formatting incurs.
509 virtual unsigned formatFromToken(LineState &State,
510 ContinuationIndenter *Indenter,
515 /// \brief Same as \c formatFromToken, but assumes that the first token has
516 /// already been set thereby deciding on the first line break.
517 virtual unsigned formatAfterToken(LineState &State,
518 ContinuationIndenter *Indenter,
523 /// \brief Notifies the \c Role that a comma was found.
524 virtual void CommaFound(const FormatToken *Token) {}
527 const FormatStyle &Style;
530 class CommaSeparatedList : public TokenRole {
532 CommaSeparatedList(const FormatStyle &Style)
533 : TokenRole(Style), HasNestedBracedList(false) {}
535 void precomputeFormattingInfos(const FormatToken *Token) override;
537 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
538 bool DryRun) override;
540 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
541 bool DryRun) override;
543 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
544 void CommaFound(const FormatToken *Token) override {
545 Commas.push_back(Token);
549 /// \brief A struct that holds information on how to format a given list with
550 /// a specific number of columns.
551 struct ColumnFormat {
552 /// \brief The number of columns to use.
555 /// \brief The total width in characters.
558 /// \brief The number of lines required for this format.
561 /// \brief The size of each column in characters.
562 SmallVector<unsigned, 8> ColumnSizes;
565 /// \brief Calculate which \c ColumnFormat fits best into
566 /// \p RemainingCharacters.
567 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
569 /// \brief The ordered \c FormatTokens making up the commas of this list.
570 SmallVector<const FormatToken *, 8> Commas;
572 /// \brief The length of each of the list's items in characters including the
574 SmallVector<unsigned, 8> ItemLengths;
576 /// \brief Precomputed formats that can be used for this list.
577 SmallVector<ColumnFormat, 4> Formats;
579 bool HasNestedBracedList;
582 /// \brief Encapsulates keywords that are context sensitive or for languages not
583 /// properly supported by Clang's lexer.
584 struct AdditionalKeywords {
585 AdditionalKeywords(IdentifierTable &IdentTable) {
586 kw_final = &IdentTable.get("final");
587 kw_override = &IdentTable.get("override");
588 kw_in = &IdentTable.get("in");
589 kw_of = &IdentTable.get("of");
590 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
591 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
592 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
593 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
595 kw_as = &IdentTable.get("as");
596 kw_async = &IdentTable.get("async");
597 kw_await = &IdentTable.get("await");
598 kw_declare = &IdentTable.get("declare");
599 kw_finally = &IdentTable.get("finally");
600 kw_from = &IdentTable.get("from");
601 kw_function = &IdentTable.get("function");
602 kw_import = &IdentTable.get("import");
603 kw_is = &IdentTable.get("is");
604 kw_let = &IdentTable.get("let");
605 kw_module = &IdentTable.get("module");
606 kw_type = &IdentTable.get("type");
607 kw_var = &IdentTable.get("var");
608 kw_yield = &IdentTable.get("yield");
610 kw_abstract = &IdentTable.get("abstract");
611 kw_assert = &IdentTable.get("assert");
612 kw_extends = &IdentTable.get("extends");
613 kw_implements = &IdentTable.get("implements");
614 kw_instanceof = &IdentTable.get("instanceof");
615 kw_interface = &IdentTable.get("interface");
616 kw_native = &IdentTable.get("native");
617 kw_package = &IdentTable.get("package");
618 kw_synchronized = &IdentTable.get("synchronized");
619 kw_throws = &IdentTable.get("throws");
620 kw___except = &IdentTable.get("__except");
622 kw_mark = &IdentTable.get("mark");
624 kw_extend = &IdentTable.get("extend");
625 kw_option = &IdentTable.get("option");
626 kw_optional = &IdentTable.get("optional");
627 kw_repeated = &IdentTable.get("repeated");
628 kw_required = &IdentTable.get("required");
629 kw_returns = &IdentTable.get("returns");
631 kw_signals = &IdentTable.get("signals");
632 kw_qsignals = &IdentTable.get("Q_SIGNALS");
633 kw_slots = &IdentTable.get("slots");
634 kw_qslots = &IdentTable.get("Q_SLOTS");
637 // Context sensitive keywords.
638 IdentifierInfo *kw_final;
639 IdentifierInfo *kw_override;
640 IdentifierInfo *kw_in;
641 IdentifierInfo *kw_of;
642 IdentifierInfo *kw_CF_ENUM;
643 IdentifierInfo *kw_CF_OPTIONS;
644 IdentifierInfo *kw_NS_ENUM;
645 IdentifierInfo *kw_NS_OPTIONS;
646 IdentifierInfo *kw___except;
648 // JavaScript keywords.
649 IdentifierInfo *kw_as;
650 IdentifierInfo *kw_async;
651 IdentifierInfo *kw_await;
652 IdentifierInfo *kw_declare;
653 IdentifierInfo *kw_finally;
654 IdentifierInfo *kw_from;
655 IdentifierInfo *kw_function;
656 IdentifierInfo *kw_import;
657 IdentifierInfo *kw_is;
658 IdentifierInfo *kw_let;
659 IdentifierInfo *kw_module;
660 IdentifierInfo *kw_type;
661 IdentifierInfo *kw_var;
662 IdentifierInfo *kw_yield;
665 IdentifierInfo *kw_abstract;
666 IdentifierInfo *kw_assert;
667 IdentifierInfo *kw_extends;
668 IdentifierInfo *kw_implements;
669 IdentifierInfo *kw_instanceof;
670 IdentifierInfo *kw_interface;
671 IdentifierInfo *kw_native;
672 IdentifierInfo *kw_package;
673 IdentifierInfo *kw_synchronized;
674 IdentifierInfo *kw_throws;
677 IdentifierInfo *kw_mark;
680 IdentifierInfo *kw_extend;
681 IdentifierInfo *kw_option;
682 IdentifierInfo *kw_optional;
683 IdentifierInfo *kw_repeated;
684 IdentifierInfo *kw_required;
685 IdentifierInfo *kw_returns;
688 IdentifierInfo *kw_signals;
689 IdentifierInfo *kw_qsignals;
690 IdentifierInfo *kw_slots;
691 IdentifierInfo *kw_qslots;
694 } // namespace format