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
,
44 TT_FunctionDeclarationName
,
46 TT_FunctionTypeLParen
,
47 TT_ImplicitStringLiteral
,
53 TT_LeadingJavaAnnotation
,
60 TT_ObjCMethodSpecifier
,
62 TT_OverloadedOperator
,
63 TT_OverloadedOperatorLParen
,
64 TT_PointerOrReference
,
65 TT_PureVirtualSpecifier
,
66 TT_RangeBasedForLoopColon
,
72 TT_TrailingAnnotation
,
73 TT_TrailingReturnArrow
,
74 TT_TrailingUnaryOperator
,
79 // Represents what type of block a set of braces open.
86 // The packing kind of a function's parameters.
87 enum ParameterPackingKind
{
102 /// \brief A wrapper around a \c Token storing information about the
103 /// whitespace characters preceding it.
106 : NewlinesBefore(0), HasUnescapedNewline(false), LastNewlineOffset(0),
107 ColumnWidth(0), LastLineColumnWidth(0), IsMultiline(false),
108 IsFirst(false), MustBreakBefore(false), IsUnterminatedLiteral(false),
109 BlockKind(BK_Unknown
), Type(TT_Unknown
), SpacesRequiredBefore(0),
110 CanBreakBefore(false), ClosesTemplateDeclaration(false),
111 ParameterCount(0), BlockParameterCount(0),
112 PackingKind(PPK_Inconclusive
), TotalLength(0), UnbreakableTailLength(0),
113 BindingStrength(0), NestingLevel(0), SplitPenalty(0),
114 LongestObjCSelectorName(0), FakeRParens(0),
115 StartsBinaryExpression(false), EndsBinaryExpression(false),
116 OperatorIndex(0), LastOperator(false),
117 PartOfMultiVariableDeclStmt(false), IsForEachMacro(false),
118 MatchingParen(nullptr), Previous(nullptr), Next(nullptr),
119 Decision(FD_Unformatted
), Finalized(false) {}
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
;
130 /// \brief Whether there is at least one unescaped newline before the \c
132 bool HasUnescapedNewline
;
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
;
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
;
146 /// \brief Contains the width in columns of the last line of a multi-line
148 unsigned LastLineColumnWidth
;
150 /// \brief Whether the token text contains newlines (escaped or not).
153 /// \brief Indicates that this is the first token.
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
;
162 /// \brief Returns actual token start location without leading escaped
163 /// newlines and whitespace.
165 /// This can be different to Tok.getLocation(), which includes leading escaped
167 SourceLocation
getStartOfNonWhitespace() const {
168 return WhitespaceRange
.getEnd();
171 /// \brief The raw text of the token.
173 /// Contains the raw token text without leading whitespace and without leading
174 /// escaped newlines.
177 /// \brief Set to \c true if this token is an unterminated literal.
178 bool IsUnterminatedLiteral
;
180 /// \brief Contains the kind of block if this token is a brace.
181 BraceBlockKind BlockKind
;
185 /// \brief The number of spaces that should be inserted before this token.
186 unsigned SpacesRequiredBefore
;
188 /// \brief \c true if it is allowed to break before this token.
191 bool ClosesTemplateDeclaration
;
193 /// \brief Number of parameters, if this is "(", "[" or "<".
195 /// This is initialized to 1 as we don't need to distinguish functions with
196 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
197 /// the number of commas.
198 unsigned ParameterCount
;
200 /// \brief Number of parameters that are nested blocks,
201 /// if this is "(", "[" or "<".
202 unsigned BlockParameterCount
;
204 /// \brief A token can have a special role that can carry extra information
205 /// about the token's formatting.
206 std::unique_ptr
<TokenRole
> Role
;
208 /// \brief If this is an opening parenthesis, how are the parameters packed?
209 ParameterPackingKind PackingKind
;
211 /// \brief The total length of the unwrapped line up to and including this
213 unsigned TotalLength
;
215 /// \brief The original 0-based column of this token, including expanded tabs.
216 /// The configured TabWidth is used as tab width.
217 unsigned OriginalColumn
;
219 /// \brief The length of following tokens until the next natural split point,
220 /// or the next token that can be broken.
221 unsigned UnbreakableTailLength
;
223 // FIXME: Come up with a 'cleaner' concept.
224 /// \brief The binding strength of a token. This is a combined value of
225 /// operator precedence, parenthesis nesting, etc.
226 unsigned BindingStrength
;
228 /// \brief The nesting level of this token, i.e. the number of surrounding (),
230 unsigned NestingLevel
;
232 /// \brief Penalty for inserting a line break before this token.
233 unsigned SplitPenalty
;
235 /// \brief If this is the first ObjC selector name in an ObjC method
236 /// definition or call, this contains the length of the longest name.
238 /// This being set to 0 means that the selectors should not be colon-aligned,
239 /// e.g. because several of them are block-type.
240 unsigned LongestObjCSelectorName
;
242 /// \brief Stores the number of required fake parentheses and the
243 /// corresponding operator precedence.
245 /// If multiple fake parentheses start at a token, this vector stores them in
246 /// reverse order, i.e. inner fake parenthesis first.
247 SmallVector
<prec::Level
, 4> FakeLParens
;
248 /// \brief Insert this many fake ) after this token for correct indentation.
249 unsigned FakeRParens
;
251 /// \brief \c true if this token starts a binary expression, i.e. has at least
252 /// one fake l_paren with a precedence greater than prec::Unknown.
253 bool StartsBinaryExpression
;
254 /// \brief \c true if this token ends a binary expression.
255 bool EndsBinaryExpression
;
257 /// \brief Is this is an operator (or "."/"->") in a sequence of operators
258 /// with the same precedence, contains the 0-based operator index.
259 unsigned OperatorIndex
;
261 /// \brief Is this the last operator (or "."/"->") in a sequence of operators
262 /// with the same precedence?
265 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
267 /// Only set if \c Type == \c TT_StartOfName.
268 bool PartOfMultiVariableDeclStmt
;
270 /// \brief Is this a foreach macro?
273 bool is(tok::TokenKind Kind
) const { return Tok
.is(Kind
); }
274 bool is(TokenType TT
) const { return Type
== TT
; }
275 bool is(const IdentifierInfo
*II
) const {
276 return II
&& II
== Tok
.getIdentifierInfo();
278 template <typename A
, typename B
> bool isOneOf(A K1
, B K2
) const {
279 return is(K1
) || is(K2
);
281 template <typename A
, typename B
, typename C
>
282 bool isOneOf(A K1
, B K2
, C K3
) const {
283 return is(K1
) || is(K2
) || is(K3
);
285 template <typename A
, typename B
, typename C
, typename D
>
286 bool isOneOf(A K1
, B K2
, C K3
, D K4
) const {
287 return is(K1
) || is(K2
) || is(K3
) || is(K4
);
289 template <typename A
, typename B
, typename C
, typename D
, typename E
>
290 bool isOneOf(A K1
, B K2
, C K3
, D K4
, E K5
) const {
291 return is(K1
) || is(K2
) || is(K3
) || is(K4
) || is(K5
);
293 template <typename T
>
294 bool isOneOf(T K1
, T K2
, T K3
, T K4
, T K5
, T K6
, T K7
= tok::NUM_TOKENS
,
295 T K8
= tok::NUM_TOKENS
, T K9
= tok::NUM_TOKENS
,
296 T K10
= tok::NUM_TOKENS
, T K11
= tok::NUM_TOKENS
,
297 T K12
= tok::NUM_TOKENS
) const {
298 return is(K1
) || is(K2
) || is(K3
) || is(K4
) || is(K5
) || is(K6
) || is(K7
) ||
299 is(K8
) || is(K9
) || is(K10
) || is(K11
) || is(K12
);
302 template <typename T
> bool isNot(T Kind
) const { return !is(Kind
); }
304 bool isStringLiteral() const { return tok::isStringLiteral(Tok
.getKind()); }
306 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind
) const {
307 return Tok
.isObjCAtKeyword(Kind
);
310 bool isAccessSpecifier(bool ColonRequired
= true) const {
311 return isOneOf(tok::kw_public
, tok::kw_protected
, tok::kw_private
) &&
312 (!ColonRequired
|| (Next
&& Next
->is(tok::colon
)));
315 /// \brief Determine whether the token is a simple-type-specifier.
316 bool isSimpleTypeSpecifier() const;
318 bool isObjCAccessSpecifier() const {
319 return is(tok::at
) && Next
&& (Next
->isObjCAtKeyword(tok::objc_public
) ||
320 Next
->isObjCAtKeyword(tok::objc_protected
) ||
321 Next
->isObjCAtKeyword(tok::objc_package
) ||
322 Next
->isObjCAtKeyword(tok::objc_private
));
325 /// \brief Returns whether \p Tok is ([{ or a template opening <.
326 bool opensScope() const {
327 return isOneOf(tok::l_paren
, tok::l_brace
, tok::l_square
,
330 /// \brief Returns whether \p Tok is )]} or a template closing >.
331 bool closesScope() const {
332 return isOneOf(tok::r_paren
, tok::r_brace
, tok::r_square
,
336 /// \brief Returns \c true if this is a "." or "->" accessing a member.
337 bool isMemberAccess() const {
338 return isOneOf(tok::arrow
, tok::period
, tok::arrowstar
) &&
339 !isOneOf(TT_DesignatedInitializerPeriod
, TT_TrailingReturnArrow
);
342 bool isUnaryOperator() const {
343 switch (Tok
.getKind()) {
347 case tok::minusminus
:
351 case tok::kw_alignof
:
358 bool isBinaryOperator() const {
359 // Comma is a binary operator, but does not behave as such wrt. formatting.
360 return getPrecedence() > prec::Comma
;
363 bool isTrailingComment() const {
364 return is(tok::comment
) &&
365 (is(TT_LineComment
) || !Next
|| Next
->NewlinesBefore
> 0);
368 /// \brief Returns \c true if this is a keyword that can be used
369 /// like a function call (e.g. sizeof, typeid, ...).
370 bool isFunctionLikeKeyword() const {
371 switch (Tok
.getKind()) {
376 case tok::kw_alignof
:
377 case tok::kw_alignas
:
378 case tok::kw_decltype
:
379 case tok::kw_noexcept
:
380 case tok::kw_static_assert
:
381 case tok::kw___attribute
:
388 prec::Level
getPrecedence() const {
389 return getBinOpPrecedence(Tok
.getKind(), true, true);
392 /// \brief Returns the previous token ignoring comments.
393 FormatToken
*getPreviousNonComment() const {
394 FormatToken
*Tok
= Previous
;
395 while (Tok
&& Tok
->is(tok::comment
))
400 /// \brief Returns the next token ignoring comments.
401 const FormatToken
*getNextNonComment() const {
402 const FormatToken
*Tok
= Next
;
403 while (Tok
&& Tok
->is(tok::comment
))
408 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
409 /// list that should be indented with a block indent.
410 bool opensBlockTypeList(const FormatStyle
&Style
) const {
411 return is(TT_ArrayInitializerLSquare
) ||
413 (BlockKind
== BK_Block
|| is(TT_DictLiteral
) ||
414 (!Style
.Cpp11BracedListStyle
&& NestingLevel
== 0)));
417 /// \brief Same as opensBlockTypeList, but for the closing token.
418 bool closesBlockTypeList(const FormatStyle
&Style
) const {
419 return MatchingParen
&& MatchingParen
->opensBlockTypeList(Style
);
422 FormatToken
*MatchingParen
;
424 FormatToken
*Previous
;
427 SmallVector
<AnnotatedLine
*, 1> Children
;
429 /// \brief Stores the formatting decision for the token once it was made.
430 FormatDecision Decision
;
432 /// \brief If \c true, this token has been fully formatted (indented and
433 /// potentially re-formatted inside), and we do not allow further formatting
439 FormatToken(const FormatToken
&) LLVM_DELETED_FUNCTION
;
440 void operator=(const FormatToken
&) LLVM_DELETED_FUNCTION
;
443 class ContinuationIndenter
;
448 TokenRole(const FormatStyle
&Style
) : Style(Style
) {}
449 virtual ~TokenRole();
451 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
452 /// this function precomputes required information for formatting.
453 virtual void precomputeFormattingInfos(const FormatToken
*Token
);
455 /// \brief Apply the special formatting that the given role demands.
457 /// Assumes that the token having this role is already formatted.
459 /// Continues formatting from \p State leaving indentation to \p Indenter and
460 /// returns the total penalty that this formatting incurs.
461 virtual unsigned formatFromToken(LineState
&State
,
462 ContinuationIndenter
*Indenter
,
467 /// \brief Same as \c formatFromToken, but assumes that the first token has
468 /// already been set thereby deciding on the first line break.
469 virtual unsigned formatAfterToken(LineState
&State
,
470 ContinuationIndenter
*Indenter
,
475 /// \brief Notifies the \c Role that a comma was found.
476 virtual void CommaFound(const FormatToken
*Token
) {}
479 const FormatStyle
&Style
;
482 class CommaSeparatedList
: public TokenRole
{
484 CommaSeparatedList(const FormatStyle
&Style
)
485 : TokenRole(Style
), HasNestedBracedList(false) {}
487 void precomputeFormattingInfos(const FormatToken
*Token
) override
;
489 unsigned formatAfterToken(LineState
&State
, ContinuationIndenter
*Indenter
,
490 bool DryRun
) override
;
492 unsigned formatFromToken(LineState
&State
, ContinuationIndenter
*Indenter
,
493 bool DryRun
) override
;
495 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
496 void CommaFound(const FormatToken
*Token
) override
{
497 Commas
.push_back(Token
);
501 /// \brief A struct that holds information on how to format a given list with
502 /// a specific number of columns.
503 struct ColumnFormat
{
504 /// \brief The number of columns to use.
507 /// \brief The total width in characters.
510 /// \brief The number of lines required for this format.
513 /// \brief The size of each column in characters.
514 SmallVector
<unsigned, 8> ColumnSizes
;
517 /// \brief Calculate which \c ColumnFormat fits best into
518 /// \p RemainingCharacters.
519 const ColumnFormat
*getColumnFormat(unsigned RemainingCharacters
) const;
521 /// \brief The ordered \c FormatTokens making up the commas of this list.
522 SmallVector
<const FormatToken
*, 8> Commas
;
524 /// \brief The length of each of the list's items in characters including the
526 SmallVector
<unsigned, 8> ItemLengths
;
528 /// \brief Precomputed formats that can be used for this list.
529 SmallVector
<ColumnFormat
, 4> Formats
;
531 bool HasNestedBracedList
;
534 /// \brief Encapsulates keywords that are context sensitive or for languages not
535 /// properly supported by Clang's lexer.
536 struct AdditionalKeywords
{
537 AdditionalKeywords(IdentifierTable
&IdentTable
) {
538 kw_in
= &IdentTable
.get("in");
539 kw_CF_ENUM
= &IdentTable
.get("CF_ENUM");
540 kw_CF_OPTIONS
= &IdentTable
.get("CF_OPTIONS");
541 kw_NS_ENUM
= &IdentTable
.get("NS_ENUM");
542 kw_NS_OPTIONS
= &IdentTable
.get("NS_OPTIONS");
544 kw_finally
= &IdentTable
.get("finally");
545 kw_function
= &IdentTable
.get("function");
546 kw_var
= &IdentTable
.get("var");
548 kw_abstract
= &IdentTable
.get("abstract");
549 kw_extends
= &IdentTable
.get("extends");
550 kw_final
= &IdentTable
.get("final");
551 kw_implements
= &IdentTable
.get("implements");
552 kw_instanceof
= &IdentTable
.get("instanceof");
553 kw_interface
= &IdentTable
.get("interface");
554 kw_native
= &IdentTable
.get("native");
555 kw_package
= &IdentTable
.get("package");
556 kw_synchronized
= &IdentTable
.get("synchronized");
557 kw_throws
= &IdentTable
.get("throws");
559 kw_option
= &IdentTable
.get("option");
560 kw_optional
= &IdentTable
.get("optional");
561 kw_repeated
= &IdentTable
.get("repeated");
562 kw_required
= &IdentTable
.get("required");
563 kw_returns
= &IdentTable
.get("returns");
566 // ObjC context sensitive keywords.
567 IdentifierInfo
*kw_in
;
568 IdentifierInfo
*kw_CF_ENUM
;
569 IdentifierInfo
*kw_CF_OPTIONS
;
570 IdentifierInfo
*kw_NS_ENUM
;
571 IdentifierInfo
*kw_NS_OPTIONS
;
573 // JavaScript keywords.
574 IdentifierInfo
*kw_finally
;
575 IdentifierInfo
*kw_function
;
576 IdentifierInfo
*kw_var
;
579 IdentifierInfo
*kw_abstract
;
580 IdentifierInfo
*kw_extends
;
581 IdentifierInfo
*kw_final
;
582 IdentifierInfo
*kw_implements
;
583 IdentifierInfo
*kw_instanceof
;
584 IdentifierInfo
*kw_interface
;
585 IdentifierInfo
*kw_native
;
586 IdentifierInfo
*kw_package
;
587 IdentifierInfo
*kw_synchronized
;
588 IdentifierInfo
*kw_throws
;
591 IdentifierInfo
*kw_option
;
592 IdentifierInfo
*kw_optional
;
593 IdentifierInfo
*kw_repeated
;
594 IdentifierInfo
*kw_required
;
595 IdentifierInfo
*kw_returns
;
598 } // namespace format