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