cmRST.cxx 15 KB

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