UnwrappedLineFormatter.cpp 58 KB

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