ContinuationIndenter.h 17 KB

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