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