blob: 8839033b983c473ef8b75022e3cc17a4de35eb52 [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
INADA Naokic351ce62017-03-08 19:07:13 +090025from sphinx.locale import translators
Steve Dower44f91c32019-06-27 10:47:59 -070026from sphinx.util import status_iterator, logging
Georg Brandl68818862010-11-06 07:19:35 +000027from sphinx.util.nodes import split_explicit_title
Georg Brandl239990d2013-10-12 20:50:21 +020028from sphinx.writers.html import HTMLTranslator
Benjamin Petersonacfb0872018-04-16 22:56:46 -070029from sphinx.writers.text import TextWriter, TextTranslator
Georg Brandl239990d2013-10-12 20:50:21 +020030from sphinx.writers.latex import LaTeXTranslator
Georg Brandl35903c82014-10-30 22:55:13 +010031from sphinx.domains.python import PyModulelevel, PyClassmember
32
33# Support for checking for suspicious markup
34
35import suspicious
36
37
38ISSUE_URI = 'https://bugs.python.org/issue%s'
Łukasz Langa9ab2fb12019-06-04 22:12:32 +020039SOURCE_URI = 'https://github.com/python/cpython/tree/master/%s'
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000040
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000041# monkey-patch reST parser to disable alphabetic and roman enumerated lists
42from docutils.parsers.rst.states import Body
43Body.enum.converters['loweralpha'] = \
44 Body.enum.converters['upperalpha'] = \
45 Body.enum.converters['lowerroman'] = \
46 Body.enum.converters['upperroman'] = lambda x: None
47
Georg Brandl83e51f42012-10-10 16:45:11 +020048# monkey-patch HTML and LaTeX translators to keep doctest blocks in the
49# doctest docs themselves
50orig_visit_literal_block = HTMLTranslator.visit_literal_block
Georg Brandl35903c82014-10-30 22:55:13 +010051orig_depart_literal_block = LaTeXTranslator.depart_literal_block
52
53
Georg Brandl83e51f42012-10-10 16:45:11 +020054def new_visit_literal_block(self, node):
55 meta = self.builder.env.metadata[self.builder.current_docname]
56 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
57 if 'keepdoctest' in meta:
58 self.highlighter.trim_doctest_flags = False
59 try:
60 orig_visit_literal_block(self, node)
61 finally:
62 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
63
Georg Brandl83e51f42012-10-10 16:45:11 +020064
Georg Brandl83e51f42012-10-10 16:45:11 +020065def new_depart_literal_block(self, node):
66 meta = self.builder.env.metadata[self.curfilestack[-1]]
67 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
68 if 'keepdoctest' in meta:
69 self.highlighter.trim_doctest_flags = False
70 try:
71 orig_depart_literal_block(self, node)
72 finally:
73 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
74
Georg Brandl35903c82014-10-30 22:55:13 +010075
76HTMLTranslator.visit_literal_block = new_visit_literal_block
Georg Brandl83e51f42012-10-10 16:45:11 +020077LaTeXTranslator.depart_literal_block = new_depart_literal_block
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000078
Georg Brandl35903c82014-10-30 22:55:13 +010079
Georg Brandl495f7b52009-10-27 15:28:25 +000080# Support for marking up and linking to bugs.python.org issues
81
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000082def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
83 issue = utils.unescape(text)
Brett Cannon79ab8be2017-02-10 15:10:13 -080084 text = 'bpo-' + issue
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000085 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
86 return [refnode], []
87
88
Georg Brandl68818862010-11-06 07:19:35 +000089# Support for linking to Python source files easily
90
91def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
92 has_t, title, target = split_explicit_title(text)
93 title = utils.unescape(title)
94 target = utils.unescape(target)
95 refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
96 return [refnode], []
97
98
Georg Brandl495f7b52009-10-27 15:28:25 +000099# Support for marking up implementation details
100
Georg Brandl495f7b52009-10-27 15:28:25 +0000101class ImplementationDetail(Directive):
102
103 has_content = True
104 required_arguments = 0
105 optional_arguments = 1
106 final_argument_whitespace = True
107
INADA Naokic351ce62017-03-08 19:07:13 +0900108 # This text is copied to templates/dummy.html
109 label_text = 'CPython implementation detail:'
110
Georg Brandl495f7b52009-10-27 15:28:25 +0000111 def run(self):
112 pnode = nodes.compound(classes=['impl-detail'])
INADA Naokic351ce62017-03-08 19:07:13 +0900113 label = translators['sphinx'].gettext(self.label_text)
Georg Brandl495f7b52009-10-27 15:28:25 +0000114 content = self.content
INADA Naokic351ce62017-03-08 19:07:13 +0900115 add_text = nodes.strong(label, label)
Georg Brandl495f7b52009-10-27 15:28:25 +0000116 if self.arguments:
117 n, m = self.state.inline_text(self.arguments[0], self.lineno)
118 pnode.append(nodes.paragraph('', '', *(n + m)))
119 self.state.nested_parse(content, self.content_offset, pnode)
120 if pnode.children and isinstance(pnode[0], nodes.paragraph):
INADA Naokic351ce62017-03-08 19:07:13 +0900121 content = nodes.inline(pnode[0].rawsource, translatable=True)
122 content.source = pnode[0].source
123 content.line = pnode[0].line
124 content += pnode[0].children
125 pnode[0].replace_self(nodes.paragraph('', '', content,
126 translatable=False))
Georg Brandl495f7b52009-10-27 15:28:25 +0000127 pnode[0].insert(0, add_text)
128 pnode[0].insert(1, nodes.Text(' '))
129 else:
130 pnode.insert(0, nodes.paragraph('', '', add_text))
131 return [pnode]
132
133
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400134# Support for documenting platform availability
135
136class Availability(Directive):
137
138 has_content = False
139 required_arguments = 1
140 optional_arguments = 0
141 final_argument_whitespace = True
142
143 def run(self):
Julien Palardbeed84c2018-11-07 22:42:40 +0100144 availability_ref = ':ref:`Availability <availability>`: '
145 pnode = nodes.paragraph(availability_ref + self.arguments[0],
146 classes=["availability"],)
147 n, m = self.state.inline_text(availability_ref, self.lineno)
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400148 pnode.extend(n + m)
149 n, m = self.state.inline_text(self.arguments[0], self.lineno)
150 pnode.extend(n + m)
151 return [pnode]
152
153
Steve Dowerb82e17e2019-05-23 08:45:22 -0700154# Support for documenting audit event
155
156class AuditEvent(Directive):
157
158 has_content = True
159 required_arguments = 1
Steve Dower44f91c32019-06-27 10:47:59 -0700160 optional_arguments = 2
Steve Dowerb82e17e2019-05-23 08:45:22 -0700161 final_argument_whitespace = True
162
163 _label = [
164 "Raises an :ref:`auditing event <auditing>` {name} with no arguments.",
165 "Raises an :ref:`auditing event <auditing>` {name} with argument {args}.",
166 "Raises an :ref:`auditing event <auditing>` {name} with arguments {args}.",
167 ]
168
Steve Dower44f91c32019-06-27 10:47:59 -0700169 @property
170 def logger(self):
171 cls = type(self)
172 return logging.getLogger(cls.__module__ + "." + cls.__name__)
173
Steve Dowerb82e17e2019-05-23 08:45:22 -0700174 def run(self):
Steve Dower44f91c32019-06-27 10:47:59 -0700175 name = self.arguments[0]
Steve Dowerb82e17e2019-05-23 08:45:22 -0700176 if len(self.arguments) >= 2 and self.arguments[1]:
Steve Dower44f91c32019-06-27 10:47:59 -0700177 args = (a.strip() for a in self.arguments[1].strip("'\"").split(","))
178 args = [a for a in args if a]
Steve Dowerb82e17e2019-05-23 08:45:22 -0700179 else:
180 args = []
181
182 label = translators['sphinx'].gettext(self._label[min(2, len(args))])
Steve Dower44f91c32019-06-27 10:47:59 -0700183 text = label.format(name="``{}``".format(name),
184 args=", ".join("``{}``".format(a) for a in args if a))
Steve Dowerb82e17e2019-05-23 08:45:22 -0700185
Steve Dower44f91c32019-06-27 10:47:59 -0700186 env = self.state.document.settings.env
187 if not hasattr(env, 'all_audit_events'):
188 env.all_audit_events = {}
189
190 new_info = {
191 'source': [],
192 'args': args
193 }
194 info = env.all_audit_events.setdefault(name, new_info)
195 if info is not new_info:
196 if not self._do_args_match(info['args'], new_info['args']):
197 self.logger.warn(
198 "Mismatched arguments for audit-event {}: {!r} != {!r}"
199 .format(name, info['args'], new_info['args'])
200 )
201
Steve Dowere226e832019-07-01 16:03:53 -0700202 ids = []
203 try:
204 target = self.arguments[2].strip("\"'")
205 except (IndexError, TypeError):
206 target = None
207 if not target:
208 target = "audit_event_{}_{}".format(
209 re.sub(r'\W', '_', name),
210 len(info['source']),
211 )
212 ids.append(target)
213
Steve Dower44f91c32019-06-27 10:47:59 -0700214 info['source'].append((env.docname, target))
215
216 pnode = nodes.paragraph(text, classes=["audit-hook"], ids=ids)
Steve Dowerb82e17e2019-05-23 08:45:22 -0700217 if self.content:
218 self.state.nested_parse(self.content, self.content_offset, pnode)
219 else:
220 n, m = self.state.inline_text(text, self.lineno)
221 pnode.extend(n + m)
222
223 return [pnode]
224
Steve Dower44f91c32019-06-27 10:47:59 -0700225 # This list of sets are allowable synonyms for event argument names.
226 # If two names are in the same set, they are treated as equal for the
227 # purposes of warning. This won't help if number of arguments is
228 # different!
229 _SYNONYMS = [
230 {"file", "path", "fd"},
231 ]
232
233 def _do_args_match(self, args1, args2):
234 if args1 == args2:
235 return True
236 if len(args1) != len(args2):
237 return False
238 for a1, a2 in zip(args1, args2):
239 if a1 == a2:
240 continue
241 if any(a1 in s and a2 in s for s in self._SYNONYMS):
242 continue
243 return False
244 return True
245
246
247class audit_event_list(nodes.General, nodes.Element):
248 pass
249
250
251class AuditEventListDirective(Directive):
252
253 def run(self):
254 return [audit_event_list('')]
255
Steve Dowerb82e17e2019-05-23 08:45:22 -0700256
Georg Brandl8a1caa22010-07-29 16:01:11 +0000257# Support for documenting decorators
258
Georg Brandl8a1caa22010-07-29 16:01:11 +0000259class PyDecoratorMixin(object):
260 def handle_signature(self, sig, signode):
261 ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
262 signode.insert(0, addnodes.desc_addname('@', '@'))
263 return ret
264
265 def needs_arglist(self):
266 return False
267
Georg Brandl35903c82014-10-30 22:55:13 +0100268
Georg Brandl8a1caa22010-07-29 16:01:11 +0000269class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
270 def run(self):
271 # a decorator function is a function after all
272 self.name = 'py:function'
273 return PyModulelevel.run(self)
274
Georg Brandl35903c82014-10-30 22:55:13 +0100275
Georg Brandl8a1caa22010-07-29 16:01:11 +0000276class PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
277 def run(self):
278 self.name = 'py:method'
279 return PyClassmember.run(self)
280
281
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100282class PyCoroutineMixin(object):
283 def handle_signature(self, sig, signode):
284 ret = super(PyCoroutineMixin, self).handle_signature(sig, signode)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100285 signode.insert(0, addnodes.desc_annotation('coroutine ', 'coroutine '))
286 return ret
287
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100288
Yury Selivanov47150392018-09-18 17:55:44 -0400289class PyAwaitableMixin(object):
290 def handle_signature(self, sig, signode):
291 ret = super(PyAwaitableMixin, self).handle_signature(sig, signode)
292 signode.insert(0, addnodes.desc_annotation('awaitable ', 'awaitable '))
293 return ret
294
295
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100296class PyCoroutineFunction(PyCoroutineMixin, PyModulelevel):
297 def run(self):
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100298 self.name = 'py:function'
299 return PyModulelevel.run(self)
300
301
302class PyCoroutineMethod(PyCoroutineMixin, PyClassmember):
303 def run(self):
304 self.name = 'py:method'
305 return PyClassmember.run(self)
306
307
Yury Selivanov47150392018-09-18 17:55:44 -0400308class PyAwaitableFunction(PyAwaitableMixin, PyClassmember):
309 def run(self):
310 self.name = 'py:function'
311 return PyClassmember.run(self)
312
313
314class PyAwaitableMethod(PyAwaitableMixin, PyClassmember):
315 def run(self):
316 self.name = 'py:method'
317 return PyClassmember.run(self)
318
319
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200320class PyAbstractMethod(PyClassmember):
321
322 def handle_signature(self, sig, signode):
323 ret = super(PyAbstractMethod, self).handle_signature(sig, signode)
324 signode.insert(0, addnodes.desc_annotation('abstractmethod ',
325 'abstractmethod '))
326 return ret
327
328 def run(self):
329 self.name = 'py:method'
330 return PyClassmember.run(self)
331
332
Georg Brandl281d6ba2010-11-12 08:57:12 +0000333# Support for documenting version of removal in deprecations
334
Georg Brandl281d6ba2010-11-12 08:57:12 +0000335class DeprecatedRemoved(Directive):
336 has_content = True
337 required_arguments = 2
338 optional_arguments = 1
339 final_argument_whitespace = True
340 option_spec = {}
341
cocoatomo0febc052018-02-23 20:47:19 +0900342 _label = 'Deprecated since version {deprecated}, will be removed in version {removed}'
Georg Brandl7ed509a2014-01-21 19:20:31 +0100343
Georg Brandl281d6ba2010-11-12 08:57:12 +0000344 def run(self):
345 node = addnodes.versionmodified()
346 node.document = self.state.document
347 node['type'] = 'deprecated-removed'
348 version = (self.arguments[0], self.arguments[1])
349 node['version'] = version
cocoatomo0febc052018-02-23 20:47:19 +0900350 label = translators['sphinx'].gettext(self._label)
351 text = label.format(deprecated=self.arguments[0], removed=self.arguments[1])
Georg Brandl281d6ba2010-11-12 08:57:12 +0000352 if len(self.arguments) == 3:
353 inodes, messages = self.state.inline_text(self.arguments[2],
354 self.lineno+1)
cocoatomo0febc052018-02-23 20:47:19 +0900355 para = nodes.paragraph(self.arguments[2], '', *inodes, translatable=False)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100356 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000357 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100358 messages = []
359 if self.content:
360 self.state.nested_parse(self.content, self.content_offset, node)
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200361 if len(node):
Georg Brandl7ed509a2014-01-21 19:20:31 +0100362 if isinstance(node[0], nodes.paragraph) and node[0].rawsource:
363 content = nodes.inline(node[0].rawsource, translatable=True)
364 content.source = node[0].source
365 content.line = node[0].line
366 content += node[0].children
cocoatomo0febc052018-02-23 20:47:19 +0900367 node[0].replace_self(nodes.paragraph('', '', content, translatable=False))
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200368 node[0].insert(0, nodes.inline('', '%s: ' % text,
369 classes=['versionmodified']))
Ned Deilyb682fd32014-09-22 14:44:22 -0700370 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100371 para = nodes.paragraph('', '',
Georg Brandl35903c82014-10-30 22:55:13 +0100372 nodes.inline('', '%s.' % text,
cocoatomo0febc052018-02-23 20:47:19 +0900373 classes=['versionmodified']),
374 translatable=False)
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200375 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000376 env = self.state.document.settings.env
Pablo Galindo960bb882019-05-10 22:58:17 +0100377 env.get_domain('changeset').note_changeset(node)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100378 return [node] + messages
Georg Brandl281d6ba2010-11-12 08:57:12 +0000379
380
Georg Brandl2cac28b2012-09-30 15:10:06 +0200381# Support for including Misc/NEWS
382
Brett Cannon79ab8be2017-02-10 15:10:13 -0800383issue_re = re.compile('(?:[Ii]ssue #|bpo-)([0-9]+)')
Georg Brandl44d0c212012-10-01 19:08:50 +0200384whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200385
Georg Brandl35903c82014-10-30 22:55:13 +0100386
Georg Brandl2cac28b2012-09-30 15:10:06 +0200387class MiscNews(Directive):
388 has_content = False
389 required_arguments = 1
390 optional_arguments = 0
391 final_argument_whitespace = False
392 option_spec = {}
393
394 def run(self):
395 fname = self.arguments[0]
396 source = self.state_machine.input_lines.source(
397 self.lineno - self.state_machine.input_offset - 1)
Steve Dowerafe17a72018-12-19 18:20:06 -0800398 source_dir = getenv('PY_MISC_NEWS_DIR')
399 if not source_dir:
400 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200401 fpath = path.join(source_dir, fname)
402 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200403 try:
Victor Stinner272d8882017-06-16 08:59:01 +0200404 with io.open(fpath, encoding='utf-8') as fp:
Georg Brandl2cac28b2012-09-30 15:10:06 +0200405 content = fp.read()
Georg Brandl2cac28b2012-09-30 15:10:06 +0200406 except Exception:
407 text = 'The NEWS file is not available.'
408 node = nodes.strong(text, text)
409 return [node]
Brett Cannon79ab8be2017-02-10 15:10:13 -0800410 content = issue_re.sub(r'`bpo-\1 <https://bugs.python.org/issue\1>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200411 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200412 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200413 # remove first 3 lines as they are the main heading
Georg Brandl6c475812012-10-01 19:27:05 +0200414 lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
Georg Brandl2cac28b2012-09-30 15:10:06 +0200415 self.state_machine.insert_input(lines, fname)
416 return []
417
418
Georg Brandl6b38daa2008-06-01 21:05:17 +0000419# Support for building "topic help" for pydoc
420
421pydoc_topic_labels = [
Jelle Zijlstraac317702017-10-05 20:24:46 -0700422 'assert', 'assignment', 'async', 'atom-identifiers', 'atom-literals',
423 'attribute-access', 'attribute-references', 'augassign', 'await',
424 'binary', 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000425 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000426 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
427 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
428 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
429 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
430 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000431 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
432 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
433 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
434 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
435 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
436 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000437]
438
Georg Brandl6b38daa2008-06-01 21:05:17 +0000439
440class PydocTopicsBuilder(Builder):
441 name = 'pydoc-topics'
442
Benjamin Petersonacfb0872018-04-16 22:56:46 -0700443 default_translator_class = TextTranslator
444
Georg Brandl6b38daa2008-06-01 21:05:17 +0000445 def init(self):
446 self.topics = {}
Benjamin Petersonacfb0872018-04-16 22:56:46 -0700447 self.secnumbers = {}
Georg Brandl6b38daa2008-06-01 21:05:17 +0000448
449 def get_outdated_docs(self):
450 return 'all pydoc topics'
451
452 def get_target_uri(self, docname, typ=None):
453 return '' # no URIs
454
455 def write(self, *ignored):
456 writer = TextWriter(self)
Benjamin Petersonacfb0872018-04-16 22:56:46 -0700457 for label in status_iterator(pydoc_topic_labels,
458 'building topics... ',
459 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000460 if label not in self.env.domaindata['std']['labels']:
Steve Dower44f91c32019-06-27 10:47:59 -0700461 self.env.logger.warn('label %r not in documentation' % label)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000462 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000463 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000464 doctree = self.env.get_and_resolve_doctree(docname, self)
465 document = new_document('<section node>')
466 document.append(doctree.ids[labelid])
467 destination = StringOutput(encoding='utf-8')
468 writer.write(document, destination)
Ned Deilyb682fd32014-09-22 14:44:22 -0700469 self.topics[label] = writer.output
Georg Brandl6b38daa2008-06-01 21:05:17 +0000470
471 def finish(self):
Ned Deilyb682fd32014-09-22 14:44:22 -0700472 f = open(path.join(self.outdir, 'topics.py'), 'wb')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000473 try:
Ned Deilyb682fd32014-09-22 14:44:22 -0700474 f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8'))
475 f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8'))
476 f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
Georg Brandl6b38daa2008-06-01 21:05:17 +0000477 finally:
478 f.close()
479
Georg Brandl495f7b52009-10-27 15:28:25 +0000480
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000481# Support for documenting Opcodes
482
Georg Brandl4833e5b2010-07-03 10:41:33 +0000483opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000484
Georg Brandl35903c82014-10-30 22:55:13 +0100485
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000486def parse_opcode_signature(env, sig, signode):
487 """Transform an opcode signature into RST nodes."""
488 m = opcode_sig_re.match(sig)
489 if m is None:
490 raise ValueError
491 opname, arglist = m.groups()
492 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000493 if arglist is not None:
494 paramlist = addnodes.desc_parameterlist()
495 signode += paramlist
496 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000497 return opname.strip()
498
499
Georg Brandl281d6ba2010-11-12 08:57:12 +0000500# Support for documenting pdb commands
501
Georg Brandl02053ee2010-07-18 10:11:03 +0000502pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
503
504# later...
Georg Brandl35903c82014-10-30 22:55:13 +0100505# pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
Georg Brandl02053ee2010-07-18 10:11:03 +0000506# [.,:]+ | # punctuation
507# [\[\]()] | # parens
508# \s+ # whitespace
509# ''', re.X)
510
Georg Brandl35903c82014-10-30 22:55:13 +0100511
Georg Brandl02053ee2010-07-18 10:11:03 +0000512def parse_pdb_command(env, sig, signode):
513 """Transform a pdb command signature into RST nodes."""
514 m = pdbcmd_sig_re.match(sig)
515 if m is None:
516 raise ValueError
517 name, args = m.groups()
518 fullname = name.replace('(', '').replace(')', '')
519 signode += addnodes.desc_name(name, name)
520 if args:
521 signode += addnodes.desc_addname(' '+args, ' '+args)
522 return fullname
523
524
Steve Dower44f91c32019-06-27 10:47:59 -0700525def process_audit_events(app, doctree, fromdocname):
526 for node in doctree.traverse(audit_event_list):
527 break
528 else:
529 return
530
531 env = app.builder.env
532
533 table = nodes.table(cols=3)
534 group = nodes.tgroup(
535 '',
536 nodes.colspec(colwidth=30),
537 nodes.colspec(colwidth=55),
538 nodes.colspec(colwidth=15),
539 )
540 head = nodes.thead()
541 body = nodes.tbody()
542
543 table += group
544 group += head
545 group += body
546
547 row = nodes.row()
548 row += nodes.entry('', nodes.paragraph('', nodes.Text('Audit event')))
549 row += nodes.entry('', nodes.paragraph('', nodes.Text('Arguments')))
550 row += nodes.entry('', nodes.paragraph('', nodes.Text('References')))
551 head += row
552
553 for name in sorted(getattr(env, "all_audit_events", ())):
554 audit_event = env.all_audit_events[name]
555
556 row = nodes.row()
557 node = nodes.paragraph('', nodes.Text(name))
558 row += nodes.entry('', node)
559
560 node = nodes.paragraph()
561 for i, a in enumerate(audit_event['args']):
562 if i:
563 node += nodes.Text(", ")
564 node += nodes.literal(a, nodes.Text(a))
565 row += nodes.entry('', node)
566
567 node = nodes.paragraph()
Steve Dowere226e832019-07-01 16:03:53 -0700568 backlinks = enumerate(sorted(set(audit_event['source'])), start=1)
569 for i, (doc, label) in backlinks:
Steve Dower44f91c32019-06-27 10:47:59 -0700570 if isinstance(label, str):
571 ref = nodes.reference("", nodes.Text("[{}]".format(i)), internal=True)
572 ref['refuri'] = "{}#{}".format(
573 app.builder.get_relative_uri(fromdocname, doc),
574 label,
575 )
576 node += ref
577 row += nodes.entry('', node)
578
579 body += row
580
581 for node in doctree.traverse(audit_event_list):
582 node.replace_self(table)
583
584
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000585def setup(app):
586 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000587 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000588 app.add_directive('impl-detail', ImplementationDetail)
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400589 app.add_directive('availability', Availability)
Steve Dowerb82e17e2019-05-23 08:45:22 -0700590 app.add_directive('audit-event', AuditEvent)
Steve Dower44f91c32019-06-27 10:47:59 -0700591 app.add_directive('audit-event-table', AuditEventListDirective)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000592 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000593 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000594 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Stéphane Wirtele385d062018-10-13 08:14:08 +0200595 app.add_object_type('opcode', 'opcode', '%s (opcode)', parse_opcode_signature)
596 app.add_object_type('pdbcommand', 'pdbcmd', '%s (pdb command)', parse_pdb_command)
597 app.add_object_type('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000598 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
599 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100600 app.add_directive_to_domain('py', 'coroutinefunction', PyCoroutineFunction)
601 app.add_directive_to_domain('py', 'coroutinemethod', PyCoroutineMethod)
Yury Selivanov47150392018-09-18 17:55:44 -0400602 app.add_directive_to_domain('py', 'awaitablefunction', PyAwaitableFunction)
603 app.add_directive_to_domain('py', 'awaitablemethod', PyAwaitableMethod)
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200604 app.add_directive_to_domain('py', 'abstractmethod', PyAbstractMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200605 app.add_directive('miscnews', MiscNews)
Steve Dower44f91c32019-06-27 10:47:59 -0700606 app.connect('doctree-resolved', process_audit_events)
Georg Brandlbae334c2014-09-30 22:17:41 +0200607 return {'version': '1.0', 'parallel_read_safe': True}