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"
29 TT_ArrayInitializerLSquare,
30 TT_ArraySubscriptLSquare,
37 TT_ConflictAlternative,
40 TT_CtorInitializerColon,
41 TT_CtorInitializerComma,
42 TT_DesignatedInitializerPeriod,
45 TT_FunctionAnnotationRParen,
46 TT_FunctionDeclarationName,
48 TT_FunctionTypeLParen,
49 TT_ImplicitStringLiteral,
54 TT_JsComputedPropertyName,
57 TT_JsTypeOptionalQuestion,
60 TT_LeadingJavaAnnotation,
67 TT_ObjCMethodSpecifier,
70 TT_OverloadedOperator,
71 TT_OverloadedOperatorLParen,
72 TT_PointerOrReference,
73 TT_PureVirtualSpecifier,
74 TT_RangeBasedForLoopColon,
81 TT_TrailingAnnotation,
82 TT_TrailingReturnArrow,
83 TT_TrailingUnaryOperator,
88 // Represents what type of block a set of braces open.
89 enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit };
91 // The packing kind of a function's parameters.
92 enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive };
94 enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break };
99 /// \brief A wrapper around a \c Token storing information about the
100 /// whitespace characters preceding it.
104 /// \brief The \c Token.
107 /// \brief The number of newlines immediately before the \c Token.
109 /// This can be used to determine what the user wrote in the original code
110 /// and thereby e.g. leave an empty line between two function definitions.
111 unsigned NewlinesBefore = 0;
113 /// \brief Whether there is at least one unescaped newline before the \c
115 bool HasUnescapedNewline = false;
117 /// \brief The range of the whitespace immediately preceding the \c Token.
118 SourceRange WhitespaceRange;
120 /// \brief The offset just past the last '\n' in this token's leading
121 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
122 unsigned LastNewlineOffset = 0;
124 /// \brief The width of the non-whitespace parts of the token (or its first
125 /// line for multi-line tokens) in columns.
126 /// We need this to correctly measure number of columns a token spans.
127 unsigned ColumnWidth = 0;
129 /// \brief Contains the width in columns of the last line of a multi-line
131 unsigned LastLineColumnWidth = 0;
133 /// \brief Whether the token text contains newlines (escaped or not).
134 bool IsMultiline = false;
136 /// \brief Indicates that this is the first token.
137 bool IsFirst = false;
139 /// \brief Whether there must be a line break before this token.
141 /// This happens for example when a preprocessor directive ended directly
142 /// before the token.
143 bool MustBreakBefore = false;
145 /// \brief The raw text of the token.
147 /// Contains the raw token text without leading whitespace and without leading
148 /// escaped newlines.
151 /// \brief Set to \c true if this token is an unterminated literal.
152 bool IsUnterminatedLiteral = 0;
154 /// \brief Contains the kind of block if this token is a brace.
155 BraceBlockKind BlockKind = BK_Unknown;
157 TokenType Type = TT_Unknown;
159 /// \brief The number of spaces that should be inserted before this token.
160 unsigned SpacesRequiredBefore = 0;
162 /// \brief \c true if it is allowed to break before this token.
163 bool CanBreakBefore = false;
165 /// \brief \c true if this is the ">" of "template<..>".
166 bool ClosesTemplateDeclaration = false;
168 /// \brief Number of parameters, if this is "(", "[" or "<".
170 /// This is initialized to 1 as we don't need to distinguish functions with
171 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
172 /// the number of commas.
173 unsigned ParameterCount = 0;
175 /// \brief Number of parameters that are nested blocks,
176 /// if this is "(", "[" or "<".
177 unsigned BlockParameterCount = 0;
179 /// \brief If this is a bracket ("<", "(", "[" or "{"), contains the kind of
180 /// the surrounding bracket.
181 tok::TokenKind ParentBracket = tok::unknown;
183 /// \brief A token can have a special role that can carry extra information
184 /// about the token's formatting.
185 std::unique_ptr<TokenRole> Role;
187 /// \brief If this is an opening parenthesis, how are the parameters packed?
188 ParameterPackingKind PackingKind = PPK_Inconclusive;
190 /// \brief The total length of the unwrapped line up to and including this
192 unsigned TotalLength = 0;
194 /// \brief The original 0-based column of this token, including expanded tabs.
195 /// The configured TabWidth is used as tab width.
196 unsigned OriginalColumn = 0;
198 /// \brief The length of following tokens until the next natural split point,
199 /// or the next token that can be broken.
200 unsigned UnbreakableTailLength = 0;
202 // FIXME: Come up with a 'cleaner' concept.
203 /// \brief The binding strength of a token. This is a combined value of
204 /// operator precedence, parenthesis nesting, etc.
205 unsigned BindingStrength = 0;
207 /// \brief The nesting level of this token, i.e. the number of surrounding (),
209 unsigned NestingLevel = 0;
211 /// \brief Penalty for inserting a line break before this token.
212 unsigned SplitPenalty = 0;
214 /// \brief If this is the first ObjC selector name in an ObjC method
215 /// definition or call, this contains the length of the longest name.
217 /// This being set to 0 means that the selectors should not be colon-aligned,
218 /// e.g. because several of them are block-type.
219 unsigned LongestObjCSelectorName = 0;
221 /// \brief Stores the number of required fake parentheses and the
222 /// corresponding operator precedence.
224 /// If multiple fake parentheses start at a token, this vector stores them in
225 /// reverse order, i.e. inner fake parenthesis first.
226 SmallVector<prec::Level, 4> FakeLParens;
227 /// \brief Insert this many fake ) after this token for correct indentation.
228 unsigned FakeRParens = 0;
230 /// \brief \c true if this token starts a binary expression, i.e. has at least
231 /// one fake l_paren with a precedence greater than prec::Unknown.
232 bool StartsBinaryExpression = false;
233 /// \brief \c true if this token ends a binary expression.
234 bool EndsBinaryExpression = false;
236 /// \brief Is this is an operator (or "."/"->") in a sequence of operators
237 /// with the same precedence, contains the 0-based operator index.
238 unsigned OperatorIndex = 0;
240 /// \brief Is this the last operator (or "."/"->") in a sequence of operators
241 /// with the same precedence?
242 bool LastOperator = false;
244 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
246 /// Only set if \c Type == \c TT_StartOfName.
247 bool PartOfMultiVariableDeclStmt = false;
249 /// \brief If this is a bracket, this points to the matching one.
250 FormatToken *MatchingParen = nullptr;
252 /// \brief The previous token in the unwrapped line.
253 FormatToken *Previous = nullptr;
255 /// \brief The next token in the unwrapped line.
256 FormatToken *Next = nullptr;
258 /// \brief If this token starts a block, this contains all the unwrapped lines
260 SmallVector<AnnotatedLine *, 1> Children;
262 /// \brief Stores the formatting decision for the token once it was made.
263 FormatDecision Decision = FD_Unformatted;
265 /// \brief If \c true, this token has been fully formatted (indented and
266 /// potentially re-formatted inside), and we do not allow further formatting
268 bool Finalized = false;
270 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
271 bool is(TokenType TT) const { return Type == TT; }
272 bool is(const IdentifierInfo *II) const {
273 return II && II == Tok.getIdentifierInfo();
275 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
276 return is(K1) || is(K2);
278 template <typename A, typename B, typename... Ts>
279 bool isOneOf(A K1, B K2, Ts... Ks) const {
280 return is(K1) || isOneOf(K2, Ks...);
282 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
284 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
286 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
287 return Tok.isObjCAtKeyword(Kind);
290 bool isAccessSpecifier(bool ColonRequired = true) const {
291 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
292 (!ColonRequired || (Next && Next->is(tok::colon)));
295 /// \brief Determine whether the token is a simple-type-specifier.
296 bool isSimpleTypeSpecifier() const;
298 bool isObjCAccessSpecifier() const {
299 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
300 Next->isObjCAtKeyword(tok::objc_protected) ||
301 Next->isObjCAtKeyword(tok::objc_package) ||
302 Next->isObjCAtKeyword(tok::objc_private));
305 /// \brief Returns whether \p Tok is ([{ or a template opening <.
306 bool opensScope() const {
307 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
310 /// \brief Returns whether \p Tok is )]} or a template closing >.
311 bool closesScope() const {
312 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
316 /// \brief Returns \c true if this is a "." or "->" accessing a member.
317 bool isMemberAccess() const {
318 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
319 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
323 bool isUnaryOperator() const {
324 switch (Tok.getKind()) {
328 case tok::minusminus:
332 case tok::kw_alignof:
339 bool isBinaryOperator() const {
340 // Comma is a binary operator, but does not behave as such wrt. formatting.
341 return getPrecedence() > prec::Comma;
344 bool isTrailingComment() const {
345 return is(tok::comment) &&
346 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
349 /// \brief Returns \c true if this is a keyword that can be used
350 /// like a function call (e.g. sizeof, typeid, ...).
351 bool isFunctionLikeKeyword() const {
352 switch (Tok.getKind()) {
357 case tok::kw_alignof:
358 case tok::kw_alignas:
359 case tok::kw_decltype:
360 case tok::kw_noexcept:
361 case tok::kw_static_assert:
362 case tok::kw___attribute:
369 /// \brief Returns actual token start location without leading escaped
370 /// newlines and whitespace.
372 /// This can be different to Tok.getLocation(), which includes leading escaped
374 SourceLocation getStartOfNonWhitespace() const {
375 return WhitespaceRange.getEnd();
378 prec::Level getPrecedence() const {
379 return getBinOpPrecedence(Tok.getKind(), true, true);
382 /// \brief Returns the previous token ignoring comments.
383 FormatToken *getPreviousNonComment() const {
384 FormatToken *Tok = Previous;
385 while (Tok && Tok->is(tok::comment))
390 /// \brief Returns the next token ignoring comments.
391 const FormatToken *getNextNonComment() const {
392 const FormatToken *Tok = Next;
393 while (Tok && Tok->is(tok::comment))
398 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
399 /// list that should be indented with a block indent.
400 bool opensBlockTypeList(const FormatStyle &Style) const {
401 return is(TT_ArrayInitializerLSquare) ||
403 (BlockKind == BK_Block || is(TT_DictLiteral) ||
404 (!Style.Cpp11BracedListStyle && NestingLevel == 0)));
407 /// \brief Same as opensBlockTypeList, but for the closing token.
408 bool closesBlockTypeList(const FormatStyle &Style) const {
409 return MatchingParen && MatchingParen->opensBlockTypeList(Style);
414 FormatToken(const FormatToken &) = delete;
415 void operator=(const FormatToken &) = delete;
418 class ContinuationIndenter;
423 TokenRole(const FormatStyle &Style) : Style(Style) {}
424 virtual ~TokenRole();
426 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
427 /// this function precomputes required information for formatting.
428 virtual void precomputeFormattingInfos(const FormatToken *Token);
430 /// \brief Apply the special formatting that the given role demands.
432 /// Assumes that the token having this role is already formatted.
434 /// Continues formatting from \p State leaving indentation to \p Indenter and
435 /// returns the total penalty that this formatting incurs.
436 virtual unsigned formatFromToken(LineState &State,
437 ContinuationIndenter *Indenter,
442 /// \brief Same as \c formatFromToken, but assumes that the first token has
443 /// already been set thereby deciding on the first line break.
444 virtual unsigned formatAfterToken(LineState &State,
445 ContinuationIndenter *Indenter,
450 /// \brief Notifies the \c Role that a comma was found.
451 virtual void CommaFound(const FormatToken *Token) {}
454 const FormatStyle &Style;
457 class CommaSeparatedList : public TokenRole {
459 CommaSeparatedList(const FormatStyle &Style)
460 : TokenRole(Style), HasNestedBracedList(false) {}
462 void precomputeFormattingInfos(const FormatToken *Token) override;
464 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
465 bool DryRun) override;
467 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
468 bool DryRun) override;
470 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
471 void CommaFound(const FormatToken *Token) override {
472 Commas.push_back(Token);
476 /// \brief A struct that holds information on how to format a given list with
477 /// a specific number of columns.
478 struct ColumnFormat {
479 /// \brief The number of columns to use.
482 /// \brief The total width in characters.
485 /// \brief The number of lines required for this format.
488 /// \brief The size of each column in characters.
489 SmallVector<unsigned, 8> ColumnSizes;
492 /// \brief Calculate which \c ColumnFormat fits best into
493 /// \p RemainingCharacters.
494 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
496 /// \brief The ordered \c FormatTokens making up the commas of this list.
497 SmallVector<const FormatToken *, 8> Commas;
499 /// \brief The length of each of the list's items in characters including the
501 SmallVector<unsigned, 8> ItemLengths;
503 /// \brief Precomputed formats that can be used for this list.
504 SmallVector<ColumnFormat, 4> Formats;
506 bool HasNestedBracedList;
509 /// \brief Encapsulates keywords that are context sensitive or for languages not
510 /// properly supported by Clang's lexer.
511 struct AdditionalKeywords {
512 AdditionalKeywords(IdentifierTable &IdentTable) {
513 kw_in = &IdentTable.get("in");
514 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
515 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
516 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
517 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
519 kw_finally = &IdentTable.get("finally");
520 kw_function = &IdentTable.get("function");
521 kw_import = &IdentTable.get("import");
522 kw_var = &IdentTable.get("var");
524 kw_abstract = &IdentTable.get("abstract");
525 kw_extends = &IdentTable.get("extends");
526 kw_final = &IdentTable.get("final");
527 kw_implements = &IdentTable.get("implements");
528 kw_instanceof = &IdentTable.get("instanceof");
529 kw_interface = &IdentTable.get("interface");
530 kw_native = &IdentTable.get("native");
531 kw_package = &IdentTable.get("package");
532 kw_synchronized = &IdentTable.get("synchronized");
533 kw_throws = &IdentTable.get("throws");
534 kw___except = &IdentTable.get("__except");
536 kw_mark = &IdentTable.get("mark");
538 kw_option = &IdentTable.get("option");
539 kw_optional = &IdentTable.get("optional");
540 kw_repeated = &IdentTable.get("repeated");
541 kw_required = &IdentTable.get("required");
542 kw_returns = &IdentTable.get("returns");
544 kw_signals = &IdentTable.get("signals");
545 kw_slots = &IdentTable.get("slots");
546 kw_qslots = &IdentTable.get("Q_SLOTS");
549 // Context sensitive keywords.
550 IdentifierInfo *kw_in;
551 IdentifierInfo *kw_CF_ENUM;
552 IdentifierInfo *kw_CF_OPTIONS;
553 IdentifierInfo *kw_NS_ENUM;
554 IdentifierInfo *kw_NS_OPTIONS;
555 IdentifierInfo *kw___except;
557 // JavaScript keywords.
558 IdentifierInfo *kw_finally;
559 IdentifierInfo *kw_function;
560 IdentifierInfo *kw_import;
561 IdentifierInfo *kw_var;
564 IdentifierInfo *kw_abstract;
565 IdentifierInfo *kw_extends;
566 IdentifierInfo *kw_final;
567 IdentifierInfo *kw_implements;
568 IdentifierInfo *kw_instanceof;
569 IdentifierInfo *kw_interface;
570 IdentifierInfo *kw_native;
571 IdentifierInfo *kw_package;
572 IdentifierInfo *kw_synchronized;
573 IdentifierInfo *kw_throws;
576 IdentifierInfo *kw_mark;
579 IdentifierInfo *kw_option;
580 IdentifierInfo *kw_optional;
581 IdentifierInfo *kw_repeated;
582 IdentifierInfo *kw_required;
583 IdentifierInfo *kw_returns;
586 IdentifierInfo *kw_signals;
587 IdentifierInfo *kw_slots;
588 IdentifierInfo *kw_qslots;
591 } // namespace format