blob: bb69366ecd4991c611dfd949f4ea9def82be864e [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
Georg Brandl35903c82014-10-30 22:55:13 +010014from os import path
15from 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
Georg Brandl68818862010-11-06 07:19:35 +000026from sphinx.util.nodes import split_explicit_title
Georg Brandl239990d2013-10-12 20:50:21 +020027from sphinx.writers.html import HTMLTranslator
Georg Brandl35903c82014-10-30 22:55:13 +010028from sphinx.writers.text import TextWriter
Georg Brandl239990d2013-10-12 20:50:21 +020029from sphinx.writers.latex import LaTeXTranslator
Georg Brandl35903c82014-10-30 22:55:13 +010030from sphinx.domains.python import PyModulelevel, PyClassmember
31
32# Support for checking for suspicious markup
33
34import suspicious
35
36
37ISSUE_URI = 'https://bugs.python.org/issue%s'
Ned Deily7f386372018-01-31 18:24:44 -050038SOURCE_URI = 'https://github.com/python/cpython/tree/3.7/%s'
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000039
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000040# monkey-patch reST parser to disable alphabetic and roman enumerated lists
41from docutils.parsers.rst.states import Body
42Body.enum.converters['loweralpha'] = \
43 Body.enum.converters['upperalpha'] = \
44 Body.enum.converters['lowerroman'] = \
45 Body.enum.converters['upperroman'] = lambda x: None
46
Georg Brandl83e51f42012-10-10 16:45:11 +020047# monkey-patch HTML and LaTeX translators to keep doctest blocks in the
48# doctest docs themselves
49orig_visit_literal_block = HTMLTranslator.visit_literal_block
Georg Brandl35903c82014-10-30 22:55:13 +010050orig_depart_literal_block = LaTeXTranslator.depart_literal_block
51
52
Georg Brandl83e51f42012-10-10 16:45:11 +020053def new_visit_literal_block(self, node):
54 meta = self.builder.env.metadata[self.builder.current_docname]
55 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
56 if 'keepdoctest' in meta:
57 self.highlighter.trim_doctest_flags = False
58 try:
59 orig_visit_literal_block(self, node)
60 finally:
61 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
62
Georg Brandl83e51f42012-10-10 16:45:11 +020063
Georg Brandl83e51f42012-10-10 16:45:11 +020064def new_depart_literal_block(self, node):
65 meta = self.builder.env.metadata[self.curfilestack[-1]]
66 old_trim_doctest_flags = self.highlighter.trim_doctest_flags
67 if 'keepdoctest' in meta:
68 self.highlighter.trim_doctest_flags = False
69 try:
70 orig_depart_literal_block(self, node)
71 finally:
72 self.highlighter.trim_doctest_flags = old_trim_doctest_flags
73
Georg Brandl35903c82014-10-30 22:55:13 +010074
75HTMLTranslator.visit_literal_block = new_visit_literal_block
Georg Brandl83e51f42012-10-10 16:45:11 +020076LaTeXTranslator.depart_literal_block = new_depart_literal_block
Benjamin Peterson5c6d7872009-02-06 02:40:07 +000077
Georg Brandl35903c82014-10-30 22:55:13 +010078
Georg Brandl495f7b52009-10-27 15:28:25 +000079# Support for marking up and linking to bugs.python.org issues
80
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000081def issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
82 issue = utils.unescape(text)
Brett Cannon79ab8be2017-02-10 15:10:13 -080083 text = 'bpo-' + issue
Martin v. Löwis5680d0c2008-04-10 03:06:53 +000084 refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
85 return [refnode], []
86
87
Georg Brandl68818862010-11-06 07:19:35 +000088# Support for linking to Python source files easily
89
90def source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
91 has_t, title, target = split_explicit_title(text)
92 title = utils.unescape(title)
93 target = utils.unescape(target)
94 refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
95 return [refnode], []
96
97
Georg Brandl495f7b52009-10-27 15:28:25 +000098# Support for marking up implementation details
99
Georg Brandl495f7b52009-10-27 15:28:25 +0000100class ImplementationDetail(Directive):
101
102 has_content = True
103 required_arguments = 0
104 optional_arguments = 1
105 final_argument_whitespace = True
106
INADA Naokic351ce62017-03-08 19:07:13 +0900107 # This text is copied to templates/dummy.html
108 label_text = 'CPython implementation detail:'
109
Georg Brandl495f7b52009-10-27 15:28:25 +0000110 def run(self):
111 pnode = nodes.compound(classes=['impl-detail'])
INADA Naokic351ce62017-03-08 19:07:13 +0900112 label = translators['sphinx'].gettext(self.label_text)
Georg Brandl495f7b52009-10-27 15:28:25 +0000113 content = self.content
INADA Naokic351ce62017-03-08 19:07:13 +0900114 add_text = nodes.strong(label, label)
Georg Brandl495f7b52009-10-27 15:28:25 +0000115 if self.arguments:
116 n, m = self.state.inline_text(self.arguments[0], self.lineno)
117 pnode.append(nodes.paragraph('', '', *(n + m)))
118 self.state.nested_parse(content, self.content_offset, pnode)
119 if pnode.children and isinstance(pnode[0], nodes.paragraph):
INADA Naokic351ce62017-03-08 19:07:13 +0900120 content = nodes.inline(pnode[0].rawsource, translatable=True)
121 content.source = pnode[0].source
122 content.line = pnode[0].line
123 content += pnode[0].children
124 pnode[0].replace_self(nodes.paragraph('', '', content,
125 translatable=False))
Georg Brandl495f7b52009-10-27 15:28:25 +0000126 pnode[0].insert(0, add_text)
127 pnode[0].insert(1, nodes.Text(' '))
128 else:
129 pnode.insert(0, nodes.paragraph('', '', add_text))
130 return [pnode]
131
132
Georg Brandl8a1caa22010-07-29 16:01:11 +0000133# Support for documenting decorators
134
Georg Brandl8a1caa22010-07-29 16:01:11 +0000135class PyDecoratorMixin(object):
136 def handle_signature(self, sig, signode):
137 ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
138 signode.insert(0, addnodes.desc_addname('@', '@'))
139 return ret
140
141 def needs_arglist(self):
142 return False
143
Georg Brandl35903c82014-10-30 22:55:13 +0100144
Georg Brandl8a1caa22010-07-29 16:01:11 +0000145class PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
146 def run(self):
147 # a decorator function is a function after all
148 self.name = 'py:function'
149 return PyModulelevel.run(self)
150
Georg Brandl35903c82014-10-30 22:55:13 +0100151
Georg Brandl8a1caa22010-07-29 16:01:11 +0000152class PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
153 def run(self):
154 self.name = 'py:method'
155 return PyClassmember.run(self)
156
157
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100158class PyCoroutineMixin(object):
159 def handle_signature(self, sig, signode):
160 ret = super(PyCoroutineMixin, self).handle_signature(sig, signode)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100161 signode.insert(0, addnodes.desc_annotation('coroutine ', 'coroutine '))
162 return ret
163
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100164
165class PyCoroutineFunction(PyCoroutineMixin, PyModulelevel):
166 def run(self):
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100167 self.name = 'py:function'
168 return PyModulelevel.run(self)
169
170
171class PyCoroutineMethod(PyCoroutineMixin, PyClassmember):
172 def run(self):
173 self.name = 'py:method'
174 return PyClassmember.run(self)
175
176
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200177class PyAbstractMethod(PyClassmember):
178
179 def handle_signature(self, sig, signode):
180 ret = super(PyAbstractMethod, self).handle_signature(sig, signode)
181 signode.insert(0, addnodes.desc_annotation('abstractmethod ',
182 'abstractmethod '))
183 return ret
184
185 def run(self):
186 self.name = 'py:method'
187 return PyClassmember.run(self)
188
189
Georg Brandl281d6ba2010-11-12 08:57:12 +0000190# Support for documenting version of removal in deprecations
191
Georg Brandl281d6ba2010-11-12 08:57:12 +0000192class DeprecatedRemoved(Directive):
193 has_content = True
194 required_arguments = 2
195 optional_arguments = 1
196 final_argument_whitespace = True
197 option_spec = {}
198
Miss Islington (bot)c673a622018-02-23 04:08:45 -0800199 _label = 'Deprecated since version {deprecated}, will be removed in version {removed}'
Georg Brandl7ed509a2014-01-21 19:20:31 +0100200
Georg Brandl281d6ba2010-11-12 08:57:12 +0000201 def run(self):
202 node = addnodes.versionmodified()
203 node.document = self.state.document
204 node['type'] = 'deprecated-removed'
205 version = (self.arguments[0], self.arguments[1])
206 node['version'] = version
Miss Islington (bot)c673a622018-02-23 04:08:45 -0800207 label = translators['sphinx'].gettext(self._label)
208 text = label.format(deprecated=self.arguments[0], removed=self.arguments[1])
Georg Brandl281d6ba2010-11-12 08:57:12 +0000209 if len(self.arguments) == 3:
210 inodes, messages = self.state.inline_text(self.arguments[2],
211 self.lineno+1)
Miss Islington (bot)c673a622018-02-23 04:08:45 -0800212 para = nodes.paragraph(self.arguments[2], '', *inodes, translatable=False)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100213 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000214 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100215 messages = []
216 if self.content:
217 self.state.nested_parse(self.content, self.content_offset, node)
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200218 if len(node):
Georg Brandl7ed509a2014-01-21 19:20:31 +0100219 if isinstance(node[0], nodes.paragraph) and node[0].rawsource:
220 content = nodes.inline(node[0].rawsource, translatable=True)
221 content.source = node[0].source
222 content.line = node[0].line
223 content += node[0].children
Miss Islington (bot)c673a622018-02-23 04:08:45 -0800224 node[0].replace_self(nodes.paragraph('', '', content, translatable=False))
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200225 node[0].insert(0, nodes.inline('', '%s: ' % text,
226 classes=['versionmodified']))
Ned Deilyb682fd32014-09-22 14:44:22 -0700227 else:
Georg Brandl7ed509a2014-01-21 19:20:31 +0100228 para = nodes.paragraph('', '',
Georg Brandl35903c82014-10-30 22:55:13 +0100229 nodes.inline('', '%s.' % text,
Miss Islington (bot)c673a622018-02-23 04:08:45 -0800230 classes=['versionmodified']),
231 translatable=False)
Berker Peksageb1a3cd2014-11-08 22:40:22 +0200232 node.append(para)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000233 env = self.state.document.settings.env
234 env.note_versionchange('deprecated', version[0], node, self.lineno)
Georg Brandl7ed509a2014-01-21 19:20:31 +0100235 return [node] + messages
Georg Brandl281d6ba2010-11-12 08:57:12 +0000236
237
Georg Brandl2cac28b2012-09-30 15:10:06 +0200238# Support for including Misc/NEWS
239
Brett Cannon79ab8be2017-02-10 15:10:13 -0800240issue_re = re.compile('(?:[Ii]ssue #|bpo-)([0-9]+)')
Georg Brandl44d0c212012-10-01 19:08:50 +0200241whatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
Georg Brandl2cac28b2012-09-30 15:10:06 +0200242
Georg Brandl35903c82014-10-30 22:55:13 +0100243
Georg Brandl2cac28b2012-09-30 15:10:06 +0200244class MiscNews(Directive):
245 has_content = False
246 required_arguments = 1
247 optional_arguments = 0
248 final_argument_whitespace = False
249 option_spec = {}
250
251 def run(self):
252 fname = self.arguments[0]
253 source = self.state_machine.input_lines.source(
254 self.lineno - self.state_machine.input_offset - 1)
255 source_dir = path.dirname(path.abspath(source))
Georg Brandl44d0c212012-10-01 19:08:50 +0200256 fpath = path.join(source_dir, fname)
257 self.state.document.settings.record_dependencies.add(fpath)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200258 try:
Victor Stinner272d8882017-06-16 08:59:01 +0200259 with io.open(fpath, encoding='utf-8') as fp:
Georg Brandl2cac28b2012-09-30 15:10:06 +0200260 content = fp.read()
Georg Brandl2cac28b2012-09-30 15:10:06 +0200261 except Exception:
262 text = 'The NEWS file is not available.'
263 node = nodes.strong(text, text)
264 return [node]
Brett Cannon79ab8be2017-02-10 15:10:13 -0800265 content = issue_re.sub(r'`bpo-\1 <https://bugs.python.org/issue\1>`__',
Georg Brandl2cac28b2012-09-30 15:10:06 +0200266 content)
Georg Brandl44d0c212012-10-01 19:08:50 +0200267 content = whatsnew_re.sub(r'\1', content)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200268 # remove first 3 lines as they are the main heading
Georg Brandl6c475812012-10-01 19:27:05 +0200269 lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
Georg Brandl2cac28b2012-09-30 15:10:06 +0200270 self.state_machine.insert_input(lines, fname)
271 return []
272
273
Georg Brandl6b38daa2008-06-01 21:05:17 +0000274# Support for building "topic help" for pydoc
275
276pydoc_topic_labels = [
Jelle Zijlstraac317702017-10-05 20:24:46 -0700277 'assert', 'assignment', 'async', 'atom-identifiers', 'atom-literals',
278 'attribute-access', 'attribute-references', 'augassign', 'await',
279 'binary', 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
Benjamin Peterson0d31d582010-06-06 02:44:41 +0000280 'bltin-null-object', 'bltin-type-objects', 'booleans',
Georg Brandl6b38daa2008-06-01 21:05:17 +0000281 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
282 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
283 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
284 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
285 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
Benjamin Petersonf5a3d692010-08-31 14:31:01 +0000286 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
287 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
288 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
289 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
290 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
291 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
Georg Brandl6b38daa2008-06-01 21:05:17 +0000292]
293
Georg Brandl6b38daa2008-06-01 21:05:17 +0000294
295class PydocTopicsBuilder(Builder):
296 name = 'pydoc-topics'
297
298 def init(self):
299 self.topics = {}
300
301 def get_outdated_docs(self):
302 return 'all pydoc topics'
303
304 def get_target_uri(self, docname, typ=None):
305 return '' # no URIs
306
307 def write(self, *ignored):
308 writer = TextWriter(self)
Benjamin Peterson5879d412009-03-30 14:51:56 +0000309 for label in self.status_iterator(pydoc_topic_labels,
310 'building topics... ',
311 length=len(pydoc_topic_labels)):
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000312 if label not in self.env.domaindata['std']['labels']:
Georg Brandl6b38daa2008-06-01 21:05:17 +0000313 self.warn('label %r not in documentation' % label)
314 continue
Georg Brandl80ff2ad2010-07-31 08:27:46 +0000315 docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
Georg Brandl6b38daa2008-06-01 21:05:17 +0000316 doctree = self.env.get_and_resolve_doctree(docname, self)
317 document = new_document('<section node>')
318 document.append(doctree.ids[labelid])
319 destination = StringOutput(encoding='utf-8')
320 writer.write(document, destination)
Ned Deilyb682fd32014-09-22 14:44:22 -0700321 self.topics[label] = writer.output
Georg Brandl6b38daa2008-06-01 21:05:17 +0000322
323 def finish(self):
Ned Deilyb682fd32014-09-22 14:44:22 -0700324 f = open(path.join(self.outdir, 'topics.py'), 'wb')
Georg Brandl6b38daa2008-06-01 21:05:17 +0000325 try:
Ned Deilyb682fd32014-09-22 14:44:22 -0700326 f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8'))
327 f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8'))
328 f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
Georg Brandl6b38daa2008-06-01 21:05:17 +0000329 finally:
330 f.close()
331
Georg Brandl495f7b52009-10-27 15:28:25 +0000332
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000333# Support for documenting Opcodes
334
Georg Brandl4833e5b2010-07-03 10:41:33 +0000335opcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000336
Georg Brandl35903c82014-10-30 22:55:13 +0100337
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000338def parse_opcode_signature(env, sig, signode):
339 """Transform an opcode signature into RST nodes."""
340 m = opcode_sig_re.match(sig)
341 if m is None:
342 raise ValueError
343 opname, arglist = m.groups()
344 signode += addnodes.desc_name(opname, opname)
Georg Brandl4833e5b2010-07-03 10:41:33 +0000345 if arglist is not None:
346 paramlist = addnodes.desc_parameterlist()
347 signode += paramlist
348 paramlist += addnodes.desc_parameter(arglist, arglist)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000349 return opname.strip()
350
351
Georg Brandl281d6ba2010-11-12 08:57:12 +0000352# Support for documenting pdb commands
353
Georg Brandl02053ee2010-07-18 10:11:03 +0000354pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
355
356# later...
Georg Brandl35903c82014-10-30 22:55:13 +0100357# pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
Georg Brandl02053ee2010-07-18 10:11:03 +0000358# [.,:]+ | # punctuation
359# [\[\]()] | # parens
360# \s+ # whitespace
361# ''', re.X)
362
Georg Brandl35903c82014-10-30 22:55:13 +0100363
Georg Brandl02053ee2010-07-18 10:11:03 +0000364def parse_pdb_command(env, sig, signode):
365 """Transform a pdb command signature into RST nodes."""
366 m = pdbcmd_sig_re.match(sig)
367 if m is None:
368 raise ValueError
369 name, args = m.groups()
370 fullname = name.replace('(', '').replace(')', '')
371 signode += addnodes.desc_name(name, name)
372 if args:
373 signode += addnodes.desc_addname(' '+args, ' '+args)
374 return fullname
375
376
Martin v. Löwis5680d0c2008-04-10 03:06:53 +0000377def setup(app):
378 app.add_role('issue', issue_role)
Georg Brandl68818862010-11-06 07:19:35 +0000379 app.add_role('source', source_role)
Georg Brandl495f7b52009-10-27 15:28:25 +0000380 app.add_directive('impl-detail', ImplementationDetail)
Georg Brandl281d6ba2010-11-12 08:57:12 +0000381 app.add_directive('deprecated-removed', DeprecatedRemoved)
Georg Brandl6b38daa2008-06-01 21:05:17 +0000382 app.add_builder(PydocTopicsBuilder)
Benjamin Peterson28d88b42009-01-09 03:03:23 +0000383 app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
Georg Brandlf0dd6a62008-07-23 15:19:11 +0000384 app.add_description_unit('opcode', 'opcode', '%s (opcode)',
385 parse_opcode_signature)
Georg Brandl02053ee2010-07-18 10:11:03 +0000386 app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
387 parse_pdb_command)
Benjamin Petersonf91df042009-02-13 02:50:59 +0000388 app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
Georg Brandl8a1caa22010-07-29 16:01:11 +0000389 app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
390 app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100391 app.add_directive_to_domain('py', 'coroutinefunction', PyCoroutineFunction)
392 app.add_directive_to_domain('py', 'coroutinemethod', PyCoroutineMethod)
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200393 app.add_directive_to_domain('py', 'abstractmethod', PyAbstractMethod)
Georg Brandl2cac28b2012-09-30 15:10:06 +0200394 app.add_directive('miscnews', MiscNews)
Georg Brandlbae334c2014-09-30 22:17:41 +0200395 return {'version': '1.0', 'parallel_read_safe': True}