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