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_LIB_FORMAT_FORMATTOKEN_H 17 #define LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H 18 19 #include "clang/Basic/OperatorPrecedence.h" 20 #include "clang/Format/Format.h" 21 #include "clang/Lex/Lexer.h" 22 #include <memory> 23 24 namespace clang { 25 namespace format { 26 27 enum TokenType { 28 TT_ArrayInitializerLSquare, 29 TT_ArraySubscriptLSquare, 30 TT_AttributeParen, 31 TT_BinaryOperator, 32 TT_BitFieldColon, 33 TT_BlockComment, 34 TT_CastRParen, 35 TT_ConditionalExpr, 36 TT_ConflictAlternative, 37 TT_ConflictEnd, 38 TT_ConflictStart, 39 TT_CtorInitializerColon, 40 TT_CtorInitializerComma, 41 TT_DesignatedInitializerPeriod, 42 TT_DictLiteral, 43 TT_FunctionDeclarationName, 44 TT_FunctionLBrace, 45 TT_FunctionTypeLParen, 46 TT_ImplicitStringLiteral, 47 TT_InheritanceColon, 48 TT_InlineASMColon, 49 TT_LambdaLSquare, 50 TT_LineComment, 51 TT_ObjCBlockLBrace, 52 TT_ObjCBlockLParen, 53 TT_ObjCDecl, 54 TT_ObjCForIn, 55 TT_ObjCMethodExpr, 56 TT_ObjCMethodSpecifier, 57 TT_ObjCProperty, 58 TT_OverloadedOperator, 59 TT_OverloadedOperatorLParen, 60 TT_PointerOrReference, 61 TT_PureVirtualSpecifier, 62 TT_RangeBasedForLoopColon, 63 TT_RegexLiteral, 64 TT_SelectorName, 65 TT_StartOfName, 66 TT_TemplateCloser, 67 TT_TemplateOpener, 68 TT_TrailingAnnotation, 69 TT_TrailingReturnArrow, 70 TT_TrailingUnaryOperator, 71 TT_UnaryOperator, 72 TT_Unknown 73 }; 74 75 // Represents what type of block a set of braces open. 76 enum BraceBlockKind { 77 BK_Unknown, 78 BK_Block, 79 BK_BracedInit 80 }; 81 82 // The packing kind of a function's parameters. 83 enum ParameterPackingKind { 84 PPK_BinPacked, 85 PPK_OnePerLine, 86 PPK_Inconclusive 87 }; 88 89 enum FormatDecision { 90 FD_Unformatted, 91 FD_Continue, 92 FD_Break 93 }; 94 95 class TokenRole; 96 class AnnotatedLine; 97 98 /// \brief A wrapper around a \c Token storing information about the 99 /// whitespace characters preceding it. 100 struct FormatToken { 101 FormatToken() 102 : NewlinesBefore(0), HasUnescapedNewline(false), LastNewlineOffset(0), 103 ColumnWidth(0), LastLineColumnWidth(0), IsMultiline(false), 104 IsFirst(false), MustBreakBefore(false), IsUnterminatedLiteral(false), 105 BlockKind(BK_Unknown), Type(TT_Unknown), SpacesRequiredBefore(0), 106 CanBreakBefore(false), ClosesTemplateDeclaration(false), 107 ParameterCount(0), BlockParameterCount(0), 108 PackingKind(PPK_Inconclusive), TotalLength(0), UnbreakableTailLength(0), 109 BindingStrength(0), NestingLevel(0), SplitPenalty(0), 110 LongestObjCSelectorName(0), FakeRParens(0), 111 StartsBinaryExpression(false), EndsBinaryExpression(false), 112 OperatorIndex(0), LastOperator(false), 113 PartOfMultiVariableDeclStmt(false), IsForEachMacro(false), 114 MatchingParen(nullptr), Previous(nullptr), Next(nullptr), 115 Decision(FD_Unformatted), Finalized(false) {} 116 117 /// \brief The \c Token. 118 Token Tok; 119 120 /// \brief The number of newlines immediately before the \c Token. 121 /// 122 /// This can be used to determine what the user wrote in the original code 123 /// and thereby e.g. leave an empty line between two function definitions. 124 unsigned NewlinesBefore; 125 126 /// \brief Whether there is at least one unescaped newline before the \c 127 /// Token. 128 bool HasUnescapedNewline; 129 130 /// \brief The range of the whitespace immediately preceding the \c Token. 131 SourceRange WhitespaceRange; 132 133 /// \brief The offset just past the last '\n' in this token's leading 134 /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'. 135 unsigned LastNewlineOffset; 136 137 /// \brief The width of the non-whitespace parts of the token (or its first 138 /// line for multi-line tokens) in columns. 139 /// We need this to correctly measure number of columns a token spans. 140 unsigned ColumnWidth; 141 142 /// \brief Contains the width in columns of the last line of a multi-line 143 /// token. 144 unsigned LastLineColumnWidth; 145 146 /// \brief Whether the token text contains newlines (escaped or not). 147 bool IsMultiline; 148 149 /// \brief Indicates that this is the first token. 150 bool IsFirst; 151 152 /// \brief Whether there must be a line break before this token. 153 /// 154 /// This happens for example when a preprocessor directive ended directly 155 /// before the token. 156 bool MustBreakBefore; 157 158 /// \brief Returns actual token start location without leading escaped 159 /// newlines and whitespace. 160 /// 161 /// This can be different to Tok.getLocation(), which includes leading escaped 162 /// newlines. 163 SourceLocation getStartOfNonWhitespace() const { 164 return WhitespaceRange.getEnd(); 165 } 166 167 /// \brief The raw text of the token. 168 /// 169 /// Contains the raw token text without leading whitespace and without leading 170 /// escaped newlines. 171 StringRef TokenText; 172 173 /// \brief Set to \c true if this token is an unterminated literal. 174 bool IsUnterminatedLiteral; 175 176 /// \brief Contains the kind of block if this token is a brace. 177 BraceBlockKind BlockKind; 178 179 TokenType Type; 180 181 /// \brief The number of spaces that should be inserted before this token. 182 unsigned SpacesRequiredBefore; 183 184 /// \brief \c true if it is allowed to break before this token. 185 bool CanBreakBefore; 186 187 bool ClosesTemplateDeclaration; 188 189 /// \brief Number of parameters, if this is "(", "[" or "<". 190 /// 191 /// This is initialized to 1 as we don't need to distinguish functions with 192 /// 0 parameters from functions with 1 parameter. Thus, we can simply count 193 /// the number of commas. 194 unsigned ParameterCount; 195 196 /// \brief Number of parameters that are nested blocks, 197 /// if this is "(", "[" or "<". 198 unsigned BlockParameterCount; 199 200 /// \brief A token can have a special role that can carry extra information 201 /// about the token's formatting. 202 std::unique_ptr<TokenRole> Role; 203 204 /// \brief If this is an opening parenthesis, how are the parameters packed? 205 ParameterPackingKind PackingKind; 206 207 /// \brief The total length of the unwrapped line up to and including this 208 /// token. 209 unsigned TotalLength; 210 211 /// \brief The original 0-based column of this token, including expanded tabs. 212 /// The configured TabWidth is used as tab width. 213 unsigned OriginalColumn; 214 215 /// \brief The length of following tokens until the next natural split point, 216 /// or the next token that can be broken. 217 unsigned UnbreakableTailLength; 218 219 // FIXME: Come up with a 'cleaner' concept. 220 /// \brief The binding strength of a token. This is a combined value of 221 /// operator precedence, parenthesis nesting, etc. 222 unsigned BindingStrength; 223 224 /// \brief The nesting level of this token, i.e. the number of surrounding (), 225 /// [], {} or <>. 226 unsigned NestingLevel; 227 228 /// \brief Penalty for inserting a line break before this token. 229 unsigned SplitPenalty; 230 231 /// \brief If this is the first ObjC selector name in an ObjC method 232 /// definition or call, this contains the length of the longest name. 233 /// 234 /// This being set to 0 means that the selectors should not be colon-aligned, 235 /// e.g. because several of them are block-type. 236 unsigned LongestObjCSelectorName; 237 238 /// \brief Stores the number of required fake parentheses and the 239 /// corresponding operator precedence. 240 /// 241 /// If multiple fake parentheses start at a token, this vector stores them in 242 /// reverse order, i.e. inner fake parenthesis first. 243 SmallVector<prec::Level, 4> FakeLParens; 244 /// \brief Insert this many fake ) after this token for correct indentation. 245 unsigned FakeRParens; 246 247 /// \brief \c true if this token starts a binary expression, i.e. has at least 248 /// one fake l_paren with a precedence greater than prec::Unknown. 249 bool StartsBinaryExpression; 250 /// \brief \c true if this token ends a binary expression. 251 bool EndsBinaryExpression; 252 253 /// \brief Is this is an operator (or "."/"->") in a sequence of operators 254 /// with the same precedence, contains the 0-based operator index. 255 unsigned OperatorIndex; 256 257 /// \brief Is this the last operator (or "."/"->") in a sequence of operators 258 /// with the same precedence? 259 bool LastOperator; 260 261 /// \brief Is this token part of a \c DeclStmt defining multiple variables? 262 /// 263 /// Only set if \c Type == \c TT_StartOfName. 264 bool PartOfMultiVariableDeclStmt; 265 266 /// \brief Is this a foreach macro? 267 bool IsForEachMacro; 268 269 bool is(tok::TokenKind Kind) const { return Tok.is(Kind); } 270 271 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const { 272 return is(K1) || is(K2); 273 } 274 275 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3) const { 276 return is(K1) || is(K2) || is(K3); 277 } 278 279 bool isOneOf(tok::TokenKind K1, tok::TokenKind K2, tok::TokenKind K3, 280 tok::TokenKind K4, tok::TokenKind K5 = tok::NUM_TOKENS, 281 tok::TokenKind K6 = tok::NUM_TOKENS, 282 tok::TokenKind K7 = tok::NUM_TOKENS, 283 tok::TokenKind K8 = tok::NUM_TOKENS, 284 tok::TokenKind K9 = tok::NUM_TOKENS, 285 tok::TokenKind K10 = tok::NUM_TOKENS, 286 tok::TokenKind K11 = tok::NUM_TOKENS, 287 tok::TokenKind K12 = tok::NUM_TOKENS) const { 288 return is(K1) || is(K2) || is(K3) || is(K4) || is(K5) || is(K6) || is(K7) || 289 is(K8) || is(K9) || is(K10) || is(K11) || is(K12); 290 } 291 292 bool isNot(tok::TokenKind Kind) const { return Tok.isNot(Kind); } 293 bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } 294 295 bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const { 296 return Tok.isObjCAtKeyword(Kind); 297 } 298 299 bool isAccessSpecifier(bool ColonRequired = true) const { 300 return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) && 301 (!ColonRequired || (Next && Next->is(tok::colon))); 302 } 303 304 /// \brief Determine whether the token is a simple-type-specifier. 305 bool isSimpleTypeSpecifier() const; 306 307 bool isObjCAccessSpecifier() const { 308 return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) || 309 Next->isObjCAtKeyword(tok::objc_protected) || 310 Next->isObjCAtKeyword(tok::objc_package) || 311 Next->isObjCAtKeyword(tok::objc_private)); 312 } 313 314 /// \brief Returns whether \p Tok is ([{ or a template opening <. 315 bool opensScope() const { 316 return isOneOf(tok::l_paren, tok::l_brace, tok::l_square) || 317 Type == TT_TemplateOpener; 318 } 319 /// \brief Returns whether \p Tok is )]} or a template closing >. 320 bool closesScope() const { 321 return isOneOf(tok::r_paren, tok::r_brace, tok::r_square) || 322 Type == TT_TemplateCloser; 323 } 324 325 /// \brief Returns \c true if this is a "." or "->" accessing a member. 326 bool isMemberAccess() const { 327 return isOneOf(tok::arrow, tok::period, tok::arrowstar) && 328 Type != TT_DesignatedInitializerPeriod; 329 } 330 331 bool isUnaryOperator() const { 332 switch (Tok.getKind()) { 333 case tok::plus: 334 case tok::plusplus: 335 case tok::minus: 336 case tok::minusminus: 337 case tok::exclaim: 338 case tok::tilde: 339 case tok::kw_sizeof: 340 case tok::kw_alignof: 341 return true; 342 default: 343 return false; 344 } 345 } 346 347 bool isBinaryOperator() const { 348 // Comma is a binary operator, but does not behave as such wrt. formatting. 349 return getPrecedence() > prec::Comma; 350 } 351 352 bool isTrailingComment() const { 353 return is(tok::comment) && 354 (Type == TT_LineComment || !Next || Next->NewlinesBefore > 0); 355 } 356 357 /// \brief Returns \c true if this is a keyword that can be used 358 /// like a function call (e.g. sizeof, typeid, ...). 359 bool isFunctionLikeKeyword() const { 360 switch (Tok.getKind()) { 361 case tok::kw_throw: 362 case tok::kw_typeid: 363 case tok::kw_return: 364 case tok::kw_sizeof: 365 case tok::kw_alignof: 366 case tok::kw_alignas: 367 case tok::kw_decltype: 368 case tok::kw_noexcept: 369 case tok::kw_static_assert: 370 case tok::kw___attribute: 371 return true; 372 default: 373 return false; 374 } 375 } 376 377 prec::Level getPrecedence() const { 378 return getBinOpPrecedence(Tok.getKind(), true, true); 379 } 380 381 /// \brief Returns the previous token ignoring comments. 382 FormatToken *getPreviousNonComment() const { 383 FormatToken *Tok = Previous; 384 while (Tok && Tok->is(tok::comment)) 385 Tok = Tok->Previous; 386 return Tok; 387 } 388 389 /// \brief Returns the next token ignoring comments. 390 const FormatToken *getNextNonComment() const { 391 const FormatToken *Tok = Next; 392 while (Tok && Tok->is(tok::comment)) 393 Tok = Tok->Next; 394 return Tok; 395 } 396 397 /// \brief Returns \c true if this tokens starts a block-type list, i.e. a 398 /// list that should be indented with a block indent. 399 bool opensBlockTypeList(const FormatStyle &Style) const { 400 return Type == TT_ArrayInitializerLSquare || 401 (is(tok::l_brace) && 402 (BlockKind == BK_Block || Type == TT_DictLiteral || 403 !Style.Cpp11BracedListStyle)); 404 } 405 406 /// \brief Same as opensBlockTypeList, but for the closing token. 407 bool closesBlockTypeList(const FormatStyle &Style) const { 408 return MatchingParen && MatchingParen->opensBlockTypeList(Style); 409 } 410 411 FormatToken *MatchingParen; 412 413 FormatToken *Previous; 414 FormatToken *Next; 415 416 SmallVector<AnnotatedLine *, 1> Children; 417 418 /// \brief Stores the formatting decision for the token once it was made. 419 FormatDecision Decision; 420 421 /// \brief If \c true, this token has been fully formatted (indented and 422 /// potentially re-formatted inside), and we do not allow further formatting 423 /// changes. 424 bool Finalized; 425 426 private: 427 // Disallow copying. 428 FormatToken(const FormatToken &) LLVM_DELETED_FUNCTION; 429 void operator=(const FormatToken &) LLVM_DELETED_FUNCTION; 430 }; 431 432 class ContinuationIndenter; 433 struct LineState; 434 435 class TokenRole { 436 public: 437 TokenRole(const FormatStyle &Style) : Style(Style) {} 438 virtual ~TokenRole(); 439 440 /// \brief After the \c TokenAnnotator has finished annotating all the tokens, 441 /// this function precomputes required information for formatting. 442 virtual void precomputeFormattingInfos(const FormatToken *Token); 443 444 /// \brief Apply the special formatting that the given role demands. 445 /// 446 /// Assumes that the token having this role is already formatted. 447 /// 448 /// Continues formatting from \p State leaving indentation to \p Indenter and 449 /// returns the total penalty that this formatting incurs. 450 virtual unsigned formatFromToken(LineState &State, 451 ContinuationIndenter *Indenter, 452 bool DryRun) { 453 return 0; 454 } 455 456 /// \brief Same as \c formatFromToken, but assumes that the first token has 457 /// already been set thereby deciding on the first line break. 458 virtual unsigned formatAfterToken(LineState &State, 459 ContinuationIndenter *Indenter, 460 bool DryRun) { 461 return 0; 462 } 463 464 /// \brief Notifies the \c Role that a comma was found. 465 virtual void CommaFound(const FormatToken *Token) {} 466 467 protected: 468 const FormatStyle &Style; 469 }; 470 471 class CommaSeparatedList : public TokenRole { 472 public: 473 CommaSeparatedList(const FormatStyle &Style) 474 : TokenRole(Style), HasNestedBracedList(false) {} 475 476 void precomputeFormattingInfos(const FormatToken *Token) override; 477 478 unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter, 479 bool DryRun) override; 480 481 unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter, 482 bool DryRun) override; 483 484 /// \brief Adds \p Token as the next comma to the \c CommaSeparated list. 485 void CommaFound(const FormatToken *Token) override { 486 Commas.push_back(Token); 487 } 488 489 private: 490 /// \brief A struct that holds information on how to format a given list with 491 /// a specific number of columns. 492 struct ColumnFormat { 493 /// \brief The number of columns to use. 494 unsigned Columns; 495 496 /// \brief The total width in characters. 497 unsigned TotalWidth; 498 499 /// \brief The number of lines required for this format. 500 unsigned LineCount; 501 502 /// \brief The size of each column in characters. 503 SmallVector<unsigned, 8> ColumnSizes; 504 }; 505 506 /// \brief Calculate which \c ColumnFormat fits best into 507 /// \p RemainingCharacters. 508 const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const; 509 510 /// \brief The ordered \c FormatTokens making up the commas of this list. 511 SmallVector<const FormatToken *, 8> Commas; 512 513 /// \brief The length of each of the list's items in characters including the 514 /// trailing comma. 515 SmallVector<unsigned, 8> ItemLengths; 516 517 /// \brief Precomputed formats that can be used for this list. 518 SmallVector<ColumnFormat, 4> Formats; 519 520 bool HasNestedBracedList; 521 }; 522 523 } // namespace format 524 } // namespace clang 525 526 #endif 527