Debian Codegraph @

doc/tools/rocqrst/rocqdomain.py

raw symbols SCIP
1 ##########################################################################
2 ## # The Rocq Prover / The Rocq Development Team ##
3 ## v # Copyright INRIA, CNRS and contributors ##
4 ## <O___,, # (see version control and CREDITS file for authors & dates) ##
5 ## \VV/ ###############################################################
6 ## // # This file is distributed under the terms of the ##
7 ## # GNU Lesser General Public License Version 2.1 ##
8 ## # (see LICENSE file for the text of the license) ##
9 ##########################################################################
10 """A Rocq domain for Sphinx.
11
12 Currently geared towards Rocq's manual, rather than Rocq source files, but one
13 could imagine extending it.
14
15 Refer to doc/sphinx/README.rst for the documentation of the coqrst domain.
16 """
17
18 # pylint: disable=missing-type-doc, missing-param-doc
19 # pylint: disable=missing-return-type-doc, missing-return-doc
20 # pylint: disable=too-few-public-methods, too-many-ancestors, arguments-differ
21 # pylint: disable=import-outside-toplevel, abstract-method, too-many-lines
22
23 import os
24 import re
25 import shlex
26 from itertools import chain
27 from collections import defaultdict
28
29 from docutils import nodes, utils
30 from docutils.transforms import Transform
31 from docutils.parsers.rst import Directive, directives
32 from docutils.parsers.rst.roles import code_role #, set_classes
33 from docutils.parsers.rst.directives.admonitions import BaseAdmonition
34
35 from sphinx import addnodes, version_info as sphinx_version
36 from sphinx.directives import ObjectDescription
37 from sphinx.domains import Domain, ObjType, Index
38 from sphinx.errors import ExtensionError
39 from sphinx.roles import XRefRole
40 from sphinx.util.docutils import ReferenceRole
41 from sphinx.util.logging import getLogger, get_node_location
42 from sphinx.util.nodes import set_source_info, set_role_source_info, make_refnode
43 from sphinx.writers.latex import LaTeXTranslator
44
45 from . import rocqdoc
46 from .repl import ansicolors
47 from .repl.rocqtop import RocqTop, RocqTopError
48 from .notations.parsing import ParseError
49 from .notations.sphinx import sphinxify
50 from .notations.plain import stringify_with_ellipses
51
52 # FIXME: Patch this in Sphinx
53 # https://github.com/rocq-prover/rocq/issues/12361
54 if sphinx_version >= (4, 5):
55 from sphinx.writers.latex import CR
56
57 def visit_desc_signature(self, node):
58 hyper = ''
59 if node.parent['objtype'] != 'describe' and node['ids']:
60 for id in node['ids']:
61 hyper += self.hypertarget(id)
62 self.body.append(hyper)
63 if not self.in_desc_signature:
64 self.in_desc_signature = True
65 self.body.append(CR + r'\pysigstartsignatures')
66 if not node.get('is_multiline'):
67 self._visit_signature_line(node)
68 else:
69 self.body.append(CR + r'\pysigstartmultiline')
70 else:
71 def visit_desc_signature(self, node):
72 hyper = ''
73 if node.parent['objtype'] != 'describe' and node['ids']:
74 for id in node['ids']:
75 hyper += self.hypertarget(id)
76 self.body.append(hyper)
77 if not node.get('is_multiline'):
78 self._visit_signature_line(node)
79 else:
80 self.body.append('%\n\\pysigstartmultiline\n')
81 LaTeXTranslator.visit_desc_signature = visit_desc_signature
82
83 PARSE_ERROR = """{}:{} Parse error in notation!
84 Offending notation: {}
85 Error message: {}"""
86
87 def notation_to_sphinx(notation, source, line, rawtext=None):
88 """Parse notation and wrap it in an inline node"""
89 try:
90 node = nodes.inline(rawtext or notation, '', *sphinxify(notation), classes=['notation'])
91 node.source, node.line = source, line
92 return node
93 except ParseError as e:
94 raise ExtensionError(PARSE_ERROR.format(os.path.basename(source), line, notation, e.msg)) from e
95
96 def notation_to_string(notation):
97 """Parse notation and format it as a string with ellipses."""
98 try:
99 return stringify_with_ellipses(notation)
100 except ParseError as e:
101 # FIXME source and line aren't defined below — see cc93f419e0
102 raise ExtensionError(PARSE_ERROR.format(os.path.basename(source), line, notation, e.msg)) from e
103
104 def highlight_using_rocqdoc(sentence):
105 """Lex sentence using rocqdoc, and yield inline nodes for each token"""
106 tokens = rocqdoc.lex(utils.unescape(sentence, 1))
107 for classes, value in tokens:
108 yield nodes.inline(value, value, classes=classes)
109
110 def make_target(objtype, targetid):
111 """Create a target to an object of type objtype and id targetid"""
112 return "rocq:{}.{}".format(objtype, targetid)
113
114 def make_math_node(latex, docname, nowrap):
115 node = nodes.math_block(latex, latex)
116 node['label'] = None # Otherwise equations are numbered
117 node['nowrap'] = nowrap
118 node['docname'] = docname
119 node['number'] = None
120 return node
121
122 # To support any character in tacn, ... names.
123 # see https://github.com/rocq-prover/rocq/pull/13564
124 def make_id(tag):
125 return tag.replace(" ", "-")
126
127 class RocqObject(ObjectDescription):
128 """A generic Rocq object for Sphinx; all Rocq objects are subclasses of this.
129
130 The fields and methods to override are listed at the top of this class'
131 implementation. Each object supports the :name: option, which gives an
132 explicit name to link to.
133
134 See the comments and docstrings in RocqObject for more information.
135 """
136
137 # The semantic domain in which this object lives (eg. “tac”, “cmd”, “chm”…).
138 # It matches exactly one of the roles used for cross-referencing.
139 subdomain = None # type: str
140
141 # The suffix to use in indices for objects of this type (eg. “(tac)”)
142 index_suffix = None # type: str
143
144 # The annotation to add to headers of objects of this type
145 # (eg. “Command”, “Theorem”)
146 annotation = None # type: str
147
148 def __init__(self, *args, **kwargs):
149 super().__init__(*args, **kwargs)
150 self._sig_names = None
151
152 def _name_from_signature(self, signature): # pylint: disable=no-self-use, unused-argument
153 """Convert a signature into a name to link to.
154
155 ‘Signature’ is Sphinx parlance for an object's header (think “type
156 signature”); for example, the signature of the simplest form of the
157 ``exact`` tactic is ``exact @id``.
158
159 Generates a name for the directive. Override this method to return None
160 to avoid generating a name automatically. This is a convenient way
161 to automatically generate names (link targets) without having to write
162 explicit names everywhere.
163
164 """
165 m = re.match(r"[a-zA-Z0-9_ ]+", signature)
166 if m:
167 return m.group(0).strip()
168
169 def _render_signature(self, signature, signode):
170 """Render a signature, placing resulting nodes into signode."""
171 raise NotImplementedError(self)
172
173 option_spec = {
174 # Explicit object naming
175 'name': directives.unchanged,
176 # Silence warnings produced by report_undocumented_rocq_objects
177 'undocumented': directives.flag,
178 # noindex omits this object from its index
179 'noindex': directives.flag
180 }
181
182 def subdomain_data(self):
183 if self.subdomain is None:
184 raise ValueError()
185 return self.env.domaindata['rocq']['objects'][self.subdomain]
186
187 def _render_annotation(self, signode):
188 if self.annotation:
189 annot_node = nodes.inline(self.annotation, self.annotation, classes=['sigannot'])
190 signode += addnodes.desc_annotation(self.annotation, '', annot_node)
191 signode += nodes.Text(' ')
192
193 def handle_signature(self, signature, signode):
194 """Prefix signature with the proper annotation, then render it using
195 ``_render_signature`` (for example, add “Command” in front of commands).
196
197 :returns: the names given to the resulting node.
198 """
199 self._render_annotation(signode)
200 self._render_signature(signature, signode)
201 names = self._sig_names.get(signature)
202 if names is None:
203 name = self._name_from_signature(signature) # pylint: disable=assignment-from-none
204 # remove trailing ‘.’ found in commands, but not ‘...’ (ellipsis)
205 if name is not None and name.endswith(".") and not name.endswith("..."):
206 name = name[:-1]
207 names = [name] if name else None
208 return names
209
210 def _warn_if_duplicate_name(self, objects, name, signode):
211 """Check that two objects in the same domain don't have the same name."""
212 if name in objects:
213 MSG = 'Duplicate name {} (other is in {}) attached to {}'
214 msg = MSG.format(name, self.env.doc2path(objects[name][0]), signode)
215 self.state_machine.reporter.warning(msg, line=self.lineno)
216
217 def _record_name(self, name, target_id, signode):
218 """Record a `name` in the current subdomain, mapping it to `target_id`.
219
220 Warns if another object of the same name already exists; `signode` is
221 used in the warning.
222 """
223 names_in_subdomain = self.subdomain_data()
224 self._warn_if_duplicate_name(names_in_subdomain, name, signode)
225 names_in_subdomain[name] = (self.env.docname, self.objtype, target_id)
226
227 def _target_id(self, name):
228 return make_target(self.objtype, make_id(name))
229
230 def _add_target(self, signode, name):
231 """Register a link target ‘name’, pointing to signode."""
232 targetid = self._target_id(name)
233 if targetid not in self.state.document.ids:
234 signode['ids'].append(targetid)
235 signode['names'].append(name)
236 signode['first'] = (not self.names)
237 self._record_name(name, targetid, signode)
238 else:
239 # We don't warn for duplicates in the SSReflect chapter, because
240 # it's the style of this chapter to repeat all the defined
241 # objects at the end.
242 if self.env.docname != 'proof-engine/ssreflect-proof-language':
243 self._warn_if_duplicate_name(self.subdomain_data(), name, signode)
244 return targetid
245
246 def _add_index_entry(self, name, target):
247 """Add `name` (pointing to `target`) to the main index."""
248 assert isinstance(name, str)
249 # remove trailing . , found in commands, but not ... (ellipsis)
250 trim = name.endswith(".") and not name.endswith("...")
251 index_text = name[:-1] if trim else name
252 if self.index_suffix:
253 index_text += " " + self.index_suffix
254 self.indexnode['entries'].append(('single', index_text, target, '', None))
255
256 def add_target_and_index(self, names, _, signode):
257 """Attach a link target to `signode` and index entries for `names`.
258 This is only called (from ``ObjectDescription.run``) if ``:noindex:`` isn't specified."""
259 if names:
260 for name in names:
261 if isinstance(name, str) and name.startswith('_'):
262 continue
263 target = self._add_target(signode, name)
264 self._add_index_entry(name, target)
265 self.state.document.note_explicit_target(signode)
266
267 def _prepare_names(self):
268 """Construct ``self._sig_names``, a map from signatures to names.
269
270 A node may have either one signature with no name, multiple signatures
271 with one name per signatures, or one signature with multiple names.
272 """
273 sigs = self.get_signatures()
274 names = self.options.get("name")
275 if names is None:
276 self._sig_names = {}
277 else:
278 names = [n.strip() for n in names.split(";")]
279 if len(names) != len(sigs):
280 if len(sigs) != 1: #Multiple names for one signature
281 ERR = ("Expected {} semicolon-separated names, got {}. " +
282 "Please provide one name per signature line.")
283 raise self.error(ERR.format(len(names), len(sigs)))
284 self._sig_names = { sigs[0]: names }
285 else:
286 self._sig_names = { sig: [name] for (sig, name) in zip(sigs, names) }
287
288 def run(self):
289 self._prepare_names()
290 return super().run()
291
292 class DocumentableObject(RocqObject):
293
294 def _warn_if_undocumented(self):
295 document = self.state.document
296 config = document.settings.env.config
297 report = config.report_undocumented_rocq_objects
298 if report and not self.content and "undocumented" not in self.options:
299 # This is annoyingly convoluted, but we don't want to raise warnings
300 # or interrupt the generation of the current node. For more details
301 # see https://github.com/sphinx-doc/sphinx/issues/4976.
302 msg = 'No contents in directive {}'.format(self.name)
303 node = document.reporter.info(msg, line=self.lineno)
304 getLogger(__name__).info(node.astext())
305 if report == "warning":
306 raise self.warning(msg)
307
308 def run(self):
309 self._warn_if_undocumented()
310 return super().run()
311
312 class PlainObject(DocumentableObject):
313 """A base class for objects whose signatures should be rendered literally."""
314 def _render_signature(self, signature, signode):
315 signode += addnodes.desc_name(signature, signature)
316
317 class NotationObject(DocumentableObject):
318 """A base class for objects whose signatures should be rendered as nested boxes.
319
320 Objects that inherit from this class can use the notation grammar (“{+ …}”,
321 “@…”, etc.) in their signature.
322 """
323 def _render_signature(self, signature, signode):
324 position = self.state_machine.get_source_and_line(self.lineno)
325 tacn_node = notation_to_sphinx(signature, *position)
326 signode += addnodes.desc_name(signature, '', tacn_node)
327
328 class GallinaObject(PlainObject):
329 """ A Theorem object.
330 See the documentation of the ".. thm::" object in doc/sphinx/README.rst.
331 """
332 subdomain = "thm"
333 index_suffix = "(theorem)"
334 annotation = "Theorem"
335
336 class VernacObject(NotationObject):
337 """A Rocq command object.
338 See the documentation of the ".. cmd::" object in doc/sphinx/README.rst.
339 """
340 subdomain = "cmd"
341 index_suffix = "(command)"
342 annotation = "Command"
343
344 def _name_from_signature(self, signature):
345 m = re.match(r"[a-zA-Z0-9_ ]+", signature)
346 return m.group(0).strip() if m else None
347
348 class VernacVariantObject(VernacObject):
349 """An object for a variant of a Rocq command.
350 See the documentation of the ".. cmdv::" object in doc/sphinx/README.rst.
351 """
352 index_suffix = "(command variant)"
353 annotation = "Variant"
354
355 def _name_from_signature(self, signature):
356 return None
357
358 class TacticObject(NotationObject):
359 """An object for a tactic, or a tactic notation.
360 See the documentation of the ".. tacn::" object in doc/sphinx/README.rst.
361 """
362 subdomain = "tacn"
363 index_suffix = "(tactic)"
364 annotation = "Tactic"
365
366 class AttributeObject(NotationObject):
367 """An attribute object.
368 See the documentation of the ".. attr::" object in doc/sphinx/README.rst.
369 """
370 subdomain = "attr"
371 index_suffix = "(attribute)"
372 annotation = "Attribute"
373
374 def _name_from_signature(self, signature):
375 return notation_to_string(signature)
376
377 class TacticVariantObject(TacticObject):
378 """An object for a variant of a tactic.
379 See the documentation of the ".. tacv::" object in doc/sphinx/README.rst.
380 """
381 index_suffix = "(tactic variant)"
382 annotation = "Variant"
383
384 def _name_from_signature(self, signature):
385 return None
386
387 class OptionObject(NotationObject):
388 """An object for a Rocq option (a setting with non-boolean value, e.g. a
389 string or numeric value).
390 See the documentation of the ".. opt::" object in doc/sphinx/README.rst.
391 """
392 subdomain = "opt"
393 index_suffix = "(option)"
394 annotation = "Option"
395
396 class FlagObject(NotationObject):
397 """An object for a Rocq flag (i.e. a boolean setting).
398 See the documentation of the ".. flag::" object in doc/sphinx/README.rst.
399 """
400 subdomain = "flag"
401 index_suffix = "(flag)"
402 annotation = "Flag"
403
404 class TableObject(NotationObject):
405 """An object for a Rocq table, i.e. a setting that is a set of values.
406 See the documentation of the ".. table::" object in doc/sphinx/README.rst.
407 """
408 subdomain = "table"
409 index_suffix = "(table)"
410 annotation = "Table"
411
412 class ProductionObject(RocqObject):
413 """A grammar production.
414 See the documentation of the ".. prodn::" object in doc/sphinx/README.rst.
415 """
416 subdomain = "prodn"
417 #annotation = "Grammar production"
418
419 # handle_signature is called for each line of input in the prodn::
420 # 'signatures' accumulates them in order to combine the lines into a single table:
421 signatures = None # FIXME this should be in init, shouldn't it?
422
423 def _render_signature(self, signature, signode):
424 raise NotImplementedError(self)
425
426 SIG_ERROR = ("{}: Invalid syntax in ``.. prodn::`` directive"
427 + "\nExpected ``name ::= ...`` or ``name += ...``"
428 + " (e.g. ``pattern += constr:(@ident)``)\n"
429 + " in `{}`")
430
431 def handle_signature(self, signature, signode):
432 parts = signature.split(maxsplit=1)
433 if parts[0].strip() == "|" and len(parts) == 2:
434 lhs = ""
435 op = "|"
436 rhs = parts[1].strip()
437 else:
438 parts = signature.split(maxsplit=2)
439 if len(parts) != 3:
440 loc = os.path.basename(get_node_location(signode))
441 raise ExtensionError(ProductionObject.SIG_ERROR.format(loc, signature))
442 lhs, op, rhs = (part.strip() for part in parts)
443 if op not in ["::=", "+="]:
444 loc = os.path.basename(get_node_location(signode))
445 raise ExtensionError(ProductionObject.SIG_ERROR.format(loc, signature))
446
447 parts = rhs.split(" ", maxsplit=1)
448 rhs = parts[0].strip()
449 tag = parts[1].strip() if len(parts) == 2 else ""
450
451 self.signatures.append((lhs, op, rhs, tag))
452 return [('token', lhs)] if op == '::=' else None
453
454 def _add_index_entry(self, name, target):
455 pass
456
457 def _target_id(self, name):
458 return make_id('grammar-token-{}'.format(name[1]))
459
460 def _record_name(self, name, targetid, signode):
461 env = self.state.document.settings.env
462 objects = env.domaindata['std']['objects']
463 self._warn_if_duplicate_name(objects, name, signode)
464 objects[name] = env.docname, targetid
465
466 def run(self):
467 self.signatures = []
468 indexnode = super().run()[0] # makes calls to handle_signature
469
470 table = nodes.inline(classes=['prodn-table'])
471 tgroup = nodes.inline(classes=['prodn-column-group'])
472 for _ in range(4):
473 tgroup += nodes.inline(classes=['prodn-column'])
474 table += tgroup
475 tbody = nodes.inline(classes=['prodn-row-group'])
476 table += tbody
477
478 # create rows
479 for signature in self.signatures:
480 lhs, op, rhs, tag = signature
481 position = self.state_machine.get_source_and_line(self.lineno)
482
483 row = nodes.inline(classes=['prodn-row'])
484 entry = nodes.inline(classes=['prodn-cell-nonterminal'])
485 if lhs != "":
486 target_name = make_id('grammar-token-' + lhs)
487 target = nodes.target('', '', ids=[target_name], names=[target_name])
488 # putting prodn-target on the target node won't appear in the tex file
489 inline = nodes.inline(classes=['prodn-target'])
490 inline += target
491 entry += inline
492 entry += notation_to_sphinx('@'+lhs, *position)
493 else:
494 entry += nodes.literal('', '')
495 row += entry
496
497 entry = nodes.inline(classes=['prodn-cell-op'])
498 entry += nodes.literal(op, op)
499 row += entry
500
501 entry = nodes.inline(classes=['prodn-cell-production'])
502 entry += notation_to_sphinx(rhs, *position)
503 row += entry
504
505 entry = nodes.inline(classes=['prodn-cell-tag'])
506 entry += nodes.literal(tag, tag)
507 row += entry
508
509 tbody += row
510
511 return [indexnode, table] # only this node goes into the doc
512
513 class ExceptionObject(NotationObject):
514 """An object for an error raised by a Rocq command or tactic.
515 See the documentation of the ".. exn::" object in doc/sphinx/README.rst.
516 """
517 subdomain = "exn"
518 index_suffix = "(error)"
519 annotation = "Error"
520 # Uses “exn” since “err” already is a CSS class added by “writer_aux”.
521
522 # Generate names automatically
523 def _name_from_signature(self, signature):
524 return notation_to_string(signature)
525
526 class WarningObject(NotationObject):
527 """An object for a warning raised by a Rocq command or tactic..
528 See the documentation of the ".. warn::" object in doc/sphinx/README.rst.
529 """
530 subdomain = "warn"
531 index_suffix = "(warning)"
532 annotation = "Warning"
533
534 # Generate names automatically
535 def _name_from_signature(self, signature):
536 return notation_to_string(signature)
537
538 def NotationRole(role, rawtext, text, lineno, inliner, options={}, content=[]):
539 #pylint: disable=unused-argument, dangerous-default-value
540 """A role for any text using the notation syntax (``@id``, ``{+, …}``, etc.).
541 See the documentation of the ":n:" role in doc/sphinx/README.rst.
542 """
543 notation = utils.unescape(text, 1)
544 position = inliner.reporter.get_source_and_line(lineno)
545 return [nodes.literal(rawtext, '', notation_to_sphinx(notation, *position, rawtext=rawtext))], []
546
547 def rocq_code_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
548 #pylint: disable=dangerous-default-value
549 """A Rocq code role for Gallina and Ltac snippets.
550 See the documentation of the ":g:" role in doc/sphinx/README.rst.
551 """
552 options['language'] = 'Coq'
553 return code_role(role, rawtext, text, lineno, inliner, options, content)
554 ## Too heavy:
555 ## Forked from code_role to use our custom tokenizer; this doesn't work for
556 ## snippets though: for example RocqDoc swallows the parentheses around this:
557 ## “(a: A) (b: B)”
558 # set_classes(options)
559 # classes = ['code', 'rocq']
560 # code = utils.unescape(text, 1)
561 # node = nodes.literal(rawtext, '', *highlight_using_rocqdoc(code), classes=classes)
562 # return [node], []
563
564 RocqCodeRole = rocq_code_role
565
566 class RocqtopDirective(Directive):
567 """A reST directive to describe interactions with Rocq Top.
568 See the documentation of the ".. rocqtop::" directive in doc/sphinx/README.rst.
569 """
570 has_content = True
571 required_arguments = 1
572 optional_arguments = 0
573 final_argument_whitespace = True
574 option_spec = { 'name': directives.unchanged }
575 directive_name = "rocqtop"
576
577 def run(self):
578 # Uses a ‘container’ instead of a ‘literal_block’ to disable
579 # Pygments-based post-processing (we could also set rawsource to '')
580 content = '\n'.join(self.content)
581 args = self.arguments[0].split()
582 node = nodes.container(content, rocqtop_options = set(args),
583 classes=['rocqtop', 'literal-block'])
584 self.add_name(node)
585 return [node]
586
587 class RocqdocDirective(Directive):
588 """A reST directive to display Rocq Doc-formatted source code.
589 See the documentation of the ".. rocqdoc::" directive in doc/sphinx/README.rst.
590 """
591 # TODO implement this as a Pygments highlighter?
592 has_content = True
593 required_arguments = 0
594 optional_arguments = 0
595 final_argument_whitespace = True
596 option_spec = { 'name': directives.unchanged }
597 directive_name = "rocqdoc"
598
599 def run(self):
600 # Uses a ‘container’ instead of a ‘literal_block’ to disable
601 # Pygments-based post-processing (we could also set rawsource to '')
602 content = '\n'.join(self.content)
603 node = nodes.inline(content, '', *highlight_using_rocqdoc(content))
604 wrapper = nodes.container(content, node, classes=['rocqdoc', 'literal-block'])
605 self.add_name(wrapper)
606 return [wrapper]
607
608 class ExampleDirective(BaseAdmonition):
609 """A reST directive for examples.
610 See the documentation of the ".. example::" directive in doc/sphinx/README.rst.
611 """
612 node_class = nodes.admonition
613 directive_name = "example"
614 optional_arguments = 1
615
616 def run(self):
617 # ‘BaseAdmonition’ checks whether ‘node_class’ is ‘nodes.admonition’,
618 # and uses arguments[0] as the title in that case (in other cases, the
619 # title is unset, and it is instead set in the HTML visitor).
620 assert len(self.arguments) <= 1
621 self.arguments = [": ".join(['Example'] + self.arguments)]
622 self.options['classes'] = ['admonition', 'note']
623 return super().run()
624
625 class PreambleDirective(Directive):
626 """A reST directive to include a TeX file.
627 See the documentation of the ".. preamble::" directive in doc/sphinx/README.rst
628 """
629 has_content = False
630 required_arguments = 1
631 optional_arguments = 0
632 final_argument_whitespace = True
633 option_spec = {}
634 directive_name = "preamble"
635
636 def run(self):
637 document = self.state.document
638 env = document.settings.env
639
640 if not document.settings.file_insertion_enabled:
641 msg = 'File insertion disabled'
642 return [document.reporter.warning(msg, line=self.lineno)]
643
644 rel_fname, abs_fname = env.relfn2path(self.arguments[0])
645 env.note_dependency(rel_fname)
646
647 with open(abs_fname, encoding="utf-8") as ltx:
648 latex = ltx.read()
649
650 node = make_math_node(latex, env.docname, nowrap=False)
651 node['classes'] = ["math-preamble"]
652 set_source_info(self, node)
653 return [node]
654
655 class InferenceDirective(Directive):
656 """A reST directive to format inference rules.
657 See the documentation of the ".. inference::" directive in doc/sphinx/README.rst
658 """
659 required_arguments = 1
660 optional_arguments = 0
661 has_content = True
662 final_argument_whitespace = True
663 directive_name = "inference"
664
665 @staticmethod
666 def prepare_latex_operand(op):
667 # TODO: Could use a fancier inference class in LaTeX
668 return '%\n\\hspace{3em}%\n'.join(op.strip().splitlines())
669
670 def prepare_latex(self, content):
671 parts = re.split('^ *----+ *$', content, flags=re.MULTILINE)
672 if len(parts) != 2:
673 raise self.error('Expected two parts in ‘inference’ directive, separated by a rule (----).')
674
675 top, bottom = tuple(InferenceDirective.prepare_latex_operand(p) for p in parts)
676 return "%\n".join(("\\frac{", top, "}{", bottom, "}"))
677
678 def run(self):
679 self.assert_has_content()
680
681 title = self.arguments[0]
682 content = '\n'.join(self.content)
683 latex = self.prepare_latex(content)
684 docname = self.state.document.settings.env.docname
685 math_node = make_math_node(latex, docname, nowrap=False)
686
687 tid = make_id(title)
688 target = nodes.target('', '', ids=['inference-' + tid])
689 self.state.document.note_explicit_target(target)
690
691 term, desc = nodes.term('', title), nodes.description('', math_node)
692 dli = nodes.definition_list_item('', term, desc)
693 dl = nodes.definition_list(content, target, dli)
694 set_source_info(self, dl)
695 return [dl]
696
697 class AnsiColorsParser():
698 """Parse ANSI-colored output from Rocqtop into Sphinx nodes."""
699
700 # Rocqtop's output crashes ansi.py, because it contains a bunch of extended codes
701 # This class is a fork of the original ansi.py, released under a BSD license in sphinx-contribs
702
703 COLOR_PATTERN = re.compile('\x1b\\[([^m]+)m')
704
705 def __init__(self):
706 self.new_nodes, self.pending_nodes = [], []
707
708 def _finalize_pending_nodes(self):
709 self.new_nodes.extend(self.pending_nodes)
710 self.pending_nodes = []
711
712 def _add_text(self, raw, beg, end):
713 if beg < end:
714 text = raw[beg:end]
715 if self.pending_nodes:
716 self.pending_nodes[-1].append(nodes.Text(text))
717 else:
718 self.new_nodes.append(nodes.inline('', text))
719
720 def colorize_str(self, raw):
721 """Parse raw (an ANSI-colored output string from Rocqtop) into Sphinx nodes."""
722 last_end = 0
723 for match in AnsiColorsParser.COLOR_PATTERN.finditer(raw):
724 self._add_text(raw, last_end, match.start())
725 last_end = match.end()
726 classes = ansicolors.parse_ansi(match.group(1))
727 if 'ansi-reset' in classes:
728 self._finalize_pending_nodes()
729 else:
730 node = nodes.inline()
731 self.pending_nodes.append(node)
732 node['classes'].extend(classes)
733 self._add_text(raw, last_end, len(raw))
734 self._finalize_pending_nodes()
735 return self.new_nodes
736
737 class RocqtopBlocksTransform(Transform):
738 """Filter handling the actual work for the rocqtop directive
739
740 Adds rocqtop's responses, colorizes input and output, and merges consecutive
741 rocqtop directives for better visual rendition.
742 """
743 default_priority = 10
744
745 @staticmethod
746 def is_rocqtop_block(node):
747 return isinstance(node, nodes.Element) and 'rocqtop_options' in node
748
749 @staticmethod
750 def is_rocqtop_args_field(node):
751 return isinstance(node, nodes.field) and node.children[0].rawsource == 'ROCQTOP_ARGS'
752
753 @staticmethod
754 def split_lines(source):
755 r"""Split Rocq input into chunks, which may include single- or
756 multi-line comments. Nested comments are not supported.
757
758 A chunk is a minimal sequence of consecutive lines of the input that
759 ends with a '.' or a focusing brace, possibly followed by blanks and/or comments.
760
761 >>> split_lines('A.\nB.''')
762 ['A.\n', 'B.']
763
764 >>> split_lines('A.\n\nB.''')
765 ['A.\n', '\nB.']
766
767 >>> split_lines('A.\n\nB.\n''')
768 ['A.\n', '\nB.']
769
770 >>> split_lines("SearchPattern (_ + _ = _ + _).\n"
771 ... "SearchPattern (nat -> bool).\n"
772 ... "SearchPattern (forall l : list _, _ l l).")
773 ... # doctest: +NORMALIZE_WHITESPACE
774 ['SearchPattern (_ + _ = _ + _).\n',
775 'SearchPattern (nat -> bool).\n',
776 'SearchPattern (forall l : list _, _ l l).']
777
778 >>> split_lines('SearchHead le.\nSearchHead (@eq bool).')
779 ['SearchHead le.\n', 'SearchHead (@eq bool).']
780
781 >>> split_lines("(* *) x. (* *)\ny.\n")
782 ['(* *) x. (* *)\n', 'y.']
783
784 >>> split_lines("(* *) x (* \n *)\ny.\n")
785 ['(* *) x (* \n *)\ny.']
786
787 >>> split_lines("Check (* check *) list (* comment *)\n"
788 ... "nat. (* another *) (*and another *)"))
789 ['Check (* check *) list (* comment *)\nnat. (* another *) (*and another *)']
790 """
791 comment = r"\(\*.*\*\)"
792 # the end of a chunk is marked by
793 # a period (\.) or a focusing brace (:\s*\{)
794 # optional blanks or comments (?:[ \t]*|{comment})*
795 # followed by a newline \n
796 # We capture everything starting from the '.' to recover it afterwards
797 blank = r"[ \t]"
798 dot = r"\."
799 focusing_brace = r":\s*\{"
800 end_of_chunk = fr"((?:{dot}|{focusing_brace})(?:{blank}*|{comment})*\n)"
801 splits = re.split(end_of_chunk, source.strip())
802 return [''.join(splits[i:i+2]) for i in range(0, len(splits), 2)]
803
804 @staticmethod
805 def parse_options(node):
806 """Parse options according to the description in RocqtopDirective."""
807
808 options = node['rocqtop_options']
809
810 # Behavior options
811 opt_reset = 'reset' in options
812 opt_fail = 'fail' in options
813 opt_warn = 'warn' in options
814 opt_restart = 'restart' in options
815 opt_abort = 'abort' in options
816 opt_extra = set([opt for opt in options if opt.startswith('extra-')])
817 options = options - {'reset', 'fail', 'warn', 'restart', 'abort'}
818 options = set([opt for opt in options if not (opt.startswith('extra-'))])
819
820 unexpected_options = list(options - {'all', 'none', 'in', 'out'})
821 if unexpected_options:
822 loc = os.path.basename(get_node_location(node))
823 raise ExtensionError("{}: Unexpected options for .. rocqtop:: {}".format(loc,unexpected_options))
824
825 # Display options
826 if len(options) != 1:
827 loc = os.path.basename(get_node_location(node))
828 raise ExtensionError("{}: Exactly one display option must be passed to .. rocqtop::".format(loc))
829
830 opt_all = 'all' in options
831 opt_input = 'in' in options
832 opt_output = 'out' in options
833
834 # if 'extra' is given and not a subset of env variable 'ROCQRST_EXTRA',
835 # allow errors
836 env_extra = os.environ.get('ROCQRST_EXTRA', '')
837 opt_fail = opt_fail or (env_extra != 'all' and len(opt_extra - set(env_extra.split(','))) != 0)
838 return {
839 'reset': opt_reset,
840 'fail': opt_fail,
841 # if errors are allowed, then warnings too
842 # and they should be displayed as warnings, not errors
843 'warn': opt_warn or opt_fail,
844 'restart': opt_restart,
845 'abort': opt_abort,
846 'input': opt_input or opt_all,
847 'output': opt_output or opt_all
848 }
849
850 @staticmethod
851 def block_classes(should_show, contents=None):
852 """Compute classes to add to a node containing contents.
853
854 :param should_show: Whether this node should be displayed"""
855 is_empty = contents is not None and re.match(r"^\s*$", contents)
856 return ['rocqtop-hidden'] if is_empty or not should_show else []
857
858 @staticmethod
859 def make_rawsource(pairs, opt_input, opt_output):
860 blocks = []
861 for sentence, output in pairs:
862 output = AnsiColorsParser.COLOR_PATTERN.sub("", output).strip()
863 if opt_input:
864 blocks.append(sentence)
865 if output and opt_output:
866 blocks.append(re.sub("^", " ", output, flags=re.MULTILINE) + "\n")
867 return '\n'.join(blocks)
868
869 def add_rocq_output_1(self, repl, node):
870 options = self.parse_options(node)
871
872 pairs = []
873
874 if options['restart']:
875 repl.sendone('Restart.')
876 if options['reset']:
877 repl.sendone('Reset Initial.')
878 repl.send_initial_options()
879 if options['fail']:
880 repl.sendone('Unset Rocqtop Exit On Error.')
881 if options['warn']:
882 repl.sendone('Set Warnings "default".')
883 for sentence in self.split_lines(node.rawsource):
884 comment = re.compile(r"\s*\(\*.*?\*\)\s*", re.DOTALL)
885 wo_comments = re.sub(comment, "", sentence)
886 has_tac = wo_comments != "" and not wo_comments.isspace()
887 output = repl.sendone(sentence) if has_tac else ""
888 pairs.append((sentence, output))
889 if options['abort']:
890 repl.sendone('Abort All.')
891 if options['fail']:
892 repl.sendone('Set Rocqtop Exit On Error.')
893 if options['warn']:
894 repl.sendone('Set Warnings "+default".')
895
896 dli = nodes.definition_list_item()
897 for sentence, output in pairs:
898 # Use Rocqdoc to highlight input
899 in_chunks = highlight_using_rocqdoc(sentence)
900 dli += nodes.term(sentence, '', *in_chunks, classes=self.block_classes(options['input']))
901 if output:
902 # Parse ANSI sequences to highlight output
903 out_chunks = AnsiColorsParser().colorize_str(output)
904 dli += nodes.definition(output, *out_chunks, classes=self.block_classes(options['output'], output))
905 node.clear()
906 node.rawsource = self.make_rawsource(pairs, options['input'], options['output'])
907 node['classes'].extend(self.block_classes(options['input'] or options['output']))
908 node += nodes.inline('', '', classes=['rocqtop-reset'] * options['reset'])
909 node += nodes.definition_list(node.rawsource, dli)
910
911 def add_rocqtop_output(self):
912 """Add rocqtop's responses to a Sphinx AST
913
914 Finds nodes to process using is_rocqtop_block."""
915 arg_fields = self.document.traverse(RocqtopBlocksTransform.is_rocqtop_args_field)
916 additional_args = [arg for field in arg_fields for arg in shlex.split(field.children[1].rawsource)]
917 with RocqTop(color=True, args=additional_args) as repl:
918 repl.send_initial_options()
919 for node in self.document.traverse(RocqtopBlocksTransform.is_rocqtop_block):
920 try:
921 self.add_rocq_output_1(repl, node)
922 except RocqTopError as err:
923 import textwrap
924 MSG = ("{}: Error while sending the following to rocqtop:\n{}" +
925 "\n rocqtop output:\n{}" +
926 "\n Full error text:\n{}")
927 indent = " "
928 loc = get_node_location(node)
929 le = textwrap.indent(str(err.last_sentence), indent)
930 bef = textwrap.indent(str(err.before), indent)
931 fe = textwrap.indent(str(err.err), indent)
932 raise ExtensionError(MSG.format(loc, le, bef, fe))
933
934 @staticmethod
935 def merge_rocqtop_classes(kept_node, discarded_node):
936 discarded_classes = discarded_node['classes']
937 if not 'rocqtop-hidden' in discarded_classes:
938 kept_node['classes'] = [c for c in kept_node['classes']
939 if c != 'rocqtop-hidden']
940
941 @staticmethod
942 def merge_consecutive_rocqtop_blocks(_app, doctree, _):
943 """Merge consecutive divs wrapping lists of Rocq sentences; keep ‘dl’s separate."""
944 for node in doctree.traverse(RocqtopBlocksTransform.is_rocqtop_block):
945 if node.parent:
946 rawsources, names = [node.rawsource], set(node['names'])
947 for sibling in node.traverse(include_self=False, descend=False,
948 siblings=True, ascend=False):
949 if RocqtopBlocksTransform.is_rocqtop_block(sibling):
950 RocqtopBlocksTransform.merge_rocqtop_classes(node, sibling)
951 rawsources.append(sibling.rawsource)
952 names.update(sibling['names'])
953 node.extend(sibling.children)
954 node.parent.remove(sibling)
955 sibling.parent = None
956 else:
957 break
958 node.rawsource = "\n\n".join(rawsources)
959 node['names'] = list(names)
960
961 def apply(self):
962 self.add_rocqtop_output()
963
964 class RocqSubdomainsIndex(Index):
965 """Index subclass to provide subdomain-specific indices.
966
967 Just as in the original manual, we want to have separate indices for each
968 Rocq subdomain (tactics, commands, options, etc)"""
969
970 name, localname, shortname, subdomains = None, None, None, [] # Must be overwritten
971
972 def generate(self, docnames=None):
973 content = defaultdict(list)
974 items = chain(*(self.domain.data['objects'][subdomain].items()
975 for subdomain in self.subdomains))
976
977 for itemname, (docname, _, anchor) in sorted(items, key=lambda x: x[0].lower()):
978 if docnames and docname not in docnames:
979 continue
980
981 entries = content[itemname[0].lower()]
982 entries.append([itemname, 0, docname, anchor, '', '', ''])
983
984 collapse = False
985 content = sorted(content.items())
986 return content, collapse
987
988 class RocqVernacIndex(RocqSubdomainsIndex):
989 name, localname, shortname, subdomains = "cmdindex", "Command Index", "commands", ["cmd"]
990
991 class RocqTacticIndex(RocqSubdomainsIndex):
992 name, localname, shortname, subdomains = "tacindex", "Tactic Index", "tactics", ["tacn"]
993
994 class RocqAttributeIndex(RocqSubdomainsIndex):
995 name, localname, shortname, subdomains = "attrindex", "Attribute Index", "attributes", ["attr"]
996
997 class RocqOptionIndex(RocqSubdomainsIndex):
998 name, localname, shortname, subdomains = "optindex", "Flags, options and Tables Index", "options", ["flag", "opt", "table"]
999
1000 class RocqGallinaIndex(RocqSubdomainsIndex):
1001 name, localname, shortname, subdomains = "thmindex", "Gallina Index", "theorems", ["thm"]
1002
1003 class RocqExceptionIndex(RocqSubdomainsIndex):
1004 name, localname, shortname, subdomains = "exnindex", "Errors and Warnings Index", "errors", ["exn", "warn"]
1005
1006 class IndexXRefRole(XRefRole):
1007 """A link to one of our domain-specific indices."""
1008 lowercase = True
1009 innernodeclass = nodes.inline
1010 warn_dangling = True
1011
1012 def process_link(self, env, refnode, has_explicit_title, title, target):
1013 if not has_explicit_title:
1014 index = RocqDomain.find_index_by_name(target)
1015 if index:
1016 title = index.localname
1017 return title, target
1018
1019 class StdGlossaryIndex(Index):
1020 name, localname, shortname = "glossindex", "Glossary", "terms"
1021
1022 def generate(self, docnames=None):
1023 def ci_sort(entry):
1024 ((type, itemname), (docname, anchor)) = entry
1025 return itemname.lower()
1026
1027 content = defaultdict(list)
1028 for ((type, itemname), (docname, anchor)) in sorted(self.domain.data['objects'].items(), key=ci_sort):
1029 if type == 'term':
1030 entries = content[itemname[0].lower()]
1031 entries.append([itemname, 0, docname, anchor, '', '', ''])
1032 return content.items(), False
1033
1034 def GrammarProductionRole(typ, rawtext, text, lineno, inliner, options={}, content=[]):
1035 """A grammar production not included in a ``prodn`` directive.
1036 See the documentation of the ":production:" role in doc/sphinx/README.rst
1037 """
1038 #pylint: disable=dangerous-default-value, unused-argument
1039 env = inliner.document.settings.env
1040 targetid = make_id('grammar-token-{}'.format(text))
1041 target = nodes.target('', '', ids=[targetid])
1042 inliner.document.note_explicit_target(target)
1043 code = nodes.literal(rawtext, text, role=typ.lower())
1044 node = nodes.inline(rawtext, '', target, code, classes=['inline-grammar-production'])
1045 set_role_source_info(inliner, lineno, node)
1046 env.domaindata['std']['objects']['token', text] = env.docname, targetid
1047 return [node], []
1048
1049 GrammarProductionRole.role_name = "production"
1050
1051
1052 def GlossaryDefRole(typ, rawtext, text, lineno, inliner, options={}, content=[]):
1053 """A role to mark the definition of a glossary term inline in the text.
1054 See the documentation of the ":gdef:" role in doc/sphinx/README.rst
1055 """
1056 #pylint: disable=dangerous-default-value, unused-argument
1057 env = inliner.document.settings.env
1058 std = env.domaindata['std']['objects']
1059 m = ReferenceRole.explicit_title_re.match(text)
1060 if m:
1061 (text, term) = m.groups()
1062 text = text.strip()
1063 else:
1064 term = text
1065 key = ('term', term)
1066
1067 if key in std:
1068 MSG = 'Duplicate object: {}; other is at {}'
1069 msg = MSG.format(term, env.doc2path(std[key][0]))
1070 inliner.document.reporter.warning(msg, line=lineno)
1071
1072 targetid = make_id('term-{}'.format(term))
1073 std[key] = (env.docname, targetid)
1074 target = nodes.target('', '', ids=[targetid], names=[term])
1075 inliner.document.note_explicit_target(target)
1076 node = nodes.inline(rawtext, '', target, nodes.Text(text), classes=['term-defn'])
1077 set_role_source_info(inliner, lineno, node)
1078 return [node], []
1079
1080 GlossaryDefRole.role_name = "gdef"
1081
1082 class RocqDomain(Domain):
1083 """A domain to document Rocq code.
1084
1085 Sphinx has a notion of “domains”, used to tailor it to a specific language.
1086 Domains mostly consist in descriptions of the objects that we wish to
1087 describe (for Rocq, this includes tactics, tactic notations, options,
1088 exceptions, etc.), as well as domain-specific roles and directives.
1089
1090 Each domain is responsible for tracking its objects, and resolving
1091 references to them. In the case of Rocq, this leads us to define Rocq
1092 “subdomains”, which classify objects into categories in which names must be
1093 unique. For example, a tactic and a theorem may share a name, but two
1094 tactics cannot be named the same.
1095 """
1096
1097 name = 'rocq'
1098 label = 'Rocq'
1099
1100 object_types = {
1101 # ObjType (= directive type) → (Local name, *xref-roles)
1102 'cmd': ObjType('cmd', 'cmd'),
1103 'cmdv': ObjType('cmdv', 'cmd'),
1104 'tacn': ObjType('tacn', 'tacn'),
1105 'tacv': ObjType('tacv', 'tacn'),
1106 'opt': ObjType('opt', 'opt'),
1107 'flag': ObjType('flag', 'flag'),
1108 'table': ObjType('table', 'table'),
1109 'attr': ObjType('attr', 'attr'),
1110 'thm': ObjType('thm', 'thm'),
1111 'prodn': ObjType('prodn', 'prodn'),
1112 'exn': ObjType('exn', 'exn'),
1113 'warn': ObjType('warn', 'exn'),
1114 'index': ObjType('index', 'index', searchprio=-1)
1115 }
1116
1117 directives = {
1118 # Note that some directives live in the same semantic subdomain; ie
1119 # there's one directive per object type, but some object types map to
1120 # the same role.
1121 'cmd': VernacObject,
1122 'cmdv': VernacVariantObject,
1123 'tacn': TacticObject,
1124 'tacv': TacticVariantObject,
1125 'opt': OptionObject,
1126 'flag': FlagObject,
1127 'table': TableObject,
1128 'attr': AttributeObject,
1129 'thm': GallinaObject,
1130 'prodn' : ProductionObject,
1131 'exn': ExceptionObject,
1132 'warn': WarningObject,
1133 }
1134
1135 roles = {
1136 # Each of these roles lives in a different semantic “subdomain”
1137 'cmd': XRefRole(warn_dangling=True),
1138 'tacn': XRefRole(warn_dangling=True),
1139 'opt': XRefRole(warn_dangling=True),
1140 'flag': XRefRole(warn_dangling=True),
1141 'table': XRefRole(warn_dangling=True),
1142 'attr': XRefRole(warn_dangling=True),
1143 'thm': XRefRole(warn_dangling=True),
1144 'prodn' : XRefRole(warn_dangling=True),
1145 'exn': XRefRole(warn_dangling=True),
1146 'warn': XRefRole(warn_dangling=True),
1147 # This one is special
1148 'index': IndexXRefRole(),
1149 # These are used for highlighting
1150 'n': NotationRole,
1151 'g': RocqCodeRole
1152 }
1153
1154 indices = [RocqVernacIndex, RocqTacticIndex, RocqOptionIndex, RocqGallinaIndex, RocqExceptionIndex, RocqAttributeIndex]
1155
1156 data_version = 1
1157 initial_data = {
1158 # Collect everything under a key that we control, since Sphinx adds
1159 # others, such as “version”
1160 'objects' : { # subdomain → name → docname, objtype, targetid
1161 'cmd': {},
1162 'tacn': {},
1163 'opt': {},
1164 'flag': {},
1165 'table': {},
1166 'attr': {},
1167 'thm': {},
1168 'prodn' : {},
1169 'exn': {},
1170 'warn': {},
1171 }
1172 }
1173
1174 @staticmethod
1175 def find_index_by_name(targetid):
1176 for index in RocqDomain.indices:
1177 if index.name == targetid:
1178 return index
1179 return None
1180
1181 def get_objects(self):
1182 # Used for searching and object inventories (intersphinx)
1183 for _, objects in self.data['objects'].items():
1184 for name, (docname, objtype, targetid) in objects.items():
1185 yield (name, name, objtype, docname, targetid, self.object_types[objtype].attrs['searchprio'])
1186 for index in self.indices:
1187 yield (index.name, index.localname, 'index', "rocq-" + index.name, '', -1)
1188
1189 def merge_domaindata(self, docnames, otherdata):
1190 DUP = "Duplicate declaration: '{}' also defined in '{}'.\n"
1191 for subdomain, their_objects in otherdata['objects'].items():
1192 our_objects = self.data['objects'][subdomain]
1193 for name, (docname, objtype, targetid) in their_objects.items():
1194 if docname in docnames:
1195 if name in our_objects:
1196 self.env.warn(docname, DUP.format(name, our_objects[name][0]))
1197 our_objects[name] = (docname, objtype, targetid)
1198
1199 def resolve_xref(self, env, fromdocname, builder, role, targetname, node, contnode):
1200 # ‘target’ is the name that was written in the document
1201 # ‘role’ is where this xref comes from; it's exactly one of our subdomains
1202 if role == 'index':
1203 index = RocqDomain.find_index_by_name(targetname)
1204 if index:
1205 return make_refnode(builder, fromdocname, "rocq-" + index.name, '', contnode, index.localname)
1206 else:
1207 resolved = self.data['objects'][role].get(targetname)
1208 if resolved:
1209 (todocname, _, targetid) = resolved
1210 return make_refnode(builder, fromdocname, todocname, targetid, contnode, targetname)
1211 return None
1212
1213 def clear_doc(self, docname_to_clear):
1214 for subdomain_objects in self.data['objects'].values():
1215 for name, (docname, _, _) in list(subdomain_objects.items()):
1216 if docname == docname_to_clear:
1217 del subdomain_objects[name]
1218
1219 def is_rocqtop_or_rocqdoc_block(node):
1220 return (isinstance(node, nodes.Element) and
1221 ('rocqtop' in node['classes'] or 'rocqdoc' in node['classes']))
1222
1223 def simplify_source_code_blocks_for_latex(app, doctree, fromdocname): # pylint: disable=unused-argument
1224 """Simplify rocqdoc and rocqtop blocks.
1225
1226 In HTML mode, this does nothing; in other formats, such as LaTeX, it
1227 replaces rocqdoc and rocqtop blocks by plain text sources, which will use
1228 pygments if available. This prevents the LaTeX builder from getting
1229 confused.
1230 """
1231 is_html = app.builder.tags.has("html")
1232 for node in doctree.traverse(is_rocqtop_or_rocqdoc_block):
1233 if is_html:
1234 node.rawsource = '' # Prevent pygments from kicking in
1235 elif 'rocqtop-hidden' in node['classes']:
1236 node.parent.remove(node)
1237 else:
1238 node.replace_self(nodes.literal_block(node.rawsource, node.rawsource, language="Coq"))
1239
1240 ROCQ_ADDITIONAL_DIRECTIVES = [RocqtopDirective,
1241 RocqdocDirective,
1242 ExampleDirective,
1243 InferenceDirective,
1244 PreambleDirective]
1245
1246 ROCQ_ADDITIONAL_ROLES = [GrammarProductionRole,
1247 GlossaryDefRole]
1248
1249 def setup(app):
1250 """Register the Rocq domain"""
1251
1252 # A few sanity checks:
1253 subdomains = set(obj.subdomain for obj in RocqDomain.directives.values())
1254 found = set (obj for obj in chain(*(idx.subdomains for idx in RocqDomain.indices)))
1255 assert subdomains.issuperset(found), "Missing subdomains: {}".format(found.difference(subdomains))
1256
1257 assert subdomains.issubset(RocqDomain.roles.keys()), \
1258 "Missing from RocqDomain.roles: {}".format(subdomains.difference(RocqDomain.roles.keys()))
1259
1260 # Add domain, directives, and roles
1261 app.add_domain(RocqDomain)
1262 app.add_index_to_domain('std', StdGlossaryIndex)
1263
1264 for role in ROCQ_ADDITIONAL_ROLES:
1265 app.add_role(role.role_name, role)
1266
1267 for directive in ROCQ_ADDITIONAL_DIRECTIVES:
1268 app.add_directive(directive.directive_name, directive)
1269
1270 app.add_transform(RocqtopBlocksTransform)
1271 app.connect('doctree-resolved', simplify_source_code_blocks_for_latex)
1272 app.connect('doctree-resolved', RocqtopBlocksTransform.merge_consecutive_rocqtop_blocks)
1273
1274 # Add extra styles
1275 app.add_css_file("ansi.css")
1276 app.add_css_file("coqdoc.css")
1277 app.add_js_file("notations.js")
1278 app.add_css_file("notations.css")
1279 app.add_css_file("pre-text.css")
1280
1281 # Tell Sphinx about extra settings
1282 app.add_config_value("report_undocumented_rocq_objects", None, 'env')
1283
1284 # ``env_version`` is used by Sphinx to know when to invalidate
1285 # rocqdomain-specific bits in its caches. It should be incremented when the
1286 # contents of ``env.domaindata['rocq']`` change. See
1287 # `https://github.com/sphinx-doc/sphinx/issues/4460`.
1288 meta = { "version": "0.1",
1289 "env_version": 2,
1290 "parallel_read_safe": True }
1291 return meta