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) \
57 TYPE(JsNonNullAssertion) \
59 TYPE(JsTypeOperator) \
60 TYPE(JsTypeOptionalQuestion) \
63 TYPE(LeadingJavaAnnotation) \
65 TYPE(MacroBlockBegin) \
67 TYPE(ObjCBlockLBrace) \
68 TYPE(ObjCBlockLParen) \
71 TYPE(ObjCMethodExpr) \
72 TYPE(ObjCMethodSpecifier) \
74 TYPE(ObjCStringLiteral) \
75 TYPE(OverloadedOperator) \
76 TYPE(OverloadedOperatorLParen) \
77 TYPE(PointerOrReference) \
78 TYPE(PureVirtualSpecifier) \
79 TYPE(RangeBasedForLoopColon) \
83 TYPE(TemplateCloser) \
84 TYPE(TemplateOpener) \
85 TYPE(TemplateString) \
86 TYPE(TrailingAnnotation) \
87 TYPE(TrailingReturnArrow) \
88 TYPE(TrailingUnaryOperator) \
93 #define TYPE(X) TT_##X,
99 /// \brief Determines the name of a token type.
100 const char *getTokenTypeName(TokenType Type);
102 // Represents what type of block a set of braces open.
103 enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
105 // The packing kind of a function's parameters.
106 enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
108 enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
113 /// \brief A wrapper around a \c Token storing information about the
114 /// whitespace characters preceding it.
118 /// \brief The \c Token.
121 /// \brief The number of newlines immediately before the \c Token.
123 /// This can be used to determine what the user wrote in the original code
124 /// and thereby e.g. leave an empty line between two function definitions.
125 unsigned NewlinesBefore = 0;
127 /// \brief Whether there is at least one unescaped newline before the \c
129 bool HasUnescapedNewline = false;
131 /// \brief The range of the whitespace immediately preceding the \c Token.
132 SourceRange WhitespaceRange;
134 /// \brief The offset just past the last '\n' in this token's leading
135 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
136 unsigned LastNewlineOffset = 0;
138 /// \brief The width of the non-whitespace parts of the token (or its first
139 /// line for multi-line tokens) in columns.
140 /// We need this to correctly measure number of columns a token spans.
141 unsigned ColumnWidth = 0;
143 /// \brief Contains the width in columns of the last line of a multi-line
145 unsigned LastLineColumnWidth = 0;
147 /// \brief Whether the token text contains newlines (escaped or not).
148 bool IsMultiline = false;
150 /// \brief Indicates that this is the first token of the file.
151 bool IsFirst = false;
153 /// \brief Whether there must be a line break before this token.
155 /// This happens for example when a preprocessor directive ended directly
156 /// before the token.
157 bool MustBreakBefore = false;
159 /// \brief The raw text of the token.
161 /// Contains the raw token text without leading whitespace and without leading
162 /// escaped newlines.
165 /// \brief Set to \c true if this token is an unterminated literal.
166 bool IsUnterminatedLiteral = 0;
168 /// \brief Contains the kind of block if this token is a brace.
169 BraceBlockKind BlockKind = BK_Unknown;
171 TokenType Type = TT_Unknown;
173 /// \brief The number of spaces that should be inserted before this token.
174 unsigned SpacesRequiredBefore = 0;
176 /// \brief \c true if it is allowed to break before this token.
177 bool CanBreakBefore = false;
179 /// \brief \c true if this is the ">" of "template<..>".
180 bool ClosesTemplateDeclaration = false;
182 /// \brief Number of parameters, if this is "(", "[" or "<".
184 /// This is initialized to 1 as we don't need to distinguish functions with
185 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
186 /// the number of commas.
187 unsigned ParameterCount = 0;
189 /// \brief Number of parameters that are nested blocks,
190 /// if this is "(", "[" or "<".
191 unsigned BlockParameterCount = 0;
193 /// \brief If this is a bracket ("<", "(", "[" or "{"), contains the kind of
194 /// the surrounding bracket.
195 tok::TokenKind ParentBracket = tok::unknown;
197 /// \brief A token can have a special role that can carry extra information
198 /// about the token's formatting.
199 std::unique_ptr<TokenRole> Role;
201 /// \brief If this is an opening parenthesis, how are the parameters packed?
202 ParameterPackingKind PackingKind = PPK_Inconclusive;
204 /// \brief The total length of the unwrapped line up to and including this
206 unsigned TotalLength = 0;
208 /// \brief The original 0-based column of this token, including expanded tabs.
209 /// The configured TabWidth is used as tab width.
210 unsigned OriginalColumn = 0;
212 /// \brief The length of following tokens until the next natural split point,
213 /// or the next token that can be broken.
214 unsigned UnbreakableTailLength = 0;
216 // FIXME: Come up with a 'cleaner' concept.
217 /// \brief The binding strength of a token. This is a combined value of
218 /// operator precedence, parenthesis nesting, etc.
219 unsigned BindingStrength = 0;
221 /// \brief The nesting level of this token, i.e. the number of surrounding (),
223 unsigned NestingLevel = 0;
225 /// \brief The indent level of this token. Copied from the surrounding line.
226 unsigned IndentLevel = 0;
228 /// \brief Penalty for inserting a line break before this token.
229 unsigned SplitPenalty = 0;
231 /// \brief If this is the first ObjC selector name in an ObjC method
232 /// definition or call, this contains the length of the longest name.
234 /// This being set to 0 means that the selectors should not be colon-aligned,
235 /// e.g. because several of them are block-type.
236 unsigned LongestObjCSelectorName = 0;
238 /// \brief Stores the number of required fake parentheses and the
239 /// corresponding operator precedence.
241 /// If multiple fake parentheses start at a token, this vector stores them in
242 /// reverse order, i.e. inner fake parenthesis first.
243 SmallVector<prec::Level, 4> FakeLParens;
244 /// \brief Insert this many fake ) after this token for correct indentation.
245 unsigned FakeRParens = 0;
247 /// \brief \c true if this token starts a binary expression, i.e. has at least
248 /// one fake l_paren with a precedence greater than prec::Unknown.
249 bool StartsBinaryExpression = false;
250 /// \brief \c true if this token ends a binary expression.
251 bool EndsBinaryExpression = false;
253 /// \brief Is this is an operator (or "."/"->") in a sequence of operators
254 /// with the same precedence, contains the 0-based operator index.
255 unsigned OperatorIndex = 0;
257 /// \brief If this is an operator (or "."/"->") in a sequence of operators
258 /// with the same precedence, points to the next operator.
259 FormatToken *NextOperator = nullptr;
261 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
263 /// Only set if \c Type == \c TT_StartOfName.
264 bool PartOfMultiVariableDeclStmt = false;
266 /// \brief Does this line comment continue a line comment section?
268 /// Only set to true if \c Type == \c TT_LineComment.
269 bool ContinuesLineCommentSection = false;
271 /// \brief If this is a bracket, this points to the matching one.
272 FormatToken *MatchingParen = nullptr;
274 /// \brief The previous token in the unwrapped line.
275 FormatToken *Previous = nullptr;
277 /// \brief The next token in the unwrapped line.
278 FormatToken *Next = nullptr;
280 /// \brief If this token starts a block, this contains all the unwrapped lines
282 SmallVector<AnnotatedLine *, 1> Children;
284 /// \brief Stores the formatting decision for the token once it was made.
285 FormatDecision Decision = FD_Unformatted;
287 /// \brief If \c true, this token has been fully formatted (indented and
288 /// potentially re-formatted inside), and we do not allow further formatting
290 bool Finalized = false;
292 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
293 bool is(TokenType TT) const { return Type == TT; }
294 bool is(const IdentifierInfo *II) const {
295 return II && II == Tok.getIdentifierInfo();
297 bool is(tok::PPKeywordKind Kind) const {
298 return Tok.getIdentifierInfo() &&
299 Tok.getIdentifierInfo()->getPPKeywordID() == Kind;
301 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
302 return is(K1) || is(K2);
304 template <typename A, typename B, typename... Ts>
305 bool isOneOf(A K1, B K2, Ts... Ks) const {
306 return is(K1) || isOneOf(K2, Ks...);
308 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
310 /// \c true if this token starts a sequence with the given tokens in order,
311 /// following the ``Next`` pointers, ignoring comments.
312 template <typename A, typename... Ts>
313 bool startsSequence(A K1, Ts... Tokens) const {
314 return startsSequenceInternal(K1, Tokens...);
317 /// \c true if this token ends a sequence with the given tokens in order,
318 /// following the ``Previous`` pointers, ignoring comments.
319 template <typename A, typename... Ts>
320 bool endsSequence(A K1, Ts... Tokens) const {
321 return endsSequenceInternal(K1, Tokens...);
324 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
326 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
327 return Tok.isObjCAtKeyword(Kind);
330 bool isAccessSpecifier(bool ColonRequired = true) const {
331 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
332 (!ColonRequired || (Next && Next->is(tok::colon)));
335 /// \brief Determine whether the token is a simple-type-specifier.
336 bool isSimpleTypeSpecifier() const;
338 bool isObjCAccessSpecifier() const {
339 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
340 Next->isObjCAtKeyword(tok::objc_protected) ||
341 Next->isObjCAtKeyword(tok::objc_package) ||
342 Next->isObjCAtKeyword(tok::objc_private));
345 /// \brief Returns whether \p Tok is ([{ or a template opening <.
346 bool opensScope() const {
347 if (is(TT_TemplateString) && TokenText.endswith("${"))
349 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
352 /// \brief Returns whether \p Tok is )]} or a template closing >.
353 bool closesScope() const {
354 if (is(TT_TemplateString) && TokenText.startswith("}"))
356 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
360 /// \brief Returns \c true if this is a "." or "->" accessing a member.
361 bool isMemberAccess() const {
362 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
363 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
367 bool isUnaryOperator() const {
368 switch (Tok.getKind()) {
372 case tok::minusminus:
376 case tok::kw_alignof:
383 bool isBinaryOperator() const {
384 // Comma is a binary operator, but does not behave as such wrt. formatting.
385 return getPrecedence() > prec::Comma;
388 bool isTrailingComment() const {
389 return is(tok::comment) &&
390 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
393 /// \brief Returns \c true if this is a keyword that can be used
394 /// like a function call (e.g. sizeof, typeid, ...).
395 bool isFunctionLikeKeyword() const {
396 switch (Tok.getKind()) {
401 case tok::kw_alignof:
402 case tok::kw_alignas:
403 case tok::kw_decltype:
404 case tok::kw_noexcept:
405 case tok::kw_static_assert:
406 case tok::kw___attribute:
413 /// \brief Returns \c true if this is a string literal that's like a label,
414 /// e.g. ends with "=" or ":".
415 bool isLabelString() const {
416 if (!is(tok::string_literal))
418 StringRef Content = TokenText;
419 if (Content.startswith("\"") || Content.startswith("'"))
420 Content = Content.drop_front(1);
421 if (Content.endswith("\"") || Content.endswith("'"))
422 Content = Content.drop_back(1);
423 Content = Content.trim();
424 return Content.size() > 1 &&
425 (Content.back() == ':' || Content.back() == '=');
428 /// \brief Returns actual token start location without leading escaped
429 /// newlines and whitespace.
431 /// This can be different to Tok.getLocation(), which includes leading escaped
433 SourceLocation getStartOfNonWhitespace() const {
434 return WhitespaceRange.getEnd();
437 prec::Level getPrecedence() const {
438 return getBinOpPrecedence(Tok.getKind(), true, true);
441 /// \brief Returns the previous token ignoring comments.
442 FormatToken *getPreviousNonComment() const {
443 FormatToken *Tok = Previous;
444 while (Tok && Tok->is(tok::comment))
449 /// \brief Returns the next token ignoring comments.
450 const FormatToken *getNextNonComment() const {
451 const FormatToken *Tok = Next;
452 while (Tok && Tok->is(tok::comment))
457 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
458 /// list that should be indented with a block indent.
459 bool opensBlockOrBlockTypeList(const FormatStyle &Style) const {
460 if (is(TT_TemplateString) && opensScope())
462 return is(TT_ArrayInitializerLSquare) ||
464 (BlockKind == BK_Block || is(TT_DictLiteral) ||
465 (!Style.Cpp11BracedListStyle && NestingLevel == 0)));
468 /// \brief Same as opensBlockOrBlockTypeList, but for the closing token.
469 bool closesBlockOrBlockTypeList(const FormatStyle &Style) const {
470 if (is(TT_TemplateString) && closesScope())
472 return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style);
477 FormatToken(const FormatToken &) = delete;
478 void operator=(const FormatToken &) = delete;
480 template <typename A, typename... Ts>
481 bool startsSequenceInternal(A K1, Ts... Tokens) const {
482 if (is(tok::comment) && Next)
483 return Next->startsSequenceInternal(K1, Tokens...);
484 return is(K1) && Next && Next->startsSequenceInternal(Tokens...);
487 template <typename A>
488 bool startsSequenceInternal(A K1) const {
489 if (is(tok::comment) && Next)
490 return Next->startsSequenceInternal(K1);
494 template <typename A, typename... Ts>
495 bool endsSequenceInternal(A K1) const {
496 if (is(tok::comment) && Previous)
497 return Previous->endsSequenceInternal(K1);
501 template <typename A, typename... Ts>
502 bool endsSequenceInternal(A K1, Ts... Tokens) const {
503 if (is(tok::comment) && Previous)
504 return Previous->endsSequenceInternal(K1, Tokens...);
505 return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...);
509 class ContinuationIndenter;
514 TokenRole(const FormatStyle &Style) : Style(Style) {}
515 virtual ~TokenRole();
517 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
518 /// this function precomputes required information for formatting.
519 virtual void precomputeFormattingInfos(const FormatToken *Token);
521 /// \brief Apply the special formatting that the given role demands.
523 /// Assumes that the token having this role is already formatted.
525 /// Continues formatting from \p State leaving indentation to \p Indenter and
526 /// returns the total penalty that this formatting incurs.
527 virtual unsigned formatFromToken(LineState &State,
528 ContinuationIndenter *Indenter,
533 /// \brief Same as \c formatFromToken, but assumes that the first token has
534 /// already been set thereby deciding on the first line break.
535 virtual unsigned formatAfterToken(LineState &State,
536 ContinuationIndenter *Indenter,
541 /// \brief Notifies the \c Role that a comma was found.
542 virtual void CommaFound(const FormatToken *Token) {}
545 const FormatStyle &Style;
548 class CommaSeparatedList : public TokenRole {
550 CommaSeparatedList(const FormatStyle &Style)
551 : TokenRole(Style), HasNestedBracedList(false) {}
553 void precomputeFormattingInfos(const FormatToken *Token) override;
555 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
556 bool DryRun) override;
558 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
559 bool DryRun) override;
561 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
562 void CommaFound(const FormatToken *Token) override {
563 Commas.push_back(Token);
567 /// \brief A struct that holds information on how to format a given list with
568 /// a specific number of columns.
569 struct ColumnFormat {
570 /// \brief The number of columns to use.
573 /// \brief The total width in characters.
576 /// \brief The number of lines required for this format.
579 /// \brief The size of each column in characters.
580 SmallVector<unsigned, 8> ColumnSizes;
583 /// \brief Calculate which \c ColumnFormat fits best into
584 /// \p RemainingCharacters.
585 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
587 /// \brief The ordered \c FormatTokens making up the commas of this list.
588 SmallVector<const FormatToken *, 8> Commas;
590 /// \brief The length of each of the list's items in characters including the
592 SmallVector<unsigned, 8> ItemLengths;
594 /// \brief Precomputed formats that can be used for this list.
595 SmallVector<ColumnFormat, 4> Formats;
597 bool HasNestedBracedList;
600 /// \brief Encapsulates keywords that are context sensitive or for languages not
601 /// properly supported by Clang's lexer.
602 struct AdditionalKeywords {
603 AdditionalKeywords(IdentifierTable &IdentTable) {
604 kw_final = &IdentTable.get("final");
605 kw_override = &IdentTable.get("override");
606 kw_in = &IdentTable.get("in");
607 kw_of = &IdentTable.get("of");
608 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
609 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
610 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
611 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
613 kw_as = &IdentTable.get("as");
614 kw_async = &IdentTable.get("async");
615 kw_await = &IdentTable.get("await");
616 kw_declare = &IdentTable.get("declare");
617 kw_finally = &IdentTable.get("finally");
618 kw_from = &IdentTable.get("from");
619 kw_function = &IdentTable.get("function");
620 kw_import = &IdentTable.get("import");
621 kw_is = &IdentTable.get("is");
622 kw_let = &IdentTable.get("let");
623 kw_module = &IdentTable.get("module");
624 kw_type = &IdentTable.get("type");
625 kw_var = &IdentTable.get("var");
626 kw_yield = &IdentTable.get("yield");
628 kw_abstract = &IdentTable.get("abstract");
629 kw_assert = &IdentTable.get("assert");
630 kw_extends = &IdentTable.get("extends");
631 kw_implements = &IdentTable.get("implements");
632 kw_instanceof = &IdentTable.get("instanceof");
633 kw_interface = &IdentTable.get("interface");
634 kw_native = &IdentTable.get("native");
635 kw_package = &IdentTable.get("package");
636 kw_synchronized = &IdentTable.get("synchronized");
637 kw_throws = &IdentTable.get("throws");
638 kw___except = &IdentTable.get("__except");
639 kw___has_include = &IdentTable.get("__has_include");
640 kw___has_include_next = &IdentTable.get("__has_include_next");
642 kw_mark = &IdentTable.get("mark");
644 kw_extend = &IdentTable.get("extend");
645 kw_option = &IdentTable.get("option");
646 kw_optional = &IdentTable.get("optional");
647 kw_repeated = &IdentTable.get("repeated");
648 kw_required = &IdentTable.get("required");
649 kw_returns = &IdentTable.get("returns");
651 kw_signals = &IdentTable.get("signals");
652 kw_qsignals = &IdentTable.get("Q_SIGNALS");
653 kw_slots = &IdentTable.get("slots");
654 kw_qslots = &IdentTable.get("Q_SLOTS");
657 // Context sensitive keywords.
658 IdentifierInfo *kw_final;
659 IdentifierInfo *kw_override;
660 IdentifierInfo *kw_in;
661 IdentifierInfo *kw_of;
662 IdentifierInfo *kw_CF_ENUM;
663 IdentifierInfo *kw_CF_OPTIONS;
664 IdentifierInfo *kw_NS_ENUM;
665 IdentifierInfo *kw_NS_OPTIONS;
666 IdentifierInfo *kw___except;
667 IdentifierInfo *kw___has_include;
668 IdentifierInfo *kw___has_include_next;
670 // JavaScript keywords.
671 IdentifierInfo *kw_as;
672 IdentifierInfo *kw_async;
673 IdentifierInfo *kw_await;
674 IdentifierInfo *kw_declare;
675 IdentifierInfo *kw_finally;
676 IdentifierInfo *kw_from;
677 IdentifierInfo *kw_function;
678 IdentifierInfo *kw_import;
679 IdentifierInfo *kw_is;
680 IdentifierInfo *kw_let;
681 IdentifierInfo *kw_module;
682 IdentifierInfo *kw_type;
683 IdentifierInfo *kw_var;
684 IdentifierInfo *kw_yield;
687 IdentifierInfo *kw_abstract;
688 IdentifierInfo *kw_assert;
689 IdentifierInfo *kw_extends;
690 IdentifierInfo *kw_implements;
691 IdentifierInfo *kw_instanceof;
692 IdentifierInfo *kw_interface;
693 IdentifierInfo *kw_native;
694 IdentifierInfo *kw_package;
695 IdentifierInfo *kw_synchronized;
696 IdentifierInfo *kw_throws;
699 IdentifierInfo *kw_mark;
702 IdentifierInfo *kw_extend;
703 IdentifierInfo *kw_option;
704 IdentifierInfo *kw_optional;
705 IdentifierInfo *kw_repeated;
706 IdentifierInfo *kw_required;
707 IdentifierInfo *kw_returns;
710 IdentifierInfo *kw_signals;
711 IdentifierInfo *kw_qsignals;
712 IdentifierInfo *kw_slots;
713 IdentifierInfo *kw_qslots;
716 } // namespace format