blob: 80fbd96d56fdc0a6e6076e078d1c259d6a8a15eb [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
Dong-hee Na6595cb02020-09-18 18:22:36 +090034
35try:
36 from sphinx.domains.python import PyFunction, PyMethod
37except ImportError:
38 from sphinx.domains.python import PyClassmember as PyMethod
39 from sphinx.domains.python import PyModulelevel as PyFunction
Georg Brandl35903c82014-10-30 22:55:13 +010040
41# Support for checking for suspicious markup
42
43import suspicious
44
45
46ISSUE_URI = 'https://bugs.python.org/issue%s'
Łukasz Langa9ab2fb12019-06-04 22:12:32 +020047SOURCE_URI = 'https://github.com/python/cpython/tree/master/%s'
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000048
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000049# monkey-patch reST parser to disable alphabetic and roman enumerated lists
50from docutils.parsers.rst.states import Body
51Body.enum.converters['loweralpha'] = \
52 Body.enum.converters['upperalpha'] = \
53 Body.enum.converters['lowerroman'] = \
54 Body.enum.converters['upperroman'] = lambda x: None
55
Georg Brandl35903c82014-10-30 22:55:13 +010056
Georg Brandl495f7b52009-10-27 15:28:25 +000057# Support for marking up and linking to bugs.python.org issues
58
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000059def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
60 issue = utils.unescape(text)
Brett Cannon79ab8be2017-02-10 15:10:13 -080061 text = 'bpo-' + issue
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000062 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
63 return [refnode], []
64
65
Georg Brandl68818862010-11-06 07:19:35 +000066# Support for linking to Python source files easily
67
68def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
69 has_t, title, target = split_explicit_title(text)
70 title = utils.unescape(title)
71 target = utils.unescape(target)
72 refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
73 return [refnode], []
74
75
Georg Brandl495f7b52009-10-27 15:28:25 +000076# Support for marking up implementation details
77
Georg Brandl495f7b52009-10-27 15:28:25 +000078class ImplementationDetail(Directive):
79
80 has_content = True
81 required_arguments = 0
82 optional_arguments = 1
83 final_argument_whitespace = True
84
INADA Naokic351ce62017-03-08 19:07:13 +090085 # This text is copied to templates/dummy.html
86 label_text = 'CPython implementation detail:'
87
Georg Brandl495f7b52009-10-27 15:28:25 +000088 def run(self):
89 pnode = nodes.compound(classes=['impl-detail'])
INADA Naokic351ce62017-03-08 19:07:13 +090090 label = translators['sphinx'].gettext(self.label_text)
Georg Brandl495f7b52009-10-27 15:28:25 +000091 content = self.content
INADA Naokic351ce62017-03-08 19:07:13 +090092 add_text = nodes.strong(label, label)
Georg Brandl495f7b52009-10-27 15:28:25 +000093 if self.arguments:
94 n, m = self.state.inline_text(self.arguments[0], self.lineno)
95 pnode.append(nodes.paragraph('', '', *(n + m)))
96 self.state.nested_parse(content, self.content_offset, pnode)
97 if pnode.children and isinstance(pnode[0], nodes.paragraph):
INADA Naokic351ce62017-03-08 19:07:13 +090098 content = nodes.inline(pnode[0].rawsource, translatable=True)
99 content.source = pnode[0].source
100 content.line = pnode[0].line
101 content += pnode[0].children
102 pnode[0].replace_self(nodes.paragraph('', '', content,
103 translatable=False))
Georg Brandl495f7b52009-10-27 15:28:25 +0000104 pnode[0].insert(0, add_text)
105 pnode[0].insert(1, nodes.Text(' '))
106 else:
107 pnode.insert(0, nodes.paragraph('', '', add_text))
108 return [pnode]
109
110
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400111# Support for documenting platform availability
112
113class Availability(Directive):
114
115 has_content = False
116 required_arguments = 1
117 optional_arguments = 0
118 final_argument_whitespace = True
119
120 def run(self):
Julien Palardbeed84c2018-11-07 22:42:40 +0100121 availability_ref = ':ref:`Availability <availability>`: '
122 pnode = nodes.paragraph(availability_ref + self.arguments[0],
123 classes=["availability"],)
124 n, m = self.state.inline_text(availability_ref, self.lineno)
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400125 pnode.extend(n + m)
126 n, m = self.state.inline_text(self.arguments[0], self.lineno)
127 pnode.extend(n + m)
128 return [pnode]
129
130
Steve Dowerb82e17e2019-05-23 08:45:22 -0700131# Support for documenting audit event
132
Julien Palarda103e732020-07-06 22:28:15 +0200133def audit_events_purge(app, env, docname):
134 """This is to remove from env.all_audit_events old traces of removed
135 documents.
136 """
137 if not hasattr(env, 'all_audit_events'):
138 return
139 fresh_all_audit_events = {}
140 for name, event in env.all_audit_events.items():
141 event["source"] = [(d, t) for d, t in event["source"] if d != docname]
142 if event["source"]:
143 # Only keep audit_events that have at least one source.
144 fresh_all_audit_events[name] = event
145 env.all_audit_events = fresh_all_audit_events
146
147
148def audit_events_merge(app, env, docnames, other):
149 """In Sphinx parallel builds, this merges env.all_audit_events from
150 subprocesses.
151
152 all_audit_events is a dict of names, with values like:
153 {'source': [(docname, target), ...], 'args': args}
154 """
155 if not hasattr(other, 'all_audit_events'):
156 return
157 if not hasattr(env, 'all_audit_events'):
158 env.all_audit_events = {}
159 for name, value in other.all_audit_events.items():
160 if name in env.all_audit_events:
161 env.all_audit_events[name]["source"].extend(value["source"])
162 else:
163 env.all_audit_events[name] = value
164
165
Steve Dowerb82e17e2019-05-23 08:45:22 -0700166class AuditEvent(Directive):
167
168 has_content = True
169 required_arguments = 1
Steve Dower44f91c32019-06-27 10:47:59 -0700170 optional_arguments = 2
Steve Dowerb82e17e2019-05-23 08:45:22 -0700171 final_argument_whitespace = True
172
173 _label = [
174 "Raises an :ref:`auditing event <auditing>` {name} with no arguments.",
175 "Raises an :ref:`auditing event <auditing>` {name} with argument {args}.",
176 "Raises an :ref:`auditing event <auditing>` {name} with arguments {args}.",
177 ]
178
Steve Dower44f91c32019-06-27 10:47:59 -0700179 @property
180 def logger(self):
181 cls = type(self)
182 return logging.getLogger(cls.__module__ + "." + cls.__name__)
183
Steve Dowerb82e17e2019-05-23 08:45:22 -0700184 def run(self):
Steve Dower44f91c32019-06-27 10:47:59 -0700185 name = self.arguments[0]
Steve Dowerb82e17e2019-05-23 08:45:22 -0700186 if len(self.arguments) >= 2 and self.arguments[1]:
Steve Dower44f91c32019-06-27 10:47:59 -0700187 args = (a.strip() for a in self.arguments[1].strip("'\"").split(","))
188 args = [a for a in args if a]
Steve Dowerb82e17e2019-05-23 08:45:22 -0700189 else:
190 args = []
191
192 label = translators['sphinx'].gettext(self._label[min(2, len(args))])
Steve Dower44f91c32019-06-27 10:47:59 -0700193 text = label.format(name="``{}``".format(name),
194 args=", ".join("``{}``".format(a) for a in args if a))
Steve Dowerb82e17e2019-05-23 08:45:22 -0700195
Steve Dower44f91c32019-06-27 10:47:59 -0700196 env = self.state.document.settings.env
197 if not hasattr(env, 'all_audit_events'):
198 env.all_audit_events = {}
199
200 new_info = {
201 'source': [],
202 'args': args
203 }
204 info = env.all_audit_events.setdefault(name, new_info)
205 if info is not new_info:
206 if not self._do_args_match(info['args'], new_info['args']):
207 self.logger.warn(
208 "Mismatched arguments for audit-event {}: {!r} != {!r}"
209 .format(name, info['args'], new_info['args'])
210 )
211
Steve Dowere226e832019-07-01 16:03:53 -0700212 ids = []
213 try:
214 target = self.arguments[2].strip("\"'")
215 except (IndexError, TypeError):
216 target = None
217 if not target:
218 target = "audit_event_{}_{}".format(
219 re.sub(r'\W', '_', name),
220 len(info['source']),
221 )
222 ids.append(target)
223
Steve Dower44f91c32019-06-27 10:47:59 -0700224 info['source'].append((env.docname, target))
225
226 pnode = nodes.paragraph(text, classes=["audit-hook"], ids=ids)
Steve Dowerb82e17e2019-05-23 08:45:22 -0700227 if self.content:
228 self.state.nested_parse(self.content, self.content_offset, pnode)
229 else:
230 n, m = self.state.inline_text(text, self.lineno)
231 pnode.extend(n + m)
232
233 return [pnode]
234
Steve Dower44f91c32019-06-27 10:47:59 -0700235 # This list of sets are allowable synonyms for event argument names.
236 # If two names are in the same set, they are treated as equal for the
237 # purposes of warning. This won't help if number of arguments is
238 # different!
239 _SYNONYMS = [
240 {"file", "path", "fd"},
241 ]
242
243 def _do_args_match(self, args1, args2):
244 if args1 == args2:
245 return True
246 if len(args1) != len(args2):
247 return False
248 for a1, a2 in zip(args1, args2):
249 if a1 == a2:
250 continue
251 if any(a1 in s and a2 in s for s in self._SYNONYMS):
252 continue
253 return False
254 return True
255
256
257class audit_event_list(nodes.General, nodes.Element):
258 pass
259
260
261class AuditEventListDirective(Directive):
262
263 def run(self):
264 return [audit_event_list('')]
265
Steve Dowerb82e17e2019-05-23 08:45:22 -0700266
Georg Brandl8a1caa22010-07-29 16:01:11 +0000267# Support for documenting decorators
268
Georg Brandl8a1caa22010-07-29 16:01:11 +0000269class PyDecoratorMixin(object):
270 def handle_signature(self, sig, signode):
271 ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
272 signode.insert(0, addnodes.desc_addname('@', '@'))
273 return ret
274
275 def needs_arglist(self):
276 return False
277
Georg Brandl35903c82014-10-30 22:55:13 +0100278
Dong-hee Na6595cb02020-09-18 18:22:36 +0900279class PyDecoratorFunction(PyDecoratorMixin, PyFunction):
Georg Brandl8a1caa22010-07-29 16:01:11 +0000280 def run(self):
281 # a decorator function is a function after all
282 self.name = 'py:function'
Dong-hee Na6595cb02020-09-18 18:22:36 +0900283 return PyFunction.run(self)
Georg Brandl8a1caa22010-07-29 16:01:11 +0000284
Georg Brandl35903c82014-10-30 22:55:13 +0100285
Dong-hee Na6595cb02020-09-18 18:22:36 +0900286# TODO: Use sphinx.domains.python.PyDecoratorMethod when possible
287class PyDecoratorMethod(PyDecoratorMixin, PyMethod):
Georg Brandl8a1caa22010-07-29 16:01:11 +0000288 def run(self):
289 self.name = 'py:method'
Dong-hee Na6595cb02020-09-18 18:22:36 +0900290 return PyMethod.run(self)
Georg Brandl8a1caa22010-07-29 16:01:11 +0000291
292
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100293class PyCoroutineMixin(object):
294 def handle_signature(self, sig, signode):
295 ret = super(PyCoroutineMixin, self).handle_signature(sig, signode)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100296 signode.insert(0, addnodes.desc_annotation('coroutine ', 'coroutine '))
297 return ret
298
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100299
Yury Selivanov47150392018-09-18 17:55:44 -0400300class PyAwaitableMixin(object):
301 def handle_signature(self, sig, signode):
302 ret = super(PyAwaitableMixin, self).handle_signature(sig, signode)
303 signode.insert(0, addnodes.desc_annotation('awaitable ', 'awaitable '))
304 return ret
305
306
Dong-hee Na6595cb02020-09-18 18:22:36 +0900307class PyCoroutineFunction(PyCoroutineMixin, PyFunction):
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100308 def run(self):
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100309 self.name = 'py:function'
Dong-hee Na6595cb02020-09-18 18:22:36 +0900310 return PyFunction.run(self)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100311
312
Dong-hee Na6595cb02020-09-18 18:22:36 +0900313class PyCoroutineMethod(PyCoroutineMixin, PyMethod):
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100314 def run(self):
315 self.name = 'py:method'
Dong-hee Na6595cb02020-09-18 18:22:36 +0900316 return PyMethod.run(self)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100317
318
Dong-hee Na6595cb02020-09-18 18:22:36 +0900319class PyAwaitableFunction(PyAwaitableMixin, PyFunction):
Yury Selivanov47150392018-09-18 17:55:44 -0400320 def run(self):
321 self.name = 'py:function'
Dong-hee Na6595cb02020-09-18 18:22:36 +0900322 return PyFunction.run(self)
Yury Selivanov47150392018-09-18 17:55:44 -0400323
324
Dong-hee Na6595cb02020-09-18 18:22:36 +0900325class PyAwaitableMethod(PyAwaitableMixin, PyMethod):
Yury Selivanov47150392018-09-18 17:55:44 -0400326 def run(self):
327 self.name = 'py:method'
Dong-hee Na6595cb02020-09-18 18:22:36 +0900328 return PyMethod.run(self)
Yury Selivanov47150392018-09-18 17:55:44 -0400329
330
Dong-hee Na6595cb02020-09-18 18:22:36 +0900331class PyAbstractMethod(PyMethod):
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200332
333 def handle_signature(self, sig, signode):
334 ret = super(PyAbstractMethod, self).handle_signature(sig, signode)
335 signode.insert(0, addnodes.desc_annotation('abstractmethod ',
336 'abstractmethod '))
337 return ret
338
339 def run(self):
340 self.name = 'py:method'
Dong-hee Na6595cb02020-09-18 18:22:36 +0900341 return PyMethod.run(self)
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200342
343
Georg Brandl281d6ba2010-11-12 08:57:12 +0000344# Support for documenting version of removal in deprecations
345
Georg Brandl281d6ba2010-11-12 08:57:12 +0000346class DeprecatedRemoved(Directive):
347 has_content = True
348 required_arguments = 2
349 optional_arguments = 1
350 final_argument_whitespace = True
351 option_spec = {}
352
Florian Dahlitz735d9022020-05-30 09:47:32 +0200353 _deprecated_label = 'Deprecated since version {deprecated}, will be removed in version {removed}'
354 _removed_label = 'Deprecated since version {deprecated}, removed in version {removed}'
Georg Brandl7ed509a2014-01-21 19:20:31 +0100355
Georg Brandl281d6ba2010-11-12 08:57:12 +0000356 def run(self):
357 node = addnodes.versionmodified()
358 node.document = self.state.document
359 node['type'] = 'deprecated-removed'
360 version = (self.arguments[0], self.arguments[1])
361 node['version'] = version
Florian Dahlitz735d9022020-05-30 09:47:32 +0200362 env = self.state.document.settings.env
363 current_version = tuple(int(e) for e in env.config.version.split('.'))
364 removed_version = tuple(int(e) for e in self.arguments[1].split('.'))
365 if current_version < removed_version:
366 label = self._deprecated_label
367 else:
368 label = self._removed_label
369
370 label = translators['sphinx'].gettext(label)
cocoatomo0febc052018-02-23 20:47:19 +0900371 text = label.format(deprecated=self.arguments[0], removed=self.arguments[1])
Georg Brandl281d6ba2010-11-12 08:57:12 +0000372 if len(self.arguments) == 3:
373 inodes, messages = self.state.inline_text(self.arguments[2],
374 self.lineno+1)
cocoatomo0febc052018-02-23 20:47:19 +0900375 para = nodes.paragraph(self.arguments[2], '', *inodes, translatable=False)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100376 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000377 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100378 messages = []
379 if self.content:
380 self.state.nested_parse(self.content, self.content_offset, node)
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200381 if len(node):
Georg Brandl7ed509a2014-01-21 19:20:31 +0100382 if isinstance(node[0], nodes.paragraph) and node[0].rawsource:
383 content = nodes.inline(node[0].rawsource, translatable=True)
384 content.source = node[0].source
385 content.line = node[0].line
386 content += node[0].children
cocoatomo0febc052018-02-23 20:47:19 +0900387 node[0].replace_self(nodes.paragraph('', '', content, translatable=False))
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200388 node[0].insert(0, nodes.inline('', '%s: ' % text,
389 classes=['versionmodified']))
Ned Deilyb682fd32014-09-22 14:44:22 -0700390 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100391 para = nodes.paragraph('', '',
Georg Brandl35903c82014-10-30 22:55:13 +0100392 nodes.inline('', '%s.' % text,
cocoatomo0febc052018-02-23 20:47:19 +0900393 classes=['versionmodified']),
394 translatable=False)
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200395 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000396 env = self.state.document.settings.env
Pablo Galindo960bb882019-05-10 22:58:17 +0100397 env.get_domain('changeset').note_changeset(node)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100398 return [node] + messages
Georg Brandl281d6ba2010-11-12 08:57:12 +0000399
400
Georg Brandl2cac28b2012-09-30 15:10:06 +0200401# Support for including Misc/NEWS
402
Brett Cannon79ab8be2017-02-10 15:10:13 -0800403issue_re = re.compile('(?:[Ii]ssue #|bpo-)([0-9]+)')
Georg Brandl44d0c212012-10-01 19:08:50 +0200404whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200405
Georg Brandl35903c82014-10-30 22:55:13 +0100406
Georg Brandl2cac28b2012-09-30 15:10:06 +0200407class MiscNews(Directive):
408 has_content = False
409 required_arguments = 1
410 optional_arguments = 0
411 final_argument_whitespace = False
412 option_spec = {}
413
414 def run(self):
415 fname = self.arguments[0]
416 source = self.state_machine.input_lines.source(
417 self.lineno - self.state_machine.input_offset - 1)
Steve Dowerafe17a72018-12-19 18:20:06 -0800418 source_dir = getenv('PY_MISC_NEWS_DIR')
419 if not source_dir:
420 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200421 fpath = path.join(source_dir, fname)
422 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200423 try:
Victor Stinner272d8882017-06-16 08:59:01 +0200424 with io.open(fpath, encoding='utf-8') as fp:
Georg Brandl2cac28b2012-09-30 15:10:06 +0200425 content = fp.read()
Georg Brandl2cac28b2012-09-30 15:10:06 +0200426 except Exception:
427 text = 'The NEWS file is not available.'
428 node = nodes.strong(text, text)
429 return [node]
Brett Cannon79ab8be2017-02-10 15:10:13 -0800430 content = issue_re.sub(r'`bpo-\1 <https://bugs.python.org/issue\1>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200431 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200432 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200433 # remove first 3 lines as they are the main heading
Georg Brandl6c475812012-10-01 19:27:05 +0200434 lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
Georg Brandl2cac28b2012-09-30 15:10:06 +0200435 self.state_machine.insert_input(lines, fname)
436 return []
437
438
Georg Brandl6b38daa2008-06-01 21:05:17 +0000439# Support for building "topic help" for pydoc
440
441pydoc_topic_labels = [
Jelle Zijlstraac317702017-10-05 20:24:46 -0700442 'assert', 'assignment', 'async', 'atom-identifiers', 'atom-literals',
443 'attribute-access', 'attribute-references', 'augassign', 'await',
444 'binary', 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000445 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000446 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
447 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
448 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
449 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
450 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000451 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
452 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
453 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
454 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
455 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
456 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000457]
458
Georg Brandl6b38daa2008-06-01 21:05:17 +0000459
460class PydocTopicsBuilder(Builder):
461 name = 'pydoc-topics'
462
Benjamin Petersonacfb0872018-04-16 22:56:46 -0700463 default_translator_class = TextTranslator
464
Georg Brandl6b38daa2008-06-01 21:05:17 +0000465 def init(self):
466 self.topics = {}
Benjamin Petersonacfb0872018-04-16 22:56:46 -0700467 self.secnumbers = {}
Georg Brandl6b38daa2008-06-01 21:05:17 +0000468
469 def get_outdated_docs(self):
470 return 'all pydoc topics'
471
472 def get_target_uri(self, docname, typ=None):
473 return '' # no URIs
474
475 def write(self, *ignored):
476 writer = TextWriter(self)
Benjamin Petersonacfb0872018-04-16 22:56:46 -0700477 for label in status_iterator(pydoc_topic_labels,
478 'building topics... ',
479 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000480 if label not in self.env.domaindata['std']['labels']:
Steve Dower44f91c32019-06-27 10:47:59 -0700481 self.env.logger.warn('label %r not in documentation' % label)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000482 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000483 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000484 doctree = self.env.get_and_resolve_doctree(docname, self)
485 document = new_document('<section node>')
486 document.append(doctree.ids[labelid])
487 destination = StringOutput(encoding='utf-8')
488 writer.write(document, destination)
Ned Deilyb682fd32014-09-22 14:44:22 -0700489 self.topics[label] = writer.output
Georg Brandl6b38daa2008-06-01 21:05:17 +0000490
491 def finish(self):
Ned Deilyb682fd32014-09-22 14:44:22 -0700492 f = open(path.join(self.outdir, 'topics.py'), 'wb')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000493 try:
Ned Deilyb682fd32014-09-22 14:44:22 -0700494 f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8'))
495 f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8'))
496 f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
Georg Brandl6b38daa2008-06-01 21:05:17 +0000497 finally:
498 f.close()
499
Georg Brandl495f7b52009-10-27 15:28:25 +0000500
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000501# Support for documenting Opcodes
502
Georg Brandl4833e5b2010-07-03 10:41:33 +0000503opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000504
Georg Brandl35903c82014-10-30 22:55:13 +0100505
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000506def parse_opcode_signature(env, sig, signode):
507 """Transform an opcode signature into RST nodes."""
508 m = opcode_sig_re.match(sig)
509 if m is None:
510 raise ValueError
511 opname, arglist = m.groups()
512 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000513 if arglist is not None:
514 paramlist = addnodes.desc_parameterlist()
515 signode += paramlist
516 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000517 return opname.strip()
518
519
Georg Brandl281d6ba2010-11-12 08:57:12 +0000520# Support for documenting pdb commands
521
Georg Brandl02053ee2010-07-18 10:11:03 +0000522pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
523
524# later...
Georg Brandl35903c82014-10-30 22:55:13 +0100525# pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
Georg Brandl02053ee2010-07-18 10:11:03 +0000526# [.,:]+ | # punctuation
527# [\[\]()] | # parens
528# \s+ # whitespace
529# ''', re.X)
530
Georg Brandl35903c82014-10-30 22:55:13 +0100531
Georg Brandl02053ee2010-07-18 10:11:03 +0000532def parse_pdb_command(env, sig, signode):
533 """Transform a pdb command signature into RST nodes."""
534 m = pdbcmd_sig_re.match(sig)
535 if m is None:
536 raise ValueError
537 name, args = m.groups()
538 fullname = name.replace('(', '').replace(')', '')
539 signode += addnodes.desc_name(name, name)
540 if args:
541 signode += addnodes.desc_addname(' '+args, ' '+args)
542 return fullname
543
544
Steve Dower44f91c32019-06-27 10:47:59 -0700545def process_audit_events(app, doctree, fromdocname):
546 for node in doctree.traverse(audit_event_list):
547 break
548 else:
549 return
550
551 env = app.builder.env
552
553 table = nodes.table(cols=3)
554 group = nodes.tgroup(
555 '',
556 nodes.colspec(colwidth=30),
557 nodes.colspec(colwidth=55),
558 nodes.colspec(colwidth=15),
Dmitry Shachnevc3d679f2019-09-10 17:40:50 +0300559 cols=3,
Steve Dower44f91c32019-06-27 10:47:59 -0700560 )
561 head = nodes.thead()
562 body = nodes.tbody()
563
564 table += group
565 group += head
566 group += body
567
568 row = nodes.row()
569 row += nodes.entry('', nodes.paragraph('', nodes.Text('Audit event')))
570 row += nodes.entry('', nodes.paragraph('', nodes.Text('Arguments')))
571 row += nodes.entry('', nodes.paragraph('', nodes.Text('References')))
572 head += row
573
574 for name in sorted(getattr(env, "all_audit_events", ())):
575 audit_event = env.all_audit_events[name]
576
577 row = nodes.row()
578 node = nodes.paragraph('', nodes.Text(name))
579 row += nodes.entry('', node)
580
581 node = nodes.paragraph()
582 for i, a in enumerate(audit_event['args']):
583 if i:
584 node += nodes.Text(", ")
585 node += nodes.literal(a, nodes.Text(a))
586 row += nodes.entry('', node)
587
588 node = nodes.paragraph()
Steve Dowere226e832019-07-01 16:03:53 -0700589 backlinks = enumerate(sorted(set(audit_event['source'])), start=1)
590 for i, (doc, label) in backlinks:
Steve Dower44f91c32019-06-27 10:47:59 -0700591 if isinstance(label, str):
592 ref = nodes.reference("", nodes.Text("[{}]".format(i)), internal=True)
Julien Palard63c98ed2019-09-09 12:54:56 +0200593 try:
594 ref['refuri'] = "{}#{}".format(
595 app.builder.get_relative_uri(fromdocname, doc),
596 label,
597 )
598 except NoUri:
599 continue
Steve Dower44f91c32019-06-27 10:47:59 -0700600 node += ref
601 row += nodes.entry('', node)
602
603 body += row
604
605 for node in doctree.traverse(audit_event_list):
606 node.replace_self(table)
607
608
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000609def setup(app):
610 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000611 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000612 app.add_directive('impl-detail', ImplementationDetail)
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400613 app.add_directive('availability', Availability)
Steve Dowerb82e17e2019-05-23 08:45:22 -0700614 app.add_directive('audit-event', AuditEvent)
Steve Dower44f91c32019-06-27 10:47:59 -0700615 app.add_directive('audit-event-table', AuditEventListDirective)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000616 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000617 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000618 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Stéphane Wirtele385d062018-10-13 08:14:08 +0200619 app.add_object_type('opcode', 'opcode', '%s (opcode)', parse_opcode_signature)
620 app.add_object_type('pdbcommand', 'pdbcmd', '%s (pdb command)', parse_pdb_command)
621 app.add_object_type('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000622 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
623 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100624 app.add_directive_to_domain('py', 'coroutinefunction', PyCoroutineFunction)
625 app.add_directive_to_domain('py', 'coroutinemethod', PyCoroutineMethod)
Yury Selivanov47150392018-09-18 17:55:44 -0400626 app.add_directive_to_domain('py', 'awaitablefunction', PyAwaitableFunction)
627 app.add_directive_to_domain('py', 'awaitablemethod', PyAwaitableMethod)
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200628 app.add_directive_to_domain('py', 'abstractmethod', PyAbstractMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200629 app.add_directive('miscnews', MiscNews)
Steve Dower44f91c32019-06-27 10:47:59 -0700630 app.connect('doctree-resolved', process_audit_events)
Julien Palarda103e732020-07-06 22:28:15 +0200631 app.connect('env-merge-info', audit_events_merge)
632 app.connect('env-purge-doc', audit_events_purge)
Georg Brandlbae334c2014-09-30 22:17:41 +0200633 return {'version': '1.0', 'parallel_read_safe': True}