1# coding=utf-8
2#
3# Copyright © 2016 Intel Corporation
4#
5# Permission is hereby granted, free of charge, to any person obtaining a
6# copy of this software and associated documentation files (the "Software"),
7# to deal in the Software without restriction, including without limitation
8# the rights to use, copy, modify, merge, publish, distribute, sublicense,
9# and/or sell copies of the Software, and to permit persons to whom the
10# Software is furnished to do so, subject to the following conditions:
11#
12# The above copyright notice and this permission notice (including the next
13# paragraph) shall be included in all copies or substantial portions of the
14# Software.
15#
16# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22# IN THE SOFTWARE.
23#
24# Authors:
25#    Jani Nikula <jani.nikula@intel.com>
26#
27# Please make sure this works on both python2 and python3.
28#
29
30import codecs
31import os
32import subprocess
33import sys
34import re
35import glob
36
37from docutils import nodes, statemachine
38from docutils.statemachine import ViewList
39from docutils.parsers.rst import directives, Directive
40import sphinx
41from sphinx.util.docutils import switch_source_input
42import kernellog
43
44__version__  = '1.0'
45
46class KernelDocDirective(Directive):
47    """Extract kernel-doc comments from the specified file"""
48    required_argument = 1
49    optional_arguments = 4
50    option_spec = {
51        'doc': directives.unchanged_required,
52        'export': directives.unchanged,
53        'internal': directives.unchanged,
54        'identifiers': directives.unchanged,
55        'no-identifiers': directives.unchanged,
56        'functions': directives.unchanged,
57    }
58    has_content = False
59
60    def run(self):
61        env = self.state.document.settings.env
62        cmd = [env.config.kerneldoc_bin, '-rst', '-enable-lineno']
63
64	# Pass the version string to kernel-doc, as it needs to use a different
65	# dialect, depending what the C domain supports for each specific
66	# Sphinx versions
67        cmd += ['-sphinx-version', sphinx.__version__]
68
69        filename = env.config.kerneldoc_srctree + '/' + self.arguments[0]
70        export_file_patterns = []
71
72        # Tell sphinx of the dependency
73        env.note_dependency(os.path.abspath(filename))
74
75        tab_width = self.options.get('tab-width', self.state.document.settings.tab_width)
76
77        # 'function' is an alias of 'identifiers'
78        if 'functions' in self.options:
79            self.options['identifiers'] = self.options.get('functions')
80
81        # FIXME: make this nicer and more robust against errors
82        if 'export' in self.options:
83            cmd += ['-export']
84            export_file_patterns = str(self.options.get('export')).split()
85        elif 'internal' in self.options:
86            cmd += ['-internal']
87            export_file_patterns = str(self.options.get('internal')).split()
88        elif 'doc' in self.options:
89            cmd += ['-function', str(self.options.get('doc'))]
90        elif 'identifiers' in self.options:
91            identifiers = self.options.get('identifiers').split()
92            if identifiers:
93                for i in identifiers:
94                    cmd += ['-function', i]
95            else:
96                cmd += ['-no-doc-sections']
97
98        if 'no-identifiers' in self.options:
99            no_identifiers = self.options.get('no-identifiers').split()
100            if no_identifiers:
101                for i in no_identifiers:
102                    cmd += ['-nosymbol', i]
103
104        for pattern in export_file_patterns:
105            for f in glob.glob(env.config.kerneldoc_srctree + '/' + pattern):
106                env.note_dependency(os.path.abspath(f))
107                cmd += ['-export-file', f]
108
109        cmd += [filename]
110
111        try:
112            kernellog.verbose(env.app,
113                              'calling kernel-doc \'%s\'' % (" ".join(cmd)))
114
115            p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
116            out, err = p.communicate()
117
118            out, err = codecs.decode(out, 'utf-8'), codecs.decode(err, 'utf-8')
119
120            if p.returncode != 0:
121                sys.stderr.write(err)
122
123                kernellog.warn(env.app,
124                               'kernel-doc \'%s\' failed with return code %d' % (" ".join(cmd), p.returncode))
125                return [nodes.error(None, nodes.paragraph(text = "kernel-doc missing"))]
126            elif env.config.kerneldoc_verbosity > 0:
127                sys.stderr.write(err)
128
129            lines = statemachine.string2lines(out, tab_width, convert_whitespace=True)
130            result = ViewList()
131
132            lineoffset = 0;
133            line_regex = re.compile(r"^\.\. LINENO ([0-9]+)$")
134            for line in lines:
135                match = line_regex.search(line)
136                if match:
137                    # sphinx counts lines from 0
138                    lineoffset = int(match.group(1)) - 1
139                    # we must eat our comments since the upset the markup
140                else:
141                    doc = env.srcdir + "/" + env.docname + ":" + str(self.lineno)
142                    result.append(line, doc + ": " + filename, lineoffset)
143                    lineoffset += 1
144
145            node = nodes.section()
146            self.do_parse(result, node)
147
148            return node.children
149
150        except Exception as e:  # pylint: disable=W0703
151            kernellog.warn(env.app, 'kernel-doc \'%s\' processing failed with: %s' %
152                           (" ".join(cmd), str(e)))
153            return [nodes.error(None, nodes.paragraph(text = "kernel-doc missing"))]
154
155    def do_parse(self, result, node):
156        with switch_source_input(self.state, result):
157            self.state.nested_parse(result, 0, node, match_titles=1)
158
159def setup(app):
160    app.add_config_value('kerneldoc_bin', None, 'env')
161    app.add_config_value('kerneldoc_srctree', None, 'env')
162    app.add_config_value('kerneldoc_verbosity', 1, 'env')
163
164    app.add_directive('kernel-doc', KernelDocDirective)
165
166    return dict(
167        version = __version__,
168        parallel_read_safe = True,
169        parallel_write_safe = True
170    )
171