1#!/usr/bin/env python3 2# SPDX-License-Identifier: GPL-2.0 3# Copyright(c) 2025: Mauro Carvalho Chehab <mchehab@kernel.org>. 4# 5# pylint: disable=C0301,C0302,R0904,R0912,R0913,R0914,R0915,R0917,R1702 6 7""" 8Classes and functions related to reading a C language source or header FILE 9and extract embedded documentation comments from it. 10""" 11 12import sys 13import re 14from pprint import pformat 15 16from kdoc.kdoc_re import NestedMatch, KernRe 17from kdoc.kdoc_item import KdocItem 18 19# 20# Regular expressions used to parse kernel-doc markups at KernelDoc class. 21# 22# Let's declare them in lowercase outside any class to make it easier to 23# convert from the Perl script. 24# 25# As those are evaluated at the beginning, no need to cache them 26# 27 28# Allow whitespace at end of comment start. 29doc_start = KernRe(r'^/\*\*\s*$', cache=False) 30 31doc_end = KernRe(r'\*/', cache=False) 32doc_com = KernRe(r'\s*\*\s*', cache=False) 33doc_com_body = KernRe(r'\s*\* ?', cache=False) 34doc_decl = doc_com + KernRe(r'(\w+)', cache=False) 35 36# @params and a strictly limited set of supported section names 37# Specifically: 38# Match @word: 39# @...: 40# @{section-name}: 41# while trying to not match literal block starts like "example::" 42# 43known_section_names = 'description|context|returns?|notes?|examples?' 44known_sections = KernRe(known_section_names, flags = re.I) 45doc_sect = doc_com + \ 46 KernRe(r'\s*(@[.\w]+|@\.\.\.|' + known_section_names + r')\s*:([^:].*)?$', 47 flags=re.I, cache=False) 48 49doc_content = doc_com_body + KernRe(r'(.*)', cache=False) 50doc_inline_start = KernRe(r'^\s*/\*\*\s*$', cache=False) 51doc_inline_sect = KernRe(r'\s*\*\s*(@\s*[\w][\w\.]*\s*):(.*)', cache=False) 52doc_inline_end = KernRe(r'^\s*\*/\s*$', cache=False) 53doc_inline_oneline = KernRe(r'^\s*/\*\*\s*(@\s*[\w][\w\.]*\s*):\s*(.*)\s*\*/\s*$', cache=False) 54 55export_symbol = KernRe(r'^\s*EXPORT_SYMBOL(_GPL)?\s*\(\s*(\w+)\s*\)\s*', cache=False) 56export_symbol_ns = KernRe(r'^\s*EXPORT_SYMBOL_NS(_GPL)?\s*\(\s*(\w+)\s*,\s*"\S+"\)\s*', cache=False) 57 58type_param = KernRe(r"@(\w*((\.\w+)|(->\w+))*(\.\.\.)?)", cache=False) 59 60# 61# Tests for the beginning of a kerneldoc block in its various forms. 62# 63doc_block = doc_com + KernRe(r'DOC:\s*(.*)?', cache=False) 64doc_begin_data = KernRe(r"^\s*\*?\s*(struct|union|enum|typedef|var)\b\s*(\w*)", cache = False) 65doc_begin_func = KernRe(str(doc_com) + # initial " * ' 66 r"(?:\w+\s*\*\s*)?" + # type (not captured) 67 r'(?:define\s+)?' + # possible "define" (not captured) 68 r'(\w+)\s*(?:\(\w*\))?\s*' + # name and optional "(...)" 69 r'(?:[-:].*)?$', # description (not captured) 70 cache = False) 71 72# 73# Here begins a long set of transformations to turn structure member prefixes 74# and macro invocations into something we can parse and generate kdoc for. 75# 76struct_args_pattern = r'([^,)]+)' 77 78struct_xforms = [ 79 # Strip attributes 80 (KernRe(r"__attribute__\s*\(\([a-z0-9,_\*\s\(\)]*\)\)", flags=re.I | re.S, cache=False), ' '), 81 (KernRe(r'\s*__aligned\s*\([^;]*\)', re.S), ' '), 82 (KernRe(r'\s*__counted_by\s*\([^;]*\)', re.S), ' '), 83 (KernRe(r'\s*__counted_by_(le|be)\s*\([^;]*\)', re.S), ' '), 84 (KernRe(r'\s*__packed\s*', re.S), ' '), 85 (KernRe(r'\s*CRYPTO_MINALIGN_ATTR', re.S), ' '), 86 (KernRe(r'\s*__private', re.S), ' '), 87 (KernRe(r'\s*__rcu', re.S), ' '), 88 (KernRe(r'\s*____cacheline_aligned_in_smp', re.S), ' '), 89 (KernRe(r'\s*____cacheline_aligned', re.S), ' '), 90 (KernRe(r'\s*__cacheline_group_(begin|end)\([^\)]+\);'), ''), 91 # 92 # Unwrap struct_group macros based on this definition: 93 # __struct_group(TAG, NAME, ATTRS, MEMBERS...) 94 # which has variants like: struct_group(NAME, MEMBERS...) 95 # Only MEMBERS arguments require documentation. 96 # 97 # Parsing them happens on two steps: 98 # 99 # 1. drop struct group arguments that aren't at MEMBERS, 100 # storing them as STRUCT_GROUP(MEMBERS) 101 # 102 # 2. remove STRUCT_GROUP() ancillary macro. 103 # 104 # The original logic used to remove STRUCT_GROUP() using an 105 # advanced regex: 106 # 107 # \bSTRUCT_GROUP(\(((?:(?>[^)(]+)|(?1))*)\))[^;]*; 108 # 109 # with two patterns that are incompatible with 110 # Python re module, as it has: 111 # 112 # - a recursive pattern: (?1) 113 # - an atomic grouping: (?>...) 114 # 115 # I tried a simpler version: but it didn't work either: 116 # \bSTRUCT_GROUP\(([^\)]+)\)[^;]*; 117 # 118 # As it doesn't properly match the end parenthesis on some cases. 119 # 120 # So, a better solution was crafted: there's now a NestedMatch 121 # class that ensures that delimiters after a search are properly 122 # matched. So, the implementation to drop STRUCT_GROUP() will be 123 # handled in separate. 124 # 125 (KernRe(r'\bstruct_group\s*\(([^,]*,)', re.S), r'STRUCT_GROUP('), 126 (KernRe(r'\bstruct_group_attr\s*\(([^,]*,){2}', re.S), r'STRUCT_GROUP('), 127 (KernRe(r'\bstruct_group_tagged\s*\(([^,]*),([^,]*),', re.S), r'struct \1 \2; STRUCT_GROUP('), 128 (KernRe(r'\b__struct_group\s*\(([^,]*,){3}', re.S), r'STRUCT_GROUP('), 129 # 130 # Replace macros 131 # 132 # TODO: use NestedMatch for FOO($1, $2, ...) matches 133 # 134 # it is better to also move those to the NestedMatch logic, 135 # to ensure that parentheses will be properly matched. 136 # 137 (KernRe(r'__ETHTOOL_DECLARE_LINK_MODE_MASK\s*\(([^\)]+)\)', re.S), 138 r'DECLARE_BITMAP(\1, __ETHTOOL_LINK_MODE_MASK_NBITS)'), 139 (KernRe(r'DECLARE_PHY_INTERFACE_MASK\s*\(([^\)]+)\)', re.S), 140 r'DECLARE_BITMAP(\1, PHY_INTERFACE_MODE_MAX)'), 141 (KernRe(r'DECLARE_BITMAP\s*\(' + struct_args_pattern + r',\s*' + struct_args_pattern + r'\)', 142 re.S), r'unsigned long \1[BITS_TO_LONGS(\2)]'), 143 (KernRe(r'DECLARE_HASHTABLE\s*\(' + struct_args_pattern + r',\s*' + struct_args_pattern + r'\)', 144 re.S), r'unsigned long \1[1 << ((\2) - 1)]'), 145 (KernRe(r'DECLARE_KFIFO\s*\(' + struct_args_pattern + r',\s*' + struct_args_pattern + 146 r',\s*' + struct_args_pattern + r'\)', re.S), r'\2 *\1'), 147 (KernRe(r'DECLARE_KFIFO_PTR\s*\(' + struct_args_pattern + r',\s*' + 148 struct_args_pattern + r'\)', re.S), r'\2 *\1'), 149 (KernRe(r'(?:__)?DECLARE_FLEX_ARRAY\s*\(' + struct_args_pattern + r',\s*' + 150 struct_args_pattern + r'\)', re.S), r'\1 \2[]'), 151 (KernRe(r'DEFINE_DMA_UNMAP_ADDR\s*\(' + struct_args_pattern + r'\)', re.S), r'dma_addr_t \1'), 152 (KernRe(r'DEFINE_DMA_UNMAP_LEN\s*\(' + struct_args_pattern + r'\)', re.S), r'__u32 \1'), 153] 154# 155# Regexes here are guaranteed to have the end delimiter matching 156# the start delimiter. Yet, right now, only one replace group 157# is allowed. 158# 159struct_nested_prefixes = [ 160 (re.compile(r'\bSTRUCT_GROUP\('), r'\1'), 161] 162 163# 164# Transforms for function prototypes 165# 166function_xforms = [ 167 (KernRe(r"^static +"), ""), 168 (KernRe(r"^extern +"), ""), 169 (KernRe(r"^asmlinkage +"), ""), 170 (KernRe(r"^inline +"), ""), 171 (KernRe(r"^__inline__ +"), ""), 172 (KernRe(r"^__inline +"), ""), 173 (KernRe(r"^__always_inline +"), ""), 174 (KernRe(r"^noinline +"), ""), 175 (KernRe(r"^__FORTIFY_INLINE +"), ""), 176 (KernRe(r"__init +"), ""), 177 (KernRe(r"__init_or_module +"), ""), 178 (KernRe(r"__exit +"), ""), 179 (KernRe(r"__deprecated +"), ""), 180 (KernRe(r"__flatten +"), ""), 181 (KernRe(r"__meminit +"), ""), 182 (KernRe(r"__must_check +"), ""), 183 (KernRe(r"__weak +"), ""), 184 (KernRe(r"__sched +"), ""), 185 (KernRe(r"_noprof"), ""), 186 (KernRe(r"__always_unused *"), ""), 187 (KernRe(r"__printf\s*\(\s*\d*\s*,\s*\d*\s*\) +"), ""), 188 (KernRe(r"__(?:re)?alloc_size\s*\(\s*\d+\s*(?:,\s*\d+\s*)?\) +"), ""), 189 (KernRe(r"__diagnose_as\s*\(\s*\S+\s*(?:,\s*\d+\s*)*\) +"), ""), 190 (KernRe(r"DECL_BUCKET_PARAMS\s*\(\s*(\S+)\s*,\s*(\S+)\s*\)"), r"\1, \2"), 191 (KernRe(r"__attribute_const__ +"), ""), 192 (KernRe(r"__attribute__\s*\(\((?:[\w\s]+(?:\([^)]*\))?\s*,?)+\)\)\s+"), ""), 193] 194 195# 196# Transforms for variable prototypes 197# 198var_xforms = [ 199 (KernRe(r"__read_mostly"), ""), 200 (KernRe(r"__ro_after_init"), ""), 201 (KernRe(r"(?://.*)$"), ""), 202 (KernRe(r"(?:/\*.*\*/)"), ""), 203 (KernRe(r";$"), ""), 204] 205 206# 207# Ancillary functions 208# 209 210def apply_transforms(xforms, text): 211 """ 212 Apply a set of transforms to a block of text. 213 """ 214 for search, subst in xforms: 215 text = search.sub(subst, text) 216 return text 217 218multi_space = KernRe(r'\s\s+') 219def trim_whitespace(s): 220 """ 221 A little helper to get rid of excess white space. 222 """ 223 return multi_space.sub(' ', s.strip()) 224 225def trim_private_members(text): 226 """ 227 Remove ``struct``/``enum`` members that have been marked "private". 228 """ 229 # First look for a "public:" block that ends a private region, then 230 # handle the "private until the end" case. 231 # 232 text = KernRe(r'/\*\s*private:.*?/\*\s*public:.*?\*/', flags=re.S).sub('', text) 233 text = KernRe(r'/\*\s*private:.*', flags=re.S).sub('', text) 234 # 235 # We needed the comments to do the above, but now we can take them out. 236 # 237 return KernRe(r'\s*/\*.*?\*/\s*', flags=re.S).sub('', text).strip() 238 239class state: 240 """ 241 States used by the parser's state machine. 242 """ 243 244 # Parser states 245 NORMAL = 0 #: Normal code. 246 NAME = 1 #: Looking for function name. 247 DECLARATION = 2 #: We have seen a declaration which might not be done. 248 BODY = 3 #: The body of the comment. 249 SPECIAL_SECTION = 4 #: Doc section ending with a blank line. 250 PROTO = 5 #: Scanning prototype. 251 DOCBLOCK = 6 #: Documentation block. 252 INLINE_NAME = 7 #: Gathering doc outside main block. 253 INLINE_TEXT = 8 #: Reading the body of inline docs. 254 255 #: Names for each parser state. 256 name = [ 257 "NORMAL", 258 "NAME", 259 "DECLARATION", 260 "BODY", 261 "SPECIAL_SECTION", 262 "PROTO", 263 "DOCBLOCK", 264 "INLINE_NAME", 265 "INLINE_TEXT", 266 ] 267 268 269SECTION_DEFAULT = "Description" #: Default section. 270 271class KernelEntry: 272 """ 273 Encapsulates a Kernel documentation entry. 274 """ 275 276 def __init__(self, config, fname, ln): 277 self.config = config 278 self.fname = fname 279 280 self._contents = [] 281 self.prototype = "" 282 283 self.warnings = [] 284 285 self.parameterlist = [] 286 self.parameterdescs = {} 287 self.parametertypes = {} 288 self.parameterdesc_start_lines = {} 289 290 self.section_start_lines = {} 291 self.sections = {} 292 293 self.anon_struct_union = False 294 295 self.leading_space = None 296 297 self.fname = fname 298 299 # State flags 300 self.brcount = 0 301 self.declaration_start_line = ln + 1 302 303 # 304 # Management of section contents 305 # 306 def add_text(self, text): 307 """Add a new text to the entry contents list.""" 308 self._contents.append(text) 309 310 def contents(self): 311 """Returns a string with all content texts that were added.""" 312 return '\n'.join(self._contents) + '\n' 313 314 # TODO: rename to emit_message after removal of kernel-doc.pl 315 def emit_msg(self, ln, msg, *, warning=True): 316 """Emit a message.""" 317 318 log_msg = f"{self.fname}:{ln} {msg}" 319 320 if not warning: 321 self.config.log.info(log_msg) 322 return 323 324 # Delegate warning output to output logic, as this way it 325 # will report warnings/info only for symbols that are output 326 327 self.warnings.append(log_msg) 328 return 329 330 def begin_section(self, line_no, title = SECTION_DEFAULT, dump = False): 331 """ 332 Begin a new section. 333 """ 334 if dump: 335 self.dump_section(start_new = True) 336 self.section = title 337 self.new_start_line = line_no 338 339 def dump_section(self, start_new=True): 340 """ 341 Dumps section contents to arrays/hashes intended for that purpose. 342 """ 343 # 344 # If we have accumulated no contents in the default ("description") 345 # section, don't bother. 346 # 347 if self.section == SECTION_DEFAULT and not self._contents: 348 return 349 name = self.section 350 contents = self.contents() 351 352 if type_param.match(name): 353 name = type_param.group(1) 354 355 self.parameterdescs[name] = contents 356 self.parameterdesc_start_lines[name] = self.new_start_line 357 358 self.new_start_line = 0 359 360 else: 361 if name in self.sections and self.sections[name] != "": 362 # Only warn on user-specified duplicate section names 363 if name != SECTION_DEFAULT: 364 self.emit_msg(self.new_start_line, 365 f"duplicate section name '{name}'") 366 # Treat as a new paragraph - add a blank line 367 self.sections[name] += '\n' + contents 368 else: 369 self.sections[name] = contents 370 self.section_start_lines[name] = self.new_start_line 371 self.new_start_line = 0 372 373# self.config.log.debug("Section: %s : %s", name, pformat(vars(self))) 374 375 if start_new: 376 self.section = SECTION_DEFAULT 377 self._contents = [] 378 379python_warning = False 380 381class KernelDoc: 382 """ 383 Read a C language source or header FILE and extract embedded 384 documentation comments. 385 """ 386 387 #: Name of context section. 388 section_context = "Context" 389 390 #: Name of return section. 391 section_return = "Return" 392 393 #: String to write when a parameter is not described. 394 undescribed = "-- undescribed --" 395 396 def __init__(self, config, fname): 397 """Initialize internal variables""" 398 399 self.fname = fname 400 self.config = config 401 402 # Initial state for the state machines 403 self.state = state.NORMAL 404 405 # Store entry currently being processed 406 self.entry = None 407 408 # Place all potential outputs into an array 409 self.entries = [] 410 411 # 412 # We need Python 3.7 for its "dicts remember the insertion 413 # order" guarantee 414 # 415 global python_warning 416 if (not python_warning and 417 sys.version_info.major == 3 and sys.version_info.minor < 7): 418 419 self.emit_msg(0, 420 'Python 3.7 or later is required for correct results') 421 python_warning = True 422 423 def emit_msg(self, ln, msg, *, warning=True): 424 """Emit a message""" 425 426 if self.entry: 427 self.entry.emit_msg(ln, msg, warning=warning) 428 return 429 430 log_msg = f"{self.fname}:{ln} {msg}" 431 432 if warning: 433 self.config.log.warning(log_msg) 434 else: 435 self.config.log.info(log_msg) 436 437 def dump_section(self, start_new=True): 438 """ 439 Dump section contents to arrays/hashes intended for that purpose. 440 """ 441 442 if self.entry: 443 self.entry.dump_section(start_new) 444 445 # TODO: rename it to store_declaration after removal of kernel-doc.pl 446 def output_declaration(self, dtype, name, **args): 447 """ 448 Store the entry into an entry array. 449 450 The actual output and output filters will be handled elsewhere. 451 """ 452 453 item = KdocItem(name, self.fname, dtype, 454 self.entry.declaration_start_line, **args) 455 item.warnings = self.entry.warnings 456 457 # Drop empty sections 458 # TODO: improve empty sections logic to emit warnings 459 sections = self.entry.sections 460 for section in ["Description", "Return"]: 461 if section in sections and not sections[section].rstrip(): 462 del sections[section] 463 item.set_sections(sections, self.entry.section_start_lines) 464 item.set_params(self.entry.parameterlist, self.entry.parameterdescs, 465 self.entry.parametertypes, 466 self.entry.parameterdesc_start_lines) 467 self.entries.append(item) 468 469 self.config.log.debug("Output: %s:%s = %s", dtype, name, pformat(args)) 470 471 def emit_unused_warnings(self): 472 """ 473 When the parser fails to produce a valid entry, it places some 474 warnings under `entry.warnings` that will be discarded when resetting 475 the state. 476 477 Ensure that those warnings are not lost. 478 479 .. note:: 480 481 Because we are calling `config.warning()` here, those 482 warnings are not filtered by the `-W` parameters: they will all 483 be produced even when `-Wreturn`, `-Wshort-desc`, and/or 484 `-Wcontents-before-sections` are used. 485 486 Allowing those warnings to be filtered is complex, because it 487 would require storing them in a buffer and then filtering them 488 during the output step of the code, depending on the 489 selected symbols. 490 """ 491 if self.entry and self.entry not in self.entries: 492 for log_msg in self.entry.warnings: 493 self.config.warning(log_msg) 494 495 def reset_state(self, ln): 496 """ 497 Ancillary routine to create a new entry. It initializes all 498 variables used by the state machine. 499 """ 500 501 self.emit_unused_warnings() 502 503 self.entry = KernelEntry(self.config, self.fname, ln) 504 505 # State flags 506 self.state = state.NORMAL 507 508 def push_parameter(self, ln, decl_type, param, dtype, 509 org_arg, declaration_name): 510 """ 511 Store parameters and their descriptions at self.entry. 512 """ 513 514 if self.entry.anon_struct_union and dtype == "" and param == "}": 515 return # Ignore the ending }; from anonymous struct/union 516 517 self.entry.anon_struct_union = False 518 519 param = KernRe(r'[\[\)].*').sub('', param, count=1) 520 521 # 522 # Look at various "anonymous type" cases. 523 # 524 if dtype == '': 525 if param.endswith("..."): 526 if len(param) > 3: # there is a name provided, use that 527 param = param[:-3] 528 if not self.entry.parameterdescs.get(param): 529 self.entry.parameterdescs[param] = "variable arguments" 530 531 elif (not param) or param == "void": 532 param = "void" 533 self.entry.parameterdescs[param] = "no arguments" 534 535 elif param in ["struct", "union"]: 536 # Handle unnamed (anonymous) union or struct 537 dtype = param 538 param = "{unnamed_" + param + "}" 539 self.entry.parameterdescs[param] = "anonymous\n" 540 self.entry.anon_struct_union = True 541 542 # Warn if parameter has no description 543 # (but ignore ones starting with # as these are not parameters 544 # but inline preprocessor statements) 545 if param not in self.entry.parameterdescs and not param.startswith("#"): 546 self.entry.parameterdescs[param] = self.undescribed 547 548 if "." not in param: 549 if decl_type == 'function': 550 dname = f"{decl_type} parameter" 551 else: 552 dname = f"{decl_type} member" 553 554 self.emit_msg(ln, 555 f"{dname} '{param}' not described in '{declaration_name}'") 556 557 # Strip spaces from param so that it is one continuous string on 558 # parameterlist. This fixes a problem where check_sections() 559 # cannot find a parameter like "addr[6 + 2]" because it actually 560 # appears as "addr[6", "+", "2]" on the parameter list. 561 # However, it's better to maintain the param string unchanged for 562 # output, so just weaken the string compare in check_sections() 563 # to ignore "[blah" in a parameter string. 564 565 self.entry.parameterlist.append(param) 566 org_arg = KernRe(r'\s\s+').sub(' ', org_arg) 567 self.entry.parametertypes[param] = org_arg 568 569 570 def create_parameter_list(self, ln, decl_type, args, 571 splitter, declaration_name): 572 """ 573 Creates a list of parameters, storing them at self.entry. 574 """ 575 576 # temporarily replace all commas inside function pointer definition 577 arg_expr = KernRe(r'(\([^\),]+),') 578 while arg_expr.search(args): 579 args = arg_expr.sub(r"\1#", args) 580 581 for arg in args.split(splitter): 582 # Ignore argument attributes 583 arg = KernRe(r'\sPOS0?\s').sub(' ', arg) 584 585 # Strip leading/trailing spaces 586 arg = arg.strip() 587 arg = KernRe(r'\s+').sub(' ', arg, count=1) 588 589 if arg.startswith('#'): 590 # Treat preprocessor directive as a typeless variable just to fill 591 # corresponding data structures "correctly". Catch it later in 592 # output_* subs. 593 594 # Treat preprocessor directive as a typeless variable 595 self.push_parameter(ln, decl_type, arg, "", 596 "", declaration_name) 597 # 598 # The pointer-to-function case. 599 # 600 elif KernRe(r'\(.+\)\s*\(').search(arg): 601 arg = arg.replace('#', ',') 602 r = KernRe(r'[^\(]+\(\*?\s*' # Everything up to "(*" 603 r'([\w\[\].]*)' # Capture the name and possible [array] 604 r'\s*\)') # Make sure the trailing ")" is there 605 if r.match(arg): 606 param = r.group(1) 607 else: 608 self.emit_msg(ln, f"Invalid param: {arg}") 609 param = arg 610 dtype = arg.replace(param, '') 611 self.push_parameter(ln, decl_type, param, dtype, arg, declaration_name) 612 # 613 # The array-of-pointers case. Dig the parameter name out from the middle 614 # of the declaration. 615 # 616 elif KernRe(r'\(.+\)\s*\[').search(arg): 617 r = KernRe(r'[^\(]+\(\s*\*\s*' # Up to "(" and maybe "*" 618 r'([\w.]*?)' # The actual pointer name 619 r'\s*(\[\s*\w+\s*\]\s*)*\)') # The [array portion] 620 if r.match(arg): 621 param = r.group(1) 622 else: 623 self.emit_msg(ln, f"Invalid param: {arg}") 624 param = arg 625 dtype = arg.replace(param, '') 626 self.push_parameter(ln, decl_type, param, dtype, arg, declaration_name) 627 elif arg: 628 # 629 # Clean up extraneous spaces and split the string at commas; the first 630 # element of the resulting list will also include the type information. 631 # 632 arg = KernRe(r'\s*:\s*').sub(":", arg) 633 arg = KernRe(r'\s*\[').sub('[', arg) 634 args = KernRe(r'\s*,\s*').split(arg) 635 args[0] = re.sub(r'(\*+)\s*', r' \1', args[0]) 636 # 637 # args[0] has a string of "type a". If "a" includes an [array] 638 # declaration, we want to not be fooled by any white space inside 639 # the brackets, so detect and handle that case specially. 640 # 641 r = KernRe(r'^([^[\]]*\s+)(.*)$') 642 if r.match(args[0]): 643 args[0] = r.group(2) 644 dtype = r.group(1) 645 else: 646 # No space in args[0]; this seems wrong but preserves previous behavior 647 dtype = '' 648 649 bitfield_re = KernRe(r'(.*?):(\w+)') 650 for param in args: 651 # 652 # For pointers, shift the star(s) from the variable name to the 653 # type declaration. 654 # 655 r = KernRe(r'^(\*+)\s*(.*)') 656 if r.match(param): 657 self.push_parameter(ln, decl_type, r.group(2), 658 f"{dtype} {r.group(1)}", 659 arg, declaration_name) 660 # 661 # Perform a similar shift for bitfields. 662 # 663 elif bitfield_re.search(param): 664 if dtype != "": # Skip unnamed bit-fields 665 self.push_parameter(ln, decl_type, bitfield_re.group(1), 666 f"{dtype}:{bitfield_re.group(2)}", 667 arg, declaration_name) 668 else: 669 self.push_parameter(ln, decl_type, param, dtype, 670 arg, declaration_name) 671 672 def check_sections(self, ln, decl_name, decl_type): 673 """ 674 Check for errors inside sections, emitting warnings if not found 675 parameters are described. 676 """ 677 for section in self.entry.sections: 678 if section not in self.entry.parameterlist and \ 679 not known_sections.search(section): 680 if decl_type == 'function': 681 dname = f"{decl_type} parameter" 682 else: 683 dname = f"{decl_type} member" 684 self.emit_msg(ln, 685 f"Excess {dname} '{section}' description in '{decl_name}'") 686 687 def check_return_section(self, ln, declaration_name, return_type): 688 """ 689 If the function doesn't return void, warns about the lack of a 690 return description. 691 """ 692 693 if not self.config.wreturn: 694 return 695 696 # Ignore an empty return type (It's a macro) 697 # Ignore functions with a "void" return type (but not "void *") 698 if not return_type or KernRe(r'void\s*\w*\s*$').search(return_type): 699 return 700 701 if not self.entry.sections.get("Return", None): 702 self.emit_msg(ln, 703 f"No description found for return value of '{declaration_name}'") 704 705 def split_struct_proto(self, proto): 706 """ 707 Split apart a structure prototype; returns (struct|union, name, 708 members) or ``None``. 709 """ 710 711 type_pattern = r'(struct|union)' 712 qualifiers = [ 713 "__attribute__", 714 "__packed", 715 "__aligned", 716 "____cacheline_aligned_in_smp", 717 "____cacheline_aligned", 718 ] 719 definition_body = r'\{(.*)\}\s*' + "(?:" + '|'.join(qualifiers) + ")?" 720 721 r = KernRe(type_pattern + r'\s+(\w+)\s*' + definition_body) 722 if r.search(proto): 723 return (r.group(1), r.group(2), r.group(3)) 724 else: 725 r = KernRe(r'typedef\s+' + type_pattern + r'\s*' + definition_body + r'\s*(\w+)\s*;') 726 if r.search(proto): 727 return (r.group(1), r.group(3), r.group(2)) 728 return None 729 730 def rewrite_struct_members(self, members): 731 """ 732 Process ``struct``/``union`` members from the most deeply nested 733 outward. 734 735 Rewrite the members of a ``struct`` or ``union`` for easier formatting 736 later on. Among other things, this function will turn a member like:: 737 738 struct { inner_members; } foo; 739 740 into:: 741 742 struct foo; inner_members; 743 """ 744 745 # 746 # The trick is in the ``^{`` below - it prevents a match of an outer 747 # ``struct``/``union`` until the inner one has been munged 748 # (removing the ``{`` in the process). 749 # 750 struct_members = KernRe(r'(struct|union)' # 0: declaration type 751 r'([^\{\};]+)' # 1: possible name 752 r'(\{)' 753 r'([^\{\}]*)' # 3: Contents of declaration 754 r'(\})' 755 r'([^\{\};]*)(;)') # 5: Remaining stuff after declaration 756 tuples = struct_members.findall(members) 757 while tuples: 758 for t in tuples: 759 newmember = "" 760 oldmember = "".join(t) # Reconstruct the original formatting 761 dtype, name, lbr, content, rbr, rest, semi = t 762 # 763 # Pass through each field name, normalizing the form and formatting. 764 # 765 for s_id in rest.split(','): 766 s_id = s_id.strip() 767 newmember += f"{dtype} {s_id}; " 768 # 769 # Remove bitfield/array/pointer info, getting the bare name. 770 # 771 s_id = KernRe(r'[:\[].*').sub('', s_id) 772 s_id = KernRe(r'^\s*\**(\S+)\s*').sub(r'\1', s_id) 773 # 774 # Pass through the members of this inner structure/union. 775 # 776 for arg in content.split(';'): 777 arg = arg.strip() 778 # 779 # Look for (type)(*name)(args) - pointer to function 780 # 781 r = KernRe(r'^([^\(]+\(\*?\s*)([\w.]*)(\s*\).*)') 782 if r.match(arg): 783 dtype, name, extra = r.group(1), r.group(2), r.group(3) 784 # Pointer-to-function 785 if not s_id: 786 # Anonymous struct/union 787 newmember += f"{dtype}{name}{extra}; " 788 else: 789 newmember += f"{dtype}{s_id}.{name}{extra}; " 790 # 791 # Otherwise a non-function member. 792 # 793 else: 794 # 795 # Remove bitmap and array portions and spaces around commas 796 # 797 arg = KernRe(r':\s*\d+\s*').sub('', arg) 798 arg = KernRe(r'\[.*\]').sub('', arg) 799 arg = KernRe(r'\s*,\s*').sub(',', arg) 800 # 801 # Look for a normal decl - "type name[,name...]" 802 # 803 r = KernRe(r'(.*)\s+([\S+,]+)') 804 if r.search(arg): 805 for name in r.group(2).split(','): 806 name = KernRe(r'^\s*\**(\S+)\s*').sub(r'\1', name) 807 if not s_id: 808 # Anonymous struct/union 809 newmember += f"{r.group(1)} {name}; " 810 else: 811 newmember += f"{r.group(1)} {s_id}.{name}; " 812 else: 813 newmember += f"{arg}; " 814 # 815 # At the end of the s_id loop, replace the original declaration with 816 # the munged version. 817 # 818 members = members.replace(oldmember, newmember) 819 # 820 # End of the tuple loop - search again and see if there are outer members 821 # that now turn up. 822 # 823 tuples = struct_members.findall(members) 824 return members 825 826 def format_struct_decl(self, declaration): 827 """ 828 Format the ``struct`` declaration into a standard form for inclusion 829 in the resulting docs. 830 """ 831 832 # 833 # Insert newlines, get rid of extra spaces. 834 # 835 declaration = KernRe(r'([\{;])').sub(r'\1\n', declaration) 836 declaration = KernRe(r'\}\s+;').sub('};', declaration) 837 # 838 # Format inline enums with each member on its own line. 839 # 840 r = KernRe(r'(enum\s+\{[^\}]+),([^\n])') 841 while r.search(declaration): 842 declaration = r.sub(r'\1,\n\2', declaration) 843 # 844 # Now go through and supply the right number of tabs 845 # for each line. 846 # 847 def_args = declaration.split('\n') 848 level = 1 849 declaration = "" 850 for clause in def_args: 851 clause = KernRe(r'\s+').sub(' ', clause.strip(), count=1) 852 if clause: 853 if '}' in clause and level > 1: 854 level -= 1 855 if not clause.startswith('#'): 856 declaration += "\t" * level 857 declaration += "\t" + clause + "\n" 858 if "{" in clause and "}" not in clause: 859 level += 1 860 return declaration 861 862 863 def dump_struct(self, ln, proto): 864 """ 865 Store an entry for a ``struct`` or ``union`` 866 """ 867 # 868 # Do the basic parse to get the pieces of the declaration. 869 # 870 struct_parts = self.split_struct_proto(proto) 871 if not struct_parts: 872 self.emit_msg(ln, f"{proto} error: Cannot parse struct or union!") 873 return 874 decl_type, declaration_name, members = struct_parts 875 876 if self.entry.identifier != declaration_name: 877 self.emit_msg(ln, f"expecting prototype for {decl_type} {self.entry.identifier}. " 878 f"Prototype was for {decl_type} {declaration_name} instead\n") 879 return 880 # 881 # Go through the list of members applying all of our transformations. 882 # 883 members = trim_private_members(members) 884 members = apply_transforms(struct_xforms, members) 885 886 nested = NestedMatch() 887 for search, sub in struct_nested_prefixes: 888 members = nested.sub(search, sub, members) 889 # 890 # Deal with embedded struct and union members, and drop enums entirely. 891 # 892 declaration = members 893 members = self.rewrite_struct_members(members) 894 members = re.sub(r'(\{[^\{\}]*\})', '', members) 895 # 896 # Output the result and we are done. 897 # 898 self.create_parameter_list(ln, decl_type, members, ';', 899 declaration_name) 900 self.check_sections(ln, declaration_name, decl_type) 901 self.output_declaration(decl_type, declaration_name, 902 definition=self.format_struct_decl(declaration), 903 purpose=self.entry.declaration_purpose) 904 905 def dump_enum(self, ln, proto): 906 """ 907 Store an ``enum`` inside self.entries array. 908 """ 909 # 910 # Strip preprocessor directives. Note that this depends on the 911 # trailing semicolon we added in process_proto_type(). 912 # 913 proto = KernRe(r'#\s*((define|ifdef|if)\s+|endif)[^;]*;', flags=re.S).sub('', proto) 914 # 915 # Parse out the name and members of the enum. Typedef form first. 916 # 917 r = KernRe(r'typedef\s+enum\s*\{(.*)\}\s*(\w*)\s*;') 918 if r.search(proto): 919 declaration_name = r.group(2) 920 members = trim_private_members(r.group(1)) 921 # 922 # Failing that, look for a straight enum 923 # 924 else: 925 r = KernRe(r'enum\s+(\w*)\s*\{(.*)\}') 926 if r.match(proto): 927 declaration_name = r.group(1) 928 members = trim_private_members(r.group(2)) 929 # 930 # OK, this isn't going to work. 931 # 932 else: 933 self.emit_msg(ln, f"{proto}: error: Cannot parse enum!") 934 return 935 # 936 # Make sure we found what we were expecting. 937 # 938 if self.entry.identifier != declaration_name: 939 if self.entry.identifier == "": 940 self.emit_msg(ln, 941 f"{proto}: wrong kernel-doc identifier on prototype") 942 else: 943 self.emit_msg(ln, 944 f"expecting prototype for enum {self.entry.identifier}. " 945 f"Prototype was for enum {declaration_name} instead") 946 return 947 948 if not declaration_name: 949 declaration_name = "(anonymous)" 950 # 951 # Parse out the name of each enum member, and verify that we 952 # have a description for it. 953 # 954 member_set = set() 955 members = KernRe(r'\([^;)]*\)').sub('', members) 956 for arg in members.split(','): 957 if not arg: 958 continue 959 arg = KernRe(r'^\s*(\w+).*').sub(r'\1', arg) 960 self.entry.parameterlist.append(arg) 961 if arg not in self.entry.parameterdescs: 962 self.entry.parameterdescs[arg] = self.undescribed 963 self.emit_msg(ln, 964 f"Enum value '{arg}' not described in enum '{declaration_name}'") 965 member_set.add(arg) 966 # 967 # Ensure that every described member actually exists in the enum. 968 # 969 for k in self.entry.parameterdescs: 970 if k not in member_set: 971 self.emit_msg(ln, 972 f"Excess enum value '@{k}' description in '{declaration_name}'") 973 974 self.output_declaration('enum', declaration_name, 975 purpose=self.entry.declaration_purpose) 976 977 def dump_var(self, ln, proto): 978 """ 979 Store variables that are part of kAPI. 980 """ 981 VAR_ATTRIBS = [ 982 "extern", 983 "const", 984 ] 985 OPTIONAL_VAR_ATTR = r"^(?:\b(?:" +"|".join(VAR_ATTRIBS) +r")\b\s*)*" 986 987 # 988 # Store the full prototype before modifying it 989 # 990 full_proto = proto 991 declaration_name = None 992 993 # 994 # Handle macro definitions 995 # 996 macro_prefixes = [ 997 KernRe(r"DEFINE_[\w_]+\s*\(([\w_]+)\)"), 998 ] 999 1000 for r in macro_prefixes: 1001 match = r.search(proto) 1002 if match: 1003 declaration_name = match.group(1) 1004 break 1005 1006 # 1007 # Drop comments and macros to have a pure C prototype 1008 # 1009 if not declaration_name: 1010 for r, sub in var_xforms: 1011 proto = r.sub(sub, proto) 1012 1013 proto = proto.rstrip() 1014 1015 # 1016 # Variable name is at the end of the declaration 1017 # 1018 1019 default_val = None 1020 1021 r= KernRe(OPTIONAL_VAR_ATTR + r"[\w_]*\s+(?:\*+)?([\w_]+)\s*[\d\]\[]*\s*(=.*)?") 1022 if r.match(proto): 1023 if not declaration_name: 1024 declaration_name = r.group(1) 1025 1026 default_val = r.group(2) 1027 else: 1028 r= KernRe(OPTIONAL_VAR_ATTR + r"(?:[\w_]*)?\s+(?:\*+)?(?:[\w_]+)\s*[\d\]\[]*\s*(=.*)?") 1029 1030 if r.match(proto): 1031 default_val = r.group(1) 1032 if not declaration_name: 1033 self.emit_msg(ln,f"{proto}: can't parse variable") 1034 return 1035 1036 if default_val: 1037 default_val = default_val.lstrip("=").strip() 1038 1039 self.output_declaration("var", declaration_name, 1040 full_proto=full_proto, 1041 default_val=default_val, 1042 purpose=self.entry.declaration_purpose) 1043 1044 def dump_declaration(self, ln, prototype): 1045 """ 1046 Store a data declaration inside self.entries array. 1047 """ 1048 1049 if self.entry.decl_type == "enum": 1050 self.dump_enum(ln, prototype) 1051 elif self.entry.decl_type == "typedef": 1052 self.dump_typedef(ln, prototype) 1053 elif self.entry.decl_type in ["union", "struct"]: 1054 self.dump_struct(ln, prototype) 1055 elif self.entry.decl_type == "var": 1056 self.dump_var(ln, prototype) 1057 else: 1058 # This would be a bug 1059 self.emit_message(ln, f'Unknown declaration type: {self.entry.decl_type}') 1060 1061 def dump_function(self, ln, prototype): 1062 """ 1063 Store a function or function macro inside self.entries array. 1064 """ 1065 1066 found = func_macro = False 1067 return_type = '' 1068 decl_type = 'function' 1069 1070 # 1071 # If we have a macro, remove the "#define" at the front. 1072 # 1073 new_proto = KernRe(r"^#\s*define\s+").sub("", prototype) 1074 if new_proto != prototype: 1075 prototype = new_proto 1076 # 1077 # Dispense with the simple "#define A B" case here; the key 1078 # is the space after the name of the symbol being defined. 1079 # NOTE that the seemingly misnamed "func_macro" indicates a 1080 # macro *without* arguments. 1081 # 1082 r = KernRe(r'^(\w+)\s+') 1083 if r.search(prototype): 1084 return_type = '' 1085 declaration_name = r.group(1) 1086 func_macro = True 1087 found = True 1088 else: 1089 # 1090 # Apply the initial transformations. 1091 # 1092 prototype = apply_transforms(function_xforms, prototype) 1093 1094 # Yes, this truly is vile. We are looking for: 1095 # 1. Return type (may be nothing if we're looking at a macro) 1096 # 2. Function name 1097 # 3. Function parameters. 1098 # 1099 # All the while we have to watch out for function pointer parameters 1100 # (which IIRC is what the two sections are for), C types (these 1101 # regexps don't even start to express all the possibilities), and 1102 # so on. 1103 # 1104 # If you mess with these regexps, it's a good idea to check that 1105 # the following functions' documentation still comes out right: 1106 # - parport_register_device (function pointer parameters) 1107 # - atomic_set (macro) 1108 # - pci_match_device, __copy_to_user (long return type) 1109 1110 name = r'\w+' 1111 type1 = r'(?:[\w\s]+)?' 1112 type2 = r'(?:[\w\s]+\*+)+' 1113 # 1114 # Attempt to match first on (args) with no internal parentheses; this 1115 # lets us easily filter out __acquires() and other post-args stuff. If 1116 # that fails, just grab the rest of the line to the last closing 1117 # parenthesis. 1118 # 1119 proto_args = r'\(([^\(]*|.*)\)' 1120 # 1121 # (Except for the simple macro case) attempt to split up the prototype 1122 # in the various ways we understand. 1123 # 1124 if not found: 1125 patterns = [ 1126 rf'^()({name})\s*{proto_args}', 1127 rf'^({type1})\s+({name})\s*{proto_args}', 1128 rf'^({type2})\s*({name})\s*{proto_args}', 1129 ] 1130 1131 for p in patterns: 1132 r = KernRe(p) 1133 if r.match(prototype): 1134 return_type = r.group(1) 1135 declaration_name = r.group(2) 1136 args = r.group(3) 1137 self.create_parameter_list(ln, decl_type, args, ',', 1138 declaration_name) 1139 found = True 1140 break 1141 # 1142 # Parsing done; make sure that things are as we expect. 1143 # 1144 if not found: 1145 self.emit_msg(ln, 1146 f"cannot understand function prototype: '{prototype}'") 1147 return 1148 if self.entry.identifier != declaration_name: 1149 self.emit_msg(ln, f"expecting prototype for {self.entry.identifier}(). " 1150 f"Prototype was for {declaration_name}() instead") 1151 return 1152 self.check_sections(ln, declaration_name, "function") 1153 self.check_return_section(ln, declaration_name, return_type) 1154 # 1155 # Store the result. 1156 # 1157 self.output_declaration(decl_type, declaration_name, 1158 typedef=('typedef' in return_type), 1159 functiontype=return_type, 1160 purpose=self.entry.declaration_purpose, 1161 func_macro=func_macro) 1162 1163 1164 def dump_typedef(self, ln, proto): 1165 """ 1166 Store a ``typedef`` inside self.entries array. 1167 """ 1168 # 1169 # We start by looking for function typedefs. 1170 # 1171 typedef_type = r'typedef((?:\s+[\w*]+\b){0,7}\s+(?:\w+\b|\*+))\s*' 1172 typedef_ident = r'\*?\s*(\w\S+)\s*' 1173 typedef_args = r'\s*\((.*)\);' 1174 1175 typedef1 = KernRe(typedef_type + r'\(' + typedef_ident + r'\)' + typedef_args) 1176 typedef2 = KernRe(typedef_type + typedef_ident + typedef_args) 1177 1178 # Parse function typedef prototypes 1179 for r in [typedef1, typedef2]: 1180 if not r.match(proto): 1181 continue 1182 1183 return_type = r.group(1).strip() 1184 declaration_name = r.group(2) 1185 args = r.group(3) 1186 1187 if self.entry.identifier != declaration_name: 1188 self.emit_msg(ln, 1189 f"expecting prototype for typedef {self.entry.identifier}. Prototype was for typedef {declaration_name} instead\n") 1190 return 1191 1192 self.create_parameter_list(ln, 'function', args, ',', declaration_name) 1193 1194 self.output_declaration('function', declaration_name, 1195 typedef=True, 1196 functiontype=return_type, 1197 purpose=self.entry.declaration_purpose) 1198 return 1199 # 1200 # Not a function, try to parse a simple typedef. 1201 # 1202 r = KernRe(r'typedef.*\s+(\w+)\s*;') 1203 if r.match(proto): 1204 declaration_name = r.group(1) 1205 1206 if self.entry.identifier != declaration_name: 1207 self.emit_msg(ln, 1208 f"expecting prototype for typedef {self.entry.identifier}. Prototype was for typedef {declaration_name} instead\n") 1209 return 1210 1211 self.output_declaration('typedef', declaration_name, 1212 purpose=self.entry.declaration_purpose) 1213 return 1214 1215 self.emit_msg(ln, "error: Cannot parse typedef!") 1216 1217 @staticmethod 1218 def process_export(function_set, line): 1219 """ 1220 process ``EXPORT_SYMBOL*`` tags 1221 1222 This method doesn't use any variable from the class, so declare it 1223 with a staticmethod decorator. 1224 """ 1225 1226 # We support documenting some exported symbols with different 1227 # names. A horrible hack. 1228 suffixes = [ '_noprof' ] 1229 1230 # Note: it accepts only one EXPORT_SYMBOL* per line, as having 1231 # multiple export lines would violate Kernel coding style. 1232 1233 if export_symbol.search(line): 1234 symbol = export_symbol.group(2) 1235 elif export_symbol_ns.search(line): 1236 symbol = export_symbol_ns.group(2) 1237 else: 1238 return False 1239 # 1240 # Found an export, trim out any special suffixes 1241 # 1242 for suffix in suffixes: 1243 # Be backward compatible with Python < 3.9 1244 if symbol.endswith(suffix): 1245 symbol = symbol[:-len(suffix)] 1246 function_set.add(symbol) 1247 return True 1248 1249 def process_normal(self, ln, line): 1250 """ 1251 STATE_NORMAL: looking for the ``/**`` to begin everything. 1252 """ 1253 1254 if not doc_start.match(line): 1255 return 1256 1257 # start a new entry 1258 self.reset_state(ln) 1259 1260 # next line is always the function name 1261 self.state = state.NAME 1262 1263 def process_name(self, ln, line): 1264 """ 1265 STATE_NAME: Looking for the "name - description" line 1266 """ 1267 # 1268 # Check for a DOC: block and handle them specially. 1269 # 1270 if doc_block.search(line): 1271 1272 if not doc_block.group(1): 1273 self.entry.begin_section(ln, "Introduction") 1274 else: 1275 self.entry.begin_section(ln, doc_block.group(1)) 1276 1277 self.entry.identifier = self.entry.section 1278 self.state = state.DOCBLOCK 1279 # 1280 # Otherwise we're looking for a normal kerneldoc declaration line. 1281 # 1282 elif doc_decl.search(line): 1283 self.entry.identifier = doc_decl.group(1) 1284 1285 # Test for data declaration 1286 if doc_begin_data.search(line): 1287 self.entry.decl_type = doc_begin_data.group(1) 1288 self.entry.identifier = doc_begin_data.group(2) 1289 # 1290 # Look for a function description 1291 # 1292 elif doc_begin_func.search(line): 1293 self.entry.identifier = doc_begin_func.group(1) 1294 self.entry.decl_type = "function" 1295 # 1296 # We struck out. 1297 # 1298 else: 1299 self.emit_msg(ln, 1300 f"This comment starts with '/**', but isn't a kernel-doc comment. Refer to Documentation/doc-guide/kernel-doc.rst\n{line}") 1301 self.state = state.NORMAL 1302 return 1303 # 1304 # OK, set up for a new kerneldoc entry. 1305 # 1306 self.state = state.BODY 1307 self.entry.identifier = self.entry.identifier.strip(" ") 1308 # if there's no @param blocks need to set up default section here 1309 self.entry.begin_section(ln + 1) 1310 # 1311 # Find the description portion, which *should* be there but 1312 # isn't always. 1313 # (We should be able to capture this from the previous parsing - someday) 1314 # 1315 r = KernRe("[-:](.*)") 1316 if r.search(line): 1317 self.entry.declaration_purpose = trim_whitespace(r.group(1)) 1318 self.state = state.DECLARATION 1319 else: 1320 self.entry.declaration_purpose = "" 1321 1322 if not self.entry.declaration_purpose and self.config.wshort_desc: 1323 self.emit_msg(ln, 1324 f"missing initial short description on line:\n{line}") 1325 1326 if not self.entry.identifier and self.entry.decl_type != "enum": 1327 self.emit_msg(ln, 1328 f"wrong kernel-doc identifier on line:\n{line}") 1329 self.state = state.NORMAL 1330 1331 if self.config.verbose: 1332 self.emit_msg(ln, 1333 f"Scanning doc for {self.entry.decl_type} {self.entry.identifier}", 1334 warning=False) 1335 # 1336 # Failed to find an identifier. Emit a warning 1337 # 1338 else: 1339 self.emit_msg(ln, f"Cannot find identifier on line:\n{line}") 1340 1341 def is_new_section(self, ln, line): 1342 """ 1343 Helper function to determine if a new section is being started. 1344 """ 1345 if doc_sect.search(line): 1346 self.state = state.BODY 1347 # 1348 # Pick out the name of our new section, tweaking it if need be. 1349 # 1350 newsection = doc_sect.group(1) 1351 if newsection.lower() == 'description': 1352 newsection = 'Description' 1353 elif newsection.lower() == 'context': 1354 newsection = 'Context' 1355 self.state = state.SPECIAL_SECTION 1356 elif newsection.lower() in ["@return", "@returns", 1357 "return", "returns"]: 1358 newsection = "Return" 1359 self.state = state.SPECIAL_SECTION 1360 elif newsection[0] == '@': 1361 self.state = state.SPECIAL_SECTION 1362 # 1363 # Initialize the contents, and get the new section going. 1364 # 1365 newcontents = doc_sect.group(2) 1366 if not newcontents: 1367 newcontents = "" 1368 self.dump_section() 1369 self.entry.begin_section(ln, newsection) 1370 self.entry.leading_space = None 1371 1372 self.entry.add_text(newcontents.lstrip()) 1373 return True 1374 return False 1375 1376 def is_comment_end(self, ln, line): 1377 """ 1378 Helper function to detect (and effect) the end of a kerneldoc comment. 1379 """ 1380 if doc_end.search(line): 1381 self.dump_section() 1382 1383 # Look for doc_com + <text> + doc_end: 1384 r = KernRe(r'\s*\*\s*[a-zA-Z_0-9:.]+\*/') 1385 if r.match(line): 1386 self.emit_msg(ln, f"suspicious ending line: {line}") 1387 1388 self.entry.prototype = "" 1389 self.entry.new_start_line = ln + 1 1390 1391 self.state = state.PROTO 1392 return True 1393 return False 1394 1395 1396 def process_decl(self, ln, line): 1397 """ 1398 STATE_DECLARATION: We've seen the beginning of a declaration. 1399 """ 1400 if self.is_new_section(ln, line) or self.is_comment_end(ln, line): 1401 return 1402 # 1403 # Look for anything with the " * " line beginning. 1404 # 1405 if doc_content.search(line): 1406 cont = doc_content.group(1) 1407 # 1408 # A blank line means that we have moved out of the declaration 1409 # part of the comment (without any "special section" parameter 1410 # descriptions). 1411 # 1412 if cont == "": 1413 self.state = state.BODY 1414 # 1415 # Otherwise we have more of the declaration section to soak up. 1416 # 1417 else: 1418 self.entry.declaration_purpose = \ 1419 trim_whitespace(self.entry.declaration_purpose + ' ' + cont) 1420 else: 1421 # Unknown line, ignore 1422 self.emit_msg(ln, f"bad line: {line}") 1423 1424 1425 def process_special(self, ln, line): 1426 """ 1427 STATE_SPECIAL_SECTION: a section ending with a blank line. 1428 """ 1429 # 1430 # If we have hit a blank line (only the " * " marker), then this 1431 # section is done. 1432 # 1433 if KernRe(r"\s*\*\s*$").match(line): 1434 self.entry.begin_section(ln, dump = True) 1435 self.state = state.BODY 1436 return 1437 # 1438 # Not a blank line, look for the other ways to end the section. 1439 # 1440 if self.is_new_section(ln, line) or self.is_comment_end(ln, line): 1441 return 1442 # 1443 # OK, we should have a continuation of the text for this section. 1444 # 1445 if doc_content.search(line): 1446 cont = doc_content.group(1) 1447 # 1448 # If the lines of text after the first in a special section have 1449 # leading white space, we need to trim it out or Sphinx will get 1450 # confused. For the second line (the None case), see what we 1451 # find there and remember it. 1452 # 1453 if self.entry.leading_space is None: 1454 r = KernRe(r'^(\s+)') 1455 if r.match(cont): 1456 self.entry.leading_space = len(r.group(1)) 1457 else: 1458 self.entry.leading_space = 0 1459 # 1460 # Otherwise, before trimming any leading chars, be *sure* 1461 # that they are white space. We should maybe warn if this 1462 # isn't the case. 1463 # 1464 for i in range(0, self.entry.leading_space): 1465 if cont[i] != " ": 1466 self.entry.leading_space = i 1467 break 1468 # 1469 # Add the trimmed result to the section and we're done. 1470 # 1471 self.entry.add_text(cont[self.entry.leading_space:]) 1472 else: 1473 # Unknown line, ignore 1474 self.emit_msg(ln, f"bad line: {line}") 1475 1476 def process_body(self, ln, line): 1477 """ 1478 STATE_BODY: the bulk of a kerneldoc comment. 1479 """ 1480 if self.is_new_section(ln, line) or self.is_comment_end(ln, line): 1481 return 1482 1483 if doc_content.search(line): 1484 cont = doc_content.group(1) 1485 self.entry.add_text(cont) 1486 else: 1487 # Unknown line, ignore 1488 self.emit_msg(ln, f"bad line: {line}") 1489 1490 def process_inline_name(self, ln, line): 1491 """STATE_INLINE_NAME: beginning of docbook comments within a prototype.""" 1492 1493 if doc_inline_sect.search(line): 1494 self.entry.begin_section(ln, doc_inline_sect.group(1)) 1495 self.entry.add_text(doc_inline_sect.group(2).lstrip()) 1496 self.state = state.INLINE_TEXT 1497 elif doc_inline_end.search(line): 1498 self.dump_section() 1499 self.state = state.PROTO 1500 elif doc_content.search(line): 1501 self.emit_msg(ln, f"Incorrect use of kernel-doc format: {line}") 1502 self.state = state.PROTO 1503 # else ... ?? 1504 1505 def process_inline_text(self, ln, line): 1506 """STATE_INLINE_TEXT: docbook comments within a prototype.""" 1507 1508 if doc_inline_end.search(line): 1509 self.dump_section() 1510 self.state = state.PROTO 1511 elif doc_content.search(line): 1512 self.entry.add_text(doc_content.group(1)) 1513 # else ... ?? 1514 1515 def syscall_munge(self, ln, proto): # pylint: disable=W0613 1516 """ 1517 Handle syscall definitions. 1518 """ 1519 1520 is_void = False 1521 1522 # Strip newlines/CR's 1523 proto = re.sub(r'[\r\n]+', ' ', proto) 1524 1525 # Check if it's a SYSCALL_DEFINE0 1526 if 'SYSCALL_DEFINE0' in proto: 1527 is_void = True 1528 1529 # Replace SYSCALL_DEFINE with correct return type & function name 1530 proto = KernRe(r'SYSCALL_DEFINE.*\(').sub('long sys_', proto) 1531 1532 r = KernRe(r'long\s+(sys_.*?),') 1533 if r.search(proto): 1534 proto = KernRe(',').sub('(', proto, count=1) 1535 elif is_void: 1536 proto = KernRe(r'\)').sub('(void)', proto, count=1) 1537 1538 # Now delete all of the odd-numbered commas in the proto 1539 # so that argument types & names don't have a comma between them 1540 count = 0 1541 length = len(proto) 1542 1543 if is_void: 1544 length = 0 # skip the loop if is_void 1545 1546 for ix in range(length): 1547 if proto[ix] == ',': 1548 count += 1 1549 if count % 2 == 1: 1550 proto = proto[:ix] + ' ' + proto[ix + 1:] 1551 1552 return proto 1553 1554 def tracepoint_munge(self, ln, proto): 1555 """ 1556 Handle tracepoint definitions. 1557 """ 1558 1559 tracepointname = None 1560 tracepointargs = None 1561 1562 # Match tracepoint name based on different patterns 1563 r = KernRe(r'TRACE_EVENT\((.*?),') 1564 if r.search(proto): 1565 tracepointname = r.group(1) 1566 1567 r = KernRe(r'DEFINE_SINGLE_EVENT\((.*?),') 1568 if r.search(proto): 1569 tracepointname = r.group(1) 1570 1571 r = KernRe(r'DEFINE_EVENT\((.*?),(.*?),') 1572 if r.search(proto): 1573 tracepointname = r.group(2) 1574 1575 if tracepointname: 1576 tracepointname = tracepointname.lstrip() 1577 1578 r = KernRe(r'TP_PROTO\((.*?)\)') 1579 if r.search(proto): 1580 tracepointargs = r.group(1) 1581 1582 if not tracepointname or not tracepointargs: 1583 self.emit_msg(ln, 1584 f"Unrecognized tracepoint format:\n{proto}\n") 1585 else: 1586 proto = f"static inline void trace_{tracepointname}({tracepointargs})" 1587 self.entry.identifier = f"trace_{self.entry.identifier}" 1588 1589 return proto 1590 1591 def process_proto_function(self, ln, line): 1592 """Ancillary routine to process a function prototype.""" 1593 1594 # strip C99-style comments to end of line 1595 line = KernRe(r"//.*$", re.S).sub('', line) 1596 # 1597 # Soak up the line's worth of prototype text, stopping at { or ; if present. 1598 # 1599 if KernRe(r'\s*#\s*define').match(line): 1600 self.entry.prototype = line 1601 elif not line.startswith('#'): # skip other preprocessor stuff 1602 r = KernRe(r'([^\{]*)') 1603 if r.match(line): 1604 self.entry.prototype += r.group(1) + " " 1605 # 1606 # If we now have the whole prototype, clean it up and declare victory. 1607 # 1608 if '{' in line or ';' in line or KernRe(r'\s*#\s*define').match(line): 1609 # strip comments and surrounding spaces 1610 self.entry.prototype = KernRe(r'/\*.*\*/').sub('', self.entry.prototype).strip() 1611 # 1612 # Handle self.entry.prototypes for function pointers like: 1613 # int (*pcs_config)(struct foo) 1614 # by turning it into 1615 # int pcs_config(struct foo) 1616 # 1617 r = KernRe(r'^(\S+\s+)\(\s*\*(\S+)\)') 1618 self.entry.prototype = r.sub(r'\1\2', self.entry.prototype) 1619 # 1620 # Handle special declaration syntaxes 1621 # 1622 if 'SYSCALL_DEFINE' in self.entry.prototype: 1623 self.entry.prototype = self.syscall_munge(ln, 1624 self.entry.prototype) 1625 else: 1626 r = KernRe(r'TRACE_EVENT|DEFINE_EVENT|DEFINE_SINGLE_EVENT') 1627 if r.search(self.entry.prototype): 1628 self.entry.prototype = self.tracepoint_munge(ln, 1629 self.entry.prototype) 1630 # 1631 # ... and we're done 1632 # 1633 self.dump_function(ln, self.entry.prototype) 1634 self.reset_state(ln) 1635 1636 def process_proto_type(self, ln, line): 1637 """ 1638 Ancillary routine to process a type. 1639 """ 1640 1641 # Strip C99-style comments and surrounding whitespace 1642 line = KernRe(r"//.*$", re.S).sub('', line).strip() 1643 if not line: 1644 return # nothing to see here 1645 1646 # To distinguish preprocessor directive from regular declaration later. 1647 if line.startswith('#'): 1648 line += ";" 1649 # 1650 # Split the declaration on any of { } or ;, and accumulate pieces 1651 # until we hit a semicolon while not inside {brackets} 1652 # 1653 r = KernRe(r'(.*?)([{};])') 1654 for chunk in r.split(line): 1655 if chunk: # Ignore empty matches 1656 self.entry.prototype += chunk 1657 # 1658 # This cries out for a match statement ... someday after we can 1659 # drop Python 3.9 ... 1660 # 1661 if chunk == '{': 1662 self.entry.brcount += 1 1663 elif chunk == '}': 1664 self.entry.brcount -= 1 1665 elif chunk == ';' and self.entry.brcount <= 0: 1666 self.dump_declaration(ln, self.entry.prototype) 1667 self.reset_state(ln) 1668 return 1669 # 1670 # We hit the end of the line while still in the declaration; put 1671 # in a space to represent the newline. 1672 # 1673 self.entry.prototype += ' ' 1674 1675 def process_proto(self, ln, line): 1676 """STATE_PROTO: reading a function/whatever prototype.""" 1677 1678 if doc_inline_oneline.search(line): 1679 self.entry.begin_section(ln, doc_inline_oneline.group(1)) 1680 self.entry.add_text(doc_inline_oneline.group(2)) 1681 self.dump_section() 1682 1683 elif doc_inline_start.search(line): 1684 self.state = state.INLINE_NAME 1685 1686 elif self.entry.decl_type == 'function': 1687 self.process_proto_function(ln, line) 1688 1689 else: 1690 self.process_proto_type(ln, line) 1691 1692 def process_docblock(self, ln, line): 1693 """STATE_DOCBLOCK: within a ``DOC:`` block.""" 1694 1695 if doc_end.search(line): 1696 self.dump_section() 1697 self.output_declaration("doc", self.entry.identifier) 1698 self.reset_state(ln) 1699 1700 elif doc_content.search(line): 1701 self.entry.add_text(doc_content.group(1)) 1702 1703 def parse_export(self): 1704 """ 1705 Parses ``EXPORT_SYMBOL*`` macros from a single Kernel source file. 1706 """ 1707 1708 export_table = set() 1709 1710 try: 1711 with open(self.fname, "r", encoding="utf8", 1712 errors="backslashreplace") as fp: 1713 1714 for line in fp: 1715 self.process_export(export_table, line) 1716 1717 except IOError: 1718 return None 1719 1720 return export_table 1721 1722 #: The state/action table telling us which function to invoke in each state. 1723 state_actions = { 1724 state.NORMAL: process_normal, 1725 state.NAME: process_name, 1726 state.BODY: process_body, 1727 state.DECLARATION: process_decl, 1728 state.SPECIAL_SECTION: process_special, 1729 state.INLINE_NAME: process_inline_name, 1730 state.INLINE_TEXT: process_inline_text, 1731 state.PROTO: process_proto, 1732 state.DOCBLOCK: process_docblock, 1733 } 1734 1735 def parse_kdoc(self): 1736 """ 1737 Open and process each line of a C source file. 1738 The parsing is controlled via a state machine, and the line is passed 1739 to a different process function depending on the state. The process 1740 function may update the state as needed. 1741 1742 Besides parsing kernel-doc tags, it also parses export symbols. 1743 """ 1744 1745 prev = "" 1746 prev_ln = None 1747 export_table = set() 1748 1749 try: 1750 with open(self.fname, "r", encoding="utf8", 1751 errors="backslashreplace") as fp: 1752 for ln, line in enumerate(fp): 1753 1754 line = line.expandtabs().strip("\n") 1755 1756 # Group continuation lines on prototypes 1757 if self.state == state.PROTO: 1758 if line.endswith("\\"): 1759 prev += line.rstrip("\\") 1760 if not prev_ln: 1761 prev_ln = ln 1762 continue 1763 1764 if prev: 1765 ln = prev_ln 1766 line = prev + line 1767 prev = "" 1768 prev_ln = None 1769 1770 self.config.log.debug("%d %s: %s", 1771 ln, state.name[self.state], 1772 line) 1773 1774 # This is an optimization over the original script. 1775 # There, when export_file was used for the same file, 1776 # it was read twice. Here, we use the already-existing 1777 # loop to parse exported symbols as well. 1778 # 1779 if (self.state != state.NORMAL) or \ 1780 not self.process_export(export_table, line): 1781 # Hand this line to the appropriate state handler 1782 self.state_actions[self.state](self, ln, line) 1783 1784 self.emit_unused_warnings() 1785 1786 except OSError: 1787 self.config.log.error(f"Error: Cannot open file {self.fname}") 1788 1789 return export_table, self.entries 1790