blob: 008dd8a6f7c8cdf6eda22fd2c5021680b4d9fbf9 [file] [log] [blame]
Martin v. Löwis5680d0c2008-04-10 03:06:53 +00001# -*- coding: utf-8 -*-
2"""
3 pyspecific.py
4 ~~~~~~~~~~~~~
5
6 Sphinx extension with Python doc-specific markup.
7
Georg Brandl7ed509a2014-01-21 19:20:31 +01008 :copyright: 2008-2014 by Georg Brandl.
Martin v. Löwis5680d0c2008-04-10 03:06:53 +00009 :license: Python license.
10"""
11
Georg Brandl35903c82014-10-30 22:55:13 +010012import re
Victor Stinner272d8882017-06-16 08:59:01 +020013import io
Steve Dowerafe17a72018-12-19 18:20:06 -080014from os import getenv, path
Georg Brandl35903c82014-10-30 22:55:13 +010015from time import asctime
16from pprint import pformat
17from docutils.io import StringOutput
Ned Deily50f58162017-07-15 15:28:02 -040018from docutils.parsers.rst import Directive
Georg Brandl35903c82014-10-30 22:55:13 +010019from docutils.utils import new_document
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000020
21from docutils import nodes, utils
Georg Brandl239990d2013-10-12 20:50:21 +020022
Georg Brandl35903c82014-10-30 22:55:13 +010023from sphinx import addnodes
24from sphinx.builders import Builder
Julien Palard63c98ed2019-09-09 12:54:56 +020025try:
26 from sphinx.errors import NoUri
27except ImportError:
28 from sphinx.environment import NoUri
INADA Naokic351ce62017-03-08 19:07:13 +090029from sphinx.locale import translators
Steve Dower44f91c32019-06-27 10:47:59 -070030from sphinx.util import status_iterator, logging
Georg Brandl68818862010-11-06 07:19:35 +000031from sphinx.util.nodes import split_explicit_title
Benjamin Petersonacfb0872018-04-16 22:56:46 -070032from sphinx.writers.text import TextWriter, TextTranslator
Georg Brandl239990d2013-10-12 20:50:21 +020033from sphinx.writers.latex import LaTeXTranslator
Georg Brandl35903c82014-10-30 22:55:13 +010034from sphinx.domains.python import PyModulelevel, PyClassmember
35
36# Support for checking for suspicious markup
37
38import suspicious
39
40
41ISSUE_URI = 'https://bugs.python.org/issue%s'
Łukasz Langa9ab2fb12019-06-04 22:12:32 +020042SOURCE_URI = 'https://github.com/python/cpython/tree/master/%s'
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000043
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000044# monkey-patch reST parser to disable alphabetic and roman enumerated lists
45from docutils.parsers.rst.states import Body
46Body.enum.converters['loweralpha'] = \
47 Body.enum.converters['upperalpha'] = \
48 Body.enum.converters['lowerroman'] = \
49 Body.enum.converters['upperroman'] = lambda x: None
50
Georg Brandl35903c82014-10-30 22:55:13 +010051
Georg Brandl495f7b52009-10-27 15:28:25 +000052# Support for marking up and linking to bugs.python.org issues
53
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000054def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
55 issue = utils.unescape(text)
Brett Cannon79ab8be2017-02-10 15:10:13 -080056 text = 'bpo-' + issue
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000057 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
58 return [refnode], []
59
60
Georg Brandl68818862010-11-06 07:19:35 +000061# Support for linking to Python source files easily
62
63def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
64 has_t, title, target = split_explicit_title(text)
65 title = utils.unescape(title)
66 target = utils.unescape(target)
67 refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
68 return [refnode], []
69
70
Georg Brandl495f7b52009-10-27 15:28:25 +000071# Support for marking up implementation details
72
Georg Brandl495f7b52009-10-27 15:28:25 +000073class ImplementationDetail(Directive):
74
75 has_content = True
76 required_arguments = 0
77 optional_arguments = 1
78 final_argument_whitespace = True
79
INADA Naokic351ce62017-03-08 19:07:13 +090080 # This text is copied to templates/dummy.html
81 label_text = 'CPython implementation detail:'
82
Georg Brandl495f7b52009-10-27 15:28:25 +000083 def run(self):
84 pnode = nodes.compound(classes=['impl-detail'])
INADA Naokic351ce62017-03-08 19:07:13 +090085 label = translators['sphinx'].gettext(self.label_text)
Georg Brandl495f7b52009-10-27 15:28:25 +000086 content = self.content
INADA Naokic351ce62017-03-08 19:07:13 +090087 add_text = nodes.strong(label, label)
Georg Brandl495f7b52009-10-27 15:28:25 +000088 if self.arguments:
89 n, m = self.state.inline_text(self.arguments[0], self.lineno)
90 pnode.append(nodes.paragraph('', '', *(n + m)))
91 self.state.nested_parse(content, self.content_offset, pnode)
92 if pnode.children and isinstance(pnode[0], nodes.paragraph):
INADA Naokic351ce62017-03-08 19:07:13 +090093 content = nodes.inline(pnode[0].rawsource, translatable=True)
94 content.source = pnode[0].source
95 content.line = pnode[0].line
96 content += pnode[0].children
97 pnode[0].replace_self(nodes.paragraph('', '', content,
98 translatable=False))
Georg Brandl495f7b52009-10-27 15:28:25 +000099 pnode[0].insert(0, add_text)
100 pnode[0].insert(1, nodes.Text(' '))
101 else:
102 pnode.insert(0, nodes.paragraph('', '', add_text))
103 return [pnode]
104
105
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400106# Support for documenting platform availability
107
108class Availability(Directive):
109
110 has_content = False
111 required_arguments = 1
112 optional_arguments = 0
113 final_argument_whitespace = True
114
115 def run(self):
Julien Palardbeed84c2018-11-07 22:42:40 +0100116 availability_ref = ':ref:`Availability <availability>`: '
117 pnode = nodes.paragraph(availability_ref + self.arguments[0],
118 classes=["availability"],)
119 n, m = self.state.inline_text(availability_ref, self.lineno)
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400120 pnode.extend(n + m)
121 n, m = self.state.inline_text(self.arguments[0], self.lineno)
122 pnode.extend(n + m)
123 return [pnode]
124
125
Steve Dowerb82e17e2019-05-23 08:45:22 -0700126# Support for documenting audit event
127
Julien Palarda103e732020-07-06 22:28:15 +0200128def audit_events_purge(app, env, docname):
129 """This is to remove from env.all_audit_events old traces of removed
130 documents.
131 """
132 if not hasattr(env, 'all_audit_events'):
133 return
134 fresh_all_audit_events = {}
135 for name, event in env.all_audit_events.items():
136 event["source"] = [(d, t) for d, t in event["source"] if d != docname]
137 if event["source"]:
138 # Only keep audit_events that have at least one source.
139 fresh_all_audit_events[name] = event
140 env.all_audit_events = fresh_all_audit_events
141
142
143def audit_events_merge(app, env, docnames, other):
144 """In Sphinx parallel builds, this merges env.all_audit_events from
145 subprocesses.
146
147 all_audit_events is a dict of names, with values like:
148 {'source': [(docname, target), ...], 'args': args}
149 """
150 if not hasattr(other, 'all_audit_events'):
151 return
152 if not hasattr(env, 'all_audit_events'):
153 env.all_audit_events = {}
154 for name, value in other.all_audit_events.items():
155 if name in env.all_audit_events:
156 env.all_audit_events[name]["source"].extend(value["source"])
157 else:
158 env.all_audit_events[name] = value
159
160
Steve Dowerb82e17e2019-05-23 08:45:22 -0700161class AuditEvent(Directive):
162
163 has_content = True
164 required_arguments = 1
Steve Dower44f91c32019-06-27 10:47:59 -0700165 optional_arguments = 2
Steve Dowerb82e17e2019-05-23 08:45:22 -0700166 final_argument_whitespace = True
167
168 _label = [
169 "Raises an :ref:`auditing event <auditing>` {name} with no arguments.",
170 "Raises an :ref:`auditing event <auditing>` {name} with argument {args}.",
171 "Raises an :ref:`auditing event <auditing>` {name} with arguments {args}.",
172 ]
173
Steve Dower44f91c32019-06-27 10:47:59 -0700174 @property
175 def logger(self):
176 cls = type(self)
177 return logging.getLogger(cls.__module__ + "." + cls.__name__)
178
Steve Dowerb82e17e2019-05-23 08:45:22 -0700179 def run(self):
Steve Dower44f91c32019-06-27 10:47:59 -0700180 name = self.arguments[0]
Steve Dowerb82e17e2019-05-23 08:45:22 -0700181 if len(self.arguments) >= 2 and self.arguments[1]:
Steve Dower44f91c32019-06-27 10:47:59 -0700182 args = (a.strip() for a in self.arguments[1].strip("'\"").split(","))
183 args = [a for a in args if a]
Steve Dowerb82e17e2019-05-23 08:45:22 -0700184 else:
185 args = []
186
187 label = translators['sphinx'].gettext(self._label[min(2, len(args))])
Steve Dower44f91c32019-06-27 10:47:59 -0700188 text = label.format(name="``{}``".format(name),
189 args=", ".join("``{}``".format(a) for a in args if a))
Steve Dowerb82e17e2019-05-23 08:45:22 -0700190
Steve Dower44f91c32019-06-27 10:47:59 -0700191 env = self.state.document.settings.env
192 if not hasattr(env, 'all_audit_events'):
193 env.all_audit_events = {}
194
195 new_info = {
196 'source': [],
197 'args': args
198 }
199 info = env.all_audit_events.setdefault(name, new_info)
200 if info is not new_info:
201 if not self._do_args_match(info['args'], new_info['args']):
202 self.logger.warn(
203 "Mismatched arguments for audit-event {}: {!r} != {!r}"
204 .format(name, info['args'], new_info['args'])
205 )
206
Steve Dowere226e832019-07-01 16:03:53 -0700207 ids = []
208 try:
209 target = self.arguments[2].strip("\"'")
210 except (IndexError, TypeError):
211 target = None
212 if not target:
213 target = "audit_event_{}_{}".format(
214 re.sub(r'\W', '_', name),
215 len(info['source']),
216 )
217 ids.append(target)
218
Steve Dower44f91c32019-06-27 10:47:59 -0700219 info['source'].append((env.docname, target))
220
221 pnode = nodes.paragraph(text, classes=["audit-hook"], ids=ids)
Steve Dowerb82e17e2019-05-23 08:45:22 -0700222 if self.content:
223 self.state.nested_parse(self.content, self.content_offset, pnode)
224 else:
225 n, m = self.state.inline_text(text, self.lineno)
226 pnode.extend(n + m)
227
228 return [pnode]
229
Steve Dower44f91c32019-06-27 10:47:59 -0700230 # This list of sets are allowable synonyms for event argument names.
231 # If two names are in the same set, they are treated as equal for the
232 # purposes of warning. This won't help if number of arguments is
233 # different!
234 _SYNONYMS = [
235 {"file", "path", "fd"},
236 ]
237
238 def _do_args_match(self, args1, args2):
239 if args1 == args2:
240 return True
241 if len(args1) != len(args2):
242 return False
243 for a1, a2 in zip(args1, args2):
244 if a1 == a2:
245 continue
246 if any(a1 in s and a2 in s for s in self._SYNONYMS):
247 continue
248 return False
249 return True
250
251
252class audit_event_list(nodes.General, nodes.Element):
253 pass
254
255
256class AuditEventListDirective(Directive):
257
258 def run(self):
259 return [audit_event_list('')]
260
Steve Dowerb82e17e2019-05-23 08:45:22 -0700261
Georg Brandl8a1caa22010-07-29 16:01:11 +0000262# Support for documenting decorators
263
Georg Brandl8a1caa22010-07-29 16:01:11 +0000264class PyDecoratorMixin(object):
265 def handle_signature(self, sig, signode):
266 ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
267 signode.insert(0, addnodes.desc_addname('@', '@'))
268 return ret
269
270 def needs_arglist(self):
271 return False
272
Georg Brandl35903c82014-10-30 22:55:13 +0100273
Georg Brandl8a1caa22010-07-29 16:01:11 +0000274class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
275 def run(self):
276 # a decorator function is a function after all
277 self.name = 'py:function'
278 return PyModulelevel.run(self)
279
Georg Brandl35903c82014-10-30 22:55:13 +0100280
Georg Brandl8a1caa22010-07-29 16:01:11 +0000281class PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
282 def run(self):
283 self.name = 'py:method'
284 return PyClassmember.run(self)
285
286
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100287class PyCoroutineMixin(object):
288 def handle_signature(self, sig, signode):
289 ret = super(PyCoroutineMixin, self).handle_signature(sig, signode)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100290 signode.insert(0, addnodes.desc_annotation('coroutine ', 'coroutine '))
291 return ret
292
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100293
Yury Selivanov47150392018-09-18 17:55:44 -0400294class PyAwaitableMixin(object):
295 def handle_signature(self, sig, signode):
296 ret = super(PyAwaitableMixin, self).handle_signature(sig, signode)
297 signode.insert(0, addnodes.desc_annotation('awaitable ', 'awaitable '))
298 return ret
299
300
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100301class PyCoroutineFunction(PyCoroutineMixin, PyModulelevel):
302 def run(self):
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100303 self.name = 'py:function'
304 return PyModulelevel.run(self)
305
306
307class PyCoroutineMethod(PyCoroutineMixin, PyClassmember):
308 def run(self):
309 self.name = 'py:method'
310 return PyClassmember.run(self)
311
312
Yury Selivanov47150392018-09-18 17:55:44 -0400313class PyAwaitableFunction(PyAwaitableMixin, PyClassmember):
314 def run(self):
315 self.name = 'py:function'
316 return PyClassmember.run(self)
317
318
319class PyAwaitableMethod(PyAwaitableMixin, PyClassmember):
320 def run(self):
321 self.name = 'py:method'
322 return PyClassmember.run(self)
323
324
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200325class PyAbstractMethod(PyClassmember):
326
327 def handle_signature(self, sig, signode):
328 ret = super(PyAbstractMethod, self).handle_signature(sig, signode)
329 signode.insert(0, addnodes.desc_annotation('abstractmethod ',
330 'abstractmethod '))
331 return ret
332
333 def run(self):
334 self.name = 'py:method'
335 return PyClassmember.run(self)
336
337
Georg Brandl281d6ba2010-11-12 08:57:12 +0000338# Support for documenting version of removal in deprecations
339
Georg Brandl281d6ba2010-11-12 08:57:12 +0000340class DeprecatedRemoved(Directive):
341 has_content = True
342 required_arguments = 2
343 optional_arguments = 1
344 final_argument_whitespace = True
345 option_spec = {}
346
Florian Dahlitz735d9022020-05-30 09:47:32 +0200347 _deprecated_label = 'Deprecated since version {deprecated}, will be removed in version {removed}'
348 _removed_label = 'Deprecated since version {deprecated}, removed in version {removed}'
Georg Brandl7ed509a2014-01-21 19:20:31 +0100349
Georg Brandl281d6ba2010-11-12 08:57:12 +0000350 def run(self):
351 node = addnodes.versionmodified()
352 node.document = self.state.document
353 node['type'] = 'deprecated-removed'
354 version = (self.arguments[0], self.arguments[1])
355 node['version'] = version
Florian Dahlitz735d9022020-05-30 09:47:32 +0200356 env = self.state.document.settings.env
357 current_version = tuple(int(e) for e in env.config.version.split('.'))
358 removed_version = tuple(int(e) for e in self.arguments[1].split('.'))
359 if current_version < removed_version:
360 label = self._deprecated_label
361 else:
362 label = self._removed_label
363
364 label = translators['sphinx'].gettext(label)
cocoatomo0febc052018-02-23 20:47:19 +0900365 text = label.format(deprecated=self.arguments[0], removed=self.arguments[1])
Georg Brandl281d6ba2010-11-12 08:57:12 +0000366 if len(self.arguments) == 3:
367 inodes, messages = self.state.inline_text(self.arguments[2],
368 self.lineno+1)
cocoatomo0febc052018-02-23 20:47:19 +0900369 para = nodes.paragraph(self.arguments[2], '', *inodes, translatable=False)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100370 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000371 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100372 messages = []
373 if self.content:
374 self.state.nested_parse(self.content, self.content_offset, node)
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200375 if len(node):
Georg Brandl7ed509a2014-01-21 19:20:31 +0100376 if isinstance(node[0], nodes.paragraph) and node[0].rawsource:
377 content = nodes.inline(node[0].rawsource, translatable=True)
378 content.source = node[0].source
379 content.line = node[0].line
380 content += node[0].children
cocoatomo0febc052018-02-23 20:47:19 +0900381 node[0].replace_self(nodes.paragraph('', '', content, translatable=False))
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200382 node[0].insert(0, nodes.inline('', '%s: ' % text,
383 classes=['versionmodified']))
Ned Deilyb682fd32014-09-22 14:44:22 -0700384 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100385 para = nodes.paragraph('', '',
Georg Brandl35903c82014-10-30 22:55:13 +0100386 nodes.inline('', '%s.' % text,
cocoatomo0febc052018-02-23 20:47:19 +0900387 classes=['versionmodified']),
388 translatable=False)
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200389 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000390 env = self.state.document.settings.env
Pablo Galindo960bb882019-05-10 22:58:17 +0100391 env.get_domain('changeset').note_changeset(node)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100392 return [node] + messages
Georg Brandl281d6ba2010-11-12 08:57:12 +0000393
394
Georg Brandl2cac28b2012-09-30 15:10:06 +0200395# Support for including Misc/NEWS
396
Brett Cannon79ab8be2017-02-10 15:10:13 -0800397issue_re = re.compile('(?:[Ii]ssue #|bpo-)([0-9]+)')
Georg Brandl44d0c212012-10-01 19:08:50 +0200398whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200399
Georg Brandl35903c82014-10-30 22:55:13 +0100400
Georg Brandl2cac28b2012-09-30 15:10:06 +0200401class MiscNews(Directive):
402 has_content = False
403 required_arguments = 1
404 optional_arguments = 0
405 final_argument_whitespace = False
406 option_spec = {}
407
408 def run(self):
409 fname = self.arguments[0]
410 source = self.state_machine.input_lines.source(
411 self.lineno - self.state_machine.input_offset - 1)
Steve Dowerafe17a72018-12-19 18:20:06 -0800412 source_dir = getenv('PY_MISC_NEWS_DIR')
413 if not source_dir:
414 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200415 fpath = path.join(source_dir, fname)
416 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200417 try:
Victor Stinner272d8882017-06-16 08:59:01 +0200418 with io.open(fpath, encoding='utf-8') as fp:
Georg Brandl2cac28b2012-09-30 15:10:06 +0200419 content = fp.read()
Georg Brandl2cac28b2012-09-30 15:10:06 +0200420 except Exception:
421 text = 'The NEWS file is not available.'
422 node = nodes.strong(text, text)
423 return [node]
Brett Cannon79ab8be2017-02-10 15:10:13 -0800424 content = issue_re.sub(r'`bpo-\1 <https://bugs.python.org/issue\1>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200425 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200426 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200427 # remove first 3 lines as they are the main heading
Georg Brandl6c475812012-10-01 19:27:05 +0200428 lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
Georg Brandl2cac28b2012-09-30 15:10:06 +0200429 self.state_machine.insert_input(lines, fname)
430 return []
431
432
Georg Brandl6b38daa2008-06-01 21:05:17 +0000433# Support for building "topic help" for pydoc
434
435pydoc_topic_labels = [
Jelle Zijlstraac317702017-10-05 20:24:46 -0700436 'assert', 'assignment', 'async', 'atom-identifiers', 'atom-literals',
437 'attribute-access', 'attribute-references', 'augassign', 'await',
438 'binary', 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000439 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000440 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
441 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
442 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
443 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
444 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000445 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
446 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
447 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
448 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
449 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
450 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000451]
452
Georg Brandl6b38daa2008-06-01 21:05:17 +0000453
454class PydocTopicsBuilder(Builder):
455 name = 'pydoc-topics'
456
Benjamin Petersonacfb0872018-04-16 22:56:46 -0700457 default_translator_class = TextTranslator
458
Georg Brandl6b38daa2008-06-01 21:05:17 +0000459 def init(self):
460 self.topics = {}
Benjamin Petersonacfb0872018-04-16 22:56:46 -0700461 self.secnumbers = {}
Georg Brandl6b38daa2008-06-01 21:05:17 +0000462
463 def get_outdated_docs(self):
464 return 'all pydoc topics'
465
466 def get_target_uri(self, docname, typ=None):
467 return '' # no URIs
468
469 def write(self, *ignored):
470 writer = TextWriter(self)
Benjamin Petersonacfb0872018-04-16 22:56:46 -0700471 for label in status_iterator(pydoc_topic_labels,
472 'building topics... ',
473 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000474 if label not in self.env.domaindata['std']['labels']:
Steve Dower44f91c32019-06-27 10:47:59 -0700475 self.env.logger.warn('label %r not in documentation' % label)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000476 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000477 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000478 doctree = self.env.get_and_resolve_doctree(docname, self)
479 document = new_document('<section node>')
480 document.append(doctree.ids[labelid])
481 destination = StringOutput(encoding='utf-8')
482 writer.write(document, destination)
Ned Deilyb682fd32014-09-22 14:44:22 -0700483 self.topics[label] = writer.output
Georg Brandl6b38daa2008-06-01 21:05:17 +0000484
485 def finish(self):
Ned Deilyb682fd32014-09-22 14:44:22 -0700486 f = open(path.join(self.outdir, 'topics.py'), 'wb')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000487 try:
Ned Deilyb682fd32014-09-22 14:44:22 -0700488 f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8'))
489 f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8'))
490 f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
Georg Brandl6b38daa2008-06-01 21:05:17 +0000491 finally:
492 f.close()
493
Georg Brandl495f7b52009-10-27 15:28:25 +0000494
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000495# Support for documenting Opcodes
496
Georg Brandl4833e5b2010-07-03 10:41:33 +0000497opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000498
Georg Brandl35903c82014-10-30 22:55:13 +0100499
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000500def parse_opcode_signature(env, sig, signode):
501 """Transform an opcode signature into RST nodes."""
502 m = opcode_sig_re.match(sig)
503 if m is None:
504 raise ValueError
505 opname, arglist = m.groups()
506 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000507 if arglist is not None:
508 paramlist = addnodes.desc_parameterlist()
509 signode += paramlist
510 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000511 return opname.strip()
512
513
Georg Brandl281d6ba2010-11-12 08:57:12 +0000514# Support for documenting pdb commands
515
Georg Brandl02053ee2010-07-18 10:11:03 +0000516pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
517
518# later...
Georg Brandl35903c82014-10-30 22:55:13 +0100519# pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
Georg Brandl02053ee2010-07-18 10:11:03 +0000520# [.,:]+ | # punctuation
521# [\[\]()] | # parens
522# \s+ # whitespace
523# ''', re.X)
524
Georg Brandl35903c82014-10-30 22:55:13 +0100525
Georg Brandl02053ee2010-07-18 10:11:03 +0000526def parse_pdb_command(env, sig, signode):
527 """Transform a pdb command signature into RST nodes."""
528 m = pdbcmd_sig_re.match(sig)
529 if m is None:
530 raise ValueError
531 name, args = m.groups()
532 fullname = name.replace('(', '').replace(')', '')
533 signode += addnodes.desc_name(name, name)
534 if args:
535 signode += addnodes.desc_addname(' '+args, ' '+args)
536 return fullname
537
538
Steve Dower44f91c32019-06-27 10:47:59 -0700539def process_audit_events(app, doctree, fromdocname):
540 for node in doctree.traverse(audit_event_list):
541 break
542 else:
543 return
544
545 env = app.builder.env
546
547 table = nodes.table(cols=3)
548 group = nodes.tgroup(
549 '',
550 nodes.colspec(colwidth=30),
551 nodes.colspec(colwidth=55),
552 nodes.colspec(colwidth=15),
Dmitry Shachnevc3d679f2019-09-10 17:40:50 +0300553 cols=3,
Steve Dower44f91c32019-06-27 10:47:59 -0700554 )
555 head = nodes.thead()
556 body = nodes.tbody()
557
558 table += group
559 group += head
560 group += body
561
562 row = nodes.row()
563 row += nodes.entry('', nodes.paragraph('', nodes.Text('Audit event')))
564 row += nodes.entry('', nodes.paragraph('', nodes.Text('Arguments')))
565 row += nodes.entry('', nodes.paragraph('', nodes.Text('References')))
566 head += row
567
568 for name in sorted(getattr(env, "all_audit_events", ())):
569 audit_event = env.all_audit_events[name]
570
571 row = nodes.row()
572 node = nodes.paragraph('', nodes.Text(name))
573 row += nodes.entry('', node)
574
575 node = nodes.paragraph()
576 for i, a in enumerate(audit_event['args']):
577 if i:
578 node += nodes.Text(", ")
579 node += nodes.literal(a, nodes.Text(a))
580 row += nodes.entry('', node)
581
582 node = nodes.paragraph()
Steve Dowere226e832019-07-01 16:03:53 -0700583 backlinks = enumerate(sorted(set(audit_event['source'])), start=1)
584 for i, (doc, label) in backlinks:
Steve Dower44f91c32019-06-27 10:47:59 -0700585 if isinstance(label, str):
586 ref = nodes.reference("", nodes.Text("[{}]".format(i)), internal=True)
Julien Palard63c98ed2019-09-09 12:54:56 +0200587 try:
588 ref['refuri'] = "{}#{}".format(
589 app.builder.get_relative_uri(fromdocname, doc),
590 label,
591 )
592 except NoUri:
593 continue
Steve Dower44f91c32019-06-27 10:47:59 -0700594 node += ref
595 row += nodes.entry('', node)
596
597 body += row
598
599 for node in doctree.traverse(audit_event_list):
600 node.replace_self(table)
601
602
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000603def setup(app):
604 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000605 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000606 app.add_directive('impl-detail', ImplementationDetail)
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400607 app.add_directive('availability', Availability)
Steve Dowerb82e17e2019-05-23 08:45:22 -0700608 app.add_directive('audit-event', AuditEvent)
Steve Dower44f91c32019-06-27 10:47:59 -0700609 app.add_directive('audit-event-table', AuditEventListDirective)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000610 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000611 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000612 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Stéphane Wirtele385d062018-10-13 08:14:08 +0200613 app.add_object_type('opcode', 'opcode', '%s (opcode)', parse_opcode_signature)
614 app.add_object_type('pdbcommand', 'pdbcmd', '%s (pdb command)', parse_pdb_command)
615 app.add_object_type('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000616 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
617 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100618 app.add_directive_to_domain('py', 'coroutinefunction', PyCoroutineFunction)
619 app.add_directive_to_domain('py', 'coroutinemethod', PyCoroutineMethod)
Yury Selivanov47150392018-09-18 17:55:44 -0400620 app.add_directive_to_domain('py', 'awaitablefunction', PyAwaitableFunction)
621 app.add_directive_to_domain('py', 'awaitablemethod', PyAwaitableMethod)
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200622 app.add_directive_to_domain('py', 'abstractmethod', PyAbstractMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200623 app.add_directive('miscnews', MiscNews)
Steve Dower44f91c32019-06-27 10:47:59 -0700624 app.connect('doctree-resolved', process_audit_events)
Julien Palarda103e732020-07-06 22:28:15 +0200625 app.connect('env-merge-info', audit_events_merge)
626 app.connect('env-purge-doc', audit_events_purge)
Georg Brandlbae334c2014-09-30 22:17:41 +0200627 return {'version': '1.0', 'parallel_read_safe': True}