UnwrappedLineFormatter.cpp 46 KB

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