BreakableToken.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. //===--- BreakableToken.h - Format C++ code ---------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. ///
  9. /// \file
  10. /// Declares BreakableToken, BreakableStringLiteral, BreakableComment,
  11. /// BreakableBlockComment and BreakableLineCommentSection classes, that contain
  12. /// token type-specific logic to break long lines in tokens and reflow content
  13. /// between tokens.
  14. ///
  15. //===----------------------------------------------------------------------===//
  16. #ifndef LLVM_CLANG_LIB_FORMAT_BREAKABLETOKEN_H
  17. #define LLVM_CLANG_LIB_FORMAT_BREAKABLETOKEN_H
  18. #include "Encoding.h"
  19. #include "TokenAnnotator.h"
  20. #include "WhitespaceManager.h"
  21. #include "llvm/ADT/StringSet.h"
  22. #include "llvm/Support/Regex.h"
  23. #include <utility>
  24. namespace clang {
  25. namespace format {
  26. /// Checks if \p Token switches formatting, like /* clang-format off */.
  27. /// \p Token must be a comment.
  28. bool switchesFormatting(const FormatToken &Token);
  29. struct FormatStyle;
  30. /// Base class for tokens / ranges of tokens that can allow breaking
  31. /// within the tokens - for example, to avoid whitespace beyond the column
  32. /// limit, or to reflow text.
  33. ///
  34. /// Generally, a breakable token consists of logical lines, addressed by a line
  35. /// index. For example, in a sequence of line comments, each line comment is its
  36. /// own logical line; similarly, for a block comment, each line in the block
  37. /// comment is on its own logical line.
  38. ///
  39. /// There are two methods to compute the layout of the token:
  40. /// - getRangeLength measures the number of columns needed for a range of text
  41. /// within a logical line, and
  42. /// - getContentStartColumn returns the start column at which we want the
  43. /// content of a logical line to start (potentially after introducing a line
  44. /// break).
  45. ///
  46. /// The mechanism to adapt the layout of the breakable token is organised
  47. /// around the concept of a \c Split, which is a whitespace range that signifies
  48. /// a position of the content of a token where a reformatting might be done.
  49. ///
  50. /// Operating with splits is divided into two operations:
  51. /// - getSplit, for finding a split starting at a position,
  52. /// - insertBreak, for executing the split using a whitespace manager.
  53. ///
  54. /// There is a pair of operations that are used to compress a long whitespace
  55. /// range with a single space if that will bring the line length under the
  56. /// column limit:
  57. /// - getLineLengthAfterCompression, for calculating the size in columns of the
  58. /// line after a whitespace range has been compressed, and
  59. /// - compressWhitespace, for executing the whitespace compression using a
  60. /// whitespace manager; note that the compressed whitespace may be in the
  61. /// middle of the original line and of the reformatted line.
  62. ///
  63. /// For tokens where the whitespace before each line needs to be also
  64. /// reformatted, for example for tokens supporting reflow, there are analogous
  65. /// operations that might be executed before the main line breaking occurs:
  66. /// - getReflowSplit, for finding a split such that the content preceding it
  67. /// needs to be specially reflown,
  68. /// - reflow, for executing the split using a whitespace manager,
  69. /// - introducesBreakBefore, for checking if reformatting the beginning
  70. /// of the content introduces a line break before it,
  71. /// - adaptStartOfLine, for executing the reflow using a whitespace
  72. /// manager.
  73. ///
  74. /// For tokens that require the whitespace after the last line to be
  75. /// reformatted, for example in multiline jsdoc comments that require the
  76. /// trailing '*/' to be on a line of itself, there are analogous operations
  77. /// that might be executed after the last line has been reformatted:
  78. /// - getSplitAfterLastLine, for finding a split after the last line that needs
  79. /// to be reflown,
  80. /// - replaceWhitespaceAfterLastLine, for executing the reflow using a
  81. /// whitespace manager.
  82. ///
  83. class BreakableToken {
  84. public:
  85. /// Contains starting character index and length of split.
  86. typedef std::pair<StringRef::size_type, unsigned> Split;
  87. virtual ~BreakableToken() {}
  88. /// Returns the number of lines in this token in the original code.
  89. virtual unsigned getLineCount() const = 0;
  90. /// Returns the number of columns required to format the text in the
  91. /// byte range [\p Offset, \p Offset \c + \p Length).
  92. ///
  93. /// \p Offset is the byte offset from the start of the content of the line
  94. /// at \p LineIndex.
  95. ///
  96. /// \p StartColumn is the column at which the text starts in the formatted
  97. /// file, needed to compute tab stops correctly.
  98. virtual unsigned getRangeLength(unsigned LineIndex, unsigned Offset,
  99. StringRef::size_type Length,
  100. unsigned StartColumn) const = 0;
  101. /// Returns the number of columns required to format the text following
  102. /// the byte \p Offset in the line \p LineIndex, including potentially
  103. /// unbreakable sequences of tokens following after the end of the token.
  104. ///
  105. /// \p Offset is the byte offset from the start of the content of the line
  106. /// at \p LineIndex.
  107. ///
  108. /// \p StartColumn is the column at which the text starts in the formatted
  109. /// file, needed to compute tab stops correctly.
  110. ///
  111. /// For breakable tokens that never use extra space at the end of a line, this
  112. /// is equivalent to getRangeLength with a Length of StringRef::npos.
  113. virtual unsigned getRemainingLength(unsigned LineIndex, unsigned Offset,
  114. unsigned StartColumn) const {
  115. return getRangeLength(LineIndex, Offset, StringRef::npos, StartColumn);
  116. }
  117. /// Returns the column at which content in line \p LineIndex starts,
  118. /// assuming no reflow.
  119. ///
  120. /// If \p Break is true, returns the column at which the line should start
  121. /// after the line break.
  122. /// If \p Break is false, returns the column at which the line itself will
  123. /// start.
  124. virtual unsigned getContentStartColumn(unsigned LineIndex,
  125. bool Break) const = 0;
  126. /// Returns additional content indent required for the second line after the
  127. /// content at line \p LineIndex is broken.
  128. ///
  129. // (Next lines do not start with `///` since otherwise -Wdocumentation picks
  130. // up the example annotations and generates warnings for them)
  131. // For example, Javadoc @param annotations require and indent of 4 spaces and
  132. // in this example getContentIndex(1) returns 4.
  133. // /**
  134. // * @param loooooooooooooong line
  135. // * continuation
  136. // */
  137. virtual unsigned getContentIndent(unsigned LineIndex) const { return 0; }
  138. /// Returns a range (offset, length) at which to break the line at
  139. /// \p LineIndex, if previously broken at \p TailOffset. If possible, do not
  140. /// violate \p ColumnLimit, assuming the text starting at \p TailOffset in
  141. /// the token is formatted starting at ContentStartColumn in the reformatted
  142. /// file.
  143. virtual Split getSplit(unsigned LineIndex, unsigned TailOffset,
  144. unsigned ColumnLimit, unsigned ContentStartColumn,
  145. const llvm::Regex &CommentPragmasRegex) const = 0;
  146. /// Emits the previously retrieved \p Split via \p Whitespaces.
  147. virtual void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split,
  148. unsigned ContentIndent,
  149. WhitespaceManager &Whitespaces) const = 0;
  150. /// Returns the number of columns needed to format
  151. /// \p RemainingTokenColumns, assuming that Split is within the range measured
  152. /// by \p RemainingTokenColumns, and that the whitespace in Split is reduced
  153. /// to a single space.
  154. unsigned getLengthAfterCompression(unsigned RemainingTokenColumns,
  155. Split Split) const;
  156. /// Replaces the whitespace range described by \p Split with a single
  157. /// space.
  158. virtual void compressWhitespace(unsigned LineIndex, unsigned TailOffset,
  159. Split Split,
  160. WhitespaceManager &Whitespaces) const = 0;
  161. /// Returns whether the token supports reflowing text.
  162. virtual bool supportsReflow() const { return false; }
  163. /// Returns a whitespace range (offset, length) of the content at \p
  164. /// LineIndex such that the content of that line is reflown to the end of the
  165. /// previous one.
  166. ///
  167. /// Returning (StringRef::npos, 0) indicates reflowing is not possible.
  168. ///
  169. /// The range will include any whitespace preceding the specified line's
  170. /// content.
  171. ///
  172. /// If the split is not contained within one token, for example when reflowing
  173. /// line comments, returns (0, <length>).
  174. virtual Split getReflowSplit(unsigned LineIndex,
  175. const llvm::Regex &CommentPragmasRegex) const {
  176. return Split(StringRef::npos, 0);
  177. }
  178. /// Reflows the current line into the end of the previous one.
  179. virtual void reflow(unsigned LineIndex,
  180. WhitespaceManager &Whitespaces) const {}
  181. /// Returns whether there will be a line break at the start of the
  182. /// token.
  183. virtual bool introducesBreakBeforeToken() const { return false; }
  184. /// Replaces the whitespace between \p LineIndex-1 and \p LineIndex.
  185. virtual void adaptStartOfLine(unsigned LineIndex,
  186. WhitespaceManager &Whitespaces) const {}
  187. /// Returns a whitespace range (offset, length) of the content at
  188. /// the last line that needs to be reformatted after the last line has been
  189. /// reformatted.
  190. ///
  191. /// A result having offset == StringRef::npos means that no reformat is
  192. /// necessary.
  193. virtual Split getSplitAfterLastLine(unsigned TailOffset) const {
  194. return Split(StringRef::npos, 0);
  195. }
  196. /// Replaces the whitespace from \p SplitAfterLastLine on the last line
  197. /// after the last line has been formatted by performing a reformatting.
  198. void replaceWhitespaceAfterLastLine(unsigned TailOffset,
  199. Split SplitAfterLastLine,
  200. WhitespaceManager &Whitespaces) const {
  201. insertBreak(getLineCount() - 1, TailOffset, SplitAfterLastLine,
  202. /*ContentIndent=*/0, Whitespaces);
  203. }
  204. /// Updates the next token of \p State to the next token after this
  205. /// one. This can be used when this token manages a set of underlying tokens
  206. /// as a unit and is responsible for the formatting of the them.
  207. virtual void updateNextToken(LineState &State) const {}
  208. protected:
  209. BreakableToken(const FormatToken &Tok, bool InPPDirective,
  210. encoding::Encoding Encoding, const FormatStyle &Style)
  211. : Tok(Tok), InPPDirective(InPPDirective), Encoding(Encoding),
  212. Style(Style) {}
  213. const FormatToken &Tok;
  214. const bool InPPDirective;
  215. const encoding::Encoding Encoding;
  216. const FormatStyle &Style;
  217. };
  218. class BreakableStringLiteral : public BreakableToken {
  219. public:
  220. /// Creates a breakable token for a single line string literal.
  221. ///
  222. /// \p StartColumn specifies the column in which the token will start
  223. /// after formatting.
  224. BreakableStringLiteral(const FormatToken &Tok, unsigned StartColumn,
  225. StringRef Prefix, StringRef Postfix,
  226. unsigned UnbreakableTailLength, bool InPPDirective,
  227. encoding::Encoding Encoding, const FormatStyle &Style);
  228. Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
  229. unsigned ContentStartColumn,
  230. const llvm::Regex &CommentPragmasRegex) const override;
  231. void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split,
  232. unsigned ContentIndent,
  233. WhitespaceManager &Whitespaces) const override;
  234. void compressWhitespace(unsigned LineIndex, unsigned TailOffset, Split Split,
  235. WhitespaceManager &Whitespaces) const override {}
  236. unsigned getLineCount() const override;
  237. unsigned getRangeLength(unsigned LineIndex, unsigned Offset,
  238. StringRef::size_type Length,
  239. unsigned StartColumn) const override;
  240. unsigned getRemainingLength(unsigned LineIndex, unsigned Offset,
  241. unsigned StartColumn) const override;
  242. unsigned getContentStartColumn(unsigned LineIndex, bool Break) const override;
  243. protected:
  244. // The column in which the token starts.
  245. unsigned StartColumn;
  246. // The prefix a line needs after a break in the token.
  247. StringRef Prefix;
  248. // The postfix a line needs before introducing a break.
  249. StringRef Postfix;
  250. // The token text excluding the prefix and postfix.
  251. StringRef Line;
  252. // Length of the sequence of tokens after this string literal that cannot
  253. // contain line breaks.
  254. unsigned UnbreakableTailLength;
  255. };
  256. class BreakableComment : public BreakableToken {
  257. protected:
  258. /// Creates a breakable token for a comment.
  259. ///
  260. /// \p StartColumn specifies the column in which the comment will start after
  261. /// formatting.
  262. BreakableComment(const FormatToken &Token, unsigned StartColumn,
  263. bool InPPDirective, encoding::Encoding Encoding,
  264. const FormatStyle &Style);
  265. public:
  266. bool supportsReflow() const override { return true; }
  267. unsigned getLineCount() const override;
  268. Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
  269. unsigned ContentStartColumn,
  270. const llvm::Regex &CommentPragmasRegex) const override;
  271. void compressWhitespace(unsigned LineIndex, unsigned TailOffset, Split Split,
  272. WhitespaceManager &Whitespaces) const override;
  273. protected:
  274. // Returns the token containing the line at LineIndex.
  275. const FormatToken &tokenAt(unsigned LineIndex) const;
  276. // Checks if the content of line LineIndex may be reflown with the previous
  277. // line.
  278. virtual bool mayReflow(unsigned LineIndex,
  279. const llvm::Regex &CommentPragmasRegex) const = 0;
  280. // Contains the original text of the lines of the block comment.
  281. //
  282. // In case of a block comments, excludes the leading /* in the first line and
  283. // trailing */ in the last line. In case of line comments, excludes the
  284. // leading // and spaces.
  285. SmallVector<StringRef, 16> Lines;
  286. // Contains the text of the lines excluding all leading and trailing
  287. // whitespace between the lines. Note that the decoration (if present) is also
  288. // not considered part of the text.
  289. SmallVector<StringRef, 16> Content;
  290. // Tokens[i] contains a reference to the token containing Lines[i] if the
  291. // whitespace range before that token is managed by this block.
  292. // Otherwise, Tokens[i] is a null pointer.
  293. SmallVector<FormatToken *, 16> Tokens;
  294. // ContentColumn[i] is the target column at which Content[i] should be.
  295. // Note that this excludes a leading "* " or "*" in case of block comments
  296. // where all lines have a "*" prefix, or the leading "// " or "//" in case of
  297. // line comments.
  298. //
  299. // In block comments, the first line's target column is always positive. The
  300. // remaining lines' target columns are relative to the first line to allow
  301. // correct indentation of comments in \c WhitespaceManager. Thus they can be
  302. // negative as well (in case the first line needs to be unindented more than
  303. // there's actual whitespace in another line).
  304. SmallVector<int, 16> ContentColumn;
  305. // The intended start column of the first line of text from this section.
  306. unsigned StartColumn;
  307. // The prefix to use in front a line that has been reflown up.
  308. // For example, when reflowing the second line after the first here:
  309. // // comment 1
  310. // // comment 2
  311. // we expect:
  312. // // comment 1 comment 2
  313. // and not:
  314. // // comment 1comment 2
  315. StringRef ReflowPrefix = " ";
  316. };
  317. class BreakableBlockComment : public BreakableComment {
  318. public:
  319. BreakableBlockComment(const FormatToken &Token, unsigned StartColumn,
  320. unsigned OriginalStartColumn, bool FirstInLine,
  321. bool InPPDirective, encoding::Encoding Encoding,
  322. const FormatStyle &Style, bool UseCRLF);
  323. Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
  324. unsigned ContentStartColumn,
  325. const llvm::Regex &CommentPragmasRegex) const override;
  326. unsigned getRangeLength(unsigned LineIndex, unsigned Offset,
  327. StringRef::size_type Length,
  328. unsigned StartColumn) const override;
  329. unsigned getRemainingLength(unsigned LineIndex, unsigned Offset,
  330. unsigned StartColumn) const override;
  331. unsigned getContentStartColumn(unsigned LineIndex, bool Break) const override;
  332. unsigned getContentIndent(unsigned LineIndex) const override;
  333. void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split,
  334. unsigned ContentIndent,
  335. WhitespaceManager &Whitespaces) const override;
  336. Split getReflowSplit(unsigned LineIndex,
  337. const llvm::Regex &CommentPragmasRegex) const override;
  338. void reflow(unsigned LineIndex,
  339. WhitespaceManager &Whitespaces) const override;
  340. bool introducesBreakBeforeToken() const override;
  341. void adaptStartOfLine(unsigned LineIndex,
  342. WhitespaceManager &Whitespaces) const override;
  343. Split getSplitAfterLastLine(unsigned TailOffset) const override;
  344. bool mayReflow(unsigned LineIndex,
  345. const llvm::Regex &CommentPragmasRegex) const override;
  346. // Contains Javadoc annotations that require additional indent when continued
  347. // on multiple lines.
  348. static const llvm::StringSet<> ContentIndentingJavadocAnnotations;
  349. private:
  350. // Rearranges the whitespace between Lines[LineIndex-1] and Lines[LineIndex].
  351. //
  352. // Updates Content[LineIndex-1] and Content[LineIndex] by stripping off
  353. // leading and trailing whitespace.
  354. //
  355. // Sets ContentColumn to the intended column in which the text at
  356. // Lines[LineIndex] starts (note that the decoration, if present, is not
  357. // considered part of the text).
  358. void adjustWhitespace(unsigned LineIndex, int IndentDelta);
  359. // The column at which the text of a broken line should start.
  360. // Note that an optional decoration would go before that column.
  361. // IndentAtLineBreak is a uniform position for all lines in a block comment,
  362. // regardless of their relative position.
  363. // FIXME: Revisit the decision to do this; the main reason was to support
  364. // patterns like
  365. // /**************//**
  366. // * Comment
  367. // We could also support such patterns by special casing the first line
  368. // instead.
  369. unsigned IndentAtLineBreak;
  370. // This is to distinguish between the case when the last line was empty and
  371. // the case when it started with a decoration ("*" or "* ").
  372. bool LastLineNeedsDecoration;
  373. // Either "* " if all lines begin with a "*", or empty.
  374. StringRef Decoration;
  375. // If this block comment has decorations, this is the column of the start of
  376. // the decorations.
  377. unsigned DecorationColumn;
  378. // If true, make sure that the opening '/**' and the closing '*/' ends on a
  379. // line of itself. Styles like jsdoc require this for multiline comments.
  380. bool DelimitersOnNewline;
  381. // Length of the sequence of tokens after this string literal that cannot
  382. // contain line breaks.
  383. unsigned UnbreakableTailLength;
  384. };
  385. class BreakableLineCommentSection : public BreakableComment {
  386. public:
  387. BreakableLineCommentSection(const FormatToken &Token, unsigned StartColumn,
  388. bool InPPDirective, encoding::Encoding Encoding,
  389. const FormatStyle &Style);
  390. unsigned getRangeLength(unsigned LineIndex, unsigned Offset,
  391. StringRef::size_type Length,
  392. unsigned StartColumn) const override;
  393. unsigned getContentStartColumn(unsigned LineIndex, bool Break) const override;
  394. void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split,
  395. unsigned ContentIndent,
  396. WhitespaceManager &Whitespaces) const override;
  397. Split getReflowSplit(unsigned LineIndex,
  398. const llvm::Regex &CommentPragmasRegex) const override;
  399. void reflow(unsigned LineIndex,
  400. WhitespaceManager &Whitespaces) const override;
  401. void adaptStartOfLine(unsigned LineIndex,
  402. WhitespaceManager &Whitespaces) const override;
  403. void updateNextToken(LineState &State) const override;
  404. bool mayReflow(unsigned LineIndex,
  405. const llvm::Regex &CommentPragmasRegex) const override;
  406. private:
  407. // OriginalPrefix[i] contains the original prefix of line i, including
  408. // trailing whitespace before the start of the content. The indentation
  409. // preceding the prefix is not included.
  410. // For example, if the line is:
  411. // // content
  412. // then the original prefix is "// ".
  413. SmallVector<StringRef, 16> OriginalPrefix;
  414. /// Prefix[i] + SpacesToAdd[i] contains the intended leading "//" with
  415. /// trailing spaces to account for the indentation of content within the
  416. /// comment at line i after formatting. It can be different than the original
  417. /// prefix.
  418. /// When the original line starts like this:
  419. /// //content
  420. /// Then the OriginalPrefix[i] is "//", but the Prefix[i] is "// " in the LLVM
  421. /// style.
  422. /// When the line starts like:
  423. /// // content
  424. /// And we want to remove the spaces the OriginalPrefix[i] is "// " and
  425. /// Prefix[i] is "//".
  426. SmallVector<std::string, 16> Prefix;
  427. /// How many spaces are added or removed from the OriginalPrefix to form
  428. /// Prefix.
  429. SmallVector<int, 16> PrefixSpaceChange;
  430. /// The token to which the last line of this breakable token belongs
  431. /// to; nullptr if that token is the initial token.
  432. ///
  433. /// The distinction is because if the token of the last line of this breakable
  434. /// token is distinct from the initial token, this breakable token owns the
  435. /// whitespace before the token of the last line, and the whitespace manager
  436. /// must be able to modify it.
  437. FormatToken *LastLineTok = nullptr;
  438. };
  439. } // namespace format
  440. } // namespace clang
  441. #endif