ContinuationIndenter.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. //===--- ContinuationIndenter.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. /// This file implements an indenter that manages the indentation of
  11. /// continuations.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_CLANG_LIB_FORMAT_CONTINUATIONINDENTER_H
  15. #define LLVM_CLANG_LIB_FORMAT_CONTINUATIONINDENTER_H
  16. #include "Encoding.h"
  17. #include "FormatToken.h"
  18. #include "clang/Format/Format.h"
  19. #include "llvm/Support/Regex.h"
  20. #include <map>
  21. #include <optional>
  22. #include <tuple>
  23. namespace clang {
  24. class SourceManager;
  25. namespace format {
  26. class AnnotatedLine;
  27. class BreakableToken;
  28. struct FormatToken;
  29. struct LineState;
  30. struct ParenState;
  31. struct RawStringFormatStyleManager;
  32. class WhitespaceManager;
  33. struct RawStringFormatStyleManager {
  34. llvm::StringMap<FormatStyle> DelimiterStyle;
  35. llvm::StringMap<FormatStyle> EnclosingFunctionStyle;
  36. RawStringFormatStyleManager(const FormatStyle &CodeStyle);
  37. std::optional<FormatStyle> getDelimiterStyle(StringRef Delimiter) const;
  38. std::optional<FormatStyle>
  39. getEnclosingFunctionStyle(StringRef EnclosingFunction) const;
  40. };
  41. class ContinuationIndenter {
  42. public:
  43. /// Constructs a \c ContinuationIndenter to format \p Line starting in
  44. /// column \p FirstIndent.
  45. ContinuationIndenter(const FormatStyle &Style,
  46. const AdditionalKeywords &Keywords,
  47. const SourceManager &SourceMgr,
  48. WhitespaceManager &Whitespaces,
  49. encoding::Encoding Encoding,
  50. bool BinPackInconclusiveFunctions);
  51. /// Get the initial state, i.e. the state after placing \p Line's
  52. /// first token at \p FirstIndent. When reformatting a fragment of code, as in
  53. /// the case of formatting inside raw string literals, \p FirstStartColumn is
  54. /// the column at which the state of the parent formatter is.
  55. LineState getInitialState(unsigned FirstIndent, unsigned FirstStartColumn,
  56. const AnnotatedLine *Line, bool DryRun);
  57. // FIXME: canBreak and mustBreak aren't strictly indentation-related. Find a
  58. // better home.
  59. /// Returns \c true, if a line break after \p State is allowed.
  60. bool canBreak(const LineState &State);
  61. /// Returns \c true, if a line break after \p State is mandatory.
  62. bool mustBreak(const LineState &State);
  63. /// Appends the next token to \p State and updates information
  64. /// necessary for indentation.
  65. ///
  66. /// Puts the token on the current line if \p Newline is \c false and adds a
  67. /// line break and necessary indentation otherwise.
  68. ///
  69. /// If \p DryRun is \c false, also creates and stores the required
  70. /// \c Replacement.
  71. unsigned addTokenToState(LineState &State, bool Newline, bool DryRun,
  72. unsigned ExtraSpaces = 0);
  73. /// Get the column limit for this line. This is the style's column
  74. /// limit, potentially reduced for preprocessor definitions.
  75. unsigned getColumnLimit(const LineState &State) const;
  76. private:
  77. /// Mark the next token as consumed in \p State and modify its stacks
  78. /// accordingly.
  79. unsigned moveStateToNextToken(LineState &State, bool DryRun, bool Newline);
  80. /// Update 'State' according to the next token's fake left parentheses.
  81. void moveStatePastFakeLParens(LineState &State, bool Newline);
  82. /// Update 'State' according to the next token's fake r_parens.
  83. void moveStatePastFakeRParens(LineState &State);
  84. /// Update 'State' according to the next token being one of "(<{[".
  85. void moveStatePastScopeOpener(LineState &State, bool Newline);
  86. /// Update 'State' according to the next token being one of ")>}]".
  87. void moveStatePastScopeCloser(LineState &State);
  88. /// Update 'State' with the next token opening a nested block.
  89. void moveStateToNewBlock(LineState &State);
  90. /// Reformats a raw string literal.
  91. ///
  92. /// \returns An extra penalty induced by reformatting the token.
  93. unsigned reformatRawStringLiteral(const FormatToken &Current,
  94. LineState &State,
  95. const FormatStyle &RawStringStyle,
  96. bool DryRun, bool Newline);
  97. /// If the current token is at the end of the current line, handle
  98. /// the transition to the next line.
  99. unsigned handleEndOfLine(const FormatToken &Current, LineState &State,
  100. bool DryRun, bool AllowBreak, bool Newline);
  101. /// If \p Current is a raw string that is configured to be reformatted,
  102. /// return the style to be used.
  103. std::optional<FormatStyle> getRawStringStyle(const FormatToken &Current,
  104. const LineState &State);
  105. /// If the current token sticks out over the end of the line, break
  106. /// it if possible.
  107. ///
  108. /// \returns A pair (penalty, exceeded), where penalty is the extra penalty
  109. /// when tokens are broken or lines exceed the column limit, and exceeded
  110. /// indicates whether the algorithm purposefully left lines exceeding the
  111. /// column limit.
  112. ///
  113. /// The returned penalty will cover the cost of the additional line breaks
  114. /// and column limit violation in all lines except for the last one. The
  115. /// penalty for the column limit violation in the last line (and in single
  116. /// line tokens) is handled in \c addNextStateToQueue.
  117. ///
  118. /// \p Strict indicates whether reflowing is allowed to leave characters
  119. /// protruding the column limit; if true, lines will be split strictly within
  120. /// the column limit where possible; if false, words are allowed to protrude
  121. /// over the column limit as long as the penalty is less than the penalty
  122. /// of a break.
  123. std::pair<unsigned, bool> breakProtrudingToken(const FormatToken &Current,
  124. LineState &State,
  125. bool AllowBreak, bool DryRun,
  126. bool Strict);
  127. /// Returns the \c BreakableToken starting at \p Current, or nullptr
  128. /// if the current token cannot be broken.
  129. std::unique_ptr<BreakableToken>
  130. createBreakableToken(const FormatToken &Current, LineState &State,
  131. bool AllowBreak);
  132. /// Appends the next token to \p State and updates information
  133. /// necessary for indentation.
  134. ///
  135. /// Puts the token on the current line.
  136. ///
  137. /// If \p DryRun is \c false, also creates and stores the required
  138. /// \c Replacement.
  139. void addTokenOnCurrentLine(LineState &State, bool DryRun,
  140. unsigned ExtraSpaces);
  141. /// Appends the next token to \p State and updates information
  142. /// necessary for indentation.
  143. ///
  144. /// Adds a line break and necessary indentation.
  145. ///
  146. /// If \p DryRun is \c false, also creates and stores the required
  147. /// \c Replacement.
  148. unsigned addTokenOnNewLine(LineState &State, bool DryRun);
  149. /// Calculate the new column for a line wrap before the next token.
  150. unsigned getNewLineColumn(const LineState &State);
  151. /// Adds a multiline token to the \p State.
  152. ///
  153. /// \returns Extra penalty for the first line of the literal: last line is
  154. /// handled in \c addNextStateToQueue, and the penalty for other lines doesn't
  155. /// matter, as we don't change them.
  156. unsigned addMultilineToken(const FormatToken &Current, LineState &State);
  157. /// Returns \c true if the next token starts a multiline string
  158. /// literal.
  159. ///
  160. /// This includes implicitly concatenated strings, strings that will be broken
  161. /// by clang-format and string literals with escaped newlines.
  162. bool nextIsMultilineString(const LineState &State);
  163. FormatStyle Style;
  164. const AdditionalKeywords &Keywords;
  165. const SourceManager &SourceMgr;
  166. WhitespaceManager &Whitespaces;
  167. encoding::Encoding Encoding;
  168. bool BinPackInconclusiveFunctions;
  169. llvm::Regex CommentPragmasRegex;
  170. const RawStringFormatStyleManager RawStringFormats;
  171. };
  172. struct ParenState {
  173. ParenState(const FormatToken *Tok, unsigned Indent, unsigned LastSpace,
  174. bool AvoidBinPacking, bool NoLineBreak)
  175. : Tok(Tok), Indent(Indent), LastSpace(LastSpace),
  176. NestedBlockIndent(Indent), IsAligned(false),
  177. BreakBeforeClosingBrace(false), BreakBeforeClosingParen(false),
  178. AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
  179. NoLineBreak(NoLineBreak), NoLineBreakInOperand(false),
  180. LastOperatorWrapped(true), ContainsLineBreak(false),
  181. ContainsUnwrappedBuilder(false), AlignColons(true),
  182. ObjCSelectorNameFound(false), HasMultipleNestedBlocks(false),
  183. NestedBlockInlined(false), IsInsideObjCArrayLiteral(false),
  184. IsCSharpGenericTypeConstraint(false), IsChainedConditional(false),
  185. IsWrappedConditional(false), UnindentOperator(false) {}
  186. /// \brief The token opening this parenthesis level, or nullptr if this level
  187. /// is opened by fake parenthesis.
  188. ///
  189. /// Not considered for memoization as it will always have the same value at
  190. /// the same token.
  191. const FormatToken *Tok;
  192. /// The position to which a specific parenthesis level needs to be
  193. /// indented.
  194. unsigned Indent;
  195. /// The position of the last space on each level.
  196. ///
  197. /// Used e.g. to break like:
  198. /// functionCall(Parameter, otherCall(
  199. /// OtherParameter));
  200. unsigned LastSpace;
  201. /// If a block relative to this parenthesis level gets wrapped, indent
  202. /// it this much.
  203. unsigned NestedBlockIndent;
  204. /// The position the first "<<" operator encountered on each level.
  205. ///
  206. /// Used to align "<<" operators. 0 if no such operator has been encountered
  207. /// on a level.
  208. unsigned FirstLessLess = 0;
  209. /// The column of a \c ? in a conditional expression;
  210. unsigned QuestionColumn = 0;
  211. /// The position of the colon in an ObjC method declaration/call.
  212. unsigned ColonPos = 0;
  213. /// The start of the most recent function in a builder-type call.
  214. unsigned StartOfFunctionCall = 0;
  215. /// Contains the start of array subscript expressions, so that they
  216. /// can be aligned.
  217. unsigned StartOfArraySubscripts = 0;
  218. /// If a nested name specifier was broken over multiple lines, this
  219. /// contains the start column of the second line. Otherwise 0.
  220. unsigned NestedNameSpecifierContinuation = 0;
  221. /// If a call expression was broken over multiple lines, this
  222. /// contains the start column of the second line. Otherwise 0.
  223. unsigned CallContinuation = 0;
  224. /// The column of the first variable name in a variable declaration.
  225. ///
  226. /// Used to align further variables if necessary.
  227. unsigned VariablePos = 0;
  228. /// Whether this block's indentation is used for alignment.
  229. bool IsAligned : 1;
  230. /// Whether a newline needs to be inserted before the block's closing
  231. /// brace.
  232. ///
  233. /// We only want to insert a newline before the closing brace if there also
  234. /// was a newline after the beginning left brace.
  235. bool BreakBeforeClosingBrace : 1;
  236. /// Whether a newline needs to be inserted before the block's closing
  237. /// paren.
  238. ///
  239. /// We only want to insert a newline before the closing paren if there also
  240. /// was a newline after the beginning left paren.
  241. bool BreakBeforeClosingParen : 1;
  242. /// Avoid bin packing, i.e. multiple parameters/elements on multiple
  243. /// lines, in this context.
  244. bool AvoidBinPacking : 1;
  245. /// Break after the next comma (or all the commas in this context if
  246. /// \c AvoidBinPacking is \c true).
  247. bool BreakBeforeParameter : 1;
  248. /// Line breaking in this context would break a formatting rule.
  249. bool NoLineBreak : 1;
  250. /// Same as \c NoLineBreak, but is restricted until the end of the
  251. /// operand (including the next ",").
  252. bool NoLineBreakInOperand : 1;
  253. /// True if the last binary operator on this level was wrapped to the
  254. /// next line.
  255. bool LastOperatorWrapped : 1;
  256. /// \c true if this \c ParenState already contains a line-break.
  257. ///
  258. /// The first line break in a certain \c ParenState causes extra penalty so
  259. /// that clang-format prefers similar breaks, i.e. breaks in the same
  260. /// parenthesis.
  261. bool ContainsLineBreak : 1;
  262. /// \c true if this \c ParenState contains multiple segments of a
  263. /// builder-type call on one line.
  264. bool ContainsUnwrappedBuilder : 1;
  265. /// \c true if the colons of the curren ObjC method expression should
  266. /// be aligned.
  267. ///
  268. /// Not considered for memoization as it will always have the same value at
  269. /// the same token.
  270. bool AlignColons : 1;
  271. /// \c true if at least one selector name was found in the current
  272. /// ObjC method expression.
  273. ///
  274. /// Not considered for memoization as it will always have the same value at
  275. /// the same token.
  276. bool ObjCSelectorNameFound : 1;
  277. /// \c true if there are multiple nested blocks inside these parens.
  278. ///
  279. /// Not considered for memoization as it will always have the same value at
  280. /// the same token.
  281. bool HasMultipleNestedBlocks : 1;
  282. /// The start of a nested block (e.g. lambda introducer in C++ or
  283. /// "function" in JavaScript) is not wrapped to a new line.
  284. bool NestedBlockInlined : 1;
  285. /// \c true if the current \c ParenState represents an Objective-C
  286. /// array literal.
  287. bool IsInsideObjCArrayLiteral : 1;
  288. bool IsCSharpGenericTypeConstraint : 1;
  289. /// \brief true if the current \c ParenState represents the false branch of
  290. /// a chained conditional expression (e.g. else-if)
  291. bool IsChainedConditional : 1;
  292. /// \brief true if there conditionnal was wrapped on the first operator (the
  293. /// question mark)
  294. bool IsWrappedConditional : 1;
  295. /// \brief Indicates the indent should be reduced by the length of the
  296. /// operator.
  297. bool UnindentOperator : 1;
  298. bool operator<(const ParenState &Other) const {
  299. if (Indent != Other.Indent)
  300. return Indent < Other.Indent;
  301. if (LastSpace != Other.LastSpace)
  302. return LastSpace < Other.LastSpace;
  303. if (NestedBlockIndent != Other.NestedBlockIndent)
  304. return NestedBlockIndent < Other.NestedBlockIndent;
  305. if (FirstLessLess != Other.FirstLessLess)
  306. return FirstLessLess < Other.FirstLessLess;
  307. if (IsAligned != Other.IsAligned)
  308. return IsAligned;
  309. if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
  310. return BreakBeforeClosingBrace;
  311. if (BreakBeforeClosingParen != Other.BreakBeforeClosingParen)
  312. return BreakBeforeClosingParen;
  313. if (QuestionColumn != Other.QuestionColumn)
  314. return QuestionColumn < Other.QuestionColumn;
  315. if (AvoidBinPacking != Other.AvoidBinPacking)
  316. return AvoidBinPacking;
  317. if (BreakBeforeParameter != Other.BreakBeforeParameter)
  318. return BreakBeforeParameter;
  319. if (NoLineBreak != Other.NoLineBreak)
  320. return NoLineBreak;
  321. if (LastOperatorWrapped != Other.LastOperatorWrapped)
  322. return LastOperatorWrapped;
  323. if (ColonPos != Other.ColonPos)
  324. return ColonPos < Other.ColonPos;
  325. if (StartOfFunctionCall != Other.StartOfFunctionCall)
  326. return StartOfFunctionCall < Other.StartOfFunctionCall;
  327. if (StartOfArraySubscripts != Other.StartOfArraySubscripts)
  328. return StartOfArraySubscripts < Other.StartOfArraySubscripts;
  329. if (CallContinuation != Other.CallContinuation)
  330. return CallContinuation < Other.CallContinuation;
  331. if (VariablePos != Other.VariablePos)
  332. return VariablePos < Other.VariablePos;
  333. if (ContainsLineBreak != Other.ContainsLineBreak)
  334. return ContainsLineBreak;
  335. if (ContainsUnwrappedBuilder != Other.ContainsUnwrappedBuilder)
  336. return ContainsUnwrappedBuilder;
  337. if (NestedBlockInlined != Other.NestedBlockInlined)
  338. return NestedBlockInlined;
  339. if (IsCSharpGenericTypeConstraint != Other.IsCSharpGenericTypeConstraint)
  340. return IsCSharpGenericTypeConstraint;
  341. if (IsChainedConditional != Other.IsChainedConditional)
  342. return IsChainedConditional;
  343. if (IsWrappedConditional != Other.IsWrappedConditional)
  344. return IsWrappedConditional;
  345. if (UnindentOperator != Other.UnindentOperator)
  346. return UnindentOperator;
  347. return false;
  348. }
  349. };
  350. /// The current state when indenting a unwrapped line.
  351. ///
  352. /// As the indenting tries different combinations this is copied by value.
  353. struct LineState {
  354. /// The number of used columns in the current line.
  355. unsigned Column;
  356. /// The token that needs to be next formatted.
  357. FormatToken *NextToken;
  358. /// \c true if \p NextToken should not continue this line.
  359. bool NoContinuation;
  360. /// The \c NestingLevel at the start of this line.
  361. unsigned StartOfLineLevel;
  362. /// The lowest \c NestingLevel on the current line.
  363. unsigned LowestLevelOnLine;
  364. /// The start column of the string literal, if we're in a string
  365. /// literal sequence, 0 otherwise.
  366. unsigned StartOfStringLiteral;
  367. /// A stack keeping track of properties applying to parenthesis
  368. /// levels.
  369. SmallVector<ParenState> Stack;
  370. /// Ignore the stack of \c ParenStates for state comparison.
  371. ///
  372. /// In long and deeply nested unwrapped lines, the current algorithm can
  373. /// be insufficient for finding the best formatting with a reasonable amount
  374. /// of time and memory. Setting this flag will effectively lead to the
  375. /// algorithm not analyzing some combinations. However, these combinations
  376. /// rarely contain the optimal solution: In short, accepting a higher
  377. /// penalty early would need to lead to different values in the \c
  378. /// ParenState stack (in an otherwise identical state) and these different
  379. /// values would need to lead to a significant amount of avoided penalty
  380. /// later.
  381. ///
  382. /// FIXME: Come up with a better algorithm instead.
  383. bool IgnoreStackForComparison;
  384. /// The indent of the first token.
  385. unsigned FirstIndent;
  386. /// The line that is being formatted.
  387. ///
  388. /// Does not need to be considered for memoization because it doesn't change.
  389. const AnnotatedLine *Line;
  390. /// Comparison operator to be able to used \c LineState in \c map.
  391. bool operator<(const LineState &Other) const {
  392. if (NextToken != Other.NextToken)
  393. return NextToken < Other.NextToken;
  394. if (Column != Other.Column)
  395. return Column < Other.Column;
  396. if (NoContinuation != Other.NoContinuation)
  397. return NoContinuation;
  398. if (StartOfLineLevel != Other.StartOfLineLevel)
  399. return StartOfLineLevel < Other.StartOfLineLevel;
  400. if (LowestLevelOnLine != Other.LowestLevelOnLine)
  401. return LowestLevelOnLine < Other.LowestLevelOnLine;
  402. if (StartOfStringLiteral != Other.StartOfStringLiteral)
  403. return StartOfStringLiteral < Other.StartOfStringLiteral;
  404. if (IgnoreStackForComparison || Other.IgnoreStackForComparison)
  405. return false;
  406. return Stack < Other.Stack;
  407. }
  408. };
  409. } // end namespace format
  410. } // end namespace clang
  411. #endif