cmRST.cxx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmRST.h"
  4. #include <algorithm>
  5. #include <cstddef>
  6. #include <iterator>
  7. #include <utility>
  8. #include "cmsys/FStream.hxx"
  9. #include "cmAlgorithms.h"
  10. #include "cmRange.h"
  11. #include "cmStringAlgorithms.h"
  12. #include "cmSystemTools.h"
  13. #include "cmVersion.h"
  14. cmRST::cmRST(std::ostream& os, std::string docroot)
  15. : OS(os)
  16. , DocRoot(std::move(docroot))
  17. , CMakeDirective("^.. (cmake:)?("
  18. "command|envvar|genex|signature|variable"
  19. ")::")
  20. , CMakeModuleDirective("^.. cmake-module::[ \t]+([^ \t\n]+)$")
  21. , ParsedLiteralDirective("^.. parsed-literal::[ \t]*(.*)$")
  22. , CodeBlockDirective("^.. code-block::[ \t]*(.*)$")
  23. , ReplaceDirective("^.. (\\|[^|]+\\|) replace::[ \t]*(.*)$")
  24. , IncludeDirective("^.. include::[ \t]+([^ \t\n]+)$")
  25. , TocTreeDirective("^.. toctree::[ \t]*(.*)$")
  26. , ProductionListDirective("^.. productionlist::[ \t]*(.*)$")
  27. , NoteDirective("^.. note::[ \t]*(.*)$")
  28. , VersionDirective("^.. version(added|changed)::[ \t]*(.*)$")
  29. , ModuleRST(R"(^#\[(=*)\[\.rst:$)")
  30. , CMakeRole("(:cmake)?:("
  31. "cref|"
  32. "command|cpack_gen|generator|genex|"
  33. "variable|envvar|module|policy|"
  34. "prop_cache|prop_dir|prop_gbl|prop_inst|prop_sf|"
  35. "prop_test|prop_tgt|"
  36. "manual"
  37. "):`(<*([^`<]|[^` \t]<)*)([ \t]+<[^`]*>)?`")
  38. , InlineLink("`(<*([^`<]|[^` \t]<)*)([ \t]+<[^`]*>)?`_")
  39. , InlineLiteral("``([^`]*)``")
  40. , Substitution("(^|[^A-Za-z0-9_])"
  41. "((\\|[^| \t\r\n]([^|\r\n]*[^| \t\r\n])?\\|)(__|_|))"
  42. "([^A-Za-z0-9_]|$)")
  43. , TocTreeLink("^.*[ \t]+<([^>]+)>$")
  44. {
  45. this->Replace["|release|"] = cmVersion::GetCMakeVersion();
  46. }
  47. bool cmRST::ProcessFile(std::string const& fname, bool isModule)
  48. {
  49. cmsys::ifstream fin(fname.c_str());
  50. if (fin) {
  51. this->DocDir = cmSystemTools::GetFilenamePath(fname);
  52. if (isModule) {
  53. this->ProcessModule(fin);
  54. } else {
  55. this->ProcessRST(fin);
  56. }
  57. this->OutputLinePending = true;
  58. return true;
  59. }
  60. return false;
  61. }
  62. void cmRST::ProcessRST(std::istream& is)
  63. {
  64. std::string line;
  65. while (cmSystemTools::GetLineFromStream(is, line)) {
  66. this->ProcessLine(line);
  67. }
  68. this->Reset();
  69. }
  70. void cmRST::ProcessModule(std::istream& is)
  71. {
  72. std::string line;
  73. std::string rst;
  74. while (cmSystemTools::GetLineFromStream(is, line)) {
  75. if (!rst.empty() && rst != "#") {
  76. // Bracket mode: check for end bracket
  77. std::string::size_type pos = line.find(rst);
  78. if (pos == std::string::npos) {
  79. this->ProcessLine(line);
  80. } else {
  81. if (line[0] != '#') {
  82. line.resize(pos);
  83. this->ProcessLine(line);
  84. }
  85. rst.clear();
  86. this->Reset();
  87. this->OutputLinePending = true;
  88. }
  89. } else {
  90. // Line mode: check for .rst start (bracket or line)
  91. if (rst == "#") {
  92. if (line == "#") {
  93. this->ProcessLine("");
  94. continue;
  95. }
  96. if (cmHasLiteralPrefix(line, "# ")) {
  97. line.erase(0, 2);
  98. this->ProcessLine(line);
  99. continue;
  100. }
  101. rst.clear();
  102. this->Reset();
  103. this->OutputLinePending = true;
  104. }
  105. if (line == "#.rst:") {
  106. rst = "#";
  107. } else if (this->ModuleRST.find(line)) {
  108. rst = "]" + this->ModuleRST.match(1) + "]";
  109. }
  110. }
  111. }
  112. if (rst == "#") {
  113. this->Reset();
  114. }
  115. }
  116. void cmRST::Reset()
  117. {
  118. if (!this->MarkupLines.empty()) {
  119. cmRST::UnindentLines(this->MarkupLines);
  120. }
  121. switch (this->DirectiveType) {
  122. case Directive::None:
  123. break;
  124. case Directive::ParsedLiteral:
  125. this->ProcessDirectiveParsedLiteral();
  126. break;
  127. case Directive::LiteralBlock:
  128. this->ProcessDirectiveLiteralBlock();
  129. break;
  130. case Directive::CodeBlock:
  131. this->ProcessDirectiveCodeBlock();
  132. break;
  133. case Directive::Replace:
  134. this->ProcessDirectiveReplace();
  135. break;
  136. case Directive::TocTree:
  137. this->ProcessDirectiveTocTree();
  138. break;
  139. }
  140. this->MarkupType = Markup::None;
  141. this->DirectiveType = Directive::None;
  142. this->MarkupLines.clear();
  143. }
  144. void cmRST::ProcessLine(std::string const& line)
  145. {
  146. bool lastLineEndedInColonColon = this->LastLineEndedInColonColon;
  147. this->LastLineEndedInColonColon = false;
  148. // A line starting in .. is an explicit markup start.
  149. if (line == ".." ||
  150. (line.size() >= 3 && line[0] == '.' && line[1] == '.' &&
  151. cmIsSpace(line[2]))) {
  152. this->Reset();
  153. this->MarkupType =
  154. (line.find_first_not_of(" \t", 2) == std::string::npos ? Markup::Empty
  155. : Markup::Normal);
  156. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  157. // NOLINTNEXTLINE(bugprone-branch-clone)
  158. if (this->CMakeDirective.find(line)) {
  159. // Output cmake domain directives and their content normally.
  160. this->NormalLine(line);
  161. } else if (this->CMakeModuleDirective.find(line)) {
  162. // Process cmake-module directive: scan .cmake file comments.
  163. std::string file = this->CMakeModuleDirective.match(1);
  164. if (file.empty() || !this->ProcessInclude(file, Include::Module)) {
  165. this->NormalLine(line);
  166. }
  167. } else if (this->ParsedLiteralDirective.find(line)) {
  168. // Record the literal lines to output after whole block.
  169. this->DirectiveType = Directive::ParsedLiteral;
  170. this->MarkupLines.push_back(this->ParsedLiteralDirective.match(1));
  171. } else if (this->CodeBlockDirective.find(line)) {
  172. // Record the literal lines to output after whole block.
  173. // Ignore the language spec and record the opening line as blank.
  174. this->DirectiveType = Directive::CodeBlock;
  175. this->MarkupLines.emplace_back();
  176. } else if (this->ReplaceDirective.find(line)) {
  177. // Record the replace directive content.
  178. this->DirectiveType = Directive::Replace;
  179. this->ReplaceName = this->ReplaceDirective.match(1);
  180. this->MarkupLines.push_back(this->ReplaceDirective.match(2));
  181. } else if (this->IncludeDirective.find(line)) {
  182. // Process the include directive or output the directive and its
  183. // content normally if it fails.
  184. std::string file = this->IncludeDirective.match(1);
  185. if (file.empty() || !this->ProcessInclude(file, Include::Normal)) {
  186. this->NormalLine(line);
  187. }
  188. } else if (this->TocTreeDirective.find(line)) {
  189. // Record the toctree entries to process after whole block.
  190. this->DirectiveType = Directive::TocTree;
  191. this->MarkupLines.push_back(this->TocTreeDirective.match(1));
  192. } else if (this->ProductionListDirective.find(line)) {
  193. // Output productionlist directives and their content normally.
  194. this->NormalLine(line);
  195. } else if (this->NoteDirective.find(line)) {
  196. // Output note directives and their content normally.
  197. this->NormalLine(line);
  198. } else if (this->VersionDirective.find(line)) {
  199. // Output versionadded and versionchanged directives and their content
  200. // normally.
  201. this->NormalLine(line);
  202. }
  203. }
  204. // An explicit markup start followed by nothing but whitespace and a
  205. // blank line does not consume any indented text following.
  206. else if (this->MarkupType == Markup::Empty && line.empty()) {
  207. this->NormalLine(line);
  208. }
  209. // Indented lines following an explicit markup start are explicit markup.
  210. else if (this->MarkupType != Markup::None &&
  211. (line.empty() || cmIsSpace(line[0]))) {
  212. this->MarkupType = Markup::Normal;
  213. // Record markup lines if the start line was recorded.
  214. if (!this->MarkupLines.empty()) {
  215. this->MarkupLines.push_back(line);
  216. }
  217. }
  218. // A blank line following a paragraph ending in "::" starts a literal block.
  219. else if (lastLineEndedInColonColon && line.empty()) {
  220. // Record the literal lines to output after whole block.
  221. this->MarkupType = Markup::Normal;
  222. this->DirectiveType = Directive::LiteralBlock;
  223. this->MarkupLines.emplace_back();
  224. this->OutputLine("", false);
  225. }
  226. // Print non-markup lines.
  227. else {
  228. this->NormalLine(line);
  229. this->LastLineEndedInColonColon =
  230. (line.size() >= 2 && line[line.size() - 2] == ':' && line.back() == ':');
  231. }
  232. }
  233. void cmRST::NormalLine(std::string const& line)
  234. {
  235. this->Reset();
  236. this->OutputLine(line, true);
  237. }
  238. void cmRST::OutputLine(std::string const& line_in, bool inlineMarkup)
  239. {
  240. if (this->OutputLinePending) {
  241. this->OS << "\n";
  242. this->OutputLinePending = false;
  243. }
  244. if (inlineMarkup) {
  245. std::string line = this->ReplaceSubstitutions(line_in);
  246. std::string::size_type pos = 0;
  247. for (;;) {
  248. std::string::size_type* first = nullptr;
  249. std::string::size_type role_start = std::string::npos;
  250. std::string::size_type link_start = std::string::npos;
  251. std::string::size_type lit_start = std::string::npos;
  252. if (this->CMakeRole.find(line.c_str() + pos)) {
  253. role_start = this->CMakeRole.start();
  254. first = &role_start;
  255. }
  256. if (this->InlineLiteral.find(line.c_str() + pos)) {
  257. lit_start = this->InlineLiteral.start();
  258. if (!first || lit_start < *first) {
  259. first = &lit_start;
  260. }
  261. }
  262. if (this->InlineLink.find(line.c_str() + pos)) {
  263. link_start = this->InlineLink.start();
  264. if (!first || link_start < *first) {
  265. first = &link_start;
  266. }
  267. }
  268. if (first == &role_start) {
  269. this->OS << line.substr(pos, role_start);
  270. std::string text = this->CMakeRole.match(3);
  271. // If a command reference has no explicit target and
  272. // no explicit "(...)" then add "()" to the text.
  273. if (this->CMakeRole.match(2) == "command" &&
  274. this->CMakeRole.match(5).empty() &&
  275. text.find_first_of("()") == std::string::npos) {
  276. text += "()";
  277. }
  278. this->OS << "``" << text << "``";
  279. pos += this->CMakeRole.end();
  280. } else if (first == &lit_start) {
  281. this->OS << line.substr(pos, lit_start);
  282. std::string text = this->InlineLiteral.match(1);
  283. pos += this->InlineLiteral.end();
  284. this->OS << "``" << text << "``";
  285. } else if (first == &link_start) {
  286. this->OS << line.substr(pos, link_start);
  287. std::string text = this->InlineLink.match(1);
  288. bool escaped = false;
  289. for (char c : text) {
  290. if (escaped) {
  291. escaped = false;
  292. this->OS << c;
  293. } else if (c == '\\') {
  294. escaped = true;
  295. } else {
  296. this->OS << c;
  297. }
  298. }
  299. pos += this->InlineLink.end();
  300. } else {
  301. break;
  302. }
  303. }
  304. this->OS << line.substr(pos) << "\n";
  305. } else {
  306. this->OS << line_in << "\n";
  307. }
  308. }
  309. std::string cmRST::ReplaceSubstitutions(std::string const& line)
  310. {
  311. std::string out;
  312. std::string::size_type pos = 0;
  313. while (this->Substitution.find(line.c_str() + pos)) {
  314. std::string::size_type start = this->Substitution.start(2);
  315. std::string::size_type end = this->Substitution.end(2);
  316. std::string substitute = this->Substitution.match(3);
  317. auto replace = this->Replace.find(substitute);
  318. if (replace != this->Replace.end()) {
  319. std::pair<std::set<std::string>::iterator, bool> replaced =
  320. this->Replaced.insert(substitute);
  321. if (replaced.second) {
  322. substitute = this->ReplaceSubstitutions(replace->second);
  323. this->Replaced.erase(replaced.first);
  324. }
  325. }
  326. out += line.substr(pos, start);
  327. out += substitute;
  328. pos += end;
  329. }
  330. out += line.substr(pos);
  331. return out;
  332. }
  333. void cmRST::OutputMarkupLines(bool inlineMarkup)
  334. {
  335. for (auto line : this->MarkupLines) {
  336. if (!line.empty()) {
  337. line = cmStrCat(' ', line);
  338. }
  339. this->OutputLine(line, inlineMarkup);
  340. }
  341. this->OutputLinePending = true;
  342. }
  343. bool cmRST::ProcessInclude(std::string file, Include type)
  344. {
  345. bool found = false;
  346. if (this->IncludeDepth < 10) {
  347. cmRST r(this->OS, this->DocRoot);
  348. r.IncludeDepth = this->IncludeDepth + 1;
  349. r.OutputLinePending = this->OutputLinePending;
  350. if (type != Include::TocTree) {
  351. r.Replace = this->Replace;
  352. }
  353. if (file[0] == '/') {
  354. file = this->DocRoot + file;
  355. } else {
  356. file = this->DocDir + "/" + file;
  357. }
  358. found = r.ProcessFile(file, type == Include::Module);
  359. if (type != Include::TocTree) {
  360. this->Replace = r.Replace;
  361. }
  362. this->OutputLinePending = r.OutputLinePending;
  363. }
  364. return found;
  365. }
  366. void cmRST::ProcessDirectiveParsedLiteral()
  367. {
  368. this->OutputMarkupLines(true);
  369. }
  370. void cmRST::ProcessDirectiveLiteralBlock()
  371. {
  372. this->OutputMarkupLines(false);
  373. }
  374. void cmRST::ProcessDirectiveCodeBlock()
  375. {
  376. this->OutputMarkupLines(false);
  377. }
  378. void cmRST::ProcessDirectiveReplace()
  379. {
  380. // Record markup lines as replacement text.
  381. std::string& replacement = this->Replace[this->ReplaceName];
  382. replacement += cmJoin(this->MarkupLines, " ");
  383. this->ReplaceName.clear();
  384. }
  385. void cmRST::ProcessDirectiveTocTree()
  386. {
  387. // Process documents referenced by toctree directive.
  388. for (std::string const& line : this->MarkupLines) {
  389. if (!line.empty() && line[0] != ':') {
  390. if (this->TocTreeLink.find(line)) {
  391. std::string const& link = this->TocTreeLink.match(1);
  392. this->ProcessInclude(link + ".rst", Include::TocTree);
  393. } else {
  394. this->ProcessInclude(line + ".rst", Include::TocTree);
  395. }
  396. }
  397. }
  398. }
  399. void cmRST::UnindentLines(std::vector<std::string>& lines)
  400. {
  401. // Remove the common indentation from the second and later lines.
  402. std::string indentText;
  403. std::string::size_type indentEnd = 0;
  404. bool first = true;
  405. for (size_t i = 1; i < lines.size(); ++i) {
  406. std::string const& line = lines[i];
  407. // Do not consider empty lines.
  408. if (line.empty()) {
  409. continue;
  410. }
  411. // Record indentation on first non-empty line.
  412. if (first) {
  413. first = false;
  414. indentEnd = line.find_first_not_of(" \t");
  415. indentText = line.substr(0, indentEnd);
  416. continue;
  417. }
  418. // Truncate indentation to match that on this line.
  419. indentEnd = std::min(indentEnd, line.size());
  420. for (std::string::size_type j = 0; j != indentEnd; ++j) {
  421. if (line[j] != indentText[j]) {
  422. indentEnd = j;
  423. break;
  424. }
  425. }
  426. }
  427. // Update second and later lines.
  428. for (size_t i = 1; i < lines.size(); ++i) {
  429. std::string& line = lines[i];
  430. if (!line.empty()) {
  431. line = line.substr(indentEnd);
  432. }
  433. }
  434. auto it = lines.cbegin();
  435. size_t leadingEmpty = std::distance(it, cmFindNot(lines, std::string()));
  436. auto rit = lines.crbegin();
  437. size_t trailingEmpty =
  438. std::distance(rit, cmFindNot(cmReverseRange(lines), std::string()));
  439. if ((leadingEmpty + trailingEmpty) >= lines.size()) {
  440. // All lines are empty. The markup block is empty. Leave only one.
  441. lines.resize(1);
  442. return;
  443. }
  444. auto contentEnd = cmRotate(lines.begin(), lines.begin() + leadingEmpty,
  445. lines.end() - trailingEmpty);
  446. lines.erase(contentEnd, lines.end());
  447. }