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