UnwrappedLineFormatter.cpp 56 KB

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