aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/lib/kdoc/kdoc_files.py
blob: 9be4a64df71de72572ab107c682eed37443cfd45 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0
# Copyright(c) 2025: Mauro Carvalho Chehab <mchehab@kernel.org>.
#
# pylint: disable=R0903,R0913,R0914,R0917

"""
Parse lernel-doc tags on multiple kernel source files.
"""

import argparse
import logging
import os
import re

from kdoc_parser import KernelDoc
from kdoc_output import OutputFormat


class GlobSourceFiles:
    """
    Parse C source code file names and directories via an Interactor.
    """

    def __init__(self, srctree=None, valid_extensions=None):
        """
        Initialize valid extensions with a tuple.

        If not defined, assume default C extensions (.c and .h)

        It would be possible to use python's glob function, but it is
        very slow, and it is not interactive. So, it would wait to read all
        directories before actually do something.

        So, let's use our own implementation.
        """

        if not valid_extensions:
            self.extensions = (".c", ".h")
        else:
            self.extensions = valid_extensions

        self.srctree = srctree

    def _parse_dir(self, dirname):
        """Internal function to parse files recursively"""

        with os.scandir(dirname) as obj:
            for entry in obj:
                name = os.path.join(dirname, entry.name)

                if entry.is_dir():
                    yield from self._parse_dir(name)

                if not entry.is_file():
                    continue

                basename = os.path.basename(name)

                if not basename.endswith(self.extensions):
                    continue

                yield name

    def parse_files(self, file_list, file_not_found_cb):
        """
        Define an interator to parse all source files from file_list,
        handling directories if any
        """

        if not file_list:
            return

        for fname in file_list:
            if self.srctree:
                f = os.path.join(self.srctree, fname)
            else:
                f = fname

            if os.path.isdir(f):
                yield from self._parse_dir(f)
            elif os.path.isfile(f):
                yield f
            elif file_not_found_cb:
                file_not_found_cb(fname)


class KernelFiles():
    """
    Parse kernel-doc tags on multiple kernel source files.

    There are two type of parsers defined here:
        - self.parse_file(): parses both kernel-doc markups and
          EXPORT_SYMBOL* macros;
        - self.process_export_file(): parses only EXPORT_SYMBOL* macros.
    """

    def warning(self, msg):
        """Ancillary routine to output a warning and increment error count"""

        self.config.log.warning(msg)
        self.errors += 1

    def error(self, msg):
        """Ancillary routine to output an error and increment error count"""

        self.config.log.error(msg)
        self.errors += 1

    def parse_file(self, fname):
        """
        Parse a single Kernel source.
        """

        # Prevent parsing the same file twice if results are cached
        if fname in self.files:
            return

        doc = KernelDoc(self.config, fname)
        export_table, entries = doc.parse_kdoc()

        self.export_table[fname] = export_table

        self.files.add(fname)
        self.export_files.add(fname)      # parse_kdoc() already check exports

        self.results[fname] = entries

    def process_export_file(self, fname):
        """
        Parses EXPORT_SYMBOL* macros from a single Kernel source file.
        """

        # Prevent parsing the same file twice if results are cached
        if fname in self.export_files:
            return

        doc = KernelDoc(self.config, fname)
        export_table = doc.parse_export()

        if not export_table:
            self.error(f"Error: Cannot check EXPORT_SYMBOL* on {fname}")
            export_table = set()

        self.export_table[fname] = export_table
        self.export_files.add(fname)

    def file_not_found_cb(self, fname):
        """
        Callback to warn if a file was not found.
        """

        self.error(f"Cannot find file {fname}")

    def __init__(self, verbose=False, out_style=None,
                 werror=False, wreturn=False, wshort_desc=False,
                 wcontents_before_sections=False,
                 logger=None):
        """
        Initialize startup variables and parse all files
        """

        if not verbose:
            verbose = bool(os.environ.get("KBUILD_VERBOSE", 0))

        if out_style is None:
            out_style = OutputFormat()

        if not werror:
            kcflags = os.environ.get("KCFLAGS", None)
            if kcflags:
                match = re.search(r"(\s|^)-Werror(\s|$)/", kcflags)
                if match:
                    werror = True

            # reading this variable is for backwards compat just in case
            # someone was calling it with the variable from outside the
            # kernel's build system
            kdoc_werror = os.environ.get("KDOC_WERROR", None)
            if kdoc_werror:
                werror = kdoc_werror

        # Some variables are global to the parser logic as a whole as they are
        # used to send control configuration to KernelDoc class. As such,
        # those variables are read-only inside the KernelDoc.
        self.config = argparse.Namespace

        self.config.verbose = verbose
        self.config.werror = werror
        self.config.wreturn = wreturn
        self.config.wshort_desc = wshort_desc
        self.config.wcontents_before_sections = wcontents_before_sections

        if not logger:
            self.config.log = logging.getLogger("kernel-doc")
        else:
            self.config.log = logger

        self.config.warning = self.warning

        self.config.src_tree = os.environ.get("SRCTREE", None)

        # Initialize variables that are internal to KernelFiles

        self.out_style = out_style

        self.errors = 0
        self.results = {}

        self.files = set()
        self.export_files = set()
        self.export_table = {}

    def parse(self, file_list, export_file=None):
        """
        Parse all files
        """

        glob = GlobSourceFiles(srctree=self.config.src_tree)

        for fname in glob.parse_files(file_list, self.file_not_found_cb):
            self.parse_file(fname)

        for fname in glob.parse_files(export_file, self.file_not_found_cb):
            self.process_export_file(fname)

    def out_msg(self, fname, name, arg):
        """
        Return output messages from a file name using the output style
        filtering.

        If output type was not handled by the syler, return None.
        """

        # NOTE: we can add rules here to filter out unwanted parts,
        # although OutputFormat.msg already does that.

        return self.out_style.msg(fname, name, arg)

    def msg(self, enable_lineno=False, export=False, internal=False,
            symbol=None, nosymbol=None, no_doc_sections=False,
            filenames=None, export_file=None):
        """
        Interacts over the kernel-doc results and output messages,
        returning kernel-doc markups on each interaction
        """

        self.out_style.set_config(self.config)

        if not filenames:
            filenames = sorted(self.results.keys())

        glob = GlobSourceFiles(srctree=self.config.src_tree)

        for fname in filenames:
            function_table = set()

            if internal or export:
                if not export_file:
                    export_file = [fname]

                for f in glob.parse_files(export_file, self.file_not_found_cb):
                    function_table |= self.export_table[f]

            if symbol:
                for s in symbol:
                    function_table.add(s)

            self.out_style.set_filter(export, internal, symbol, nosymbol,
                                      function_table, enable_lineno,
                                      no_doc_sections)

            msg = ""
            if fname not in self.results:
                self.config.log.warning("No kernel-doc for file %s", fname)
                continue

            for name, arg in self.results[fname]:
                m = self.out_msg(fname, name, arg)

                if m is None:
                    ln = arg.get("ln", 0)
                    dtype = arg.get('type', "")

                    self.config.log.warning("%s:%d Can't handle %s",
                                            fname, ln, dtype)
                else:
                    msg += m

            if msg:
                yield fname, msg
