···582582 ("kernel-documentation", "Kernel", "Kernel", "J. Random Bozo"),583583]584584585585-# kernel-doc extension configuration for running Sphinx directly (e.g. by Read586586-# the Docs). In a normal build, these are supplied from the Makefile via command587587-# line arguments.588588-kerneldoc_bin = "../scripts/kernel-doc.py"589585kerneldoc_srctree = ".."590586591587def setup(app):
+4-4
Documentation/doc-guide/kernel-doc.rst
···5454output generation may be used to verify proper formatting of the5555documentation comments. For example::56565757- scripts/kernel-doc -v -none drivers/foo/bar.c5757+ tools/docs/kernel-doc -v -none drivers/foo/bar.c58585959The documentation format of ``.c`` files is also verified by the kernel build6060when it is requested to perform extra gcc checks::···365365left parenthesis ('(') for function-like macros or not followed by one366366for object-like macros.367367368368-Function-like macros are handled like functions by ``scripts/kernel-doc``.368368+Function-like macros are handled like functions by ``tools/docs/kernel-doc``.369369They may have a parameter list. Object-like macros have do not have a370370parameter list.371371···596596597597The kernel-doc extension is included in the kernel source tree, at598598``Documentation/sphinx/kerneldoc.py``. Internally, it uses the599599-``scripts/kernel-doc`` script to extract the documentation comments from the600600-source.599599+``tools/docs/kernel-doc`` script to extract the documentation comments from600600+the source.601601602602.. _kernel_doc:603603
+1-1
Documentation/kbuild/kbuild.rst
···180180KDOCFLAGS181181---------182182Specify extra (warning/error) flags for kernel-doc checks during the build,183183-see scripts/kernel-doc for which flags are supported. Note that this doesn't183183+see tools/docs/kernel-doc for which flags are supported. Note that this doesn't184184(currently) apply to documentation builds.185185186186ARCH
+1-1
Documentation/process/coding-style.rst
···614614615615When commenting the kernel API functions, please use the kernel-doc format.616616See the files at :ref:`Documentation/doc-guide/ <doc_guide>` and617617-``scripts/kernel-doc`` for details. Note that the danger of over-commenting617617+``tools/docs/kernel-doc`` for details. Note that the danger of over-commenting618618applies to kernel-doc comments all the same. Do not add boilerplate619619kernel-doc which simply reiterates what's obvious from the signature620620of the function.
+11-49
Documentation/sphinx/kerneldoc.py
···4747from kdoc.kdoc_files import KernelFiles4848from kdoc.kdoc_output import RestFormat49495050+# Used when verbose is active to show how to reproduce kernel-doc5151+# issues via command line5252+kerneldoc_bin = "tools/docs/kernel-doc"5353+5054__version__ = '1.0'5155kfiles = None5256logger = logging.getLogger(__name__)···9995 def handle_args(self):1009610197 env = self.state.document.settings.env102102- cmd = [env.config.kerneldoc_bin, '-rst', '-enable-lineno']9898+ cmd = [kerneldoc_bin, '-rst', '-enable-lineno']10399104100 filename = env.config.kerneldoc_srctree + '/' + self.arguments[0]105101···194190195191 return cmd196192197197- def run_cmd(self, cmd):198198- """199199- Execute an external kernel-doc command.200200- """201201-202202- env = self.state.document.settings.env203203- node = nodes.section()204204-205205- p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)206206- out, err = p.communicate()207207-208208- out, err = codecs.decode(out, 'utf-8'), codecs.decode(err, 'utf-8')209209-210210- if p.returncode != 0:211211- sys.stderr.write(err)212212-213213- logger.warning("kernel-doc '%s' failed with return code %d"214214- % (" ".join(cmd), p.returncode))215215- return [nodes.error(None, nodes.paragraph(text = "kernel-doc missing"))]216216- elif env.config.kerneldoc_verbosity > 0:217217- sys.stderr.write(err)218218-219219- filenames = self.parse_args["file_list"]220220- for filename in filenames:221221- self.parse_msg(filename, node, out, cmd)222222-223223- return node.children224224-225225- def parse_msg(self, filename, node, out, cmd):193193+ def parse_msg(self, filename, node, out):226194 """227195 Handles a kernel-doc output for a given file228196 """···220244221245 self.do_parse(result, node)222246223223- def run_kdoc(self, cmd, kfiles):247247+ def run_kdoc(self, kfiles):224248 """225249 Execute kernel-doc classes directly instead of running as a separate226250 command.···234258 filenames = self.parse_args["file_list"]235259236260 for filename, out in kfiles.msg(**self.msg_args, filenames=filenames):237237- self.parse_msg(filename, node, out, cmd)261261+ self.parse_msg(filename, node, out)238262239263 return node.children240264241265 def run(self):242242- global kfiles243243-244266 cmd = self.handle_args()245267 if self.verbose >= 1:246268 logger.info(cmd_str(cmd))247269248270 try:249249- if kfiles:250250- return self.run_kdoc(cmd, kfiles)251251- else:252252- return self.run_cmd(cmd)253253-271271+ return self.run_kdoc(kfiles)254272 except Exception as e: # pylint: disable=W0703255273 logger.warning("kernel-doc '%s' processing failed with: %s" %256274 (cmd_str(cmd), pformat(e)))···256286257287def setup_kfiles(app):258288 global kfiles259259-260260- kerneldoc_bin = app.env.config.kerneldoc_bin261261-262262- if kerneldoc_bin and kerneldoc_bin.endswith("kernel-doc.py"):263263- print("Using Python kernel-doc")264264- out_style = RestFormat()265265- kfiles = KernelFiles(out_style=out_style, logger=logger)266266- else:267267- print(f"Using {kerneldoc_bin}")289289+ out_style = RestFormat()290290+ kfiles = KernelFiles(out_style=out_style, logger=logger)268291269292270293def setup(app):271271- app.add_config_value('kerneldoc_bin', None, 'env')272294 app.add_config_value('kerneldoc_srctree', None, 'env')273295 app.add_config_value('kerneldoc_verbosity', 1, 'env')274296
···8080eseguire il programma ``kernel-doc`` con un livello di verbosità alto e senza8181che questo produca alcuna documentazione. Per esempio::82828383- scripts/kernel-doc -v -none drivers/foo/bar.c8383+ tools/docs/kernel-doc -v -none drivers/foo/bar.c84848585Il formato della documentazione è verificato della procedura di generazione8686del kernel quando viene richiesto di effettuare dei controlli extra con GCC::···378378immediatamente seguito da una parentesi sinistra ('(') mentre in quelle simili a379379oggetti no.380380381381-Le macro simili a funzioni sono gestite come funzioni da ``scripts/kernel-doc``.381381+Le macro simili a funzioni sono gestite come funzioni da ``tools/docs/kernel-doc``.382382Possono avere un elenco di parametri. Le macro simili a oggetti non hanno un383383elenco di parametri.384384···595595596596L'estensione kernel-doc fa parte dei sorgenti del kernel, la si può trovare597597in ``Documentation/sphinx/kerneldoc.py``. Internamente, viene utilizzato598598-lo script ``scripts/kernel-doc`` per estrarre i commenti di documentazione598598+lo script ``tools/docs/kernel-doc`` per estrarre i commenti di documentazione599599dai file sorgenti.600600601601Come utilizzare kernel-doc per generare pagine man···604604Se volete utilizzare kernel-doc solo per generare delle pagine man, potete605605farlo direttamente dai sorgenti del kernel::606606607607- $ scripts/kernel-doc -man $(git grep -l '/\*\*' -- :^Documentation :^tools) | scripts/split-man.pl /tmp/man607607+ $ tools/docs/kernel-doc -man $(git grep -l '/\*\*' -- :^Documentation :^tools) | scripts/split-man.pl /tmp/man
···633633634634Al comentar las funciones de la API del kernel, utilice el formato635635kernel-doc. Consulte los archivos en :ref:`Documentation/doc-guide/ <doc_guide>`636636-y ``scripts/kernel-doc`` para más detalles.636636+y ``tools/docs/kernel-doc`` para más detalles.637637638638El estilo preferido para comentarios largos (de varias líneas) es:639639
···460460461461# the KERNELDOC macro needs to be exported, as scripts/Makefile.build462462# has a logic to call it463463-KERNELDOC = $(srctree)/scripts/kernel-doc.py463463+KERNELDOC = $(srctree)/tools/docs/kernel-doc464464export KERNELDOC465465466466KBUILD_USERHOSTCFLAGS := -Wall -Wmissing-prototypes -Wstrict-prototypes \
···33# Copyright(c) 2025: Mauro Carvalho Chehab <mchehab@kernel.org>.44#55# pylint: disable=C0103,R0912,R0914,R091566-66+#77# NOTE: While kernel-doc requires at least version 3.6 to run, the88# command line should work with Python 3.2+ (tested with 3.4).99# The rationale is that it shall fail gracefully during Kernel1010# compilation with older Kernel versions. Due to that:1111# - encoding line is needed here;1212-# - no f-strings can be used on this file.1313-# - the libraries that require newer versions can only be included1414-# after Python version is checked.1515-1212+# - f-strings cannot be used in this file.1313+# - libraries that require newer versions can only be included1414+# after the Python version has been checked.1515+#1616# Converted from the kernel-doc script originally written in Perl1717# under GPLv2, copyrighted since 1998 by the following authors:1818#···8888# Yujie Liu <yujie.liu@intel.com>89899090"""9191-kernel_doc9292-==========9393-9494-Print formatted kernel documentation to stdout9191+Print formatted kernel documentation to stdout.95929693Read C language source or header FILEs, extract embedded9794documentation comments, and print formatted documentation9895to standard output.9996100100-The documentation comments are identified by the "/**"9797+The documentation comments are identified by the ``/**``10198opening comment mark.10299103100See Documentation/doc-guide/kernel-doc.rst for the···108111109112# Import Python modules110113111111-LIB_DIR = "../tools/lib/python"114114+LIB_DIR = "../lib/python"112115SRC_DIR = os.path.dirname(os.path.realpath(__file__))113116114117sys.path.insert(0, os.path.join(SRC_DIR, LIB_DIR))118118+119119+WERROR_RETURN_CODE = 3115120116121DESC = """117122Read C language source or header FILEs, extract embedded documentation comments,···131132"""132133133134EXPORT_DESC = """134134-Only output documentation for the symbols that have been135135+Only output documentation for symbols that have been135136exported using EXPORT_SYMBOL() and related macros in any input136137FILE or -export-file FILE.137138"""138139139140INTERNAL_DESC = """140140-Only output documentation for the symbols that have NOT been141141+Only output documentation for symbols that have NOT been141142exported using EXPORT_SYMBOL() and related macros in any input142143FILE or -export-file FILE.143144"""···160161"""161162162163WARN_CONTENTS_BEFORE_SECTIONS_DESC = """163163-Warns if there are contents before sections (deprecated).164164+Warn if there are contents before sections (deprecated).164165165166This option is kept just for backward-compatibility, but it does nothing,166167neither here nor at the original Perl script.167168"""168169170170+EPILOG = """171171+The return value is:172172+173173+- 0: success or Python version is not compatible with174174+kernel-doc. If -Werror is not used, it will also175175+return 0 if there are issues at kernel-doc markups;176176+177177+- 1: an abnormal condition happened;178178+179179+- 2: argparse issued an error;180180+181181+- 3: When -Werror is used, it means that one or more unfiltered parse182182+ warnings happened.183183+"""169184170185class MsgFormatter(logging.Formatter):171171- """Helper class to format warnings on a similar way to kernel-doc.pl"""186186+ """187187+ Helper class to capitalize errors and warnings, the same way188188+ the venerable (now retired) kernel-doc.pl used to do.189189+ """172190173191 def format(self, record):174192 record.levelname = record.levelname.capitalize()175193 return logging.Formatter.format(self, record)176194177195def main():178178- """Main program"""196196+ """197197+ Main program.198198+199199+ """179200180201 parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,181181- description=DESC)202202+ description=DESC, epilog=EPILOG)182203204204+ #183205 # Normal arguments184184-206206+ #185207 parser.add_argument("-v", "-verbose", "--verbose", action="store_true",186208 help="Verbose output, more warnings and other information.")187209···217197 action="store_true",218198 help="Enable line number output (only in ReST mode)")219199200200+ #220201 # Arguments to control the warning behavior221221-202202+ #222203 parser.add_argument("-Wreturn", "--wreturn", action="store_true",223204 help="Warns about the lack of a return markup on functions.")224205···240219 parser.add_argument("-export-file", "--export-file", action='append',241220 help=EXPORT_FILE_DESC)242221222222+ #243223 # Output format mutually-exclusive group244244-224224+ #245225 out_group = parser.add_argument_group("Output format selection (mutually exclusive)")246226247227 out_fmt = out_group.add_mutually_exclusive_group()···254232 out_fmt.add_argument("-N", "-none", "--none", action="store_true",255233 help="Do not output documentation, only warnings.")256234235235+ #257236 # Output selection mutually-exclusive group258258-237237+ #259238 sel_group = parser.add_argument_group("Output selection (mutually exclusive)")260239 sel_mut = sel_group.add_mutually_exclusive_group()261240···269246 sel_mut.add_argument("-s", "-function", "--symbol", action='append',270247 help=FUNCTION_DESC)271248249249+ #272250 # Those are valid for all 3 types of filter251251+ #273252 parser.add_argument("-n", "-nosymbol", "--nosymbol", action='append',274253 help=NOSYMBOL_DESC)275254276255 parser.add_argument("-D", "-no-doc-sections", "--no-doc-sections",277277- action='store_true', help="Don't outputt DOC sections")256256+ action='store_true', help="Don't output DOC sections")278257279258 parser.add_argument("files", metavar="FILE",280259 nargs="+", help=FILES_DESC)···304279305280 python_ver = sys.version_info[:2]306281 if python_ver < (3,6):307307- # Depending on Kernel configuration, kernel-doc --none is called at282282+ #283283+ # Depending on the Kernel configuration, kernel-doc --none is called at308284 # build time. As we don't want to break compilation due to the309285 # usage of an old Python version, return 0 here.286286+ #310287 if args.none:311311- logger.error("Python 3.6 or later is required by kernel-doc. skipping checks")288288+ logger.error("Python 3.6 or later is required by kernel-doc. Skipping checks")312289 sys.exit(0)313290314291 sys.exit("Python 3.6 or later is required by kernel-doc. Aborting.")···318291 if python_ver < (3,7):319292 logger.warning("Python 3.7 or later is required for correct results")320293321321- # Import kernel-doc libraries only after checking Python version294294+ #295295+ # Import kernel-doc libraries only after checking the Python version296296+ #322297 from kdoc.kdoc_files import KernelFiles # pylint: disable=C0415323298 from kdoc.kdoc_output import RestFormat, ManFormat # pylint: disable=C0415324299···352323353324 if args.werror:354325 print("%s warnings as errors" % error_count) # pylint: disable=C0209355355- sys.exit(error_count)326326+ sys.exit(WERROR_RETURN_CODE)356327357328 if args.verbose:358329 print("%s errors" % error_count) # pylint: disable=C0209359330360360- if args.none:361361- sys.exit(0)331331+ sys.exit(0)362332363363- sys.exit(error_count)364364-365365-333333+#366334# Call main method335335+#367336if __name__ == "__main__":368337 main()
+1-1
tools/docs/find-unused-docs.sh
···5454 if [[ ${FILES_INCLUDED[$file]+_} ]]; then5555 continue;5656 fi5757- str=$(PYTHONDONTWRITEBYTECODE=1 scripts/kernel-doc -export "$file" 2>/dev/null)5757+ str=$(PYTHONDONTWRITEBYTECODE=1 tools/docs/kernel-doc -export "$file" 2>/dev/null)5858 if [[ -n "$str" ]]; then5959 echo "$file"6060 fi
···295295296296 # TODO: rename to emit_message after removal of kernel-doc.pl297297 def emit_msg(self, ln, msg, *, warning=True):298298- """Emit a message"""298298+ """Emit a message."""299299300300 log_msg = f"{self.fname}:{ln} {msg}"301301···448448449449 self.config.log.debug("Output: %s:%s = %s", dtype, name, pformat(args))450450451451+ def emit_unused_warnings(self):452452+ """453453+ When the parser fails to produce a valid entry, it places some454454+ warnings under `entry.warnings` that will be discarded when resetting455455+ the state.456456+457457+ Ensure that those warnings are not lost.458458+459459+ .. note::460460+461461+ Because we are calling `config.warning()` here, those462462+ warnings are not filtered by the `-W` parameters: they will all463463+ be produced even when `-Wreturn`, `-Wshort-desc`, and/or464464+ `-Wcontents-before-sections` are used.465465+466466+ Allowing those warnings to be filtered is complex, because it467467+ would require storing them in a buffer and then filtering them468468+ during the output step of the code, depending on the469469+ selected symbols.470470+ """471471+ if self.entry and self.entry not in self.entries:472472+ for log_msg in self.entry.warnings:473473+ self.config.warning(log_msg)474474+451475 def reset_state(self, ln):452476 """453477 Ancillary routine to create a new entry. It initializes all454478 variables used by the state machine.455479 """456480457457- #458458- # Flush the warnings out before we proceed further459459- #460460- if self.entry and self.entry not in self.entries:461461- for log_msg in self.entry.warnings:462462- self.config.log.warning(log_msg)481481+ self.emit_unused_warnings()463482464483 self.entry = KernelEntry(self.config, self.fname, ln)465484···17591740 not self.process_export(export_table, line):17601741 # Hand this line to the appropriate state handler17611742 self.state_actions[self.state](self, ln, line)17431743+17441744+ self.emit_unused_warnings()1762174517631746 except OSError:17641747 self.config.log.error(f"Error: Cannot open file {self.fname}")