cmRST.cxx 14 KB

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