1# coding=utf-8 2# SPDX-License-Identifier: MIT 3# 4# Copyright © 2016 Intel Corporation 5# 6# Permission is hereby granted, free of charge, to any person obtaining a 7# copy of this software and associated documentation files (the "Software"), 8# to deal in the Software without restriction, including without limitation 9# the rights to use, copy, modify, merge, publish, distribute, sublicense, 10# and/or sell copies of the Software, and to permit persons to whom the 11# Software is furnished to do so, subject to the following conditions: 12# 13# The above copyright notice and this permission notice (including the next 14# paragraph) shall be included in all copies or substantial portions of the 15# Software. 16# 17# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 20# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 22# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 23# IN THE SOFTWARE. 24# 25# Authors: 26# Jani Nikula <jani.nikula@intel.com> 27# 28 29import codecs 30import os 31import subprocess 32import sys 33import re 34import glob 35 36from docutils import nodes, statemachine 37from docutils.statemachine import ViewList 38from docutils.parsers.rst import directives, Directive 39import sphinx 40from sphinx.util.docutils import switch_source_input 41from sphinx.util.nodes import nested_parse_with_titles 42from sphinx.util import logging 43from pprint import pformat 44 45srctree = os.path.abspath(os.environ["srctree"]) 46sys.path.insert(0, os.path.join(srctree, "tools/lib/python")) 47 48from kdoc.kdoc_files import KernelFiles 49from kdoc.kdoc_output import RestFormat 50 51# Used when verbose is active to show how to reproduce kernel-doc 52# issues via command line 53kerneldoc_bin = "tools/docs/kernel-doc" 54 55__version__ = '1.0' 56kfiles = None 57logger = logging.getLogger(__name__) 58 59def cmd_str(cmd): 60 """ 61 Helper function to output a command line that can be used to produce 62 the same records via command line. Helpful to debug troubles at the 63 script. 64 """ 65 66 cmd_line = "" 67 68 for w in cmd: 69 if w == "" or " " in w: 70 esc_cmd = "'" + w + "'" 71 else: 72 esc_cmd = w 73 74 if cmd_line: 75 cmd_line += " " + esc_cmd 76 continue 77 else: 78 cmd_line = esc_cmd 79 80 return cmd_line 81 82class KernelDocDirective(Directive): 83 """Extract kernel-doc comments from the specified file""" 84 required_argument = 1 85 optional_arguments = 4 86 option_spec = { 87 'doc': directives.unchanged_required, 88 'export': directives.unchanged, 89 'internal': directives.unchanged, 90 'identifiers': directives.unchanged, 91 'no-identifiers': directives.unchanged, 92 'functions': directives.unchanged, 93 } 94 has_content = False 95 verbose = 0 96 97 parse_args = {} 98 msg_args = {} 99 100 def handle_args(self): 101 102 env = self.state.document.settings.env 103 cmd = [kerneldoc_bin, '-rst', '-enable-lineno'] 104 105 filename = env.config.kerneldoc_srctree + '/' + self.arguments[0] 106 107 # Arguments used by KernelFiles.parse() function 108 self.parse_args = { 109 "file_list": [filename], 110 "export_file": [] 111 } 112 113 # Arguments used by KernelFiles.msg() function 114 self.msg_args = { 115 "enable_lineno": True, 116 "export": False, 117 "internal": False, 118 "symbol": [], 119 "nosymbol": [], 120 "no_doc_sections": False 121 } 122 123 export_file_patterns = [] 124 125 verbose = os.environ.get("V") 126 if verbose: 127 try: 128 self.verbose = int(verbose) 129 except ValueError: 130 pass 131 132 # Tell sphinx of the dependency 133 env.note_dependency(os.path.abspath(filename)) 134 135 self.tab_width = self.options.get('tab-width', 136 self.state.document.settings.tab_width) 137 138 # 'function' is an alias of 'identifiers' 139 if 'functions' in self.options: 140 self.options['identifiers'] = self.options.get('functions') 141 142 # FIXME: make this nicer and more robust against errors 143 if 'export' in self.options: 144 cmd += ['-export'] 145 self.msg_args["export"] = True 146 export_file_patterns = str(self.options.get('export')).split() 147 elif 'internal' in self.options: 148 cmd += ['-internal'] 149 self.msg_args["internal"] = True 150 export_file_patterns = str(self.options.get('internal')).split() 151 elif 'doc' in self.options: 152 func = str(self.options.get('doc')) 153 cmd += ['-function', func] 154 self.msg_args["symbol"].append(func) 155 elif 'identifiers' in self.options: 156 identifiers = self.options.get('identifiers').split() 157 if identifiers: 158 for i in identifiers: 159 i = i.rstrip("\\").strip() 160 if not i: 161 continue 162 163 cmd += ['-function', i] 164 self.msg_args["symbol"].append(i) 165 else: 166 cmd += ['-no-doc-sections'] 167 self.msg_args["no_doc_sections"] = True 168 169 if 'no-identifiers' in self.options: 170 no_identifiers = self.options.get('no-identifiers').split() 171 if no_identifiers: 172 for i in no_identifiers: 173 i = i.rstrip("\\").strip() 174 if not i: 175 continue 176 177 cmd += ['-nosymbol', i] 178 self.msg_args["nosymbol"].append(i) 179 180 for pattern in export_file_patterns: 181 pattern = pattern.rstrip("\\").strip() 182 if not pattern: 183 continue 184 185 for f in glob.glob(env.config.kerneldoc_srctree + '/' + pattern): 186 env.note_dependency(os.path.abspath(f)) 187 cmd += ['-export-file', f] 188 self.parse_args["export_file"].append(f) 189 190 # Export file is needed by both parse and msg, as kernel-doc 191 # cache exports. 192 self.msg_args["export_file"] = self.parse_args["export_file"] 193 194 cmd += [filename] 195 196 return cmd 197 198 def parse_msg(self, filename, node, out): 199 """ 200 Handles a kernel-doc output for a given file 201 """ 202 203 env = self.state.document.settings.env 204 205 lines = statemachine.string2lines(out, self.tab_width, 206 convert_whitespace=True) 207 result = ViewList() 208 209 lineoffset = 0; 210 line_regex = re.compile(r"^\.\. LINENO ([0-9]+)$") 211 for line in lines: 212 match = line_regex.search(line) 213 if match: 214 # sphinx counts lines from 0 215 lineoffset = int(match.group(1)) - 1 216 # we must eat our comments since the upset the markup 217 else: 218 doc = str(env.srcdir) + "/" + env.docname + ":" + str(self.lineno) 219 result.append(line, doc + ": " + filename, lineoffset) 220 lineoffset += 1 221 222 self.do_parse(result, node) 223 224 def run_kdoc(self, kfiles): 225 """ 226 Execute kernel-doc classes directly instead of running as a separate 227 command. 228 """ 229 230 env = self.state.document.settings.env 231 232 node = nodes.section() 233 234 kfiles.parse(**self.parse_args) 235 filenames = self.parse_args["file_list"] 236 237 for filename, out in kfiles.msg(**self.msg_args, filenames=filenames): 238 self.parse_msg(filename, node, out) 239 240 return node.children 241 242 def run(self): 243 cmd = self.handle_args() 244 if self.verbose >= 1: 245 logger.info(cmd_str(cmd)) 246 247 try: 248 return self.run_kdoc(kfiles) 249 except Exception as e: # pylint: disable=W0703 250 logger.warning("kernel-doc '%s' processing failed with: %s" % 251 (cmd_str(cmd), pformat(e))) 252 return [nodes.error(None, nodes.paragraph(text = "kernel-doc missing"))] 253 254 def do_parse(self, result, node): 255 with switch_source_input(self.state, result): 256 nested_parse_with_titles(self.state, result, node) 257 258def setup_kfiles(app): 259 global kfiles 260 out_style = RestFormat() 261 kfiles = KernelFiles(out_style=out_style, logger=logger) 262 263 264def setup(app): 265 app.add_config_value('kerneldoc_srctree', None, 'env') 266 app.add_config_value('kerneldoc_verbosity', 1, 'env') 267 268 app.add_directive('kernel-doc', KernelDocDirective) 269 270 app.connect('builder-inited', setup_kfiles) 271 272 return dict( 273 version = __version__, 274 parallel_read_safe = True, 275 parallel_write_safe = True 276 ) 277