FormatToken.h revision 263508
1//===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9/// 10/// \file 11/// \brief This file contains the declaration of the FormatToken, a wrapper 12/// around Token with additional information related to formatting. 13/// 14//===----------------------------------------------------------------------===// 15 16#ifndef LLVM_CLANG_FORMAT_FORMAT_TOKEN_H 17#define LLVM_CLANG_FORMAT_FORMAT_TOKEN_H 18 19#include "clang/Basic/OperatorPrecedence.h" 20#include "clang/Format/Format.h" 21#include "clang/Lex/Lexer.h" 22#include "llvm/ADT/OwningPtr.h" 23 24namespace clang { 25namespace format { 26 27enum TokenType { 28 TT_ArrayInitializerLSquare, 29 TT_ArraySubscriptLSquare, 30 TT_BinaryOperator, 31 TT_BitFieldColon, 32 TT_BlockComment, 33 TT_CastRParen, 34 TT_ConditionalExpr, 35 TT_CtorInitializerColon, 36 TT_CtorInitializerComma, 37 TT_DesignatedInitializerPeriod, 38 TT_DictLiteral, 39 TT_ImplicitStringLiteral, 40 TT_InlineASMColon, 41 TT_InheritanceColon, 42 TT_FunctionTypeLParen, 43 TT_LambdaLSquare, 44 TT_LineComment, 45 TT_ObjCBlockLParen, 46 TT_ObjCDecl, 47 TT_ObjCForIn, 48 TT_ObjCMethodExpr, 49 TT_ObjCMethodSpecifier, 50 TT_ObjCProperty, 51 TT_ObjCSelectorName, 52 TT_OverloadedOperator, 53 TT_OverloadedOperatorLParen, 54 TT_PointerOrReference, 55 TT_PureVirtualSpecifier, 56 TT_RangeBasedForLoopColon, 57 TT_StartOfName, 58 TT_TemplateCloser, 59 TT_TemplateOpener, 60 TT_TrailingReturnArrow, 61 TT_TrailingUnaryOperator, 62 TT_UnaryOperator, 63 TT_Unknown 64}; 65 66// Represents what type of block a set of braces open. 67enum BraceBlockKind { 68 BK_Unknown, 69 BK_Block, 70 BK_BracedInit 71}; 72 73// The packing kind of a function's parameters. 74enum ParameterPackingKind { 75 PPK_BinPacked, 76 PPK_OnePerLine, 77 PPK_Inconclusive 78}; 79 80enum FormatDecision { 81 FD_Unformatted, 82 FD_Continue, 83 FD_Break 84}; 85 86class TokenRole; 87class AnnotatedLine; 88 89/// \brief A wrapper around a \c Token storing information about the 90/// whitespace characters preceeding it. 91struct FormatToken { 92 FormatToken() 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) {} 105 106 /// \brief The \c Token. 107 Token Tok; 108 109 /// \brief The number of newlines immediately before the \c Token. 110 /// 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; 114 115 /// \brief Whether there is at least one unescaped newline before the \c 116 /// Token. 117 bool HasUnescapedNewline; 118 119 /// \brief The range of the whitespace immediately preceeding the \c Token. 120 SourceRange WhitespaceRange; 121 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; 125 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; 130 131 /// \brief Contains the width in columns of the last line of a multi-line 132 /// token. 133 unsigned LastLineColumnWidth; 134 135 /// \brief Whether the token text contains newlines (escaped or not). 136 bool IsMultiline; 137 138 /// \brief Indicates that this is the first token. 139 bool IsFirst; 140 141 /// \brief Whether there must be a line break before this token. 142 /// 143 /// This happens for example when a preprocessor directive ended directly 144 /// before the token. 145 bool MustBreakBefore; 146 147 /// \brief Returns actual token start location without leading escaped 148 /// newlines and whitespace. 149 /// 150 /// This can be different to Tok.getLocation(), which includes leading escaped 151 /// newlines. 152 SourceLocation getStartOfNonWhitespace() const { 153 return WhitespaceRange.getEnd(); 154 } 155 156 /// \brief The raw text of the token. 157 /// 158 /// Contains the raw token text without leading whitespace and without leading 159 /// escaped newlines. 160 StringRef TokenText; 161 162 /// \brief Set to \c true if this token is an unterminated literal. 163 bool IsUnterminatedLiteral; 164 165 /// \brief Contains the kind of block if this token is a brace. 166 BraceBlockKind BlockKind; 167 168 TokenType Type; 169 170 /// \brief The number of spaces that should be inserted before this token. 171 unsigned SpacesRequiredBefore; 172 173 /// \brief \c true if it is allowed to break before this token. 174 bool CanBreakBefore; 175 176 bool ClosesTemplateDeclaration; 177 178 /// \brief Number of parameters, if this is "(", "[" or "<". 179 /// 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; 184 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; 188 189 /// \brief If this is an opening parenthesis, how are the parameters packed? 190 ParameterPackingKind PackingKind; 191 192 /// \brief The total length of the unwrapped line up to and including this 193 /// token. 194 unsigned TotalLength; 195 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; 199 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; 203 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; 208 209 /// \brief Penalty for inserting a line break before this token. 210 unsigned SplitPenalty; 211 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; 215 216 /// \brief Stores the number of required fake parentheses and the 217 /// corresponding operator precedence. 218 /// 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; 224 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; 230 231 /// \brief Is this the last "." or "->" in a builder-type call? 232 bool LastInChainOfCalls; 233 234 /// \brief Is this token part of a \c DeclStmt defining multiple variables? 235 /// 236 /// Only set if \c Type == \c TT_StartOfName. 237 bool PartOfMultiVariableDeclStmt; 238 239 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); } 240 241 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const { 242 return is(K1) || is(K2); 243 } 244 245 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const { 246 return is(K1) || is(K2) || is(K3); 247 } 248 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); 260 } 261 262 bool isNot(tok::TokenKind Kind) const { return Tok.isNot(Kind); } 263 264 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const { 265 return Tok.isObjCAtKeyword(Kind); 266 } 267 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))); 271 } 272 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)); 278 } 279 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; 284 } 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; 289 } 290 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; 295 } 296 297 bool isUnaryOperator() const { 298 switch (Tok.getKind()) { 299 case tok::plus: 300 case tok::plusplus: 301 case tok::minus: 302 case tok::minusminus: 303 case tok::exclaim: 304 case tok::tilde: 305 case tok::kw_sizeof: 306 case tok::kw_alignof: 307 return true; 308 default: 309 return false; 310 } 311 } 312 313 bool isBinaryOperator() const { 314 // Comma is a binary operator, but does not behave as such wrt. formatting. 315 return getPrecedence() > prec::Comma; 316 } 317 318 bool isTrailingComment() const { 319 return is(tok::comment) && (!Next || Next->NewlinesBefore > 0); 320 } 321 322 prec::Level getPrecedence() const { 323 return getBinOpPrecedence(Tok.getKind(), true, true); 324 } 325 326 /// \brief Returns the previous token ignoring comments. 327 FormatToken *getPreviousNonComment() const { 328 FormatToken *Tok = Previous; 329 while (Tok != NULL && Tok->is(tok::comment)) 330 Tok = Tok->Previous; 331 return Tok; 332 } 333 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)) 338 Tok = Tok->Next; 339 return Tok; 340 } 341 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 || 346 (is(tok::l_brace) && 347 (BlockKind == BK_Block || Type == TT_DictLiteral || 348 !Style.Cpp11BracedListStyle)); 349 } 350 351 /// \brief Same as opensBlockTypeList, but for the closing token. 352 bool closesBlockTypeList(const FormatStyle &Style) const { 353 return MatchingParen && MatchingParen->opensBlockTypeList(Style); 354 } 355 356 FormatToken *MatchingParen; 357 358 FormatToken *Previous; 359 FormatToken *Next; 360 361 SmallVector<AnnotatedLine *, 1> Children; 362 363 /// \brief Stores the formatting decision for the token once it was made. 364 FormatDecision Decision; 365 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 368 /// changes. 369 bool Finalized; 370 371private: 372 // Disallow copying. 373 FormatToken(const FormatToken &) LLVM_DELETED_FUNCTION; 374 void operator=(const FormatToken &) LLVM_DELETED_FUNCTION; 375}; 376 377class ContinuationIndenter; 378struct LineState; 379 380class TokenRole { 381public: 382 TokenRole(const FormatStyle &Style) : Style(Style) {} 383 virtual ~TokenRole(); 384 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); 388 389 /// \brief Apply the special formatting that the given role demands. 390 /// 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, 394 bool DryRun) { 395 return 0; 396 } 397 398 /// \brief Notifies the \c Role that a comma was found. 399 virtual void CommaFound(const FormatToken *Token) {} 400 401protected: 402 const FormatStyle &Style; 403}; 404 405class CommaSeparatedList : public TokenRole { 406public: 407 CommaSeparatedList(const FormatStyle &Style) : TokenRole(Style) {} 408 409 virtual void precomputeFormattingInfos(const FormatToken *Token); 410 411 virtual unsigned format(LineState &State, ContinuationIndenter *Indenter, 412 bool DryRun); 413 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); } 416 417private: 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. 422 unsigned Columns; 423 424 /// \brief The total width in characters. 425 unsigned TotalWidth; 426 427 /// \brief The number of lines required for this format. 428 unsigned LineCount; 429 430 /// \brief The size of each column in characters. 431 SmallVector<unsigned, 8> ColumnSizes; 432 }; 433 434 /// \brief Calculate which \c ColumnFormat fits best into 435 /// \p RemainingCharacters. 436 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const; 437 438 /// \brief The ordered \c FormatTokens making up the commas of this list. 439 SmallVector<const FormatToken *, 8> Commas; 440 441 /// \brief The length of each of the list's items in characters including the 442 /// trailing comma. 443 SmallVector<unsigned, 8> ItemLengths; 444 445 /// \brief Precomputed formats that can be used for this list. 446 SmallVector<ColumnFormat, 4> Formats; 447}; 448 449} // namespace format 450} // namespace clang 451 452#endif // LLVM_CLANG_FORMAT_FORMAT_TOKEN_H 453