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_FORMAT_FORMAT_TOKEN_H
17 #define LLVM_CLANG_FORMAT_FORMAT_TOKEN_H
19 #include "clang/Basic/OperatorPrecedence.h"
20 #include "clang/Format/Format.h"
21 #include "clang/Lex/Lexer.h"
22 #include "llvm/ADT/OwningPtr.h"
28 TT_ArrayInitializerLSquare,
29 TT_ArraySubscriptLSquare,
35 TT_CtorInitializerColon,
36 TT_CtorInitializerComma,
37 TT_DesignatedInitializerPeriod,
39 TT_ImplicitStringLiteral,
42 TT_FunctionTypeLParen,
49 TT_ObjCMethodSpecifier,
52 TT_OverloadedOperator,
53 TT_OverloadedOperatorLParen,
54 TT_PointerOrReference,
55 TT_PureVirtualSpecifier,
56 TT_RangeBasedForLoopColon,
60 TT_TrailingReturnArrow,
61 TT_TrailingUnaryOperator,
66 // Represents what type of block a set of braces open.
73 // The packing kind of a function's parameters.
74 enum ParameterPackingKind {
89 /// \brief A wrapper around a \c Token storing information about the
90 /// whitespace characters preceeding it.
93 : NewlinesBefore(0), HasUnescapedNewline(false), LastNewlineOffset(0),
94 ColumnWidth(0), LastLineColumnWidth(0), IsMultiline(false),
95 IsFirst(false), MustBreakBefore(false), IsUnterminatedLiteral(false),
96 BlockKind(BK_Unknown), Type(TT_Unknown), SpacesRequiredBefore(0),
97 CanBreakBefore(false), ClosesTemplateDeclaration(false),
98 ParameterCount(0), PackingKind(PPK_Inconclusive), TotalLength(0),
99 UnbreakableTailLength(0), BindingStrength(0), SplitPenalty(0),
100 LongestObjCSelectorName(0), FakeRParens(0),
101 StartsBinaryExpression(false), EndsBinaryExpression(false),
102 LastInChainOfCalls(false), PartOfMultiVariableDeclStmt(false),
103 MatchingParen(NULL), Previous(NULL), Next(NULL),
104 Decision(FD_Unformatted), Finalized(false) {}
106 /// \brief The \c Token.
109 /// \brief The number of newlines immediately before the \c Token.
111 /// This can be used to determine what the user wrote in the original code
112 /// and thereby e.g. leave an empty line between two function definitions.
113 unsigned NewlinesBefore;
115 /// \brief Whether there is at least one unescaped newline before the \c
117 bool HasUnescapedNewline;
119 /// \brief The range of the whitespace immediately preceeding the \c Token.
120 SourceRange WhitespaceRange;
122 /// \brief The offset just past the last '\n' in this token's leading
123 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'.
124 unsigned LastNewlineOffset;
126 /// \brief The width of the non-whitespace parts of the token (or its first
127 /// line for multi-line tokens) in columns.
128 /// We need this to correctly measure number of columns a token spans.
129 unsigned ColumnWidth;
131 /// \brief Contains the width in columns of the last line of a multi-line
133 unsigned LastLineColumnWidth;
135 /// \brief Whether the token text contains newlines (escaped or not).
138 /// \brief Indicates that this is the first token.
141 /// \brief Whether there must be a line break before this token.
143 /// This happens for example when a preprocessor directive ended directly
144 /// before the token.
145 bool MustBreakBefore;
147 /// \brief Returns actual token start location without leading escaped
148 /// newlines and whitespace.
150 /// This can be different to Tok.getLocation(), which includes leading escaped
152 SourceLocation getStartOfNonWhitespace() const {
153 return WhitespaceRange.getEnd();
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;
165 /// \brief Contains the kind of block if this token is a brace.
166 BraceBlockKind BlockKind;
170 /// \brief The number of spaces that should be inserted before this token.
171 unsigned SpacesRequiredBefore;
173 /// \brief \c true if it is allowed to break before this token.
176 bool ClosesTemplateDeclaration;
178 /// \brief Number of parameters, if this is "(", "[" or "<".
180 /// This is initialized to 1 as we don't need to distinguish functions with
181 /// 0 parameters from functions with 1 parameter. Thus, we can simply count
182 /// the number of commas.
183 unsigned ParameterCount;
185 /// \brief A token can have a special role that can carry extra information
186 /// about the token's formatting.
187 llvm::OwningPtr<TokenRole> Role;
189 /// \brief If this is an opening parenthesis, how are the parameters packed?
190 ParameterPackingKind PackingKind;
192 /// \brief The total length of the unwrapped line up to and including this
194 unsigned TotalLength;
196 /// \brief The original 0-based column of this token, including expanded tabs.
197 /// The configured TabWidth is used as tab width.
198 unsigned OriginalColumn;
200 /// \brief The length of following tokens until the next natural split point,
201 /// or the next token that can be broken.
202 unsigned UnbreakableTailLength;
204 // FIXME: Come up with a 'cleaner' concept.
205 /// \brief The binding strength of a token. This is a combined value of
206 /// operator precedence, parenthesis nesting, etc.
207 unsigned BindingStrength;
209 /// \brief Penalty for inserting a line break before this token.
210 unsigned SplitPenalty;
212 /// \brief If this is the first ObjC selector name in an ObjC method
213 /// definition or call, this contains the length of the longest name.
214 unsigned LongestObjCSelectorName;
216 /// \brief Stores the number of required fake parentheses and the
217 /// corresponding operator precedence.
219 /// If multiple fake parentheses start at a token, this vector stores them in
220 /// reverse order, i.e. inner fake parenthesis first.
221 SmallVector<prec::Level, 4> FakeLParens;
222 /// \brief Insert this many fake ) after this token for correct indentation.
223 unsigned FakeRParens;
225 /// \brief \c true if this token starts a binary expression, i.e. has at least
226 /// one fake l_paren with a precedence greater than prec::Unknown.
227 bool StartsBinaryExpression;
228 /// \brief \c true if this token ends a binary expression.
229 bool EndsBinaryExpression;
231 /// \brief Is this the last "." or "->" in a builder-type call?
232 bool LastInChainOfCalls;
234 /// \brief Is this token part of a \c DeclStmt defining multiple variables?
236 /// Only set if \c Type == \c TT_StartOfName.
237 bool PartOfMultiVariableDeclStmt;
239 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); }
241 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const {
242 return is(K1) || is(K2);
245 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const {
246 return is(K1) || is(K2) || is(K3);
249 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3,
250 tok::TokenKind K4, tok::TokenKind K5 = tok::NUM_TOKENS,
251 tok::TokenKind K6 = tok::NUM_TOKENS,
252 tok::TokenKind K7 = tok::NUM_TOKENS,
253 tok::TokenKind K8 = tok::NUM_TOKENS,
254 tok::TokenKind K9 = tok::NUM_TOKENS,
255 tok::TokenKind K10 = tok::NUM_TOKENS,
256 tok::TokenKind K11 = tok::NUM_TOKENS,
257 tok::TokenKind K12 = tok::NUM_TOKENS) const {
258 return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) ||
259 is(K8) || is(K9) || is(K10) || is(K11) || is(K12);
262 bool isNot(tok::TokenKind Kind) const { return Tok.isNot(Kind); }
264 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const {
265 return Tok.isObjCAtKeyword(Kind);
268 bool isAccessSpecifier(bool ColonRequired = true) const {
269 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) &&
270 (!ColonRequired || (Next && Next->is(tok::colon)));
273 bool isObjCAccessSpecifier() const {
274 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) ||
275 Next->isObjCAtKeyword(tok::objc_protected) ||
276 Next->isObjCAtKeyword(tok::objc_package) ||
277 Next->isObjCAtKeyword(tok::objc_private));
280 /// \brief Returns whether \p Tok is ([{ or a template opening <.
281 bool opensScope() const {
282 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square) ||
283 Type == TT_TemplateOpener;
285 /// \brief Returns whether \p Tok is )]} or a template closing >.
286 bool closesScope() const {
287 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square) ||
288 Type == TT_TemplateCloser;
291 /// \brief Returns \c true if this is a "." or "->" accessing a member.
292 bool isMemberAccess() const {
293 return isOneOf(tok::arrow, tok::period) &&
294 Type != TT_DesignatedInitializerPeriod;
297 bool isUnaryOperator() const {
298 switch (Tok.getKind()) {
302 case tok::minusminus:
306 case tok::kw_alignof:
313 bool isBinaryOperator() const {
314 // Comma is a binary operator, but does not behave as such wrt. formatting.
315 return getPrecedence() > prec::Comma;
318 bool isTrailingComment() const {
319 return is(tok::comment) && (!Next || Next->NewlinesBefore > 0);
322 prec::Level getPrecedence() const {
323 return getBinOpPrecedence(Tok.getKind(), true, true);
326 /// \brief Returns the previous token ignoring comments.
327 FormatToken *getPreviousNonComment() const {
328 FormatToken *Tok = Previous;
329 while (Tok != NULL && Tok->is(tok::comment))
334 /// \brief Returns the next token ignoring comments.
335 const FormatToken *getNextNonComment() const {
336 const FormatToken *Tok = Next;
337 while (Tok != NULL && Tok->is(tok::comment))
342 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a
343 /// list that should be indented with a block indent.
344 bool opensBlockTypeList(const FormatStyle &Style) const {
345 return Type == TT_ArrayInitializerLSquare ||
347 (BlockKind == BK_Block || Type == TT_DictLiteral ||
348 !Style.Cpp11BracedListStyle));
351 /// \brief Same as opensBlockTypeList, but for the closing token.
352 bool closesBlockTypeList(const FormatStyle &Style) const {
353 return MatchingParen && MatchingParen->opensBlockTypeList(Style);
356 FormatToken *MatchingParen;
358 FormatToken *Previous;
361 SmallVector<AnnotatedLine *, 1> Children;
363 /// \brief Stores the formatting decision for the token once it was made.
364 FormatDecision Decision;
366 /// \brief If \c true, this token has been fully formatted (indented and
367 /// potentially re-formatted inside), and we do not allow further formatting
373 FormatToken(const FormatToken &) LLVM_DELETED_FUNCTION;
374 void operator=(const FormatToken &) LLVM_DELETED_FUNCTION;
377 class ContinuationIndenter;
382 TokenRole(const FormatStyle &Style) : Style(Style) {}
383 virtual ~TokenRole();
385 /// \brief After the \c TokenAnnotator has finished annotating all the tokens,
386 /// this function precomputes required information for formatting.
387 virtual void precomputeFormattingInfos(const FormatToken *Token);
389 /// \brief Apply the special formatting that the given role demands.
391 /// Continues formatting from \p State leaving indentation to \p Indenter and
392 /// returns the total penalty that this formatting incurs.
393 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
398 /// \brief Notifies the \c Role that a comma was found.
399 virtual void CommaFound(const FormatToken *Token) {}
402 const FormatStyle &Style;
405 class CommaSeparatedList : public TokenRole {
407 CommaSeparatedList(const FormatStyle &Style) : TokenRole(Style) {}
409 virtual void precomputeFormattingInfos(const FormatToken *Token);
411 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter,
414 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list.
415 virtual void CommaFound(const FormatToken *Token) { Commas.push_back(Token); }
418 /// \brief A struct that holds information on how to format a given list with
419 /// a specific number of columns.
420 struct ColumnFormat {
421 /// \brief The number of columns to use.
424 /// \brief The total width in characters.
427 /// \brief The number of lines required for this format.
430 /// \brief The size of each column in characters.
431 SmallVector<unsigned, 8> ColumnSizes;
434 /// \brief Calculate which \c ColumnFormat fits best into
435 /// \p RemainingCharacters.
436 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const;
438 /// \brief The ordered \c FormatTokens making up the commas of this list.
439 SmallVector<const FormatToken *, 8> Commas;
441 /// \brief The length of each of the list's items in characters including the
443 SmallVector<unsigned, 8> ItemLengths;
445 /// \brief Precomputed formats that can be used for this list.
446 SmallVector<ColumnFormat, 4> Formats;
449 } // namespace format
452 #endif // LLVM_CLANG_FORMAT_FORMAT_TOKEN_H