kdoc_parser.py 65 KB

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