cmake.py 26 KB

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