parse_data_structs.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0
  3. # Copyright (c) 2016-2025 by Mauro Carvalho Chehab <mchehab@kernel.org>.
  4. # pylint: disable=R0912,R0915
  5. """
  6. Parse a source file or header, creating ReStructured Text cross references.
  7. It accepts an optional file to change the default symbol reference or to
  8. suppress symbols from the output.
  9. It is capable of identifying ``define``, function, ``struct``, ``typedef``,
  10. ``enum`` and ``enum`` symbols and create cross-references for all of them.
  11. It is also capable of distinguish #define used for specifying a Linux
  12. ioctl.
  13. The optional rules file contains a set of rules like::
  14. ignore ioctl VIDIOC_ENUM_FMT
  15. replace ioctl VIDIOC_DQBUF vidioc_qbuf
  16. replace define V4L2_EVENT_MD_FL_HAVE_FRAME_SEQ :c:type:`v4l2_event_motion_det`
  17. """
  18. import os
  19. import re
  20. import sys
  21. class ParseDataStructs:
  22. """
  23. Creates an enriched version of a Kernel header file with cross-links
  24. to each C data structure type.
  25. It is meant to allow having a more comprehensive documentation, where
  26. uAPI headers will create cross-reference links to the code.
  27. It is capable of identifying ``define``, function, ``struct``, ``typedef``,
  28. ``enum`` and ``enum`` symbols and create cross-references for all of them.
  29. It is also capable of distinguish #define used for specifying a Linux
  30. ioctl.
  31. By default, it create rules for all symbols and defines, but it also
  32. allows parsing an exception file. Such file contains a set of rules
  33. using the syntax below:
  34. 1. Ignore rules::
  35. ignore <type> <symbol>`
  36. Removes the symbol from reference generation.
  37. 2. Replace rules::
  38. replace <type> <old_symbol> <new_reference>
  39. Replaces how old_symbol with a new reference. The new_reference can be:
  40. - A simple symbol name;
  41. - A full Sphinx reference.
  42. 3. Namespace rules::
  43. namespace <namespace>
  44. Sets C namespace to be used during cross-reference generation. Can
  45. be overridden by replace rules.
  46. On ignore and replace rules, ``<type>`` can be:
  47. - ``ioctl``: for defines that end with ``_IO*``, e.g. ioctl definitions
  48. - ``define``: for other defines
  49. - ``symbol``: for symbols defined within enums;
  50. - ``typedef``: for typedefs;
  51. - ``enum``: for the name of a non-anonymous enum;
  52. - ``struct``: for structs.
  53. Examples::
  54. ignore define __LINUX_MEDIA_H
  55. ignore ioctl VIDIOC_ENUM_FMT
  56. replace ioctl VIDIOC_DQBUF vidioc_qbuf
  57. replace define V4L2_EVENT_MD_FL_HAVE_FRAME_SEQ :c:type:`v4l2_event_motion_det`
  58. namespace MC
  59. """
  60. #: Parser regex with multiple ways to capture enums.
  61. RE_ENUMS = [
  62. re.compile(r"^\s*enum\s+([\w_]+)\s*\{"),
  63. re.compile(r"^\s*enum\s+([\w_]+)\s*$"),
  64. re.compile(r"^\s*typedef\s*enum\s+([\w_]+)\s*\{"),
  65. re.compile(r"^\s*typedef\s*enum\s+([\w_]+)\s*$"),
  66. ]
  67. #: Parser regex with multiple ways to capture structs.
  68. RE_STRUCTS = [
  69. re.compile(r"^\s*struct\s+([_\w][\w\d_]+)\s*\{"),
  70. re.compile(r"^\s*struct\s+([_\w][\w\d_]+)$"),
  71. re.compile(r"^\s*typedef\s*struct\s+([_\w][\w\d_]+)\s*\{"),
  72. re.compile(r"^\s*typedef\s*struct\s+([_\w][\w\d_]+)$"),
  73. ]
  74. # NOTE: the original code was written a long time before Sphinx C
  75. # domain to have multiple namespaces. To avoid to much turn at the
  76. # existing hyperlinks, the code kept using "c:type" instead of the
  77. # right types. To change that, we need to change the types not only
  78. # here, but also at the uAPI media documentation.
  79. #: Dictionary containing C type identifiers to be transformed.
  80. DEF_SYMBOL_TYPES = {
  81. "ioctl": {
  82. "prefix": "\\ ",
  83. "suffix": "\\ ",
  84. "ref_type": ":ref",
  85. "description": "IOCTL Commands",
  86. },
  87. "define": {
  88. "prefix": "\\ ",
  89. "suffix": "\\ ",
  90. "ref_type": ":ref",
  91. "description": "Macros and Definitions",
  92. },
  93. # We're calling each definition inside an enum as "symbol"
  94. "symbol": {
  95. "prefix": "\\ ",
  96. "suffix": "\\ ",
  97. "ref_type": ":ref",
  98. "description": "Enumeration values",
  99. },
  100. "typedef": {
  101. "prefix": "\\ ",
  102. "suffix": "\\ ",
  103. "ref_type": ":c:type",
  104. "description": "Type Definitions",
  105. },
  106. # This is the description of the enum itself
  107. "enum": {
  108. "prefix": "\\ ",
  109. "suffix": "\\ ",
  110. "ref_type": ":c:type",
  111. "description": "Enumerations",
  112. },
  113. "struct": {
  114. "prefix": "\\ ",
  115. "suffix": "\\ ",
  116. "ref_type": ":c:type",
  117. "description": "Structures",
  118. },
  119. }
  120. def __init__(self, debug: bool = False):
  121. """Initialize internal vars"""
  122. self.debug = debug
  123. self.data = ""
  124. self.symbols = {}
  125. self.namespace = None
  126. self.ignore = []
  127. self.replace = []
  128. for symbol_type in self.DEF_SYMBOL_TYPES:
  129. self.symbols[symbol_type] = {}
  130. def read_exceptions(self, fname: str):
  131. """
  132. Read an optional exceptions file, used to override defaults.
  133. """
  134. if not fname:
  135. return
  136. name = os.path.basename(fname)
  137. with open(fname, "r", encoding="utf-8", errors="backslashreplace") as f:
  138. for ln, line in enumerate(f):
  139. ln += 1
  140. line = line.strip()
  141. if not line or line.startswith("#"):
  142. continue
  143. # ignore rules
  144. match = re.match(r"^ignore\s+(\w+)\s+(\S+)", line)
  145. if match:
  146. self.ignore.append((ln, match.group(1), match.group(2)))
  147. continue
  148. # replace rules
  149. match = re.match(r"^replace\s+(\S+)\s+(\S+)\s+(\S+)", line)
  150. if match:
  151. self.replace.append((ln, match.group(1), match.group(2),
  152. match.group(3)))
  153. continue
  154. match = re.match(r"^namespace\s+(\S+)", line)
  155. if match:
  156. self.namespace = match.group(1)
  157. continue
  158. sys.exit(f"{name}:{ln}: invalid line: {line}")
  159. def apply_exceptions(self):
  160. """
  161. Process exceptions file with rules to ignore or replace references.
  162. """
  163. # Handle ignore rules
  164. for ln, c_type, symbol in self.ignore:
  165. if c_type not in self.DEF_SYMBOL_TYPES:
  166. sys.exit(f"{name}:{ln}: {c_type} is invalid")
  167. d = self.symbols[c_type]
  168. if symbol in d:
  169. del d[symbol]
  170. # Handle replace rules
  171. for ln, c_type, old, new in self.replace:
  172. if c_type not in self.DEF_SYMBOL_TYPES:
  173. sys.exit(f"{name}:{ln}: {c_type} is invalid")
  174. reftype = None
  175. # Parse reference type when the type is specified
  176. match = re.match(r"^\:c\:(\w+)\:\`(.+)\`", new)
  177. if match:
  178. reftype = f":c:{match.group(1)}"
  179. new = match.group(2)
  180. else:
  181. match = re.search(r"(\:ref)\:\`(.+)\`", new)
  182. if match:
  183. reftype = match.group(1)
  184. new = match.group(2)
  185. # If the replacement rule doesn't have a type, get default
  186. if not reftype:
  187. reftype = self.DEF_SYMBOL_TYPES[c_type].get("ref_type")
  188. if not reftype:
  189. reftype = self.DEF_SYMBOL_TYPES[c_type].get("real_type")
  190. new_ref = f"{reftype}:`{old} <{new}>`"
  191. # Change self.symbols to use the replacement rule
  192. if old in self.symbols[c_type]:
  193. (_, ln) = self.symbols[c_type][old]
  194. self.symbols[c_type][old] = (new_ref, ln)
  195. else:
  196. print(f"{name}:{ln}: Warning: can't find {old} {c_type}")
  197. def store_type(self, ln, symbol_type: str, symbol: str,
  198. ref_name: str = None, replace_underscores: bool = True):
  199. """
  200. Store a new symbol at self.symbols under symbol_type.
  201. By default, underscores are replaced by ``-``.
  202. """
  203. defs = self.DEF_SYMBOL_TYPES[symbol_type]
  204. prefix = defs.get("prefix", "")
  205. suffix = defs.get("suffix", "")
  206. ref_type = defs.get("ref_type")
  207. # Determine ref_link based on symbol type
  208. if ref_type or self.namespace:
  209. if not ref_name:
  210. ref_name = symbol.lower()
  211. # c-type references don't support hash
  212. if ref_type == ":ref" and replace_underscores:
  213. ref_name = ref_name.replace("_", "-")
  214. # C domain references may have namespaces
  215. if ref_type.startswith(":c:"):
  216. if self.namespace:
  217. ref_name = f"{self.namespace}.{ref_name}"
  218. if ref_type:
  219. ref_link = f"{ref_type}:`{symbol} <{ref_name}>`"
  220. else:
  221. ref_link = f"`{symbol} <{ref_name}>`"
  222. else:
  223. ref_link = symbol
  224. self.symbols[symbol_type][symbol] = (f"{prefix}{ref_link}{suffix}", ln)
  225. def store_line(self, line):
  226. """
  227. Store a line at self.data, properly indented.
  228. """
  229. line = " " + line.expandtabs()
  230. self.data += line.rstrip(" ")
  231. def parse_file(self, file_in: str, exceptions: str = None):
  232. """
  233. Read a C source file and get identifiers.
  234. """
  235. self.data = ""
  236. is_enum = False
  237. is_comment = False
  238. multiline = ""
  239. self.read_exceptions(exceptions)
  240. with open(file_in, "r",
  241. encoding="utf-8", errors="backslashreplace") as f:
  242. for line_no, line in enumerate(f):
  243. self.store_line(line)
  244. line = line.strip("\n")
  245. # Handle continuation lines
  246. if line.endswith(r"\\"):
  247. multiline += line[-1]
  248. continue
  249. if multiline:
  250. line = multiline + line
  251. multiline = ""
  252. # Handle comments. They can be multilined
  253. if not is_comment:
  254. if re.search(r"/\*.*", line):
  255. is_comment = True
  256. else:
  257. # Strip C99-style comments
  258. line = re.sub(r"(//.*)", "", line)
  259. if is_comment:
  260. if re.search(r".*\*/", line):
  261. is_comment = False
  262. else:
  263. multiline = line
  264. continue
  265. # At this point, line variable may be a multilined statement,
  266. # if lines end with \ or if they have multi-line comments
  267. # With that, it can safely remove the entire comments,
  268. # and there's no need to use re.DOTALL for the logic below
  269. line = re.sub(r"(/\*.*\*/)", "", line)
  270. if not line.strip():
  271. continue
  272. # It can be useful for debug purposes to print the file after
  273. # having comments stripped and multi-lines grouped.
  274. if self.debug > 1:
  275. print(f"line {line_no + 1}: {line}")
  276. # Now the fun begins: parse each type and store it.
  277. # We opted for a two parsing logic here due to:
  278. # 1. it makes easier to debug issues not-parsed symbols;
  279. # 2. we want symbol replacement at the entire content, not
  280. # just when the symbol is detected.
  281. if is_enum:
  282. match = re.match(r"^\s*([_\w][\w\d_]+)\s*[\,=]?", line)
  283. if match:
  284. self.store_type(line_no, "symbol", match.group(1))
  285. if "}" in line:
  286. is_enum = False
  287. continue
  288. match = re.match(r"^\s*#\s*define\s+([\w_]+)\s+_IO", line)
  289. if match:
  290. self.store_type(line_no, "ioctl", match.group(1),
  291. replace_underscores=False)
  292. continue
  293. match = re.match(r"^\s*#\s*define\s+([\w_]+)(\s+|$)", line)
  294. if match:
  295. self.store_type(line_no, "define", match.group(1))
  296. continue
  297. match = re.match(r"^\s*typedef\s+([_\w][\w\d_]+)\s+(.*)\s+([_\w][\w\d_]+);",
  298. line)
  299. if match:
  300. name = match.group(2).strip()
  301. symbol = match.group(3)
  302. self.store_type(line_no, "typedef", symbol, ref_name=name)
  303. continue
  304. for re_enum in self.RE_ENUMS:
  305. match = re_enum.match(line)
  306. if match:
  307. self.store_type(line_no, "enum", match.group(1))
  308. is_enum = True
  309. break
  310. for re_struct in self.RE_STRUCTS:
  311. match = re_struct.match(line)
  312. if match:
  313. self.store_type(line_no, "struct", match.group(1))
  314. break
  315. self.apply_exceptions()
  316. def debug_print(self):
  317. """
  318. Print debug information containing the replacement rules per symbol.
  319. To make easier to check, group them per type.
  320. """
  321. if not self.debug:
  322. return
  323. for c_type, refs in self.symbols.items():
  324. if not refs: # Skip empty dictionaries
  325. continue
  326. print(f"{c_type}:")
  327. for symbol, (ref, ln) in sorted(refs.items()):
  328. print(f" #{ln:<5d} {symbol} -> {ref}")
  329. print()
  330. def gen_output(self):
  331. """Write the formatted output to a file."""
  332. # Avoid extra blank lines
  333. text = re.sub(r"\s+$", "", self.data) + "\n"
  334. text = re.sub(r"\n\s+\n", "\n\n", text)
  335. # Escape Sphinx special characters
  336. text = re.sub(r"([\_\`\*\<\>\&\\\\:\/\|\%\$\#\{\}\~\^])", r"\\\1", text)
  337. # Source uAPI files may have special notes. Use bold font for them
  338. text = re.sub(r"DEPRECATED", "**DEPRECATED**", text)
  339. # Delimiters to catch the entire symbol after escaped
  340. start_delim = r"([ \n\t\(=\*\@])"
  341. end_delim = r"(\s|,|\\=|\\:|\;|\)|\}|\{)"
  342. # Process all reference types
  343. for ref_dict in self.symbols.values():
  344. for symbol, (replacement, _) in ref_dict.items():
  345. symbol = re.escape(re.sub(r"([\_\`\*\<\>\&\\\\:\/])", r"\\\1", symbol))
  346. text = re.sub(fr'{start_delim}{symbol}{end_delim}',
  347. fr'\1{replacement}\2', text)
  348. # Remove "\ " where not needed: before spaces and at the end of lines
  349. text = re.sub(r"\\ ([\n ])", r"\1", text)
  350. text = re.sub(r" \\ ", " ", text)
  351. return text
  352. def gen_toc(self):
  353. """
  354. Create a list of symbols to be part of a TOC contents table.
  355. """
  356. text = []
  357. # Sort symbol types per description
  358. symbol_descriptions = []
  359. for k, v in self.DEF_SYMBOL_TYPES.items():
  360. symbol_descriptions.append((v['description'], k))
  361. symbol_descriptions.sort()
  362. # Process each category
  363. for description, c_type in symbol_descriptions:
  364. refs = self.symbols[c_type]
  365. if not refs: # Skip empty categories
  366. continue
  367. text.append(f"{description}")
  368. text.append("-" * len(description))
  369. text.append("")
  370. # Sort symbols alphabetically
  371. for symbol, (ref, ln) in sorted(refs.items()):
  372. text.append(f"- LINENO_{ln}: {ref}")
  373. text.append("") # Add empty line between categories
  374. return "\n".join(text)
  375. def write_output(self, file_in: str, file_out: str, toc: bool):
  376. """
  377. Write a ReST output file.
  378. """
  379. title = os.path.basename(file_in)
  380. if toc:
  381. text = self.gen_toc()
  382. else:
  383. text = self.gen_output()
  384. with open(file_out, "w", encoding="utf-8", errors="backslashreplace") as f:
  385. f.write(".. -*- coding: utf-8; mode: rst -*-\n\n")
  386. f.write(f"{title}\n")
  387. f.write("=" * len(title) + "\n\n")
  388. if not toc:
  389. f.write(".. parsed-literal::\n\n")
  390. f.write(text)