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