ยปCore Development>Code coverage>Doc/tools/extensions/pyspecific.py

Python code coverage for Doc/tools/extensions/pyspecific.py

#countcontent
1n/a# -*- coding: utf-8 -*-
2n/a"""
3n/a pyspecific.py
4n/a ~~~~~~~~~~~~~
5n/a
6n/a Sphinx extension with Python doc-specific markup.
7n/a
8n/a :copyright: 2008-2014 by Georg Brandl.
9n/a :license: Python license.
10n/a"""
11n/a
12n/aimport re
13n/aimport codecs
14n/afrom os import path
15n/afrom time import asctime
16n/afrom pprint import pformat
17n/afrom docutils.io import StringOutput
18n/afrom docutils.utils import new_document
19n/a
20n/afrom docutils import nodes, utils
21n/a
22n/afrom sphinx import addnodes
23n/afrom sphinx.builders import Builder
24n/afrom sphinx.util.nodes import split_explicit_title
25n/afrom sphinx.util.compat import Directive
26n/afrom sphinx.writers.html import HTMLTranslator
27n/afrom sphinx.writers.text import TextWriter
28n/afrom sphinx.writers.latex import LaTeXTranslator
29n/afrom sphinx.domains.python import PyModulelevel, PyClassmember
30n/a
31n/a# Support for checking for suspicious markup
32n/a
33n/aimport suspicious
34n/a
35n/a
36n/aISSUE_URI = 'https://bugs.python.org/issue%s'
37n/aSOURCE_URI = 'https://hg.python.org/cpython/file/3.6/%s'
38n/a
39n/a# monkey-patch reST parser to disable alphabetic and roman enumerated lists
40n/afrom docutils.parsers.rst.states import Body
41n/aBody.enum.converters['loweralpha'] = \
42n/a Body.enum.converters['upperalpha'] = \
43n/a Body.enum.converters['lowerroman'] = \
44n/a Body.enum.converters['upperroman'] = lambda x: None
45n/a
46n/a# monkey-patch HTML and LaTeX translators to keep doctest blocks in the
47n/a# doctest docs themselves
48n/aorig_visit_literal_block = HTMLTranslator.visit_literal_block
49n/aorig_depart_literal_block = LaTeXTranslator.depart_literal_block
50n/a
51n/a
52n/adef new_visit_literal_block(self, node):
53n/a meta = self.builder.env.metadata[self.builder.current_docname]
54n/a old_trim_doctest_flags = self.highlighter.trim_doctest_flags
55n/a if 'keepdoctest' in meta:
56n/a self.highlighter.trim_doctest_flags = False
57n/a try:
58n/a orig_visit_literal_block(self, node)
59n/a finally:
60n/a self.highlighter.trim_doctest_flags = old_trim_doctest_flags
61n/a
62n/a
63n/adef new_depart_literal_block(self, node):
64n/a meta = self.builder.env.metadata[self.curfilestack[-1]]
65n/a old_trim_doctest_flags = self.highlighter.trim_doctest_flags
66n/a if 'keepdoctest' in meta:
67n/a self.highlighter.trim_doctest_flags = False
68n/a try:
69n/a orig_depart_literal_block(self, node)
70n/a finally:
71n/a self.highlighter.trim_doctest_flags = old_trim_doctest_flags
72n/a
73n/a
74n/aHTMLTranslator.visit_literal_block = new_visit_literal_block
75n/aLaTeXTranslator.depart_literal_block = new_depart_literal_block
76n/a
77n/a
78n/a# Support for marking up and linking to bugs.python.org issues
79n/a
80n/adef issue_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
81n/a issue = utils.unescape(text)
82n/a text = 'issue ' + issue
83n/a refnode = nodes.reference(text, text, refuri=ISSUE_URI % issue)
84n/a return [refnode], []
85n/a
86n/a
87n/a# Support for linking to Python source files easily
88n/a
89n/adef source_role(typ, rawtext, text, lineno, inliner, options={}, content=[]):
90n/a has_t, title, target = split_explicit_title(text)
91n/a title = utils.unescape(title)
92n/a target = utils.unescape(target)
93n/a refnode = nodes.reference(title, title, refuri=SOURCE_URI % target)
94n/a return [refnode], []
95n/a
96n/a
97n/a# Support for marking up implementation details
98n/a
99n/aclass ImplementationDetail(Directive):
100n/a
101n/a has_content = True
102n/a required_arguments = 0
103n/a optional_arguments = 1
104n/a final_argument_whitespace = True
105n/a
106n/a def run(self):
107n/a pnode = nodes.compound(classes=['impl-detail'])
108n/a content = self.content
109n/a add_text = nodes.strong('CPython implementation detail:',
110n/a 'CPython implementation detail:')
111n/a if self.arguments:
112n/a n, m = self.state.inline_text(self.arguments[0], self.lineno)
113n/a pnode.append(nodes.paragraph('', '', *(n + m)))
114n/a self.state.nested_parse(content, self.content_offset, pnode)
115n/a if pnode.children and isinstance(pnode[0], nodes.paragraph):
116n/a pnode[0].insert(0, add_text)
117n/a pnode[0].insert(1, nodes.Text(' '))
118n/a else:
119n/a pnode.insert(0, nodes.paragraph('', '', add_text))
120n/a return [pnode]
121n/a
122n/a
123n/a# Support for documenting decorators
124n/a
125n/aclass PyDecoratorMixin(object):
126n/a def handle_signature(self, sig, signode):
127n/a ret = super(PyDecoratorMixin, self).handle_signature(sig, signode)
128n/a signode.insert(0, addnodes.desc_addname('@', '@'))
129n/a return ret
130n/a
131n/a def needs_arglist(self):
132n/a return False
133n/a
134n/a
135n/aclass PyDecoratorFunction(PyDecoratorMixin, PyModulelevel):
136n/a def run(self):
137n/a # a decorator function is a function after all
138n/a self.name = 'py:function'
139n/a return PyModulelevel.run(self)
140n/a
141n/a
142n/aclass PyDecoratorMethod(PyDecoratorMixin, PyClassmember):
143n/a def run(self):
144n/a self.name = 'py:method'
145n/a return PyClassmember.run(self)
146n/a
147n/a
148n/aclass PyCoroutineMixin(object):
149n/a def handle_signature(self, sig, signode):
150n/a ret = super(PyCoroutineMixin, self).handle_signature(sig, signode)
151n/a signode.insert(0, addnodes.desc_annotation('coroutine ', 'coroutine '))
152n/a return ret
153n/a
154n/a
155n/aclass PyCoroutineFunction(PyCoroutineMixin, PyModulelevel):
156n/a def run(self):
157n/a self.name = 'py:function'
158n/a return PyModulelevel.run(self)
159n/a
160n/a
161n/aclass PyCoroutineMethod(PyCoroutineMixin, PyClassmember):
162n/a def run(self):
163n/a self.name = 'py:method'
164n/a return PyClassmember.run(self)
165n/a
166n/a
167n/aclass PyAbstractMethod(PyClassmember):
168n/a
169n/a def handle_signature(self, sig, signode):
170n/a ret = super(PyAbstractMethod, self).handle_signature(sig, signode)
171n/a signode.insert(0, addnodes.desc_annotation('abstractmethod ',
172n/a 'abstractmethod '))
173n/a return ret
174n/a
175n/a def run(self):
176n/a self.name = 'py:method'
177n/a return PyClassmember.run(self)
178n/a
179n/a
180n/a# Support for documenting version of removal in deprecations
181n/a
182n/aclass DeprecatedRemoved(Directive):
183n/a has_content = True
184n/a required_arguments = 2
185n/a optional_arguments = 1
186n/a final_argument_whitespace = True
187n/a option_spec = {}
188n/a
189n/a _label = 'Deprecated since version %s, will be removed in version %s'
190n/a
191n/a def run(self):
192n/a node = addnodes.versionmodified()
193n/a node.document = self.state.document
194n/a node['type'] = 'deprecated-removed'
195n/a version = (self.arguments[0], self.arguments[1])
196n/a node['version'] = version
197n/a text = self._label % version
198n/a if len(self.arguments) == 3:
199n/a inodes, messages = self.state.inline_text(self.arguments[2],
200n/a self.lineno+1)
201n/a para = nodes.paragraph(self.arguments[2], '', *inodes)
202n/a node.append(para)
203n/a else:
204n/a messages = []
205n/a if self.content:
206n/a self.state.nested_parse(self.content, self.content_offset, node)
207n/a if len(node):
208n/a if isinstance(node[0], nodes.paragraph) and node[0].rawsource:
209n/a content = nodes.inline(node[0].rawsource, translatable=True)
210n/a content.source = node[0].source
211n/a content.line = node[0].line
212n/a content += node[0].children
213n/a node[0].replace_self(nodes.paragraph('', '', content))
214n/a node[0].insert(0, nodes.inline('', '%s: ' % text,
215n/a classes=['versionmodified']))
216n/a else:
217n/a para = nodes.paragraph('', '',
218n/a nodes.inline('', '%s.' % text,
219n/a classes=['versionmodified']))
220n/a node.append(para)
221n/a env = self.state.document.settings.env
222n/a env.note_versionchange('deprecated', version[0], node, self.lineno)
223n/a return [node] + messages
224n/a
225n/a
226n/a# Support for including Misc/NEWS
227n/a
228n/aissue_re = re.compile('([Ii])ssue #([0-9]+)')
229n/awhatsnew_re = re.compile(r"(?im)^what's new in (.*?)\??$")
230n/a
231n/a
232n/aclass MiscNews(Directive):
233n/a has_content = False
234n/a required_arguments = 1
235n/a optional_arguments = 0
236n/a final_argument_whitespace = False
237n/a option_spec = {}
238n/a
239n/a def run(self):
240n/a fname = self.arguments[0]
241n/a source = self.state_machine.input_lines.source(
242n/a self.lineno - self.state_machine.input_offset - 1)
243n/a source_dir = path.dirname(path.abspath(source))
244n/a fpath = path.join(source_dir, fname)
245n/a self.state.document.settings.record_dependencies.add(fpath)
246n/a try:
247n/a fp = codecs.open(fpath, encoding='utf-8')
248n/a try:
249n/a content = fp.read()
250n/a finally:
251n/a fp.close()
252n/a except Exception:
253n/a text = 'The NEWS file is not available.'
254n/a node = nodes.strong(text, text)
255n/a return [node]
256n/a content = issue_re.sub(r'`\1ssue #\2 <https://bugs.python.org/\2>`__',
257n/a content)
258n/a content = whatsnew_re.sub(r'\1', content)
259n/a # remove first 3 lines as they are the main heading
260n/a lines = ['.. default-role:: obj', ''] + content.splitlines()[3:]
261n/a self.state_machine.insert_input(lines, fname)
262n/a return []
263n/a
264n/a
265n/a# Support for building "topic help" for pydoc
266n/a
267n/apydoc_topic_labels = [
268n/a 'assert', 'assignment', 'atom-identifiers', 'atom-literals',
269n/a 'attribute-access', 'attribute-references', 'augassign', 'binary',
270n/a 'bitwise', 'bltin-code-objects', 'bltin-ellipsis-object',
271n/a 'bltin-null-object', 'bltin-type-objects', 'booleans',
272n/a 'break', 'callable-types', 'calls', 'class', 'comparisons', 'compound',
273n/a 'context-managers', 'continue', 'conversions', 'customization', 'debugger',
274n/a 'del', 'dict', 'dynamic-features', 'else', 'exceptions', 'execmodel',
275n/a 'exprlists', 'floating', 'for', 'formatstrings', 'function', 'global',
276n/a 'id-classes', 'identifiers', 'if', 'imaginary', 'import', 'in', 'integers',
277n/a 'lambda', 'lists', 'naming', 'nonlocal', 'numbers', 'numeric-types',
278n/a 'objects', 'operator-summary', 'pass', 'power', 'raise', 'return',
279n/a 'sequence-types', 'shifting', 'slicings', 'specialattrs', 'specialnames',
280n/a 'string-methods', 'strings', 'subscriptions', 'truth', 'try', 'types',
281n/a 'typesfunctions', 'typesmapping', 'typesmethods', 'typesmodules',
282n/a 'typesseq', 'typesseq-mutable', 'unary', 'while', 'with', 'yield'
283n/a]
284n/a
285n/a
286n/aclass PydocTopicsBuilder(Builder):
287n/a name = 'pydoc-topics'
288n/a
289n/a def init(self):
290n/a self.topics = {}
291n/a
292n/a def get_outdated_docs(self):
293n/a return 'all pydoc topics'
294n/a
295n/a def get_target_uri(self, docname, typ=None):
296n/a return '' # no URIs
297n/a
298n/a def write(self, *ignored):
299n/a writer = TextWriter(self)
300n/a for label in self.status_iterator(pydoc_topic_labels,
301n/a 'building topics... ',
302n/a length=len(pydoc_topic_labels)):
303n/a if label not in self.env.domaindata['std']['labels']:
304n/a self.warn('label %r not in documentation' % label)
305n/a continue
306n/a docname, labelid, sectname = self.env.domaindata['std']['labels'][label]
307n/a doctree = self.env.get_and_resolve_doctree(docname, self)
308n/a document = new_document('<section node>')
309n/a document.append(doctree.ids[labelid])
310n/a destination = StringOutput(encoding='utf-8')
311n/a writer.write(document, destination)
312n/a self.topics[label] = writer.output
313n/a
314n/a def finish(self):
315n/a f = open(path.join(self.outdir, 'topics.py'), 'wb')
316n/a try:
317n/a f.write('# -*- coding: utf-8 -*-\n'.encode('utf-8'))
318n/a f.write(('# Autogenerated by Sphinx on %s\n' % asctime()).encode('utf-8'))
319n/a f.write(('topics = ' + pformat(self.topics) + '\n').encode('utf-8'))
320n/a finally:
321n/a f.close()
322n/a
323n/a
324n/a# Support for documenting Opcodes
325n/a
326n/aopcode_sig_re = re.compile(r'(\w+(?:\+\d)?)(?:\s*\((.*)\))?')
327n/a
328n/a
329n/adef parse_opcode_signature(env, sig, signode):
330n/a """Transform an opcode signature into RST nodes."""
331n/a m = opcode_sig_re.match(sig)
332n/a if m is None:
333n/a raise ValueError
334n/a opname, arglist = m.groups()
335n/a signode += addnodes.desc_name(opname, opname)
336n/a if arglist is not None:
337n/a paramlist = addnodes.desc_parameterlist()
338n/a signode += paramlist
339n/a paramlist += addnodes.desc_parameter(arglist, arglist)
340n/a return opname.strip()
341n/a
342n/a
343n/a# Support for documenting pdb commands
344n/a
345n/apdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
346n/a
347n/a# later...
348n/a# pdbargs_tokens_re = re.compile(r'''[a-zA-Z]+ | # identifiers
349n/a# [.,:]+ | # punctuation
350n/a# [\[\]()] | # parens
351n/a# \s+ # whitespace
352n/a# ''', re.X)
353n/a
354n/a
355n/adef parse_pdb_command(env, sig, signode):
356n/a """Transform a pdb command signature into RST nodes."""
357n/a m = pdbcmd_sig_re.match(sig)
358n/a if m is None:
359n/a raise ValueError
360n/a name, args = m.groups()
361n/a fullname = name.replace('(', '').replace(')', '')
362n/a signode += addnodes.desc_name(name, name)
363n/a if args:
364n/a signode += addnodes.desc_addname(' '+args, ' '+args)
365n/a return fullname
366n/a
367n/a
368n/adef setup(app):
369n/a app.add_role('issue', issue_role)
370n/a app.add_role('source', source_role)
371n/a app.add_directive('impl-detail', ImplementationDetail)
372n/a app.add_directive('deprecated-removed', DeprecatedRemoved)
373n/a app.add_builder(PydocTopicsBuilder)
374n/a app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
375n/a app.add_description_unit('opcode', 'opcode', '%s (opcode)',
376n/a parse_opcode_signature)
377n/a app.add_description_unit('pdbcommand', 'pdbcmd', '%s (pdb command)',
378n/a parse_pdb_command)
379n/a app.add_description_unit('2to3fixer', '2to3fixer', '%s (2to3 fixer)')
380n/a app.add_directive_to_domain('py', 'decorator', PyDecoratorFunction)
381n/a app.add_directive_to_domain('py', 'decoratormethod', PyDecoratorMethod)
382n/a app.add_directive_to_domain('py', 'coroutinefunction', PyCoroutineFunction)
383n/a app.add_directive_to_domain('py', 'coroutinemethod', PyCoroutineMethod)
384n/a app.add_directive_to_domain('py', 'abstractmethod', PyAbstractMethod)
385n/a app.add_directive('miscnews', MiscNews)
386n/a return {'version': '1.0', 'parallel_read_safe': True}