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