cmake.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file Copyright.txt or https://cmake.org/licensing for details.
  3. import os
  4. import re
  5. from dataclasses import dataclass
  6. from typing import Any, List, Tuple, cast
  7. # Override much of pygments' CMakeLexer.
  8. # We need to parse CMake syntax definitions, not CMake code.
  9. # For hard test cases that use much of the syntax below, see
  10. # - module/FindPkgConfig.html (with "glib-2.0>=2.10 gtk+-2.0" and similar)
  11. # - module/ExternalProject.html (with http:// https:// git@; also has command options -E --build)
  12. # - manual/cmake-buildsystem.7.html (with nested $<..>; relative and absolute paths, "::")
  13. from pygments.lexers import CMakeLexer
  14. from pygments.token import Name, Operator, Punctuation, String, Text, Comment, Generic, Whitespace, Number
  15. from pygments.lexer import bygroups
  16. # RE to split multiple command signatures
  17. sig_end_re = re.compile(r'(?<=[)])\n')
  18. # Notes on regular expressions below:
  19. # - [\.\+-] are needed for string constants like gtk+-2.0
  20. # - Unix paths are recognized by '/'; support for Windows paths may be added if needed
  21. # - (\\.) allows for \-escapes (used in manual/cmake-language.7)
  22. # - $<..$<..$>..> nested occurrence in cmake-buildsystem
  23. # - Nested variable evaluations are only supported in a limited capacity. Only
  24. # one level of nesting is supported and at most one nested variable can be present.
  25. CMakeLexer.tokens["root"] = [
  26. (r'\b(\w+)([ \t]*)(\()', bygroups(Name.Function, Text, Name.Function), '#push'), # fctn(
  27. (r'\(', Name.Function, '#push'),
  28. (r'\)', Name.Function, '#pop'),
  29. (r'\[', Punctuation, '#push'),
  30. (r'\]', Punctuation, '#pop'),
  31. (r'[|;,.=*\-]', Punctuation),
  32. (r'\\\\', Punctuation), # used in commands/source_group
  33. (r'[:]', Operator),
  34. (r'[<>]=', Punctuation), # used in FindPkgConfig.cmake
  35. (r'\$<', Operator, '#push'), # $<...>
  36. (r'<[^<|]+?>(\w*\.\.\.)?', Name.Variable), # <expr>
  37. (r'(\$\w*\{)([^\}\$]*)?(?:(\$\w*\{)([^\}]+?)(\}))?([^\}]*?)(\})', # ${..} $ENV{..}, possibly nested
  38. bygroups(Operator, Name.Tag, Operator, Name.Tag, Operator, Name.Tag, Operator)),
  39. (r'([A-Z]+\{)(.+?)(\})', bygroups(Operator, Name.Tag, Operator)), # DATA{ ...}
  40. (r'[a-z]+(@|(://))((\\.)|[\w.+-:/\\])+', Name.Attribute), # URL, git@, ...
  41. (r'/\w[\w\.\+-/\\]*', Name.Attribute), # absolute path
  42. (r'/', Name.Attribute),
  43. (r'\w[\w\.\+-]*/[\w.+-/\\]*', Name.Attribute), # relative path
  44. (r'[A-Z]((\\.)|[\w.+-])*[a-z]((\\.)|[\w.+-])*', Name.Builtin), # initial A-Z, contains a-z
  45. (r'@?[A-Z][A-Z0-9_]*', Name.Constant),
  46. (r'[a-z_]((\\;)|(\\ )|[\w.+-])*', Name.Builtin),
  47. (r'[0-9][0-9\.]*', Number),
  48. (r'(?s)"(\\"|[^"])*"', String), # "string"
  49. (r'\.\.\.', Name.Variable),
  50. (r'<', Operator, '#push'), # <..|..> is different from <expr>
  51. (r'>', Operator, '#pop'),
  52. (r'\n', Whitespace),
  53. (r'[ \t]+', Whitespace),
  54. (r'#.*\n', Comment),
  55. # (r'[^<>\])\}\|$"# \t\n]+', Name.Exception), # fallback, for debugging only
  56. ]
  57. from docutils.utils.code_analyzer import Lexer, LexerError
  58. from docutils.parsers.rst import Directive, directives
  59. from docutils.transforms import Transform
  60. from docutils.nodes import Element, Node, TextElement, system_message
  61. from docutils import io, nodes
  62. from sphinx.directives import ObjectDescription, nl_escape_re
  63. from sphinx.domains import Domain, ObjType
  64. from sphinx.roles import XRefRole
  65. from sphinx.util.nodes import make_refnode
  66. from sphinx.util import logging, ws_re
  67. from sphinx import addnodes
  68. logger = logging.getLogger(__name__)
  69. sphinx_before_1_4 = False
  70. sphinx_before_1_7_2 = False
  71. try:
  72. from sphinx import version_info
  73. if version_info < (1, 4):
  74. sphinx_before_1_4 = True
  75. if version_info < (1, 7, 2):
  76. sphinx_before_1_7_2 = True
  77. except ImportError:
  78. # The `sphinx.version_info` tuple was added in Sphinx v1.2:
  79. sphinx_before_1_4 = True
  80. sphinx_before_1_7_2 = True
  81. if sphinx_before_1_7_2:
  82. # Monkey patch for sphinx generating invalid content for qcollectiongenerator
  83. # https://github.com/sphinx-doc/sphinx/issues/1435
  84. from sphinx.util.pycompat import htmlescape
  85. from sphinx.builders.qthelp import QtHelpBuilder
  86. old_build_keywords = QtHelpBuilder.build_keywords
  87. def new_build_keywords(self, title, refs, subitems):
  88. old_items = old_build_keywords(self, title, refs, subitems)
  89. new_items = []
  90. for item in old_items:
  91. before, rest = item.split("ref=\"", 1)
  92. ref, after = rest.split("\"")
  93. if ("<" in ref and ">" in ref):
  94. new_items.append(before + "ref=\"" + htmlescape(ref) + "\"" + after)
  95. else:
  96. new_items.append(item)
  97. return new_items
  98. QtHelpBuilder.build_keywords = new_build_keywords
  99. @dataclass
  100. class ObjectEntry:
  101. docname: str
  102. objtype: str
  103. node_id: str
  104. name: str
  105. class CMakeModule(Directive):
  106. required_arguments = 1
  107. optional_arguments = 0
  108. final_argument_whitespace = True
  109. option_spec = {'encoding': directives.encoding}
  110. def __init__(self, *args, **keys):
  111. self.re_start = re.compile(r'^#\[(?P<eq>=*)\[\.rst:$')
  112. Directive.__init__(self, *args, **keys)
  113. def run(self):
  114. settings = self.state.document.settings
  115. if not settings.file_insertion_enabled:
  116. raise self.warning('"%s" directive disabled.' % self.name)
  117. env = self.state.document.settings.env
  118. rel_path, path = env.relfn2path(self.arguments[0])
  119. path = os.path.normpath(path)
  120. encoding = self.options.get('encoding', settings.input_encoding)
  121. e_handler = settings.input_encoding_error_handler
  122. try:
  123. settings.record_dependencies.add(path)
  124. f = io.FileInput(source_path=path, encoding=encoding,
  125. error_handler=e_handler)
  126. except UnicodeEncodeError as error:
  127. msg = ('Problems with "%s" directive path:\n'
  128. 'Cannot encode input file path "%s" '
  129. '(wrong locale?).' % (self.name, path))
  130. raise self.severe(msg)
  131. except IOError as error:
  132. msg = 'Problems with "%s" directive path:\n%s.' % (self.name, error)
  133. raise self.severe(msg)
  134. raw_lines = f.read().splitlines()
  135. f.close()
  136. rst = None
  137. lines = []
  138. for line in raw_lines:
  139. if rst is not None and rst != '#':
  140. # Bracket mode: check for end bracket
  141. pos = line.find(rst)
  142. if pos >= 0:
  143. if line[0] == '#':
  144. line = ''
  145. else:
  146. line = line[0:pos]
  147. rst = None
  148. else:
  149. # Line mode: check for .rst start (bracket or line)
  150. m = self.re_start.match(line)
  151. if m:
  152. rst = ']%s]' % m.group('eq')
  153. line = ''
  154. elif line == '#.rst:':
  155. rst = '#'
  156. line = ''
  157. elif rst == '#':
  158. if line == '#' or line[:2] == '# ':
  159. line = line[2:]
  160. else:
  161. rst = None
  162. line = ''
  163. elif rst is None:
  164. line = ''
  165. lines.append(line)
  166. if rst is not None and rst != '#':
  167. raise self.warning('"%s" found unclosed bracket "#[%s[.rst:" in %s' %
  168. (self.name, rst[1:-1], path))
  169. self.state_machine.insert_input(lines, path)
  170. return []
  171. class _cmake_index_entry:
  172. def __init__(self, desc):
  173. self.desc = desc
  174. def __call__(self, title, targetid, main = 'main'):
  175. # See https://github.com/sphinx-doc/sphinx/issues/2673
  176. if sphinx_before_1_4:
  177. return ('pair', u'%s ; %s' % (self.desc, title), targetid, main)
  178. else:
  179. return ('pair', u'%s ; %s' % (self.desc, title), targetid, main, None)
  180. _cmake_index_objs = {
  181. 'command': _cmake_index_entry('command'),
  182. 'cpack_gen': _cmake_index_entry('cpack generator'),
  183. 'envvar': _cmake_index_entry('envvar'),
  184. 'generator': _cmake_index_entry('generator'),
  185. 'genex': _cmake_index_entry('genex'),
  186. 'guide': _cmake_index_entry('guide'),
  187. 'manual': _cmake_index_entry('manual'),
  188. 'module': _cmake_index_entry('module'),
  189. 'policy': _cmake_index_entry('policy'),
  190. 'prop_cache': _cmake_index_entry('cache property'),
  191. 'prop_dir': _cmake_index_entry('directory property'),
  192. 'prop_gbl': _cmake_index_entry('global property'),
  193. 'prop_inst': _cmake_index_entry('installed file property'),
  194. 'prop_sf': _cmake_index_entry('source file property'),
  195. 'prop_test': _cmake_index_entry('test property'),
  196. 'prop_tgt': _cmake_index_entry('target property'),
  197. 'variable': _cmake_index_entry('variable'),
  198. }
  199. class CMakeTransform(Transform):
  200. # Run this transform early since we insert nodes we want
  201. # treated as if they were written in the documents.
  202. default_priority = 210
  203. def __init__(self, document, startnode):
  204. Transform.__init__(self, document, startnode)
  205. self.titles = {}
  206. def parse_title(self, docname):
  207. """Parse a document title as the first line starting in [A-Za-z0-9<$]
  208. or fall back to the document basename if no such line exists.
  209. The cmake --help-*-list commands also depend on this convention.
  210. Return the title or False if the document file does not exist.
  211. """
  212. env = self.document.settings.env
  213. title = self.titles.get(docname)
  214. if title is None:
  215. fname = os.path.join(env.srcdir, docname+'.rst')
  216. try:
  217. f = open(fname, 'r')
  218. except IOError:
  219. title = False
  220. else:
  221. for line in f:
  222. if len(line) > 0 and (line[0].isalnum() or line[0] == '<' or line[0] == '$'):
  223. title = line.rstrip()
  224. break
  225. f.close()
  226. if title is None:
  227. title = os.path.basename(docname)
  228. self.titles[docname] = title
  229. return title
  230. def apply(self):
  231. env = self.document.settings.env
  232. # Treat some documents as cmake domain objects.
  233. objtype, sep, tail = env.docname.partition('/')
  234. make_index_entry = _cmake_index_objs.get(objtype)
  235. if make_index_entry:
  236. title = self.parse_title(env.docname)
  237. # Insert the object link target.
  238. if objtype == 'command':
  239. targetname = title.lower()
  240. elif objtype == 'guide' and not tail.endswith('/index'):
  241. targetname = tail
  242. else:
  243. if objtype == 'genex':
  244. m = CMakeXRefRole._re_genex.match(title)
  245. if m:
  246. title = m.group(1)
  247. targetname = title
  248. targetid = '%s:%s' % (objtype, targetname)
  249. targetnode = nodes.target('', '', ids=[targetid])
  250. self.document.note_explicit_target(targetnode)
  251. self.document.insert(0, targetnode)
  252. # Insert the object index entry.
  253. indexnode = addnodes.index()
  254. indexnode['entries'] = [make_index_entry(title, targetid)]
  255. self.document.insert(0, indexnode)
  256. # Add to cmake domain object inventory
  257. domain = cast(CMakeDomain, env.get_domain('cmake'))
  258. domain.note_object(objtype, targetname, targetid, targetid)
  259. class CMakeObject(ObjectDescription):
  260. def __init__(self, *args, **kwargs):
  261. self.targetname = None
  262. super().__init__(*args, **kwargs)
  263. def handle_signature(self, sig, signode):
  264. # called from sphinx.directives.ObjectDescription.run()
  265. signode += addnodes.desc_name(sig, sig)
  266. return sig
  267. def add_target_and_index(self, name, sig, signode):
  268. if self.objtype == 'command':
  269. targetname = name.lower()
  270. elif self.targetname:
  271. targetname = self.targetname
  272. else:
  273. targetname = name
  274. targetid = '%s:%s' % (self.objtype, targetname)
  275. if targetid not in self.state.document.ids:
  276. signode['names'].append(targetid)
  277. signode['ids'].append(targetid)
  278. signode['first'] = (not self.names)
  279. self.state.document.note_explicit_target(signode)
  280. domain = cast(CMakeDomain, self.env.get_domain('cmake'))
  281. domain.note_object(self.objtype, targetname, targetid, targetid,
  282. location=signode)
  283. make_index_entry = _cmake_index_objs.get(self.objtype)
  284. if make_index_entry:
  285. self.indexnode['entries'].append(make_index_entry(name, targetid))
  286. class CMakeGenexObject(CMakeObject):
  287. option_spec = {
  288. 'target': directives.unchanged,
  289. }
  290. def handle_signature(self, sig, signode):
  291. name = super().handle_signature(sig, signode)
  292. m = CMakeXRefRole._re_genex.match(sig)
  293. if m:
  294. name = m.group(1)
  295. return name
  296. def run(self):
  297. target = self.options.get('target')
  298. if target is not None:
  299. self.targetname = target
  300. return super().run()
  301. class CMakeSignatureObject(CMakeObject):
  302. object_type = 'signature'
  303. BREAK_ALL = 'all'
  304. BREAK_SMART = 'smart'
  305. BREAK_VERBATIM = 'verbatim'
  306. BREAK_CHOICES = {BREAK_ALL, BREAK_SMART, BREAK_VERBATIM}
  307. def break_option(argument):
  308. return directives.choice(argument, CMakeSignatureObject.BREAK_CHOICES)
  309. option_spec = {
  310. 'target': directives.unchanged,
  311. 'break': break_option,
  312. }
  313. def _break_signature_all(sig: str) -> str:
  314. return ws_re.sub(' ', sig)
  315. def _break_signature_verbatim(sig: str) -> str:
  316. lines = [ws_re.sub('\xa0', line.strip()) for line in sig.split('\n')]
  317. return ' '.join(lines)
  318. def _break_signature_smart(sig: str) -> str:
  319. tokens = []
  320. for line in sig.split('\n'):
  321. token = ''
  322. delim = ''
  323. for c in line.strip():
  324. if len(delim) == 0 and ws_re.match(c):
  325. if len(token):
  326. tokens.append(ws_re.sub('\xa0', token))
  327. token = ''
  328. else:
  329. if c == '[':
  330. delim += ']'
  331. elif c == '<':
  332. delim += '>'
  333. elif len(delim) and c == delim[-1]:
  334. delim = delim[:-1]
  335. token += c
  336. if len(token):
  337. tokens.append(ws_re.sub('\xa0', token))
  338. return ' '.join(tokens)
  339. def __init__(self, *args, **kwargs):
  340. self.targetnames = {}
  341. self.break_style = CMakeSignatureObject.BREAK_SMART
  342. super().__init__(*args, **kwargs)
  343. def get_signatures(self) -> List[str]:
  344. content = nl_escape_re.sub('', self.arguments[0])
  345. lines = sig_end_re.split(content)
  346. if self.break_style == CMakeSignatureObject.BREAK_VERBATIM:
  347. fixup = CMakeSignatureObject._break_signature_verbatim
  348. elif self.break_style == CMakeSignatureObject.BREAK_SMART:
  349. fixup = CMakeSignatureObject._break_signature_smart
  350. else:
  351. fixup = CMakeSignatureObject._break_signature_all
  352. return [fixup(line.strip()) for line in lines]
  353. def handle_signature(self, sig, signode):
  354. language = 'cmake'
  355. classes = ['code', 'cmake', 'highlight']
  356. node = addnodes.desc_name(sig, '', classes=classes)
  357. try:
  358. tokens = Lexer(sig, language, 'short')
  359. except LexerError as error:
  360. if self.state.document.settings.report_level > 2:
  361. # Silently insert without syntax highlighting.
  362. tokens = Lexer(sig, language, 'none')
  363. else:
  364. raise self.warning(error)
  365. for classes, value in tokens:
  366. if value == '\xa0':
  367. node += nodes.inline(value, value, classes=['nbsp'])
  368. elif classes:
  369. node += nodes.inline(value, value, classes=classes)
  370. else:
  371. node += nodes.Text(value)
  372. signode.clear()
  373. signode += node
  374. return sig
  375. def add_target_and_index(self, name, sig, signode):
  376. sig = sig.replace('\xa0', ' ')
  377. if sig in self.targetnames:
  378. sigargs = self.targetnames[sig]
  379. else:
  380. def extract_keywords(params):
  381. for p in params:
  382. if p[0].isalpha():
  383. yield p
  384. else:
  385. return
  386. keywords = extract_keywords(sig.split('(')[1].split())
  387. sigargs = ' '.join(keywords)
  388. targetname = sigargs.lower()
  389. targetid = nodes.make_id(targetname)
  390. if targetid not in self.state.document.ids:
  391. signode['names'].append(targetname)
  392. signode['ids'].append(targetid)
  393. signode['first'] = (not self.names)
  394. self.state.document.note_explicit_target(signode)
  395. # Register the signature as a command object.
  396. command = sig.split('(')[0].lower()
  397. refname = f'{command}({sigargs})'
  398. refid = f'command:{command}({targetname})'
  399. domain = cast(CMakeDomain, self.env.get_domain('cmake'))
  400. domain.note_object('command', name=refname, target_id=refid,
  401. node_id=targetid, location=signode)
  402. def run(self):
  403. self.break_style = CMakeSignatureObject.BREAK_ALL
  404. targets = self.options.get('target')
  405. if targets is not None:
  406. signatures = self.get_signatures()
  407. targets = [t.strip() for t in targets.split('\n')]
  408. for signature, target in zip(signatures, targets):
  409. self.targetnames[signature] = target
  410. self.break_style = (
  411. self.options.get('break', CMakeSignatureObject.BREAK_SMART))
  412. return super().run()
  413. class CMakeReferenceRole:
  414. # See sphinx.util.nodes.explicit_title_re; \x00 escapes '<'.
  415. _re = re.compile(r'^(.+?)(\s*)(?<!\x00)<(.*?)>$', re.DOTALL)
  416. @staticmethod
  417. def _escape_angle_brackets(text: str) -> str:
  418. # CMake cross-reference targets frequently contain '<' so escape
  419. # any explicit `<target>` with '<' not preceded by whitespace.
  420. while True:
  421. m = CMakeReferenceRole._re.match(text)
  422. if m and len(m.group(2)) == 0:
  423. text = f'{m.group(1)}\x00<{m.group(3)}>'
  424. else:
  425. break
  426. return text
  427. def __class_getitem__(cls, parent: Any):
  428. class Class(parent):
  429. def __call__(self, name: str, rawtext: str, text: str,
  430. *args, **kwargs
  431. ) -> Tuple[List[Node], List[system_message]]:
  432. text = CMakeReferenceRole._escape_angle_brackets(text)
  433. return super().__call__(name, rawtext, text, *args, **kwargs)
  434. return Class
  435. class CMakeXRefRole(CMakeReferenceRole[XRefRole]):
  436. _re_sub = re.compile(r'^([^()\s]+)\s*\(([^()]*)\)$', re.DOTALL)
  437. _re_genex = re.compile(r'^\$<([^<>:]+)(:[^<>]+)?>$', re.DOTALL)
  438. _re_guide = re.compile(r'^([^<>/]+)/([^<>]*)$', re.DOTALL)
  439. def __call__(self, typ, rawtext, text, *args, **kwargs):
  440. if typ == 'cmake:command':
  441. # Translate a CMake command cross-reference of the form:
  442. # `command_name(SUB_COMMAND)`
  443. # to be its own explicit target:
  444. # `command_name(SUB_COMMAND) <command_name(SUB_COMMAND)>`
  445. # so the XRefRole `fix_parens` option does not add more `()`.
  446. m = CMakeXRefRole._re_sub.match(text)
  447. if m:
  448. text = f'{text} <{text}>'
  449. elif typ == 'cmake:genex':
  450. m = CMakeXRefRole._re_genex.match(text)
  451. if m:
  452. text = '%s <%s>' % (text, m.group(1))
  453. elif typ == 'cmake:guide':
  454. m = CMakeXRefRole._re_guide.match(text)
  455. if m:
  456. text = '%s <%s>' % (m.group(2), text)
  457. return super().__call__(typ, rawtext, text, *args, **kwargs)
  458. # We cannot insert index nodes using the result_nodes method
  459. # because CMakeXRefRole is processed before substitution_reference
  460. # nodes are evaluated so target nodes (with 'ids' fields) would be
  461. # duplicated in each evaluated substitution replacement. The
  462. # docutils substitution transform does not allow this. Instead we
  463. # use our own CMakeXRefTransform below to add index entries after
  464. # substitutions are completed.
  465. #
  466. # def result_nodes(self, document, env, node, is_ref):
  467. # pass
  468. class CMakeXRefTransform(Transform):
  469. # Run this transform early since we insert nodes we want
  470. # treated as if they were written in the documents, but
  471. # after the sphinx (210) and docutils (220) substitutions.
  472. default_priority = 221
  473. def apply(self):
  474. env = self.document.settings.env
  475. # Find CMake cross-reference nodes and add index and target
  476. # nodes for them.
  477. for ref in self.document.traverse(addnodes.pending_xref):
  478. if not ref['refdomain'] == 'cmake':
  479. continue
  480. objtype = ref['reftype']
  481. make_index_entry = _cmake_index_objs.get(objtype)
  482. if not make_index_entry:
  483. continue
  484. objname = ref['reftarget']
  485. if objtype == 'guide' and CMakeXRefRole._re_guide.match(objname):
  486. # Do not index cross-references to guide sections.
  487. continue
  488. if objtype == 'command':
  489. # Index signature references to their parent command.
  490. objname = objname.split('(')[0].lower()
  491. targetnum = env.new_serialno('index-%s:%s' % (objtype, objname))
  492. targetid = 'index-%s-%s:%s' % (targetnum, objtype, objname)
  493. targetnode = nodes.target('', '', ids=[targetid])
  494. self.document.note_explicit_target(targetnode)
  495. indexnode = addnodes.index()
  496. indexnode['entries'] = [make_index_entry(objname, targetid, '')]
  497. ref.replace_self([indexnode, targetnode, ref])
  498. class CMakeDomain(Domain):
  499. """CMake domain."""
  500. name = 'cmake'
  501. label = 'CMake'
  502. object_types = {
  503. 'command': ObjType('command', 'command'),
  504. 'cpack_gen': ObjType('cpack_gen', 'cpack_gen'),
  505. 'envvar': ObjType('envvar', 'envvar'),
  506. 'generator': ObjType('generator', 'generator'),
  507. 'genex': ObjType('genex', 'genex'),
  508. 'guide': ObjType('guide', 'guide'),
  509. 'variable': ObjType('variable', 'variable'),
  510. 'module': ObjType('module', 'module'),
  511. 'policy': ObjType('policy', 'policy'),
  512. 'prop_cache': ObjType('prop_cache', 'prop_cache'),
  513. 'prop_dir': ObjType('prop_dir', 'prop_dir'),
  514. 'prop_gbl': ObjType('prop_gbl', 'prop_gbl'),
  515. 'prop_inst': ObjType('prop_inst', 'prop_inst'),
  516. 'prop_sf': ObjType('prop_sf', 'prop_sf'),
  517. 'prop_test': ObjType('prop_test', 'prop_test'),
  518. 'prop_tgt': ObjType('prop_tgt', 'prop_tgt'),
  519. 'manual': ObjType('manual', 'manual'),
  520. }
  521. directives = {
  522. 'command': CMakeObject,
  523. 'envvar': CMakeObject,
  524. 'genex': CMakeGenexObject,
  525. 'signature': CMakeSignatureObject,
  526. 'variable': CMakeObject,
  527. # Other `object_types` cannot be created except by the `CMakeTransform`
  528. }
  529. roles = {
  530. 'command': CMakeXRefRole(fix_parens = True, lowercase = True),
  531. 'cpack_gen': CMakeXRefRole(),
  532. 'envvar': CMakeXRefRole(),
  533. 'generator': CMakeXRefRole(),
  534. 'genex': CMakeXRefRole(),
  535. 'guide': CMakeXRefRole(),
  536. 'variable': CMakeXRefRole(),
  537. 'module': CMakeXRefRole(),
  538. 'policy': CMakeXRefRole(),
  539. 'prop_cache': CMakeXRefRole(),
  540. 'prop_dir': CMakeXRefRole(),
  541. 'prop_gbl': CMakeXRefRole(),
  542. 'prop_inst': CMakeXRefRole(),
  543. 'prop_sf': CMakeXRefRole(),
  544. 'prop_test': CMakeXRefRole(),
  545. 'prop_tgt': CMakeXRefRole(),
  546. 'manual': CMakeXRefRole(),
  547. }
  548. initial_data = {
  549. 'objects': {}, # fullname -> docname, objtype
  550. }
  551. def clear_doc(self, docname):
  552. to_clear = set()
  553. for fullname, obj in self.data['objects'].items():
  554. if obj.docname == docname:
  555. to_clear.add(fullname)
  556. for fullname in to_clear:
  557. del self.data['objects'][fullname]
  558. def resolve_xref(self, env, fromdocname, builder,
  559. typ, target, node, contnode):
  560. targetid = f'{typ}:{target}'
  561. obj = self.data['objects'].get(targetid)
  562. if obj is None and typ == 'command':
  563. # If 'command(args)' wasn't found, try just 'command'.
  564. # TODO: remove this fallback? warn?
  565. # logger.warning(f'no match for {targetid}')
  566. command = target.split('(')[0]
  567. targetid = f'{typ}:{command}'
  568. obj = self.data['objects'].get(targetid)
  569. if obj is None:
  570. # TODO: warn somehow?
  571. return None
  572. return make_refnode(builder, fromdocname, obj.docname, obj.node_id,
  573. contnode, target)
  574. def note_object(self, objtype: str, name: str, target_id: str,
  575. node_id: str, location: Any = None):
  576. if target_id in self.data['objects']:
  577. other = self.data['objects'][target_id].docname
  578. logger.warning(
  579. f'CMake object {target_id!r} also described in {other!r}',
  580. location=location)
  581. self.data['objects'][target_id] = ObjectEntry(
  582. self.env.docname, objtype, node_id, name)
  583. def get_objects(self):
  584. for refname, obj in self.data['objects'].items():
  585. yield (refname, obj.name, obj.objtype, obj.docname, obj.node_id, 1)
  586. def setup(app):
  587. app.add_directive('cmake-module', CMakeModule)
  588. app.add_transform(CMakeTransform)
  589. app.add_transform(CMakeXRefTransform)
  590. app.add_domain(CMakeDomain)
  591. return {"parallel_read_safe": True}