source: specdomain/trunk/src/specdomain/sphinxcontrib/specdomain.py @ 1007

Last change on this file since 1007 was 1007, checked in by jemian, 11 years ago

refs #8, much, MUCH better reporting, almost ready for release, need to improve the "howto" documentation in the docs/ subdir

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 15.1 KB
Line 
1# -*- coding: utf-8 -*-
2"""
3    sphinxcontrib.specdomain
4    ~~~~~~~~~~~~~~~~~~~~~~~~~~
5
6    :synopsis: SPEC domain for Sphinx
7   
8    Automatically insert ReST-formatted extended comments
9    from SPEC files for macro definitions and variable declarations into
10    the Sphinx doctree, thus avoiding duplication between docstrings and documentation
11    for those who like elaborate docstrings.
12
13    :copyright: Copyright 2012 by BCDA, Advanced Photon Source, Argonne National Laboratory
14    :license: ANL Open Source License, see LICENSE for details.
15"""
16
17# http://sphinx.pocoo.org/ext/appapi.html
18
19import os
20import re
21
22from docutils import nodes
23
24from sphinx import addnodes
25from sphinx.roles import XRefRole
26from sphinx.locale import l_, _
27from sphinx.directives import ObjectDescription
28from sphinx.domains import Domain, ObjType
29from sphinx.util.nodes import make_refnode
30from sphinx.util.docfields import Field, TypedField
31from sphinx.util.docstrings import prepare_docstring
32
33from sphinx.ext.autodoc import Documenter, bool_option
34from specmacrofileparser import SpecMacrofileParser
35
36
37# TODO: merge these with specmacrofileparser.py
38match_all                   = r'.*'
39non_greedy_filler           = match_all + r'?'
40double_quote_string_match   = r'("' + non_greedy_filler + r'")'
41word_match                  = r'((?:[a-z_]\w*))'
42cdef_match                  = r'(cdef)'
43
44
45spec_macro_sig_re = re.compile(
46                               r'''^ ([a-zA-Z_]\w*)         # macro name
47                               ''', re.VERBOSE)
48
49spec_func_sig_re = re.compile(word_match + r'\('
50                      + r'(' + match_all + r')' 
51                      + r'\)', 
52                      re.IGNORECASE|re.DOTALL)
53
54spec_cdef_name_sig_re = re.compile(double_quote_string_match, 
55                                   re.IGNORECASE|re.DOTALL)
56
57
58class SpecMacroDocumenter(Documenter):
59    """
60    Document a SPEC macro source code file (autodoc.Documenter subclass)
61   
62    This code responds to the ReST file directive::
63   
64        .. autospecmacro:: partial/path/name/somefile.mac
65            :displayorder: fileorder
66   
67    The ``:displayorder`` parameter indicates how the
68    contents will be sorted for appearance in the ReST document.
69   
70        **fileorder** or **file**
71            Items will be documented in the order in
72            which they appear in the ``.mac`` file.
73            (Default)
74       
75        **alphabetical** or **alpha**
76            Items will be documented in alphabetical order.
77            (Not implemented at present.)
78   
79    .. tip::
80        A (near) future enhancement will provide for
81        documenting all macro files in a directory, with optional
82        recursion into subdirectories.  By default, the code will
83        only document files that match the glob pattern ``*.mac``.
84        (This could be defined as a list in the ``conf.py`` file.)
85        Such as::
86       
87           .. spec:directory:: partial/path/name
88              :recursion:
89              :displayorder: alphabetical
90    """
91
92    objtype = 'specmacro'
93    member_order = 50
94    priority = 0
95    #: true if the generated content may contain titles
96    titles_allowed = True
97
98    option_spec = {
99        'displayorder': bool_option,
100    }
101
102    @classmethod
103    def can_document_member(cls, member, membername, isattr, parent):
104        # don't document submodules automatically
105        #return isinstance(member, (FunctionType, BuiltinFunctionType))
106        r = membername in ('SpecMacroDocumenter', )
107        return r
108   
109    def generate(self, *args, **kw):
110        """
111        Generate reST for the object given by *self.name*, and possibly for
112        its members.
113        """
114        # now, parse the SPEC macro file
115        macrofile = self.parse_name()
116        spec = SpecMacrofileParser(macrofile)
117        extended_comment = spec.ReST()
118        rest = prepare_docstring(extended_comment)
119
120        #self.add_line(u'', '<autodoc>')
121        #sig = self.format_signature()
122        #self.add_directive_header(sig)
123       
124        self.add_line(u'', '<autodoc>')
125        self.add_line(u'.. index:: SPEC macro file; %s' % macrofile, '<autodoc>')
126        self.add_line(u'.. index:: !%s' % os.path.split(macrofile)[1], '<autodoc>')
127        self.add_line(u'', '<autodoc>')
128        self.add_line(u'', '<autodoc>')
129        title = 'SPEC Macro File: %s' %  macrofile
130        self.add_line('@'*len(title), '<autodoc>')
131        self.add_line(title, '<autodoc>')
132        self.add_line('@'*len(title), '<autodoc>')
133        self.add_line(u'', '<autodoc>')
134        # TODO: provide links from each to highlighted source code blocks (like Python documenters).
135        # This works for now.
136        line = 'source code:  :download:`%s <%s>`' % (macrofile, macrofile)
137        self.add_line(line, macrofile)
138
139        self.add_line(u'', '<autodoc>')
140        for linenumber, line in enumerate(rest):
141            self.add_line(line, macrofile, linenumber)
142
143        #self.add_content(rest)
144        #self.document_members(all_members)
145
146    def resolve_name(self, modname, parents, path, base):
147        if modname is not None:
148            self.directive.warn('"::" in autospecmacro name doesn\'t make sense')
149        return (path or '') + base, []
150
151    def parse_name(self):
152        """Determine what file to parse.
153       
154        :returns: True if if parsing was successful
155        """
156        ret = self.name
157        self.fullname = os.path.abspath(ret)
158        self.objpath, self.modname = os.path.split(self.fullname)
159        self.args = None
160        self.retann = None
161        if self.args or self.retann:
162            self.directive.warn('signature arguments or return annotation '
163                                'given for autospecmacro %s' % self.fullname)
164        return ret
165
166
167class SpecDirDocumenter(Documenter):
168    """
169    Document a directory containing SPEC macro source code files.
170   
171    This code responds to the ReST file directive::
172   
173        .. autospecdir:: partial/path/name
174    """
175    objtype = 'specdir'
176    member_order = 50
177    priority = 0
178    #: true if the generated content may contain titles
179    titles_allowed = True
180    option_spec = {
181        'include_subdirs': bool_option,
182    }
183
184    @classmethod
185    def can_document_member(cls, member, membername, isattr, parent):
186        return membername in ('SpecDirDocumenter', )
187   
188    def generate(self, *args, **kw):
189        """
190        Look at the named directory and generate reST for the
191        object given by *self.name*, and possibly for its members.
192        """
193        # now, parse the .mac files in the SPEC directory
194        specdir = self.name
195#        self.add_line(u'', '<autodoc>')
196#        self.add_line(u'directory:\n   ``%s``' % specdir, '<autodoc>')
197        if os.path.exists(specdir):
198            for f in sorted(os.listdir(specdir)):
199                filename = os.path.join(specdir, f)
200                if os.path.isfile(filename) and filename.endswith('.mac'):
201                    # TODO: support a user choice for pattern match to the file name (glob v. re)
202                    # TODO: support the option to include subdirectories (include_subdirs)
203                    # TODO: do not add the same SPEC macro file more than once
204                    self.add_line(u'', '<autodoc>')
205                    self.add_line(u'.. autospecmacro:: %s' % filename, '<autodoc>')
206                    # TODO: any options?
207                    self.add_line(u'', '<autodoc>')
208                    # TODO: suppress delimiter after last file
209                    self.add_line(u'-'*15, '<autodoc>')         # delimiter between files
210        else:
211            self.add_line(u'', '<autodoc>')
212            self.add_line(u'Could not find directory: ``%s``' % specdir, '<autodoc>')
213
214
215
216class SpecMacroObject(ObjectDescription):
217    """
218    Description of a SPEC macro definition
219    """
220
221    doc_field_types = [
222        TypedField('parameter', label=l_('Parameters'),
223                   names=('param', 'parameter', 'arg', 'argument',
224                          'keyword', 'kwarg', 'kwparam'),
225                   typerolename='def', typenames=('paramtype', 'type'),
226                   can_collapse=True),
227        Field('returnvalue', label=l_('Returns'), has_arg=False,
228              names=('returns', 'return')),
229        Field('returntype', label=l_('Return type'), has_arg=False,
230              names=('rtype',)),
231    ]
232
233    def add_target_and_index(self, name, sig, signode):
234        targetname = '%s-%s' % (self.objtype, name)
235        signode['ids'].append(targetname)
236        self.state.document.note_explicit_target(signode)
237        indextext = self._get_index_text(name)
238        if indextext:
239            self.indexnode['entries'].append(('single', indextext, targetname, ''))
240            self.indexnode['entries'].append(('single', sig, targetname, ''))
241
242    def _get_index_text(self, name):
243        macro_types = {
244            'def':  'SPEC macro definition; %s',
245            'rdef': 'SPEC run-time macro definition; %s',
246            'cdef': 'SPEC chained macro definition; %s',
247        }
248        if self.objtype in macro_types:
249            return _(macro_types[self.objtype]) % name
250        else:
251            return ''
252
253    def handle_signature(self, sig, signode):
254        '''return the name of this object from its signature'''
255        # Must be able to match these (without preceding def or rdef)
256        #     def macro_name
257        #     def macro_name()
258        #     def macro_name(arg1, arg2)
259        #     rdef macro_name
260        #     cdef("macro_name", "content", "groupname", flags)
261        m = spec_func_sig_re.match(sig) or spec_macro_sig_re.match(sig)
262        if m is None:
263            raise ValueError
264        arglist = m.groups()
265        name = arglist[0]
266        args = []
267        if len(arglist) > 1:
268            args = arglist[1:]
269            if name == 'cdef':
270                # TODO: need to match complete arg list
271                # several different signatures are possible (see cdef-examples.mac)
272                # for now, just get the macro name and ignore the arg list
273                m = spec_cdef_name_sig_re.match(args[0])
274                arglist = m.groups()
275                name = arglist[0].strip('"')
276                args = ['<<< cdef argument list not handled yet >>>']       # FIXME:
277        signode += addnodes.desc_name(name, name)
278        if len(args) > 0:
279            signode += addnodes.desc_addname(args, args)
280        return name
281
282
283class SpecVariableObject(ObjectDescription):
284    """
285    Description of a SPEC variable
286    """
287   
288    # TODO: The directive that declares the variable should be the primary (bold) index.
289    # TODO: array variables are not handled at all
290    # TODO: variables cited by *role* should link back to their *directive* declarations
291
292    def handle_signature(self, sig, signode):
293        '''return the name of this object from its signature'''
294        # TODO: Should it match a regular expression?
295        # TODO: What if global or local? 
296        signode += addnodes.desc_name(sig, sig)
297        return sig
298
299    def add_target_and_index(self, name, sig, signode):
300        targetname = '%s-%s' % (self.objtype, name)
301        signode['ids'].append(targetname)
302        # TODO: role does not point back to it yet
303        # http://sphinx.pocoo.org/markup/misc.html#directive-index
304        text = u'! ' + sig      # TODO: How to use emphasized index entry in this context?
305        text = sig              # FIXME: temporary override
306        self.indexnode['entries'].append(('single', text, targetname, ''))
307        text = u'SPEC %s variable; %s' % (self.objtype, sig)
308        self.indexnode['entries'].append(('single', text, targetname, ''))
309
310class SpecXRefRole(XRefRole):
311    """ """
312   
313    def process_link(self, env, refnode, has_explicit_title, title, target):
314        key = ":".join((refnode['refdomain'], refnode['reftype']))
315        refnode[key] = env.temp_data.get(key)        # key was 'spec:def'
316        if not has_explicit_title:
317            title = title.lstrip(':')   # only has a meaning for the target
318            target = target.lstrip('~') # only has a meaning for the title
319            # if the first character is a tilde, don't display the module/class
320            # parts of the contents
321            if title[0:1] == '~':
322                title = title[1:]
323                colon = title.rfind(':')
324                if colon != -1:
325                    title = title[colon+1:]
326        return title, target
327
328    def result_nodes(self, document, env, node, is_ref):
329        # this code adds index entries for each role instance
330        if not is_ref:
331            return [node], []
332        varname = node['reftarget']
333        tgtid = 'index-%s' % env.new_serialno('index')
334        indexnode = addnodes.index()
335        indexnode['entries'] = [
336            ('single', varname, tgtid, ''),
337            #('single', _('environment variable; %s') % varname, tgtid, ''),
338        ]
339        targetnode = nodes.target('', '', ids=[tgtid])
340        document.note_explicit_target(targetnode)
341        return [indexnode, targetnode, node], []
342
343
344class SpecDomain(Domain):
345    """SPEC language domain."""
346   
347    name = 'spec'
348    label = 'SPEC, http://www.certif.com'
349    object_types = {    # type of object that a domain can document
350        'def':        ObjType(l_('def'),        'def'),
351        'rdef':       ObjType(l_('rdef'),       'rdef'),
352        'cdef':       ObjType(l_('cdef'),       'cdef'),
353        'global':     ObjType(l_('global'),     'global'),
354        'local':      ObjType(l_('local'),      'local'),
355        'constant':   ObjType(l_('constant'),   'constant'),
356        #'specmacro':  ObjType(l_('specmacro'),  'specmacro'),
357    }
358    directives = {
359        'def':          SpecMacroObject,
360        'rdef':         SpecMacroObject,
361        'cdef':         SpecMacroObject,
362        'global':       SpecVariableObject,
363        'local':        SpecVariableObject,
364        'constant':     SpecVariableObject,
365    }
366    roles = {
367        'def' :     SpecXRefRole(),
368        'rdef':     SpecXRefRole(),
369        'cdef':     SpecXRefRole(),
370        'global':   SpecXRefRole(),
371        'local':    SpecXRefRole(),
372        'constant': SpecXRefRole(),
373    }
374    initial_data = {
375        'objects': {}, # fullname -> docname, objtype
376    }
377
378    def clear_doc(self, docname):
379        for (typ, name), doc in self.data['objects'].items():
380            if doc == docname:
381                del self.data['objects'][typ, name]
382
383    def resolve_xref(self, env, fromdocname, builder, typ, target, node,
384                     contnode):
385        objects = self.data['objects']
386        objtypes = self.objtypes_for_role(typ)
387        for objtype in objtypes:
388            if (objtype, target) in objects:
389                return make_refnode(builder, fromdocname,
390                                    objects[objtype, target],
391                                    objtype + '-' + target,
392                                    contnode, target + ' ' + objtype)
393
394    def get_objects(self):
395        for (typ, name), docname in self.data['objects'].iteritems():
396            yield name, name, typ, docname, typ + '-' + name, 1
397
398
399# http://sphinx.pocoo.org/ext/tutorial.html#the-setup-function
400
401def setup(app):
402    app.add_domain(SpecDomain)
403    app.add_autodocumenter(SpecMacroDocumenter)
404    app.add_autodocumenter(SpecDirDocumenter)
405    app.add_config_value('autospecmacrodir_process_subdirs', True, True)
Note: See TracBrowser for help on using the repository browser.