1# coding=utf-8
2#
3# Copyright © 2016-2022 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
40from sphinx.util.docutils import switch_source_input
41
42from sphinx.util import logging
43logger = logging.getLogger(__name__)
44
45__version__  = '1.0'
46
47class KernelDocDirective(Directive):
48    """Extract kernel-doc comments from the specified file"""
49    required_argument = 1
50    optional_arguments = 4
51    option_spec = {
52        'doc': directives.unchanged_required,
53        'functions': directives.unchanged,
54        'export': directives.unchanged,
55        'internal': directives.unchanged,
56    }
57    has_content = False
58
59    def run(self):
60        env = self.state.document.settings.env
61        cmd = [env.config.kerneldoc_bin, '-rst', '-enable-lineno']
62
63        filename = env.config.kerneldoc_srctree + '/' + self.arguments[0]
64        export_file_patterns = []
65
66        # Tell sphinx of the dependency
67        env.note_dependency(os.path.abspath(filename))
68
69        tab_width = self.options.get('tab-width', self.state.document.settings.tab_width)
70
71        # FIXME: make this nicer and more robust against errors
72        if 'export' in self.options:
73            cmd += ['-export']
74            export_file_patterns = str(self.options.get('export')).split()
75        elif 'internal' in self.options:
76            cmd += ['-internal']
77            export_file_patterns = str(self.options.get('internal')).split()
78        elif 'doc' in self.options:
79            cmd += ['-function', str(self.options.get('doc'))]
80        elif 'functions' in self.options:
81            functions = self.options.get('functions').split()
82            if functions:
83                for f in functions:
84                    cmd += ['-function', f]
85            else:
86                cmd += ['-no-doc-sections']
87
88        for pattern in export_file_patterns:
89            for f in glob.glob(env.config.kerneldoc_srctree + '/' + pattern):
90                env.note_dependency(os.path.abspath(f))
91                cmd += ['-export-file', f]
92
93        cmd += [filename]
94
95        try:
96            logger.verbose('calling kernel-doc \'%s\'' % (" ".join(cmd)))
97
98            p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
99            out, err = p.communicate()
100
101            out, err = codecs.decode(out, 'utf-8'), codecs.decode(err, 'utf-8')
102
103            if p.returncode != 0:
104                sys.stderr.write(err)
105
106                logger.warning('kernel-doc \'%s\' failed with return code %d' % (" ".join(cmd), p.returncode))
107                return [nodes.error(None, nodes.paragraph(text = "kernel-doc missing"))]
108            elif env.config.kerneldoc_verbosity > 0:
109                sys.stderr.write(err)
110
111            lines = statemachine.string2lines(out, tab_width, convert_whitespace=True)
112            result = ViewList()
113
114            lineoffset = 0;
115            line_regex = re.compile("^#define LINENO ([0-9]+)$")
116            for line in lines:
117                match = line_regex.search(line)
118                if match:
119                    # sphinx counts lines from 0
120                    lineoffset = int(match.group(1)) - 1
121                    # we must eat our comments since the upset the markup
122                else:
123                    result.append(line, filename, lineoffset)
124                    lineoffset += 1
125
126            node = nodes.section()
127            buf = self.state.memo.title_styles, self.state.memo.section_level, self.state.memo.reporter
128            self.state.memo.title_styles, self.state.memo.section_level = [], 0
129            try:
130                with switch_source_input(self.state, result):
131                    self.state.nested_parse(result, 0, node, match_titles=1)
132            finally:
133                self.state.memo.title_styles, self.state.memo.section_level, self.state.memo.reporter = buf
134
135            return node.children
136
137        except Exception as e:  # pylint: disable=W0703
138            logger.warning('kernel-doc \'%s\' processing failed with: %s' %
139                         (" ".join(cmd), str(e)))
140            return [nodes.error(None, nodes.paragraph(text = "kernel-doc missing"))]
141
142def setup(app):
143    app.add_config_value('kerneldoc_bin', None, 'env')
144    app.add_config_value('kerneldoc_srctree', None, 'env')
145    app.add_config_value('kerneldoc_verbosity', 1, 'env')
146
147    app.add_directive('kernel-doc', KernelDocDirective)
148
149    return dict(
150        version = __version__,
151        parallel_read_safe = True,
152        parallel_write_safe = True
153    )
154