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