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