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