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