class='logsubject'>Makefile: Fix compilation of Windows resource fileJohannes Sixt2-3/+3 If the git version number consists of less than three period separated numbers, then the Windows resource file compilation issues a syntax error: $ touch git.rc $ make V=1 git.res GIT_VERSION = 1.9.rc0 windres -O coff \ -DMAJOR=1 -DMINOR=9 -DPATCH=rc0 \ -DGIT_VERSION="\\\"1.9.rc0\\\"" git.rc -o git.res C:\msysgit\msysgit\mingw\bin\windres.exe: git.rc:2: syntax error make: *** [git.res] Error 1 $ Note that -DPATCH=rc0. The values passed via -DMAJOR=, -DMINOR=, and -DPATCH= are used in FILEVERSION and PRODUCTVERSION statements, which expect up to four numeric values. These version numbers are intended for machine consumption. They are typically inspected by installers to decide whether a file to be installed is newer than one that exists on the system, but are not used for much else. We can be pretty certain that there are no tools that look at these version numbers, not even the installer of Git for Windows does. Therefore, to fix the syntax error, fill in only the first two numbers, which we are guaranteed to find in Git version numbers. Signed-off-by: Johannes Sixt <j6t@kdbg.org> Acked-by: Pat Thoyts <patthoyts@users.sourceforge.net> Signed-off-by: Junio C Hamano <gitster@pobox.com> 2014-01-23gitk: Indent word-wrapped lines in commit display headerPaul Mackerras1-1/+1 In the cases where the lines starting with Precedes:, Follows: and Branches: in the commit display are long enough to be word-wrapped, this adds a 1cm margin on the left of the wrapped lines, to make the display more readable. Suggested by Stephen Rothwell. Signed-off-by: Paul Mackerras <paulus@samba.org> 2014-01-23git-svn: memoize _rev_list and rebuildlin zuojian1-3/+38 According to profile data, _rev_list and rebuild consume a large portion of time. Memoize the results of _rev_list and memoize rebuild internals to avoid subprocess invocation. When importing 15152 revisions on a LAN, time improved from 10 hours to 3-4 hours. Signed-off-by: lin zuojian <manjian2006@gmail.com> Signed-off-by: Eric Wong <normalperson@yhbt.net> 2014-01-22Add cross-references between docs for for-each-ref and show-refMichael Haggerty2-0/+5 Add cross-references between the manpages for git-for-each-ref(1) and git-show-ref(1). Signed-off-by: Michael Haggerty <mhagger@alum.mit.edu> Signed-off-by: Junio C Hamano <gitster@pobox.com> 2014-01-22safe_create_leading_directories(): on Windows, \ can separate path componentsMichael Haggerty1-4/+8 When cloning to a directory "C:\foo\bar" from Windows' cmd.exe where "foo" does not exist yet, Git would throw an error like fatal: could not create work tree dir 'c:\foo\bar'.: No such file or directory Fix this by not hard-coding a platform specific directory separator into safe_create_leading_directories(). This patch, including its entire commit message, is derived from a patch by Sebastian Schuberth. Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de> Signed-off-by: Sebastian Schuberth <sschuberth@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com> Signed-off-by: Michael Haggerty <mhagger@alum.mit.edu> Signed-off-by: Junio C Hamano <gitster@pobox.com> 2014-01-22git p4 doc: use two-line style for options with multiple spellingsPete Wyckoff1-2/+4 Thomas Rast noticed the docs have a mix of styles when it comes to options with multiple spellings. Standardize the couple in git-p4.txt that are odd. Instead of: -n, --dry-run:: Do this: -n:: --dry-run:: See http://thread.gmane.org/gmane.comp.version-control.git/219936/focus=219945 Signed-off-by: Pete Wyckoff <pw@padd.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>