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