cmRST.cxx 15 KB

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