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,
56 TT_JsTypeOptionalQuestion,
59 TT_LeadingJavaAnnotation,
66 TT_ObjCMethodSpecifier,
69 TT_OverloadedOperator,
70 TT_OverloadedOperatorLParen,
71 TT_PointerOrReference,
72 TT_PureVirtualSpecifier,
73 TT_RangeBasedForLoopColon,
80 TT_TrailingAnnotation,
81 TT_TrailingReturnArrow,
82 TT_TrailingUnaryOperator,
87 // Represents what type of block a set of braces open.
94 // The packing kind of a function's parameters.
95 enum ParameterPackingKind {
101 enum FormatDecision {
110 /// \brief A wrapper around a \c Token storing information about the
111 /// whitespace characters preceding it.
115 /// \brief The \c Token.
118 /// \brief The number of newlines immediately before the \c Token.
120 /// This can be used to determine what the user wrote in the original code
121 /// and thereby e.g. leave an empty line between two function definitions.
122 unsigned NewlinesBefore = 0;
124 /// \brief Whether there is at least one unescaped newline before the \c
126 bool HasUnescapedNewline = false;
128 /// \brief The range of the whitespace immediately preceding the \c Token.
129 SourceRange WhitespaceRange;
131 /// \brief The offset just past the last '\n' in this token's leading
132 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
133 unsigned LastNewlineOffset = 0;
135 /// \brief The width of the non-whitespace parts of the token (or its first
136 /// line for multi-line tokens) in columns.
137 /// We need this to correctly measure number of columns a token spans.
138 unsigned ColumnWidth = 0;
140 /// \brief Contains the width in columns of the last line of a multi-line
142 unsigned LastLineColumnWidth = 0;
144 /// \brief Whether the token text contains newlines (escaped or not).
145 bool IsMultiline = false;
147 /// \brief Indicates that this is the first token.
148 bool IsFirst = false;
150 /// \brief Whether there must be a line break before this token.
152 /// This happens for example when a preprocessor directive ended directly
153 /// before the token.
154 bool MustBreakBefore = false;
156 /// \brief The raw text of the token.
158 /// Contains the raw token text without leading whitespace and without leading
159 /// escaped newlines.
162 /// \brief Set to \c true if this token is an unterminated literal.
163 bool IsUnterminatedLiteral = 0;
165 /// \brief Contains the kind of block if this token is a brace.
166 BraceBlockKind BlockKind = BK_Unknown;
168 TokenType Type = TT_Unknown;
170 /// \brief The number of spaces that should be inserted before this token.
171 unsigned SpacesRequiredBefore = 0;
173 /// \brief \c true if it is allowed to break before this token.
174 bool CanBreakBefore = false;
176 /// \brief \c true if this is the ">" of "template<..>".
177 bool ClosesTemplateDeclaration = false;
179 /// \brief Number of parameters, if this is "(", "[" or "<".
181 /// This is initialized to 1 as we don't need to distinguish functions with
182 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
183 /// the number of commas.
184 unsigned ParameterCount = 0;
186 /// \brief Number of parameters that are nested blocks,
187 /// if this is "(", "[" or "<".
188 unsigned BlockParameterCount = 0;
190 /// \brief If this is a bracket ("<", "(", "[" or "{"), contains the kind of
191 /// the surrounding bracket.
192 tok::TokenKind ParentBracket = tok::unknown;
194 /// \brief A token can have a special role that can carry extra information
195 /// about the token's formatting.
196 std::unique_ptr<TokenRole> Role;
198 /// \brief If this is an opening parenthesis, how are the parameters packed?
199 ParameterPackingKind PackingKind = PPK_Inconclusive;
201 /// \brief The total length of the unwrapped line up to and including this
203 unsigned TotalLength = 0;
205 /// \brief The original 0-based column of this token, including expanded tabs.
206 /// The configured TabWidth is used as tab width.
207 unsigned OriginalColumn = 0;
209 /// \brief The length of following tokens until the next natural split point,
210 /// or the next token that can be broken.
211 unsigned UnbreakableTailLength = 0;
213 // FIXME: Come up with a 'cleaner' concept.
214 /// \brief The binding strength of a token. This is a combined value of
215 /// operator precedence, parenthesis nesting, etc.
216 unsigned BindingStrength = 0;
218 /// \brief The nesting level of this token, i.e. the number of surrounding (),
220 unsigned NestingLevel = 0;
222 /// \brief Penalty for inserting a line break before this token.
223 unsigned SplitPenalty = 0;
225 /// \brief If this is the first ObjC selector name in an ObjC method
226 /// definition or call, this contains the length of the longest name.
228 /// This being set to 0 means that the selectors should not be colon-aligned,
229 /// e.g. because several of them are block-type.
230 unsigned LongestObjCSelectorName = 0;
232 /// \brief Stores the number of required fake parentheses and the
233 /// corresponding operator precedence.
235 /// If multiple fake parentheses start at a token, this vector stores them in
236 /// reverse order, i.e. inner fake parenthesis first.
237 SmallVector<prec::Level, 4> FakeLParens;
238 /// \brief Insert this many fake ) after this token for correct indentation.
239 unsigned FakeRParens = 0;
241 /// \brief \c true if this token starts a binary expression, i.e. has at least
242 /// one fake l_paren with a precedence greater than prec::Unknown.
243 bool StartsBinaryExpression = false;
244 /// \brief \c true if this token ends a binary expression.
245 bool EndsBinaryExpression = false;
247 /// \brief Is this is an operator (or "."/"->") in a sequence of operators
248 /// with the same precedence, contains the 0-based operator index.
249 unsigned OperatorIndex = 0;
251 /// \brief Is this the last operator (or "."/"->") in a sequence of operators
252 /// with the same precedence?
253 bool LastOperator = false;
255 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
257 /// Only set if \c Type == \c TT_StartOfName.
258 bool PartOfMultiVariableDeclStmt = false;
260 /// \brief If this is a bracket, this points to the matching one.
261 FormatToken *MatchingParen = nullptr;
263 /// \brief The previous token in the unwrapped line.
264 FormatToken *Previous = nullptr;
266 /// \brief The next token in the unwrapped line.
267 FormatToken *Next = nullptr;
269 /// \brief If this token starts a block, this contains all the unwrapped lines
271 SmallVector<AnnotatedLine *, 1> Children;
273 /// \brief Stores the formatting decision for the token once it was made.
274 FormatDecision Decision = FD_Unformatted;
276 /// \brief If \c true, this token has been fully formatted (indented and
277 /// potentially re-formatted inside), and we do not allow further formatting
279 bool Finalized = false;
281 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
282 bool is(TokenType TT) const { return Type == TT; }
283 bool is(const IdentifierInfo *II) const {
284 return II && II == Tok.getIdentifierInfo();
286 template <typename A, typename B> bool isOneOf(A K1, B K2) const {
287 return is(K1) || is(K2);
289 template <typename A, typename B, typename... Ts>
290 bool isOneOf(A K1, B K2, Ts... Ks) const {
291 return is(K1) || isOneOf(K2, Ks...);
293 template <typename T> bool isNot(T Kind) const { return !is(Kind); }
295 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); }
297 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
298 return Tok.isObjCAtKeyword(Kind);
301 bool isAccessSpecifier(bool ColonRequired = true) const {
302 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
303 (!ColonRequired || (Next && Next->is(tok::colon)));
306 /// \brief Determine whether the token is a simple-type-specifier.
307 bool isSimpleTypeSpecifier() const;
309 bool isObjCAccessSpecifier() const {
310 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
311 Next->isObjCAtKeyword(tok::objc_protected) ||
312 Next->isObjCAtKeyword(tok::objc_package) ||
313 Next->isObjCAtKeyword(tok::objc_private));
316 /// \brief Returns whether \p Tok is ([{ or a template opening <.
317 bool opensScope() const {
318 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square,
321 /// \brief Returns whether \p Tok is )]} or a template closing >.
322 bool closesScope() const {
323 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square,
327 /// \brief Returns \c true if this is a "." or "->" accessing a member.
328 bool isMemberAccess() const {
329 return isOneOf(tok::arrow, tok::period, tok::arrowstar) &&
330 !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow,
334 bool isUnaryOperator() const {
335 switch (Tok.getKind()) {
339 case tok::minusminus:
343 case tok::kw_alignof:
350 bool isBinaryOperator() const {
351 // Comma is a binary operator, but does not behave as such wrt. formatting.
352 return getPrecedence() > prec::Comma;
355 bool isTrailingComment() const {
356 return is(tok::comment) &&
357 (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0);
360 /// \brief Returns \c true if this is a keyword that can be used
361 /// like a function call (e.g. sizeof, typeid, ...).
362 bool isFunctionLikeKeyword() const {
363 switch (Tok.getKind()) {
368 case tok::kw_alignof:
369 case tok::kw_alignas:
370 case tok::kw_decltype:
371 case tok::kw_noexcept:
372 case tok::kw_static_assert:
373 case tok::kw___attribute:
380 /// \brief Returns actual token start location without leading escaped
381 /// newlines and whitespace.
383 /// This can be different to Tok.getLocation(), which includes leading escaped
385 SourceLocation getStartOfNonWhitespace() const {
386 return WhitespaceRange.getEnd();
389 prec::Level getPrecedence() const {
390 return getBinOpPrecedence(Tok.getKind(), true, true);
393 /// \brief Returns the previous token ignoring comments.
394 FormatToken *getPreviousNonComment() const {
395 FormatToken *Tok = Previous;
396 while (Tok && Tok->is(tok::comment))
401 /// \brief Returns the next token ignoring comments.
402 const FormatToken *getNextNonComment() const {
403 const FormatToken *Tok = Next;
404 while (Tok && Tok->is(tok::comment))
409 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
410 /// list that should be indented with a block indent.
411 bool opensBlockTypeList(const FormatStyle &Style) const {
412 return is(TT_ArrayInitializerLSquare) ||
414 (BlockKind == BK_Block || is(TT_DictLiteral) ||
415 (!Style.Cpp11BracedListStyle && NestingLevel == 0)));
418 /// \brief Same as opensBlockTypeList, but for the closing token.
419 bool closesBlockTypeList(const FormatStyle &Style) const {
420 return MatchingParen && MatchingParen->opensBlockTypeList(Style);
425 FormatToken(const FormatToken &) = delete;
426 void operator=(const FormatToken &) = delete;
429 class ContinuationIndenter;
434 TokenRole(const FormatStyle &Style) : Style(Style) {}
435 virtual ~TokenRole();
437 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
438 /// this function precomputes required information for formatting.
439 virtual void precomputeFormattingInfos(const FormatToken *Token);
441 /// \brief Apply the special formatting that the given role demands.
443 /// Assumes that the token having this role is already formatted.
445 /// Continues formatting from \p State leaving indentation to \p Indenter and
446 /// returns the total penalty that this formatting incurs.
447 virtual unsigned formatFromToken(LineState &State,
448 ContinuationIndenter *Indenter,
453 /// \brief Same as \c formatFromToken, but assumes that the first token has
454 /// already been set thereby deciding on the first line break.
455 virtual unsigned formatAfterToken(LineState &State,
456 ContinuationIndenter *Indenter,
461 /// \brief Notifies the \c Role that a comma was found.
462 virtual void CommaFound(const FormatToken *Token) {}
465 const FormatStyle &Style;
468 class CommaSeparatedList : public TokenRole {
470 CommaSeparatedList(const FormatStyle &Style)
471 : TokenRole(Style), HasNestedBracedList(false) {}
473 void precomputeFormattingInfos(const FormatToken *Token) override;
475 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter,
476 bool DryRun) override;
478 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter,
479 bool DryRun) override;
481 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
482 void CommaFound(const FormatToken *Token) override {
483 Commas.push_back(Token);
487 /// \brief A struct that holds information on how to format a given list with
488 /// a specific number of columns.
489 struct ColumnFormat {
490 /// \brief The number of columns to use.
493 /// \brief The total width in characters.
496 /// \brief The number of lines required for this format.
499 /// \brief The size of each column in characters.
500 SmallVector<unsigned, 8> ColumnSizes;
503 /// \brief Calculate which \c ColumnFormat fits best into
504 /// \p RemainingCharacters.
505 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
507 /// \brief The ordered \c FormatTokens making up the commas of this list.
508 SmallVector<const FormatToken *, 8> Commas;
510 /// \brief The length of each of the list's items in characters including the
512 SmallVector<unsigned, 8> ItemLengths;
514 /// \brief Precomputed formats that can be used for this list.
515 SmallVector<ColumnFormat, 4> Formats;
517 bool HasNestedBracedList;
520 /// \brief Encapsulates keywords that are context sensitive or for languages not
521 /// properly supported by Clang's lexer.
522 struct AdditionalKeywords {
523 AdditionalKeywords(IdentifierTable &IdentTable) {
524 kw_in = &IdentTable.get("in");
525 kw_CF_ENUM = &IdentTable.get("CF_ENUM");
526 kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS");
527 kw_NS_ENUM = &IdentTable.get("NS_ENUM");
528 kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS");
530 kw_finally = &IdentTable.get("finally");
531 kw_function = &IdentTable.get("function");
532 kw_import = &IdentTable.get("import");
533 kw_var = &IdentTable.get("var");
535 kw_abstract = &IdentTable.get("abstract");
536 kw_extends = &IdentTable.get("extends");
537 kw_final = &IdentTable.get("final");
538 kw_implements = &IdentTable.get("implements");
539 kw_instanceof = &IdentTable.get("instanceof");
540 kw_interface = &IdentTable.get("interface");
541 kw_native = &IdentTable.get("native");
542 kw_package = &IdentTable.get("package");
543 kw_synchronized = &IdentTable.get("synchronized");
544 kw_throws = &IdentTable.get("throws");
545 kw___except = &IdentTable.get("__except");
547 kw_mark = &IdentTable.get("mark");
549 kw_option = &IdentTable.get("option");
550 kw_optional = &IdentTable.get("optional");
551 kw_repeated = &IdentTable.get("repeated");
552 kw_required = &IdentTable.get("required");
553 kw_returns = &IdentTable.get("returns");
555 kw_signals = &IdentTable.get("signals");
556 kw_slots = &IdentTable.get("slots");
557 kw_qslots = &IdentTable.get("Q_SLOTS");
560 // Context sensitive keywords.
561 IdentifierInfo *kw_in;
562 IdentifierInfo *kw_CF_ENUM;
563 IdentifierInfo *kw_CF_OPTIONS;
564 IdentifierInfo *kw_NS_ENUM;
565 IdentifierInfo *kw_NS_OPTIONS;
566 IdentifierInfo *kw___except;
568 // JavaScript keywords.
569 IdentifierInfo *kw_finally;
570 IdentifierInfo *kw_function;
571 IdentifierInfo *kw_import;
572 IdentifierInfo *kw_var;
575 IdentifierInfo *kw_abstract;
576 IdentifierInfo *kw_extends;
577 IdentifierInfo *kw_final;
578 IdentifierInfo *kw_implements;
579 IdentifierInfo *kw_instanceof;
580 IdentifierInfo *kw_interface;
581 IdentifierInfo *kw_native;
582 IdentifierInfo *kw_package;
583 IdentifierInfo *kw_synchronized;
584 IdentifierInfo *kw_throws;
587 IdentifierInfo *kw_mark;
590 IdentifierInfo *kw_option;
591 IdentifierInfo *kw_optional;
592 IdentifierInfo *kw_repeated;
593 IdentifierInfo *kw_required;
594 IdentifierInfo *kw_returns;
597 IdentifierInfo *kw_signals;
598 IdentifierInfo *kw_slots;
599 IdentifierInfo *kw_qslots;
602 } // namespace format