kdoc_files.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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=R0903,R0913,R0914,R0917
  6. """
  7. Classes for navigating through the files that kernel-doc needs to handle
  8. to generate documentation.
  9. """
  10. import argparse
  11. import logging
  12. import os
  13. import re
  14. from kdoc.kdoc_parser import KernelDoc
  15. from kdoc.kdoc_output import OutputFormat
  16. class GlobSourceFiles:
  17. """
  18. Parse C source code file names and directories via an Interactor.
  19. """
  20. def __init__(self, srctree=None, valid_extensions=None):
  21. """
  22. Initialize valid extensions with a tuple.
  23. If not defined, assume default C extensions (.c and .h)
  24. It would be possible to use python's glob function, but it is
  25. very slow, and it is not interactive. So, it would wait to read all
  26. directories before actually do something.
  27. So, let's use our own implementation.
  28. """
  29. if not valid_extensions:
  30. self.extensions = (".c", ".h")
  31. else:
  32. self.extensions = valid_extensions
  33. self.srctree = srctree
  34. def _parse_dir(self, dirname):
  35. """Internal function to parse files recursively."""
  36. with os.scandir(dirname) as obj:
  37. for entry in obj:
  38. name = os.path.join(dirname, entry.name)
  39. if entry.is_dir(follow_symlinks=False):
  40. yield from self._parse_dir(name)
  41. if not entry.is_file():
  42. continue
  43. basename = os.path.basename(name)
  44. if not basename.endswith(self.extensions):
  45. continue
  46. yield name
  47. def parse_files(self, file_list, file_not_found_cb):
  48. """
  49. Define an iterator to parse all source files from file_list,
  50. handling directories if any.
  51. """
  52. if not file_list:
  53. return
  54. for fname in file_list:
  55. if self.srctree:
  56. f = os.path.join(self.srctree, fname)
  57. else:
  58. f = fname
  59. if os.path.isdir(f):
  60. yield from self._parse_dir(f)
  61. elif os.path.isfile(f):
  62. yield f
  63. elif file_not_found_cb:
  64. file_not_found_cb(fname)
  65. class KernelFiles():
  66. """
  67. Parse kernel-doc tags on multiple kernel source files.
  68. There are two type of parsers defined here:
  69. - self.parse_file(): parses both kernel-doc markups and
  70. ``EXPORT_SYMBOL*`` macros;
  71. - self.process_export_file(): parses only ``EXPORT_SYMBOL*`` macros.
  72. """
  73. def warning(self, msg):
  74. """Ancillary routine to output a warning and increment error count."""
  75. self.config.log.warning(msg)
  76. self.errors += 1
  77. def error(self, msg):
  78. """Ancillary routine to output an error and increment error count."""
  79. self.config.log.error(msg)
  80. self.errors += 1
  81. def parse_file(self, fname):
  82. """
  83. Parse a single Kernel source.
  84. """
  85. # Prevent parsing the same file twice if results are cached
  86. if fname in self.files:
  87. return
  88. doc = KernelDoc(self.config, fname)
  89. export_table, entries = doc.parse_kdoc()
  90. self.export_table[fname] = export_table
  91. self.files.add(fname)
  92. self.export_files.add(fname) # parse_kdoc() already check exports
  93. self.results[fname] = entries
  94. def process_export_file(self, fname):
  95. """
  96. Parses ``EXPORT_SYMBOL*`` macros from a single Kernel source file.
  97. """
  98. # Prevent parsing the same file twice if results are cached
  99. if fname in self.export_files:
  100. return
  101. doc = KernelDoc(self.config, fname)
  102. export_table = doc.parse_export()
  103. if not export_table:
  104. self.error(f"Error: Cannot check EXPORT_SYMBOL* on {fname}")
  105. export_table = set()
  106. self.export_table[fname] = export_table
  107. self.export_files.add(fname)
  108. def file_not_found_cb(self, fname):
  109. """
  110. Callback to warn if a file was not found.
  111. """
  112. self.error(f"Cannot find file {fname}")
  113. def __init__(self, verbose=False, out_style=None,
  114. werror=False, wreturn=False, wshort_desc=False,
  115. wcontents_before_sections=False,
  116. logger=None):
  117. """
  118. Initialize startup variables and parse all files.
  119. """
  120. if not verbose:
  121. verbose = bool(os.environ.get("KBUILD_VERBOSE", 0))
  122. if out_style is None:
  123. out_style = OutputFormat()
  124. if not werror:
  125. kcflags = os.environ.get("KCFLAGS", None)
  126. if kcflags:
  127. match = re.search(r"(\s|^)-Werror(\s|$)/", kcflags)
  128. if match:
  129. werror = True
  130. # reading this variable is for backwards compat just in case
  131. # someone was calling it with the variable from outside the
  132. # kernel's build system
  133. kdoc_werror = os.environ.get("KDOC_WERROR", None)
  134. if kdoc_werror:
  135. werror = kdoc_werror
  136. # Some variables are global to the parser logic as a whole as they are
  137. # used to send control configuration to KernelDoc class. As such,
  138. # those variables are read-only inside the KernelDoc.
  139. self.config = argparse.Namespace
  140. self.config.verbose = verbose
  141. self.config.werror = werror
  142. self.config.wreturn = wreturn
  143. self.config.wshort_desc = wshort_desc
  144. self.config.wcontents_before_sections = wcontents_before_sections
  145. if not logger:
  146. self.config.log = logging.getLogger("kernel-doc")
  147. else:
  148. self.config.log = logger
  149. self.config.warning = self.warning
  150. self.config.src_tree = os.environ.get("SRCTREE", None)
  151. # Initialize variables that are internal to KernelFiles
  152. self.out_style = out_style
  153. self.errors = 0
  154. self.results = {}
  155. self.files = set()
  156. self.export_files = set()
  157. self.export_table = {}
  158. def parse(self, file_list, export_file=None):
  159. """
  160. Parse all files.
  161. """
  162. glob = GlobSourceFiles(srctree=self.config.src_tree)
  163. for fname in glob.parse_files(file_list, self.file_not_found_cb):
  164. self.parse_file(fname)
  165. for fname in glob.parse_files(export_file, self.file_not_found_cb):
  166. self.process_export_file(fname)
  167. def out_msg(self, fname, name, arg):
  168. """
  169. Return output messages from a file name using the output style
  170. filtering.
  171. If output type was not handled by the styler, return None.
  172. """
  173. # NOTE: we can add rules here to filter out unwanted parts,
  174. # although OutputFormat.msg already does that.
  175. return self.out_style.msg(fname, name, arg)
  176. def msg(self, enable_lineno=False, export=False, internal=False,
  177. symbol=None, nosymbol=None, no_doc_sections=False,
  178. filenames=None, export_file=None):
  179. """
  180. Interacts over the kernel-doc results and output messages,
  181. returning kernel-doc markups on each interaction.
  182. """
  183. self.out_style.set_config(self.config)
  184. if not filenames:
  185. filenames = sorted(self.results.keys())
  186. glob = GlobSourceFiles(srctree=self.config.src_tree)
  187. for fname in filenames:
  188. function_table = set()
  189. if internal or export:
  190. if not export_file:
  191. export_file = [fname]
  192. for f in glob.parse_files(export_file, self.file_not_found_cb):
  193. function_table |= self.export_table[f]
  194. if symbol:
  195. for s in symbol:
  196. function_table.add(s)
  197. self.out_style.set_filter(export, internal, symbol, nosymbol,
  198. function_table, enable_lineno,
  199. no_doc_sections)
  200. msg = ""
  201. if fname not in self.results:
  202. self.config.log.warning("No kernel-doc for file %s", fname)
  203. continue
  204. symbols = self.results[fname]
  205. self.out_style.set_symbols(symbols)
  206. for arg in symbols:
  207. m = self.out_msg(fname, arg.name, arg)
  208. if m is None:
  209. ln = arg.get("ln", 0)
  210. dtype = arg.get('type', "")
  211. self.config.log.warning("%s:%d Can't handle %s",
  212. fname, ln, dtype)
  213. else:
  214. msg += m
  215. if msg:
  216. yield fname, msg