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