Path: blob/main/contrib/llvm-project/clang/lib/Format/BreakableToken.h
35233 views
//===--- BreakableToken.h - Format C++ code ---------------------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// \file9/// Declares BreakableToken, BreakableStringLiteral, BreakableComment,10/// BreakableBlockComment and BreakableLineCommentSection classes, that contain11/// token type-specific logic to break long lines in tokens and reflow content12/// between tokens.13///14//===----------------------------------------------------------------------===//1516#ifndef LLVM_CLANG_LIB_FORMAT_BREAKABLETOKEN_H17#define LLVM_CLANG_LIB_FORMAT_BREAKABLETOKEN_H1819#include "Encoding.h"20#include "WhitespaceManager.h"21#include "llvm/ADT/StringSet.h"2223namespace clang {24namespace format {2526/// Checks if \p Token switches formatting, like /* clang-format off */.27/// \p Token must be a comment.28bool switchesFormatting(const FormatToken &Token);2930struct FormatStyle;3132/// Base class for tokens / ranges of tokens that can allow breaking33/// within the tokens - for example, to avoid whitespace beyond the column34/// limit, or to reflow text.35///36/// Generally, a breakable token consists of logical lines, addressed by a line37/// index. For example, in a sequence of line comments, each line comment is its38/// own logical line; similarly, for a block comment, each line in the block39/// comment is on its own logical line.40///41/// There are two methods to compute the layout of the token:42/// - getRangeLength measures the number of columns needed for a range of text43/// within a logical line, and44/// - getContentStartColumn returns the start column at which we want the45/// content of a logical line to start (potentially after introducing a line46/// break).47///48/// The mechanism to adapt the layout of the breakable token is organised49/// around the concept of a \c Split, which is a whitespace range that signifies50/// a position of the content of a token where a reformatting might be done.51///52/// Operating with splits is divided into two operations:53/// - getSplit, for finding a split starting at a position,54/// - insertBreak, for executing the split using a whitespace manager.55///56/// There is a pair of operations that are used to compress a long whitespace57/// range with a single space if that will bring the line length under the58/// column limit:59/// - getLineLengthAfterCompression, for calculating the size in columns of the60/// line after a whitespace range has been compressed, and61/// - compressWhitespace, for executing the whitespace compression using a62/// whitespace manager; note that the compressed whitespace may be in the63/// middle of the original line and of the reformatted line.64///65/// For tokens where the whitespace before each line needs to be also66/// reformatted, for example for tokens supporting reflow, there are analogous67/// operations that might be executed before the main line breaking occurs:68/// - getReflowSplit, for finding a split such that the content preceding it69/// needs to be specially reflown,70/// - reflow, for executing the split using a whitespace manager,71/// - introducesBreakBefore, for checking if reformatting the beginning72/// of the content introduces a line break before it,73/// - adaptStartOfLine, for executing the reflow using a whitespace74/// manager.75///76/// For tokens that require the whitespace after the last line to be77/// reformatted, for example in multiline jsdoc comments that require the78/// trailing '*/' to be on a line of itself, there are analogous operations79/// that might be executed after the last line has been reformatted:80/// - getSplitAfterLastLine, for finding a split after the last line that needs81/// to be reflown,82/// - replaceWhitespaceAfterLastLine, for executing the reflow using a83/// whitespace manager.84///85class BreakableToken {86public:87/// Contains starting character index and length of split.88typedef std::pair<StringRef::size_type, unsigned> Split;8990virtual ~BreakableToken() {}9192/// Returns the number of lines in this token in the original code.93virtual unsigned getLineCount() const = 0;9495/// Returns the number of columns required to format the text in the96/// byte range [\p Offset, \p Offset \c + \p Length).97///98/// \p Offset is the byte offset from the start of the content of the line99/// at \p LineIndex.100///101/// \p StartColumn is the column at which the text starts in the formatted102/// file, needed to compute tab stops correctly.103virtual unsigned getRangeLength(unsigned LineIndex, unsigned Offset,104StringRef::size_type Length,105unsigned StartColumn) const = 0;106107/// Returns the number of columns required to format the text following108/// the byte \p Offset in the line \p LineIndex, including potentially109/// unbreakable sequences of tokens following after the end of the token.110///111/// \p Offset is the byte offset from the start of the content of the line112/// at \p LineIndex.113///114/// \p StartColumn is the column at which the text starts in the formatted115/// file, needed to compute tab stops correctly.116///117/// For breakable tokens that never use extra space at the end of a line, this118/// is equivalent to getRangeLength with a Length of StringRef::npos.119virtual unsigned getRemainingLength(unsigned LineIndex, unsigned Offset,120unsigned StartColumn) const {121return getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn);122}123124/// Returns the column at which content in line \p LineIndex starts,125/// assuming no reflow.126///127/// If \p Break is true, returns the column at which the line should start128/// after the line break.129/// If \p Break is false, returns the column at which the line itself will130/// start.131virtual unsigned getContentStartColumn(unsigned LineIndex,132bool Break) const = 0;133134/// Returns additional content indent required for the second line after the135/// content at line \p LineIndex is broken.136///137// (Next lines do not start with `///` since otherwise -Wdocumentation picks138// up the example annotations and generates warnings for them)139// For example, Javadoc @param annotations require and indent of 4 spaces and140// in this example getContentIndex(1) returns 4.141// /**142// * @param loooooooooooooong line143// * continuation144// */145virtual unsigned getContentIndent(unsigned LineIndex) const { return 0; }146147/// Returns a range (offset, length) at which to break the line at148/// \p LineIndex, if previously broken at \p TailOffset. If possible, do not149/// violate \p ColumnLimit, assuming the text starting at \p TailOffset in150/// the token is formatted starting at ContentStartColumn in the reformatted151/// file.152virtual Split getSplit(unsigned LineIndex, unsigned TailOffset,153unsigned ColumnLimit, unsigned ContentStartColumn,154const llvm::Regex &CommentPragmasRegex) const = 0;155156/// Emits the previously retrieved \p Split via \p Whitespaces.157virtual void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split,158unsigned ContentIndent,159WhitespaceManager &Whitespaces) const = 0;160161/// Returns the number of columns needed to format162/// \p RemainingTokenColumns, assuming that Split is within the range measured163/// by \p RemainingTokenColumns, and that the whitespace in Split is reduced164/// to a single space.165unsigned getLengthAfterCompression(unsigned RemainingTokenColumns,166Split Split) const;167168/// Replaces the whitespace range described by \p Split with a single169/// space.170virtual void compressWhitespace(unsigned LineIndex, unsigned TailOffset,171Split Split,172WhitespaceManager &Whitespaces) const = 0;173174/// Returns whether the token supports reflowing text.175virtual bool supportsReflow() const { return false; }176177/// Returns a whitespace range (offset, length) of the content at \p178/// LineIndex such that the content of that line is reflown to the end of the179/// previous one.180///181/// Returning (StringRef::npos, 0) indicates reflowing is not possible.182///183/// The range will include any whitespace preceding the specified line's184/// content.185///186/// If the split is not contained within one token, for example when reflowing187/// line comments, returns (0, <length>).188virtual Split getReflowSplit(unsigned LineIndex,189const llvm::Regex &CommentPragmasRegex) const {190return Split(StringRef::npos, 0);191}192193/// Reflows the current line into the end of the previous one.194virtual void reflow(unsigned LineIndex,195WhitespaceManager &Whitespaces) const {}196197/// Returns whether there will be a line break at the start of the198/// token.199virtual bool introducesBreakBeforeToken() const { return false; }200201/// Replaces the whitespace between \p LineIndex-1 and \p LineIndex.202virtual void adaptStartOfLine(unsigned LineIndex,203WhitespaceManager &Whitespaces) const {}204205/// Returns a whitespace range (offset, length) of the content at206/// the last line that needs to be reformatted after the last line has been207/// reformatted.208///209/// A result having offset == StringRef::npos means that no reformat is210/// necessary.211virtual Split getSplitAfterLastLine(unsigned TailOffset) const {212return Split(StringRef::npos, 0);213}214215/// Replaces the whitespace from \p SplitAfterLastLine on the last line216/// after the last line has been formatted by performing a reformatting.217void replaceWhitespaceAfterLastLine(unsigned TailOffset,218Split SplitAfterLastLine,219WhitespaceManager &Whitespaces) const {220insertBreak(getLineCount() - 1, TailOffset, SplitAfterLastLine,221/*ContentIndent=*/0, Whitespaces);222}223224/// Updates the next token of \p State to the next token after this225/// one. This can be used when this token manages a set of underlying tokens226/// as a unit and is responsible for the formatting of the them.227virtual void updateNextToken(LineState &State) const {}228229/// Adds replacements that are needed when the token is broken. Such as230/// wrapping a JavaScript string in parentheses after it gets broken with plus231/// signs.232virtual void updateAfterBroken(WhitespaceManager &Whitespaces) const {}233234protected:235BreakableToken(const FormatToken &Tok, bool InPPDirective,236encoding::Encoding Encoding, const FormatStyle &Style)237: Tok(Tok), InPPDirective(InPPDirective), Encoding(Encoding),238Style(Style) {}239240const FormatToken &Tok;241const bool InPPDirective;242const encoding::Encoding Encoding;243const FormatStyle &Style;244};245246class BreakableStringLiteral : public BreakableToken {247public:248/// Creates a breakable token for a single line string literal.249///250/// \p StartColumn specifies the column in which the token will start251/// after formatting.252BreakableStringLiteral(const FormatToken &Tok, unsigned StartColumn,253StringRef Prefix, StringRef Postfix,254unsigned UnbreakableTailLength, bool InPPDirective,255encoding::Encoding Encoding, const FormatStyle &Style);256257Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,258unsigned ContentStartColumn,259const llvm::Regex &CommentPragmasRegex) const override;260void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split,261unsigned ContentIndent,262WhitespaceManager &Whitespaces) const override;263void compressWhitespace(unsigned LineIndex, unsigned TailOffset, Split Split,264WhitespaceManager &Whitespaces) const override {}265unsigned getLineCount() const override;266unsigned getRangeLength(unsigned LineIndex, unsigned Offset,267StringRef::size_type Length,268unsigned StartColumn) const override;269unsigned getRemainingLength(unsigned LineIndex, unsigned Offset,270unsigned StartColumn) const override;271unsigned getContentStartColumn(unsigned LineIndex, bool Break) const override;272273protected:274// The column in which the token starts.275unsigned StartColumn;276// The prefix a line needs after a break in the token.277StringRef Prefix;278// The postfix a line needs before introducing a break.279StringRef Postfix;280// The token text excluding the prefix and postfix.281StringRef Line;282// Length of the sequence of tokens after this string literal that cannot283// contain line breaks.284unsigned UnbreakableTailLength;285};286287class BreakableStringLiteralUsingOperators : public BreakableStringLiteral {288public:289enum QuoteStyleType {290DoubleQuotes, // The string is quoted with double quotes.291SingleQuotes, // The JavaScript string is quoted with single quotes.292AtDoubleQuotes, // The C# verbatim string is quoted with the at sign and293// double quotes.294};295/// Creates a breakable token for a single line string literal for C#, Java,296/// JavaScript, or Verilog.297///298/// \p StartColumn specifies the column in which the token will start299/// after formatting.300BreakableStringLiteralUsingOperators(301const FormatToken &Tok, QuoteStyleType QuoteStyle, bool UnindentPlus,302unsigned StartColumn, unsigned UnbreakableTailLength, bool InPPDirective,303encoding::Encoding Encoding, const FormatStyle &Style);304unsigned getRemainingLength(unsigned LineIndex, unsigned Offset,305unsigned StartColumn) const override;306unsigned getContentStartColumn(unsigned LineIndex, bool Break) const override;307void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split,308unsigned ContentIndent,309WhitespaceManager &Whitespaces) const override;310void updateAfterBroken(WhitespaceManager &Whitespaces) const override;311312protected:313// Whether braces or parentheses should be inserted around the string to form314// a concatenation.315bool BracesNeeded;316QuoteStyleType QuoteStyle;317// The braces or parentheses along with the first character which they318// replace, either a quote or at sign.319StringRef LeftBraceQuote;320StringRef RightBraceQuote;321// Width added to the left due to the added brace or parenthesis. Does not322// apply to the first line.323int ContinuationIndent;324};325326class BreakableComment : public BreakableToken {327protected:328/// Creates a breakable token for a comment.329///330/// \p StartColumn specifies the column in which the comment will start after331/// formatting.332BreakableComment(const FormatToken &Token, unsigned StartColumn,333bool InPPDirective, encoding::Encoding Encoding,334const FormatStyle &Style);335336public:337bool supportsReflow() const override { return true; }338unsigned getLineCount() const override;339Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,340unsigned ContentStartColumn,341const llvm::Regex &CommentPragmasRegex) const override;342void compressWhitespace(unsigned LineIndex, unsigned TailOffset, Split Split,343WhitespaceManager &Whitespaces) const override;344345protected:346// Returns the token containing the line at LineIndex.347const FormatToken &tokenAt(unsigned LineIndex) const;348349// Checks if the content of line LineIndex may be reflown with the previous350// line.351virtual bool mayReflow(unsigned LineIndex,352const llvm::Regex &CommentPragmasRegex) const = 0;353354// Contains the original text of the lines of the block comment.355//356// In case of a block comments, excludes the leading /* in the first line and357// trailing */ in the last line. In case of line comments, excludes the358// leading // and spaces.359SmallVector<StringRef, 16> Lines;360361// Contains the text of the lines excluding all leading and trailing362// whitespace between the lines. Note that the decoration (if present) is also363// not considered part of the text.364SmallVector<StringRef, 16> Content;365366// Tokens[i] contains a reference to the token containing Lines[i] if the367// whitespace range before that token is managed by this block.368// Otherwise, Tokens[i] is a null pointer.369SmallVector<FormatToken *, 16> Tokens;370371// ContentColumn[i] is the target column at which Content[i] should be.372// Note that this excludes a leading "* " or "*" in case of block comments373// where all lines have a "*" prefix, or the leading "// " or "//" in case of374// line comments.375//376// In block comments, the first line's target column is always positive. The377// remaining lines' target columns are relative to the first line to allow378// correct indentation of comments in \c WhitespaceManager. Thus they can be379// negative as well (in case the first line needs to be unindented more than380// there's actual whitespace in another line).381SmallVector<int, 16> ContentColumn;382383// The intended start column of the first line of text from this section.384unsigned StartColumn;385386// The prefix to use in front a line that has been reflown up.387// For example, when reflowing the second line after the first here:388// // comment 1389// // comment 2390// we expect:391// // comment 1 comment 2392// and not:393// // comment 1comment 2394StringRef ReflowPrefix = " ";395};396397class BreakableBlockComment : public BreakableComment {398public:399BreakableBlockComment(const FormatToken &Token, unsigned StartColumn,400unsigned OriginalStartColumn, bool FirstInLine,401bool InPPDirective, encoding::Encoding Encoding,402const FormatStyle &Style, bool UseCRLF);403404Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,405unsigned ContentStartColumn,406const llvm::Regex &CommentPragmasRegex) const override;407unsigned getRangeLength(unsigned LineIndex, unsigned Offset,408StringRef::size_type Length,409unsigned StartColumn) const override;410unsigned getRemainingLength(unsigned LineIndex, unsigned Offset,411unsigned StartColumn) const override;412unsigned getContentStartColumn(unsigned LineIndex, bool Break) const override;413unsigned getContentIndent(unsigned LineIndex) const override;414void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split,415unsigned ContentIndent,416WhitespaceManager &Whitespaces) const override;417Split getReflowSplit(unsigned LineIndex,418const llvm::Regex &CommentPragmasRegex) const override;419void reflow(unsigned LineIndex,420WhitespaceManager &Whitespaces) const override;421bool introducesBreakBeforeToken() const override;422void adaptStartOfLine(unsigned LineIndex,423WhitespaceManager &Whitespaces) const override;424Split getSplitAfterLastLine(unsigned TailOffset) const override;425426bool mayReflow(unsigned LineIndex,427const llvm::Regex &CommentPragmasRegex) const override;428429// Contains Javadoc annotations that require additional indent when continued430// on multiple lines.431static const llvm::StringSet<> ContentIndentingJavadocAnnotations;432433private:434// Rearranges the whitespace between Lines[LineIndex-1] and Lines[LineIndex].435//436// Updates Content[LineIndex-1] and Content[LineIndex] by stripping off437// leading and trailing whitespace.438//439// Sets ContentColumn to the intended column in which the text at440// Lines[LineIndex] starts (note that the decoration, if present, is not441// considered part of the text).442void adjustWhitespace(unsigned LineIndex, int IndentDelta);443444// The column at which the text of a broken line should start.445// Note that an optional decoration would go before that column.446// IndentAtLineBreak is a uniform position for all lines in a block comment,447// regardless of their relative position.448// FIXME: Revisit the decision to do this; the main reason was to support449// patterns like450// /**************//**451// * Comment452// We could also support such patterns by special casing the first line453// instead.454unsigned IndentAtLineBreak;455456// This is to distinguish between the case when the last line was empty and457// the case when it started with a decoration ("*" or "* ").458bool LastLineNeedsDecoration;459460// Either "* " if all lines begin with a "*", or empty.461StringRef Decoration;462463// If this block comment has decorations, this is the column of the start of464// the decorations.465unsigned DecorationColumn;466467// If true, make sure that the opening '/**' and the closing '*/' ends on a468// line of itself. Styles like jsdoc require this for multiline comments.469bool DelimitersOnNewline;470471// Length of the sequence of tokens after this string literal that cannot472// contain line breaks.473unsigned UnbreakableTailLength;474};475476class BreakableLineCommentSection : public BreakableComment {477public:478BreakableLineCommentSection(const FormatToken &Token, unsigned StartColumn,479bool InPPDirective, encoding::Encoding Encoding,480const FormatStyle &Style);481482unsigned getRangeLength(unsigned LineIndex, unsigned Offset,483StringRef::size_type Length,484unsigned StartColumn) const override;485unsigned getContentStartColumn(unsigned LineIndex, bool Break) const override;486void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split,487unsigned ContentIndent,488WhitespaceManager &Whitespaces) const override;489Split getReflowSplit(unsigned LineIndex,490const llvm::Regex &CommentPragmasRegex) const override;491void reflow(unsigned LineIndex,492WhitespaceManager &Whitespaces) const override;493void adaptStartOfLine(unsigned LineIndex,494WhitespaceManager &Whitespaces) const override;495void updateNextToken(LineState &State) const override;496bool mayReflow(unsigned LineIndex,497const llvm::Regex &CommentPragmasRegex) const override;498499private:500// OriginalPrefix[i] contains the original prefix of line i, including501// trailing whitespace before the start of the content. The indentation502// preceding the prefix is not included.503// For example, if the line is:504// // content505// then the original prefix is "// ".506SmallVector<StringRef, 16> OriginalPrefix;507508/// Prefix[i] + SpacesToAdd[i] contains the intended leading "//" with509/// trailing spaces to account for the indentation of content within the510/// comment at line i after formatting. It can be different than the original511/// prefix.512/// When the original line starts like this:513/// //content514/// Then the OriginalPrefix[i] is "//", but the Prefix[i] is "// " in the LLVM515/// style.516/// When the line starts like:517/// // content518/// And we want to remove the spaces the OriginalPrefix[i] is "// " and519/// Prefix[i] is "//".520SmallVector<std::string, 16> Prefix;521522/// How many spaces are added or removed from the OriginalPrefix to form523/// Prefix.524SmallVector<int, 16> PrefixSpaceChange;525526/// The token to which the last line of this breakable token belongs527/// to; nullptr if that token is the initial token.528///529/// The distinction is because if the token of the last line of this breakable530/// token is distinct from the initial token, this breakable token owns the531/// whitespace before the token of the last line, and the whitespace manager532/// must be able to modify it.533FormatToken *LastLineTok = nullptr;534};535} // namespace format536} // namespace clang537538#endif539540541