UnwrappedLineFormatter.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. //===--- UnwrappedLineFormatter.cpp - Format C++ code ---------------------===//
  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. #include "UnwrappedLineFormatter.h"
  9. #include "NamespaceEndCommentsFixer.h"
  10. #include "WhitespaceManager.h"
  11. #include "llvm/Support/Debug.h"
  12. #include <queue>
  13. #define DEBUG_TYPE "format-formatter"
  14. namespace clang {
  15. namespace format {
  16. namespace {
  17. bool startsExternCBlock(const AnnotatedLine &Line) {
  18. const FormatToken *Next = Line.First->getNextNonComment();
  19. const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr;
  20. return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() &&
  21. NextNext && NextNext->is(tok::l_brace);
  22. }
  23. /// Tracks the indent level of \c AnnotatedLines across levels.
  24. ///
  25. /// \c nextLine must be called for each \c AnnotatedLine, after which \c
  26. /// getIndent() will return the indent for the last line \c nextLine was called
  27. /// with.
  28. /// If the line is not formatted (and thus the indent does not change), calling
  29. /// \c adjustToUnmodifiedLine after the call to \c nextLine will cause
  30. /// subsequent lines on the same level to be indented at the same level as the
  31. /// given line.
  32. class LevelIndentTracker {
  33. public:
  34. LevelIndentTracker(const FormatStyle &Style,
  35. const AdditionalKeywords &Keywords, unsigned StartLevel,
  36. int AdditionalIndent)
  37. : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) {
  38. for (unsigned i = 0; i != StartLevel; ++i)
  39. IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
  40. }
  41. /// Returns the indent for the current line.
  42. unsigned getIndent() const { return Indent; }
  43. /// Update the indent state given that \p Line is going to be formatted
  44. /// next.
  45. void nextLine(const AnnotatedLine &Line) {
  46. Offset = getIndentOffset(*Line.First);
  47. // Update the indent level cache size so that we can rely on it
  48. // having the right size in adjustToUnmodifiedline.
  49. while (IndentForLevel.size() <= Line.Level)
  50. IndentForLevel.push_back(-1);
  51. if (Line.InPPDirective) {
  52. Indent = Line.Level * Style.IndentWidth + AdditionalIndent;
  53. } else {
  54. IndentForLevel.resize(Line.Level + 1);
  55. Indent = getIndent(IndentForLevel, Line.Level);
  56. }
  57. if (static_cast<int>(Indent) + Offset >= 0)
  58. Indent += Offset;
  59. }
  60. /// Update the indent state given that \p Line indent should be
  61. /// skipped.
  62. void skipLine(const AnnotatedLine &Line) {
  63. while (IndentForLevel.size() <= Line.Level)
  64. IndentForLevel.push_back(Indent);
  65. }
  66. /// Update the level indent to adapt to the given \p Line.
  67. ///
  68. /// When a line is not formatted, we move the subsequent lines on the same
  69. /// level to the same indent.
  70. /// Note that \c nextLine must have been called before this method.
  71. void adjustToUnmodifiedLine(const AnnotatedLine &Line) {
  72. unsigned LevelIndent = Line.First->OriginalColumn;
  73. if (static_cast<int>(LevelIndent) - Offset >= 0)
  74. LevelIndent -= Offset;
  75. if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
  76. !Line.InPPDirective)
  77. IndentForLevel[Line.Level] = LevelIndent;
  78. }
  79. private:
  80. /// Get the offset of the line relatively to the level.
  81. ///
  82. /// For example, 'public:' labels in classes are offset by 1 or 2
  83. /// characters to the left from their level.
  84. int getIndentOffset(const FormatToken &RootToken) {
  85. if (Style.Language == FormatStyle::LK_Java ||
  86. Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp())
  87. return 0;
  88. if (RootToken.isAccessSpecifier(false) ||
  89. RootToken.isObjCAccessSpecifier() ||
  90. (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
  91. RootToken.Next && RootToken.Next->is(tok::colon)))
  92. return Style.AccessModifierOffset;
  93. return 0;
  94. }
  95. /// Get the indent of \p Level from \p IndentForLevel.
  96. ///
  97. /// \p IndentForLevel must contain the indent for the level \c l
  98. /// at \p IndentForLevel[l], or a value < 0 if the indent for
  99. /// that level is unknown.
  100. unsigned getIndent(ArrayRef<int> IndentForLevel, unsigned Level) {
  101. if (IndentForLevel[Level] != -1)
  102. return IndentForLevel[Level];
  103. if (Level == 0)
  104. return 0;
  105. return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
  106. }
  107. const FormatStyle &Style;
  108. const AdditionalKeywords &Keywords;
  109. const unsigned AdditionalIndent;
  110. /// The indent in characters for each level.
  111. std::vector<int> IndentForLevel;
  112. /// Offset of the current line relative to the indent level.
  113. ///
  114. /// For example, the 'public' keywords is often indented with a negative
  115. /// offset.
  116. int Offset = 0;
  117. /// The current line's indent.
  118. unsigned Indent = 0;
  119. };
  120. const FormatToken *getMatchingNamespaceToken(
  121. const AnnotatedLine *Line,
  122. const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  123. if (!Line->startsWith(tok::r_brace))
  124. return nullptr;
  125. size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
  126. if (StartLineIndex == UnwrappedLine::kInvalidIndex)
  127. return nullptr;
  128. assert(StartLineIndex < AnnotatedLines.size());
  129. return AnnotatedLines[StartLineIndex]->First->getNamespaceToken();
  130. }
  131. StringRef getNamespaceTokenText(const AnnotatedLine *Line) {
  132. const FormatToken *NamespaceToken = Line->First->getNamespaceToken();
  133. return NamespaceToken ? NamespaceToken->TokenText : StringRef();
  134. }
  135. StringRef getMatchingNamespaceTokenText(
  136. const AnnotatedLine *Line,
  137. const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  138. const FormatToken *NamespaceToken =
  139. getMatchingNamespaceToken(Line, AnnotatedLines);
  140. return NamespaceToken ? NamespaceToken->TokenText : StringRef();
  141. }
  142. class LineJoiner {
  143. public:
  144. LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords,
  145. const SmallVectorImpl<AnnotatedLine *> &Lines)
  146. : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()),
  147. AnnotatedLines(Lines) {}
  148. /// Returns the next line, merging multiple lines into one if possible.
  149. const AnnotatedLine *getNextMergedLine(bool DryRun,
  150. LevelIndentTracker &IndentTracker) {
  151. if (Next == End)
  152. return nullptr;
  153. const AnnotatedLine *Current = *Next;
  154. IndentTracker.nextLine(*Current);
  155. unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End);
  156. if (MergedLines > 0 && Style.ColumnLimit == 0)
  157. // Disallow line merging if there is a break at the start of one of the
  158. // input lines.
  159. for (unsigned i = 0; i < MergedLines; ++i)
  160. if (Next[i + 1]->First->NewlinesBefore > 0)
  161. MergedLines = 0;
  162. if (!DryRun)
  163. for (unsigned i = 0; i < MergedLines; ++i)
  164. join(*Next[0], *Next[i + 1]);
  165. Next = Next + MergedLines + 1;
  166. return Current;
  167. }
  168. private:
  169. /// Calculates how many lines can be merged into 1 starting at \p I.
  170. unsigned
  171. tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker,
  172. SmallVectorImpl<AnnotatedLine *>::const_iterator I,
  173. SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
  174. const unsigned Indent = IndentTracker.getIndent();
  175. // Can't join the last line with anything.
  176. if (I + 1 == E)
  177. return 0;
  178. // We can never merge stuff if there are trailing line comments.
  179. const AnnotatedLine *TheLine = *I;
  180. if (TheLine->Last->is(TT_LineComment))
  181. return 0;
  182. if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
  183. return 0;
  184. if (TheLine->InPPDirective &&
  185. (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline))
  186. return 0;
  187. if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
  188. return 0;
  189. unsigned Limit =
  190. Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
  191. // If we already exceed the column limit, we set 'Limit' to 0. The different
  192. // tryMerge..() functions can then decide whether to still do merging.
  193. Limit = TheLine->Last->TotalLength > Limit
  194. ? 0
  195. : Limit - TheLine->Last->TotalLength;
  196. if (TheLine->Last->is(TT_FunctionLBrace) &&
  197. TheLine->First == TheLine->Last &&
  198. !Style.BraceWrapping.SplitEmptyFunction &&
  199. I[1]->First->is(tok::r_brace))
  200. return tryMergeSimpleBlock(I, E, Limit);
  201. // Handle empty record blocks where the brace has already been wrapped
  202. if (TheLine->Last->is(tok::l_brace) && TheLine->First == TheLine->Last &&
  203. I != AnnotatedLines.begin()) {
  204. bool EmptyBlock = I[1]->First->is(tok::r_brace);
  205. const FormatToken *Tok = I[-1]->First;
  206. if (Tok && Tok->is(tok::comment))
  207. Tok = Tok->getNextNonComment();
  208. if (Tok && Tok->getNamespaceToken())
  209. return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock
  210. ? tryMergeSimpleBlock(I, E, Limit)
  211. : 0;
  212. if (Tok && Tok->is(tok::kw_typedef))
  213. Tok = Tok->getNextNonComment();
  214. if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union,
  215. tok::kw_extern, Keywords.kw_interface))
  216. return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock
  217. ? tryMergeSimpleBlock(I, E, Limit)
  218. : 0;
  219. }
  220. // FIXME: TheLine->Level != 0 might or might not be the right check to do.
  221. // If necessary, change to something smarter.
  222. bool MergeShortFunctions =
  223. Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
  224. (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
  225. I[1]->First->is(tok::r_brace)) ||
  226. (Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly &&
  227. TheLine->Level != 0);
  228. if (Style.CompactNamespaces) {
  229. if (auto nsToken = TheLine->First->getNamespaceToken()) {
  230. int i = 0;
  231. unsigned closingLine = TheLine->MatchingClosingBlockLineIndex - 1;
  232. for (; I + 1 + i != E &&
  233. nsToken->TokenText == getNamespaceTokenText(I[i + 1]) &&
  234. closingLine == I[i + 1]->MatchingClosingBlockLineIndex &&
  235. I[i + 1]->Last->TotalLength < Limit;
  236. i++, closingLine--) {
  237. // No extra indent for compacted namespaces
  238. IndentTracker.skipLine(*I[i + 1]);
  239. Limit -= I[i + 1]->Last->TotalLength;
  240. }
  241. return i;
  242. }
  243. if (auto nsToken = getMatchingNamespaceToken(TheLine, AnnotatedLines)) {
  244. int i = 0;
  245. unsigned openingLine = TheLine->MatchingOpeningBlockLineIndex - 1;
  246. for (; I + 1 + i != E &&
  247. nsToken->TokenText ==
  248. getMatchingNamespaceTokenText(I[i + 1], AnnotatedLines) &&
  249. openingLine == I[i + 1]->MatchingOpeningBlockLineIndex;
  250. i++, openingLine--) {
  251. // No space between consecutive braces
  252. I[i + 1]->First->SpacesRequiredBefore = !I[i]->Last->is(tok::r_brace);
  253. // Indent like the outer-most namespace
  254. IndentTracker.nextLine(*I[i + 1]);
  255. }
  256. return i;
  257. }
  258. }
  259. // Try to merge a function block with left brace unwrapped
  260. if (TheLine->Last->is(TT_FunctionLBrace) &&
  261. TheLine->First != TheLine->Last) {
  262. return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
  263. }
  264. // Try to merge a control statement block with left brace unwrapped
  265. if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last &&
  266. TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
  267. return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never
  268. ? tryMergeSimpleBlock(I, E, Limit)
  269. : 0;
  270. }
  271. // Try to merge a control statement block with left brace wrapped
  272. if (I[1]->First->is(tok::l_brace) &&
  273. (TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
  274. tok::kw_switch, tok::kw_try, tok::kw_do) ||
  275. (TheLine->First->is(tok::r_brace) && TheLine->First->Next &&
  276. TheLine->First->Next->isOneOf(tok::kw_else, tok::kw_catch))) &&
  277. Style.BraceWrapping.AfterControlStatement ==
  278. FormatStyle::BWACS_MultiLine) {
  279. // If possible, merge the next line's wrapped left brace with the current
  280. // line. Otherwise, leave it on the next line, as this is a multi-line
  281. // control statement.
  282. return (Style.ColumnLimit == 0 ||
  283. TheLine->Last->TotalLength <= Style.ColumnLimit)
  284. ? 1
  285. : 0;
  286. } else if (I[1]->First->is(tok::l_brace) &&
  287. TheLine->First->isOneOf(tok::kw_if, tok::kw_while,
  288. tok::kw_for)) {
  289. return (Style.BraceWrapping.AfterControlStatement ==
  290. FormatStyle::BWACS_Always)
  291. ? tryMergeSimpleBlock(I, E, Limit)
  292. : 0;
  293. }
  294. // Try to merge either empty or one-line block if is precedeed by control
  295. // statement token
  296. if (TheLine->First->is(tok::l_brace) && TheLine->First == TheLine->Last &&
  297. I != AnnotatedLines.begin() &&
  298. I[-1]->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for)) {
  299. unsigned MergedLines = 0;
  300. if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never) {
  301. MergedLines = tryMergeSimpleBlock(I - 1, E, Limit);
  302. // If we managed to merge the block, discard the first merged line
  303. // since we are merging starting from I.
  304. if (MergedLines > 0)
  305. --MergedLines;
  306. }
  307. return MergedLines;
  308. }
  309. // Don't merge block with left brace wrapped after ObjC special blocks
  310. if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() &&
  311. I[-1]->First->is(tok::at) && I[-1]->First->Next) {
  312. tok::ObjCKeywordKind kwId = I[-1]->First->Next->Tok.getObjCKeywordID();
  313. if (kwId == clang::tok::objc_autoreleasepool ||
  314. kwId == clang::tok::objc_synchronized)
  315. return 0;
  316. }
  317. // Don't merge block with left brace wrapped after case labels
  318. if (TheLine->First->is(tok::l_brace) && I != AnnotatedLines.begin() &&
  319. I[-1]->First->isOneOf(tok::kw_case, tok::kw_default))
  320. return 0;
  321. // Try to merge a block with left brace wrapped that wasn't yet covered
  322. if (TheLine->Last->is(tok::l_brace)) {
  323. return !Style.BraceWrapping.AfterFunction ||
  324. (I[1]->First->is(tok::r_brace) &&
  325. !Style.BraceWrapping.SplitEmptyRecord)
  326. ? tryMergeSimpleBlock(I, E, Limit)
  327. : 0;
  328. }
  329. // Try to merge a function block with left brace wrapped
  330. if (I[1]->First->is(TT_FunctionLBrace) &&
  331. Style.BraceWrapping.AfterFunction) {
  332. if (I[1]->Last->is(TT_LineComment))
  333. return 0;
  334. // Check for Limit <= 2 to account for the " {".
  335. if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
  336. return 0;
  337. Limit -= 2;
  338. unsigned MergedLines = 0;
  339. if (MergeShortFunctions ||
  340. (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty &&
  341. I[1]->First == I[1]->Last && I + 2 != E &&
  342. I[2]->First->is(tok::r_brace))) {
  343. MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
  344. // If we managed to merge the block, count the function header, which is
  345. // on a separate line.
  346. if (MergedLines > 0)
  347. ++MergedLines;
  348. }
  349. return MergedLines;
  350. }
  351. if (TheLine->First->is(tok::kw_if)) {
  352. return Style.AllowShortIfStatementsOnASingleLine
  353. ? tryMergeSimpleControlStatement(I, E, Limit)
  354. : 0;
  355. }
  356. if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
  357. return Style.AllowShortLoopsOnASingleLine
  358. ? tryMergeSimpleControlStatement(I, E, Limit)
  359. : 0;
  360. }
  361. if (TheLine->First->isOneOf(tok::kw_case, tok::kw_default)) {
  362. return Style.AllowShortCaseLabelsOnASingleLine
  363. ? tryMergeShortCaseLabels(I, E, Limit)
  364. : 0;
  365. }
  366. if (TheLine->InPPDirective &&
  367. (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
  368. return tryMergeSimplePPDirective(I, E, Limit);
  369. }
  370. return 0;
  371. }
  372. unsigned
  373. tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
  374. SmallVectorImpl<AnnotatedLine *>::const_iterator E,
  375. unsigned Limit) {
  376. if (Limit == 0)
  377. return 0;
  378. if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
  379. return 0;
  380. if (1 + I[1]->Last->TotalLength > Limit)
  381. return 0;
  382. return 1;
  383. }
  384. unsigned tryMergeSimpleControlStatement(
  385. SmallVectorImpl<AnnotatedLine *>::const_iterator I,
  386. SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
  387. if (Limit == 0)
  388. return 0;
  389. if (Style.BraceWrapping.AfterControlStatement ==
  390. FormatStyle::BWACS_Always &&
  391. I[1]->First->is(tok::l_brace) &&
  392. Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
  393. return 0;
  394. if (I[1]->InPPDirective != (*I)->InPPDirective ||
  395. (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
  396. return 0;
  397. Limit = limitConsideringMacros(I + 1, E, Limit);
  398. AnnotatedLine &Line = **I;
  399. if (Line.Last->isNot(tok::r_paren))
  400. return 0;
  401. if (1 + I[1]->Last->TotalLength > Limit)
  402. return 0;
  403. if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while,
  404. TT_LineComment))
  405. return 0;
  406. // Only inline simple if's (no nested if or else), unless specified
  407. if (Style.AllowShortIfStatementsOnASingleLine != FormatStyle::SIS_Always) {
  408. if (I + 2 != E && Line.startsWith(tok::kw_if) &&
  409. I[2]->First->is(tok::kw_else))
  410. return 0;
  411. }
  412. return 1;
  413. }
  414. unsigned
  415. tryMergeShortCaseLabels(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
  416. SmallVectorImpl<AnnotatedLine *>::const_iterator E,
  417. unsigned Limit) {
  418. if (Limit == 0 || I + 1 == E ||
  419. I[1]->First->isOneOf(tok::kw_case, tok::kw_default))
  420. return 0;
  421. if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace))
  422. return 0;
  423. unsigned NumStmts = 0;
  424. unsigned Length = 0;
  425. bool EndsWithComment = false;
  426. bool InPPDirective = I[0]->InPPDirective;
  427. const unsigned Level = I[0]->Level;
  428. for (; NumStmts < 3; ++NumStmts) {
  429. if (I + 1 + NumStmts == E)
  430. break;
  431. const AnnotatedLine *Line = I[1 + NumStmts];
  432. if (Line->InPPDirective != InPPDirective)
  433. break;
  434. if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
  435. break;
  436. if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch,
  437. tok::kw_while) ||
  438. EndsWithComment)
  439. return 0;
  440. if (Line->First->is(tok::comment)) {
  441. if (Level != Line->Level)
  442. return 0;
  443. SmallVectorImpl<AnnotatedLine *>::const_iterator J = I + 2 + NumStmts;
  444. for (; J != E; ++J) {
  445. Line = *J;
  446. if (Line->InPPDirective != InPPDirective)
  447. break;
  448. if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace))
  449. break;
  450. if (Line->First->isNot(tok::comment) || Level != Line->Level)
  451. return 0;
  452. }
  453. break;
  454. }
  455. if (Line->Last->is(tok::comment))
  456. EndsWithComment = true;
  457. Length += I[1 + NumStmts]->Last->TotalLength + 1; // 1 for the space.
  458. }
  459. if (NumStmts == 0 || NumStmts == 3 || Length > Limit)
  460. return 0;
  461. return NumStmts;
  462. }
  463. unsigned
  464. tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
  465. SmallVectorImpl<AnnotatedLine *>::const_iterator E,
  466. unsigned Limit) {
  467. AnnotatedLine &Line = **I;
  468. // Don't merge ObjC @ keywords and methods.
  469. // FIXME: If an option to allow short exception handling clauses on a single
  470. // line is added, change this to not return for @try and friends.
  471. if (Style.Language != FormatStyle::LK_Java &&
  472. Line.First->isOneOf(tok::at, tok::minus, tok::plus))
  473. return 0;
  474. // Check that the current line allows merging. This depends on whether we
  475. // are in a control flow statements as well as several style flags.
  476. if (Line.First->isOneOf(tok::kw_else, tok::kw_case) ||
  477. (Line.First->Next && Line.First->Next->is(tok::kw_else)))
  478. return 0;
  479. // default: in switch statement
  480. if (Line.First->is(tok::kw_default)) {
  481. const FormatToken *Tok = Line.First->getNextNonComment();
  482. if (Tok && Tok->is(tok::colon))
  483. return 0;
  484. }
  485. if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
  486. tok::kw___try, tok::kw_catch, tok::kw___finally,
  487. tok::kw_for, tok::r_brace, Keywords.kw___except)) {
  488. if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never)
  489. return 0;
  490. // Don't merge when we can't except the case when
  491. // the control statement block is empty
  492. if (!Style.AllowShortIfStatementsOnASingleLine &&
  493. Line.startsWith(tok::kw_if) &&
  494. !Style.BraceWrapping.AfterControlStatement &&
  495. !I[1]->First->is(tok::r_brace))
  496. return 0;
  497. if (!Style.AllowShortIfStatementsOnASingleLine &&
  498. Line.startsWith(tok::kw_if) &&
  499. Style.BraceWrapping.AfterControlStatement ==
  500. FormatStyle::BWACS_Always &&
  501. I + 2 != E && !I[2]->First->is(tok::r_brace))
  502. return 0;
  503. if (!Style.AllowShortLoopsOnASingleLine &&
  504. Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
  505. !Style.BraceWrapping.AfterControlStatement &&
  506. !I[1]->First->is(tok::r_brace))
  507. return 0;
  508. if (!Style.AllowShortLoopsOnASingleLine &&
  509. Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for) &&
  510. Style.BraceWrapping.AfterControlStatement ==
  511. FormatStyle::BWACS_Always &&
  512. I + 2 != E && !I[2]->First->is(tok::r_brace))
  513. return 0;
  514. // FIXME: Consider an option to allow short exception handling clauses on
  515. // a single line.
  516. // FIXME: This isn't covered by tests.
  517. // FIXME: For catch, __except, __finally the first token on the line
  518. // is '}', so this isn't correct here.
  519. if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch,
  520. Keywords.kw___except, tok::kw___finally))
  521. return 0;
  522. }
  523. if (Line.Last->is(tok::l_brace)) {
  524. FormatToken *Tok = I[1]->First;
  525. if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
  526. (Tok->getNextNonComment() == nullptr ||
  527. Tok->getNextNonComment()->is(tok::semi))) {
  528. // We merge empty blocks even if the line exceeds the column limit.
  529. Tok->SpacesRequiredBefore = Style.SpaceInEmptyBlock ? 1 : 0;
  530. Tok->CanBreakBefore = true;
  531. return 1;
  532. } else if (Limit != 0 && !Line.startsWithNamespace() &&
  533. !startsExternCBlock(Line)) {
  534. // We don't merge short records.
  535. FormatToken *RecordTok = Line.First;
  536. // Skip record modifiers.
  537. while (RecordTok->Next &&
  538. RecordTok->isOneOf(tok::kw_typedef, tok::kw_export,
  539. Keywords.kw_declare, Keywords.kw_abstract,
  540. tok::kw_default))
  541. RecordTok = RecordTok->Next;
  542. if (RecordTok &&
  543. RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,
  544. Keywords.kw_interface))
  545. return 0;
  546. // Check that we still have three lines and they fit into the limit.
  547. if (I + 2 == E || I[2]->Type == LT_Invalid)
  548. return 0;
  549. Limit = limitConsideringMacros(I + 2, E, Limit);
  550. if (!nextTwoLinesFitInto(I, Limit))
  551. return 0;
  552. // Second, check that the next line does not contain any braces - if it
  553. // does, readability declines when putting it into a single line.
  554. if (I[1]->Last->is(TT_LineComment))
  555. return 0;
  556. do {
  557. if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
  558. return 0;
  559. Tok = Tok->Next;
  560. } while (Tok);
  561. // Last, check that the third line starts with a closing brace.
  562. Tok = I[2]->First;
  563. if (Tok->isNot(tok::r_brace))
  564. return 0;
  565. // Don't merge "if (a) { .. } else {".
  566. if (Tok->Next && Tok->Next->is(tok::kw_else))
  567. return 0;
  568. // Don't merge a trailing multi-line control statement block like:
  569. // } else if (foo &&
  570. // bar)
  571. // { <-- current Line
  572. // baz();
  573. // }
  574. if (Line.First == Line.Last &&
  575. Style.BraceWrapping.AfterControlStatement ==
  576. FormatStyle::BWACS_MultiLine)
  577. return 0;
  578. return 2;
  579. }
  580. } else if (I[1]->First->is(tok::l_brace)) {
  581. if (I[1]->Last->is(TT_LineComment))
  582. return 0;
  583. // Check for Limit <= 2 to account for the " {".
  584. if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(*I)))
  585. return 0;
  586. Limit -= 2;
  587. unsigned MergedLines = 0;
  588. if (Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never ||
  589. (I[1]->First == I[1]->Last && I + 2 != E &&
  590. I[2]->First->is(tok::r_brace))) {
  591. MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
  592. // If we managed to merge the block, count the statement header, which
  593. // is on a separate line.
  594. if (MergedLines > 0)
  595. ++MergedLines;
  596. }
  597. return MergedLines;
  598. }
  599. return 0;
  600. }
  601. /// Returns the modified column limit for \p I if it is inside a macro and
  602. /// needs a trailing '\'.
  603. unsigned
  604. limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
  605. SmallVectorImpl<AnnotatedLine *>::const_iterator E,
  606. unsigned Limit) {
  607. if (I[0]->InPPDirective && I + 1 != E &&
  608. !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
  609. return Limit < 2 ? 0 : Limit - 2;
  610. }
  611. return Limit;
  612. }
  613. bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
  614. unsigned Limit) {
  615. if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
  616. return false;
  617. return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
  618. }
  619. bool containsMustBreak(const AnnotatedLine *Line) {
  620. for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
  621. if (Tok->MustBreakBefore)
  622. return true;
  623. }
  624. return false;
  625. }
  626. void join(AnnotatedLine &A, const AnnotatedLine &B) {
  627. assert(!A.Last->Next);
  628. assert(!B.First->Previous);
  629. if (B.Affected)
  630. A.Affected = true;
  631. A.Last->Next = B.First;
  632. B.First->Previous = A.Last;
  633. B.First->CanBreakBefore = true;
  634. unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
  635. for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
  636. Tok->TotalLength += LengthA;
  637. A.Last = Tok;
  638. }
  639. }
  640. const FormatStyle &Style;
  641. const AdditionalKeywords &Keywords;
  642. const SmallVectorImpl<AnnotatedLine *>::const_iterator End;
  643. SmallVectorImpl<AnnotatedLine *>::const_iterator Next;
  644. const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines;
  645. };
  646. static void markFinalized(FormatToken *Tok) {
  647. for (; Tok; Tok = Tok->Next) {
  648. Tok->Finalized = true;
  649. for (AnnotatedLine *Child : Tok->Children)
  650. markFinalized(Child->First);
  651. }
  652. }
  653. #ifndef NDEBUG
  654. static void printLineState(const LineState &State) {
  655. llvm::dbgs() << "State: ";
  656. for (const ParenState &P : State.Stack) {
  657. llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|"
  658. << P.LastSpace << "|" << P.NestedBlockIndent << " ";
  659. }
  660. llvm::dbgs() << State.NextToken->TokenText << "\n";
  661. }
  662. #endif
  663. /// Base class for classes that format one \c AnnotatedLine.
  664. class LineFormatter {
  665. public:
  666. LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces,
  667. const FormatStyle &Style,
  668. UnwrappedLineFormatter *BlockFormatter)
  669. : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
  670. BlockFormatter(BlockFormatter) {}
  671. virtual ~LineFormatter() {}
  672. /// Formats an \c AnnotatedLine and returns the penalty.
  673. ///
  674. /// If \p DryRun is \c false, directly applies the changes.
  675. virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
  676. unsigned FirstStartColumn, bool DryRun) = 0;
  677. protected:
  678. /// If the \p State's next token is an r_brace closing a nested block,
  679. /// format the nested block before it.
  680. ///
  681. /// Returns \c true if all children could be placed successfully and adapts
  682. /// \p Penalty as well as \p State. If \p DryRun is false, also directly
  683. /// creates changes using \c Whitespaces.
  684. ///
  685. /// The crucial idea here is that children always get formatted upon
  686. /// encountering the closing brace right after the nested block. Now, if we
  687. /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
  688. /// \c false), the entire block has to be kept on the same line (which is only
  689. /// possible if it fits on the line, only contains a single statement, etc.
  690. ///
  691. /// If \p NewLine is true, we format the nested block on separate lines, i.e.
  692. /// break after the "{", format all lines with correct indentation and the put
  693. /// the closing "}" on yet another new line.
  694. ///
  695. /// This enables us to keep the simple structure of the
  696. /// \c UnwrappedLineFormatter, where we only have two options for each token:
  697. /// break or don't break.
  698. bool formatChildren(LineState &State, bool NewLine, bool DryRun,
  699. unsigned &Penalty) {
  700. const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
  701. FormatToken &Previous = *State.NextToken->Previous;
  702. if (!LBrace || LBrace->isNot(tok::l_brace) ||
  703. LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
  704. // The previous token does not open a block. Nothing to do. We don't
  705. // assert so that we can simply call this function for all tokens.
  706. return true;
  707. if (NewLine) {
  708. int AdditionalIndent = State.Stack.back().Indent -
  709. Previous.Children[0]->Level * Style.IndentWidth;
  710. Penalty +=
  711. BlockFormatter->format(Previous.Children, DryRun, AdditionalIndent,
  712. /*FixBadIndentation=*/true);
  713. return true;
  714. }
  715. if (Previous.Children[0]->First->MustBreakBefore)
  716. return false;
  717. // Cannot merge into one line if this line ends on a comment.
  718. if (Previous.is(tok::comment))
  719. return false;
  720. // Cannot merge multiple statements into a single line.
  721. if (Previous.Children.size() > 1)
  722. return false;
  723. const AnnotatedLine *Child = Previous.Children[0];
  724. // We can't put the closing "}" on a line with a trailing comment.
  725. if (Child->Last->isTrailingComment())
  726. return false;
  727. // If the child line exceeds the column limit, we wouldn't want to merge it.
  728. // We add +2 for the trailing " }".
  729. if (Style.ColumnLimit > 0 &&
  730. Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit)
  731. return false;
  732. if (!DryRun) {
  733. Whitespaces->replaceWhitespace(
  734. *Child->First, /*Newlines=*/0, /*Spaces=*/1,
  735. /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
  736. }
  737. Penalty +=
  738. formatLine(*Child, State.Column + 1, /*FirstStartColumn=*/0, DryRun);
  739. State.Column += 1 + Child->Last->TotalLength;
  740. return true;
  741. }
  742. ContinuationIndenter *Indenter;
  743. private:
  744. WhitespaceManager *Whitespaces;
  745. const FormatStyle &Style;
  746. UnwrappedLineFormatter *BlockFormatter;
  747. };
  748. /// Formatter that keeps the existing line breaks.
  749. class NoColumnLimitLineFormatter : public LineFormatter {
  750. public:
  751. NoColumnLimitLineFormatter(ContinuationIndenter *Indenter,
  752. WhitespaceManager *Whitespaces,
  753. const FormatStyle &Style,
  754. UnwrappedLineFormatter *BlockFormatter)
  755. : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
  756. /// Formats the line, simply keeping all of the input's line breaking
  757. /// decisions.
  758. unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
  759. unsigned FirstStartColumn, bool DryRun) override {
  760. assert(!DryRun);
  761. LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn,
  762. &Line, /*DryRun=*/false);
  763. while (State.NextToken) {
  764. bool Newline =
  765. Indenter->mustBreak(State) ||
  766. (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
  767. unsigned Penalty = 0;
  768. formatChildren(State, Newline, /*DryRun=*/false, Penalty);
  769. Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
  770. }
  771. return 0;
  772. }
  773. };
  774. /// Formatter that puts all tokens into a single line without breaks.
  775. class NoLineBreakFormatter : public LineFormatter {
  776. public:
  777. NoLineBreakFormatter(ContinuationIndenter *Indenter,
  778. WhitespaceManager *Whitespaces, const FormatStyle &Style,
  779. UnwrappedLineFormatter *BlockFormatter)
  780. : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
  781. /// Puts all tokens into a single line.
  782. unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
  783. unsigned FirstStartColumn, bool DryRun) override {
  784. unsigned Penalty = 0;
  785. LineState State =
  786. Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
  787. while (State.NextToken) {
  788. formatChildren(State, /*NewLine=*/false, DryRun, Penalty);
  789. Indenter->addTokenToState(
  790. State, /*Newline=*/State.NextToken->MustBreakBefore, DryRun);
  791. }
  792. return Penalty;
  793. }
  794. };
  795. /// Finds the best way to break lines.
  796. class OptimizingLineFormatter : public LineFormatter {
  797. public:
  798. OptimizingLineFormatter(ContinuationIndenter *Indenter,
  799. WhitespaceManager *Whitespaces,
  800. const FormatStyle &Style,
  801. UnwrappedLineFormatter *BlockFormatter)
  802. : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {}
  803. /// Formats the line by finding the best line breaks with line lengths
  804. /// below the column limit.
  805. unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent,
  806. unsigned FirstStartColumn, bool DryRun) override {
  807. LineState State =
  808. Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun);
  809. // If the ObjC method declaration does not fit on a line, we should format
  810. // it with one arg per line.
  811. if (State.Line->Type == LT_ObjCMethodDecl)
  812. State.Stack.back().BreakBeforeParameter = true;
  813. // Find best solution in solution space.
  814. return analyzeSolutionSpace(State, DryRun);
  815. }
  816. private:
  817. struct CompareLineStatePointers {
  818. bool operator()(LineState *obj1, LineState *obj2) const {
  819. return *obj1 < *obj2;
  820. }
  821. };
  822. /// A pair of <penalty, count> that is used to prioritize the BFS on.
  823. ///
  824. /// In case of equal penalties, we want to prefer states that were inserted
  825. /// first. During state generation we make sure that we insert states first
  826. /// that break the line as late as possible.
  827. typedef std::pair<unsigned, unsigned> OrderedPenalty;
  828. /// An edge in the solution space from \c Previous->State to \c State,
  829. /// inserting a newline dependent on the \c NewLine.
  830. struct StateNode {
  831. StateNode(const LineState &State, bool NewLine, StateNode *Previous)
  832. : State(State), NewLine(NewLine), Previous(Previous) {}
  833. LineState State;
  834. bool NewLine;
  835. StateNode *Previous;
  836. };
  837. /// An item in the prioritized BFS search queue. The \c StateNode's
  838. /// \c State has the given \c OrderedPenalty.
  839. typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
  840. /// The BFS queue type.
  841. typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
  842. std::greater<QueueItem>>
  843. QueueType;
  844. /// Analyze the entire solution space starting from \p InitialState.
  845. ///
  846. /// This implements a variant of Dijkstra's algorithm on the graph that spans
  847. /// the solution space (\c LineStates are the nodes). The algorithm tries to
  848. /// find the shortest path (the one with lowest penalty) from \p InitialState
  849. /// to a state where all tokens are placed. Returns the penalty.
  850. ///
  851. /// If \p DryRun is \c false, directly applies the changes.
  852. unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun) {
  853. std::set<LineState *, CompareLineStatePointers> Seen;
  854. // Increasing count of \c StateNode items we have created. This is used to
  855. // create a deterministic order independent of the container.
  856. unsigned Count = 0;
  857. QueueType Queue;
  858. // Insert start element into queue.
  859. StateNode *Node =
  860. new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
  861. Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
  862. ++Count;
  863. unsigned Penalty = 0;
  864. // While not empty, take first element and follow edges.
  865. while (!Queue.empty()) {
  866. Penalty = Queue.top().first.first;
  867. StateNode *Node = Queue.top().second;
  868. if (!Node->State.NextToken) {
  869. LLVM_DEBUG(llvm::dbgs()
  870. << "\n---\nPenalty for line: " << Penalty << "\n");
  871. break;
  872. }
  873. Queue.pop();
  874. // Cut off the analysis of certain solutions if the analysis gets too
  875. // complex. See description of IgnoreStackForComparison.
  876. if (Count > 50000)
  877. Node->State.IgnoreStackForComparison = true;
  878. if (!Seen.insert(&Node->State).second)
  879. // State already examined with lower penalty.
  880. continue;
  881. FormatDecision LastFormat = Node->State.NextToken->Decision;
  882. if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
  883. addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
  884. if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
  885. addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
  886. }
  887. if (Queue.empty()) {
  888. // We were unable to find a solution, do nothing.
  889. // FIXME: Add diagnostic?
  890. LLVM_DEBUG(llvm::dbgs() << "Could not find a solution.\n");
  891. return 0;
  892. }
  893. // Reconstruct the solution.
  894. if (!DryRun)
  895. reconstructPath(InitialState, Queue.top().second);
  896. LLVM_DEBUG(llvm::dbgs()
  897. << "Total number of analyzed states: " << Count << "\n");
  898. LLVM_DEBUG(llvm::dbgs() << "---\n");
  899. return Penalty;
  900. }
  901. /// Add the following state to the analysis queue \c Queue.
  902. ///
  903. /// Assume the current state is \p PreviousNode and has been reached with a
  904. /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
  905. void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
  906. bool NewLine, unsigned *Count, QueueType *Queue) {
  907. if (NewLine && !Indenter->canBreak(PreviousNode->State))
  908. return;
  909. if (!NewLine && Indenter->mustBreak(PreviousNode->State))
  910. return;
  911. StateNode *Node = new (Allocator.Allocate())
  912. StateNode(PreviousNode->State, NewLine, PreviousNode);
  913. if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
  914. return;
  915. Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
  916. Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
  917. ++(*Count);
  918. }
  919. /// Applies the best formatting by reconstructing the path in the
  920. /// solution space that leads to \c Best.
  921. void reconstructPath(LineState &State, StateNode *Best) {
  922. std::deque<StateNode *> Path;
  923. // We do not need a break before the initial token.
  924. while (Best->Previous) {
  925. Path.push_front(Best);
  926. Best = Best->Previous;
  927. }
  928. for (auto I = Path.begin(), E = Path.end(); I != E; ++I) {
  929. unsigned Penalty = 0;
  930. formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
  931. Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
  932. LLVM_DEBUG({
  933. printLineState((*I)->Previous->State);
  934. if ((*I)->NewLine) {
  935. llvm::dbgs() << "Penalty for placing "
  936. << (*I)->Previous->State.NextToken->Tok.getName()
  937. << " on a new line: " << Penalty << "\n";
  938. }
  939. });
  940. }
  941. }
  942. llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
  943. };
  944. } // anonymous namespace
  945. unsigned UnwrappedLineFormatter::format(
  946. const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
  947. int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn,
  948. unsigned NextStartColumn, unsigned LastStartColumn) {
  949. LineJoiner Joiner(Style, Keywords, Lines);
  950. // Try to look up already computed penalty in DryRun-mode.
  951. std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
  952. &Lines, AdditionalIndent);
  953. auto CacheIt = PenaltyCache.find(CacheKey);
  954. if (DryRun && CacheIt != PenaltyCache.end())
  955. return CacheIt->second;
  956. assert(!Lines.empty());
  957. unsigned Penalty = 0;
  958. LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level,
  959. AdditionalIndent);
  960. const AnnotatedLine *PreviousLine = nullptr;
  961. const AnnotatedLine *NextLine = nullptr;
  962. // The minimum level of consecutive lines that have been formatted.
  963. unsigned RangeMinLevel = UINT_MAX;
  964. bool FirstLine = true;
  965. for (const AnnotatedLine *Line =
  966. Joiner.getNextMergedLine(DryRun, IndentTracker);
  967. Line; Line = NextLine, FirstLine = false) {
  968. const AnnotatedLine &TheLine = *Line;
  969. unsigned Indent = IndentTracker.getIndent();
  970. // We continue formatting unchanged lines to adjust their indent, e.g. if a
  971. // scope was added. However, we need to carefully stop doing this when we
  972. // exit the scope of affected lines to prevent indenting a the entire
  973. // remaining file if it currently missing a closing brace.
  974. bool PreviousRBrace =
  975. PreviousLine && PreviousLine->startsWith(tok::r_brace);
  976. bool ContinueFormatting =
  977. TheLine.Level > RangeMinLevel ||
  978. (TheLine.Level == RangeMinLevel && !PreviousRBrace &&
  979. !TheLine.startsWith(tok::r_brace));
  980. bool FixIndentation = (FixBadIndentation || ContinueFormatting) &&
  981. Indent != TheLine.First->OriginalColumn;
  982. bool ShouldFormat = TheLine.Affected || FixIndentation;
  983. // We cannot format this line; if the reason is that the line had a
  984. // parsing error, remember that.
  985. if (ShouldFormat && TheLine.Type == LT_Invalid && Status) {
  986. Status->FormatComplete = false;
  987. Status->Line =
  988. SourceMgr.getSpellingLineNumber(TheLine.First->Tok.getLocation());
  989. }
  990. if (ShouldFormat && TheLine.Type != LT_Invalid) {
  991. if (!DryRun) {
  992. bool LastLine = Line->First->is(tok::eof);
  993. formatFirstToken(TheLine, PreviousLine, Lines, Indent,
  994. LastLine ? LastStartColumn : NextStartColumn + Indent);
  995. }
  996. NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
  997. unsigned ColumnLimit = getColumnLimit(TheLine.InPPDirective, NextLine);
  998. bool FitsIntoOneLine =
  999. TheLine.Last->TotalLength + Indent <= ColumnLimit ||
  1000. (TheLine.Type == LT_ImportStatement &&
  1001. (Style.Language != FormatStyle::LK_JavaScript ||
  1002. !Style.JavaScriptWrapImports)) ||
  1003. (Style.isCSharp() &&
  1004. TheLine.InPPDirective); // don't split #regions in C#
  1005. if (Style.ColumnLimit == 0)
  1006. NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this)
  1007. .formatLine(TheLine, NextStartColumn + Indent,
  1008. FirstLine ? FirstStartColumn : 0, DryRun);
  1009. else if (FitsIntoOneLine)
  1010. Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this)
  1011. .formatLine(TheLine, NextStartColumn + Indent,
  1012. FirstLine ? FirstStartColumn : 0, DryRun);
  1013. else
  1014. Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this)
  1015. .formatLine(TheLine, NextStartColumn + Indent,
  1016. FirstLine ? FirstStartColumn : 0, DryRun);
  1017. RangeMinLevel = std::min(RangeMinLevel, TheLine.Level);
  1018. } else {
  1019. // If no token in the current line is affected, we still need to format
  1020. // affected children.
  1021. if (TheLine.ChildrenAffected)
  1022. for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next)
  1023. if (!Tok->Children.empty())
  1024. format(Tok->Children, DryRun);
  1025. // Adapt following lines on the current indent level to the same level
  1026. // unless the current \c AnnotatedLine is not at the beginning of a line.
  1027. bool StartsNewLine =
  1028. TheLine.First->NewlinesBefore > 0 || TheLine.First->IsFirst;
  1029. if (StartsNewLine)
  1030. IndentTracker.adjustToUnmodifiedLine(TheLine);
  1031. if (!DryRun) {
  1032. bool ReformatLeadingWhitespace =
  1033. StartsNewLine && ((PreviousLine && PreviousLine->Affected) ||
  1034. TheLine.LeadingEmptyLinesAffected);
  1035. // Format the first token.
  1036. if (ReformatLeadingWhitespace)
  1037. formatFirstToken(TheLine, PreviousLine, Lines,
  1038. TheLine.First->OriginalColumn,
  1039. TheLine.First->OriginalColumn);
  1040. else
  1041. Whitespaces->addUntouchableToken(*TheLine.First,
  1042. TheLine.InPPDirective);
  1043. // Notify the WhitespaceManager about the unchanged whitespace.
  1044. for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next)
  1045. Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
  1046. }
  1047. NextLine = Joiner.getNextMergedLine(DryRun, IndentTracker);
  1048. RangeMinLevel = UINT_MAX;
  1049. }
  1050. if (!DryRun)
  1051. markFinalized(TheLine.First);
  1052. PreviousLine = &TheLine;
  1053. }
  1054. PenaltyCache[CacheKey] = Penalty;
  1055. return Penalty;
  1056. }
  1057. void UnwrappedLineFormatter::formatFirstToken(
  1058. const AnnotatedLine &Line, const AnnotatedLine *PreviousLine,
  1059. const SmallVectorImpl<AnnotatedLine *> &Lines, unsigned Indent,
  1060. unsigned NewlineIndent) {
  1061. FormatToken &RootToken = *Line.First;
  1062. if (RootToken.is(tok::eof)) {
  1063. unsigned Newlines = std::min(RootToken.NewlinesBefore, 1u);
  1064. unsigned TokenIndent = Newlines ? NewlineIndent : 0;
  1065. Whitespaces->replaceWhitespace(RootToken, Newlines, TokenIndent,
  1066. TokenIndent);
  1067. return;
  1068. }
  1069. unsigned Newlines =
  1070. std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
  1071. // Remove empty lines before "}" where applicable.
  1072. if (RootToken.is(tok::r_brace) &&
  1073. (!RootToken.Next ||
  1074. (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) &&
  1075. // Do not remove empty lines before namespace closing "}".
  1076. !getNamespaceToken(&Line, Lines))
  1077. Newlines = std::min(Newlines, 1u);
  1078. // Remove empty lines at the start of nested blocks (lambdas/arrow functions)
  1079. if (PreviousLine == nullptr && Line.Level > 0)
  1080. Newlines = std::min(Newlines, 1u);
  1081. if (Newlines == 0 && !RootToken.IsFirst)
  1082. Newlines = 1;
  1083. if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
  1084. Newlines = 0;
  1085. // Remove empty lines after "{".
  1086. if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
  1087. PreviousLine->Last->is(tok::l_brace) &&
  1088. !PreviousLine->startsWithNamespace() &&
  1089. !startsExternCBlock(*PreviousLine))
  1090. Newlines = 1;
  1091. // Insert extra new line before access specifiers.
  1092. if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
  1093. RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
  1094. ++Newlines;
  1095. // Remove empty lines after access specifiers.
  1096. if (PreviousLine && PreviousLine->First->isAccessSpecifier() &&
  1097. (!PreviousLine->InPPDirective || !RootToken.HasUnescapedNewline))
  1098. Newlines = std::min(1u, Newlines);
  1099. if (Newlines)
  1100. Indent = NewlineIndent;
  1101. // If in Whitemsmiths mode, indent start and end of blocks
  1102. if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
  1103. if (RootToken.isOneOf(tok::l_brace, tok::r_brace, tok::kw_case))
  1104. Indent += Style.IndentWidth;
  1105. }
  1106. // Preprocessor directives get indented before the hash only if specified
  1107. if (Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
  1108. (Line.Type == LT_PreprocessorDirective ||
  1109. Line.Type == LT_ImportStatement))
  1110. Indent = 0;
  1111. Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent,
  1112. Line.InPPDirective &&
  1113. !RootToken.HasUnescapedNewline);
  1114. }
  1115. unsigned
  1116. UnwrappedLineFormatter::getColumnLimit(bool InPPDirective,
  1117. const AnnotatedLine *NextLine) const {
  1118. // In preprocessor directives reserve two chars for trailing " \" if the
  1119. // next line continues the preprocessor directive.
  1120. bool ContinuesPPDirective =
  1121. InPPDirective &&
  1122. // If there is no next line, this is likely a child line and the parent
  1123. // continues the preprocessor directive.
  1124. (!NextLine ||
  1125. (NextLine->InPPDirective &&
  1126. // If there is an unescaped newline between this line and the next, the
  1127. // next line starts a new preprocessor directive.
  1128. !NextLine->First->HasUnescapedNewline));
  1129. return Style.ColumnLimit - (ContinuesPPDirective ? 2 : 0);
  1130. }
  1131. } // namespace format
  1132. } // namespace clang