gendynapi.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. #!/usr/bin/env python3
  2. # Simple DirectMedia Layer
  3. # Copyright (C) 1997-2024 Sam Lantinga <slouken@libsdl.org>
  4. #
  5. # This software is provided 'as-is', without any express or implied
  6. # warranty. In no event will the authors be held liable for any damages
  7. # arising from the use of this software.
  8. #
  9. # Permission is granted to anyone to use this software for any purpose,
  10. # including commercial applications, and to alter it and redistribute it
  11. # freely, subject to the following restrictions:
  12. #
  13. # 1. The origin of this software must not be misrepresented; you must not
  14. # claim that you wrote the original software. If you use this software
  15. # in a product, an acknowledgment in the product documentation would be
  16. # appreciated but is not required.
  17. # 2. Altered source versions must be plainly marked as such, and must not be
  18. # misrepresented as being the original software.
  19. # 3. This notice may not be removed or altered from any source distribution.
  20. # WHAT IS THIS?
  21. # When you add a public API to SDL, please run this script, make sure the
  22. # output looks sane (git diff, it adds to existing files), and commit it.
  23. # It keeps the dynamic API jump table operating correctly.
  24. #
  25. # OS-specific API:
  26. # After running the script, you have to manually add #ifdef SDL_PLATFORM_WIN32
  27. # or similar around the function in 'SDL_dynapi_procs.h'
  28. #
  29. import argparse
  30. import json
  31. import os
  32. import pathlib
  33. import pprint
  34. import re
  35. SDL_ROOT = pathlib.Path(__file__).resolve().parents[2]
  36. SDL_INCLUDE_DIR = SDL_ROOT / "include/SDL3"
  37. SDL_DYNAPI_PROCS_H = SDL_ROOT / "src/dynapi/SDL_dynapi_procs.h"
  38. SDL_DYNAPI_OVERRIDES_H = SDL_ROOT / "src/dynapi/SDL_dynapi_overrides.h"
  39. SDL_DYNAPI_SYM = SDL_ROOT / "src/dynapi/SDL_dynapi.sym"
  40. full_API = []
  41. def main():
  42. # Parse 'sdl_dynapi_procs_h' file to find existing functions
  43. existing_procs = find_existing_procs()
  44. # Get list of SDL headers
  45. sdl_list_includes = get_header_list()
  46. reg_externC = re.compile(r'.*extern[ "]*C[ "].*')
  47. reg_comment_remove_content = re.compile(r'\/\*.*\*/')
  48. reg_parsing_function = re.compile(r'(.*SDLCALL[^\(\)]*) ([a-zA-Z0-9_]+) *\((.*)\) *;.*')
  49. #eg:
  50. # void (SDLCALL *callback)(void*, int)
  51. # \1(\2)\3
  52. reg_parsing_callback = re.compile(r'([^\(\)]*)\(([^\(\)]+)\)(.*)')
  53. for filename in sdl_list_includes:
  54. if args.debug:
  55. print("Parse header: %s" % filename)
  56. input = open(filename)
  57. parsing_function = False
  58. current_func = ""
  59. parsing_comment = False
  60. current_comment = ""
  61. ignore_wiki_documentation = False
  62. for line in input:
  63. # Skip lines if we're in a wiki documentation block.
  64. if ignore_wiki_documentation:
  65. if line.startswith("#endif"):
  66. ignore_wiki_documentation = False
  67. continue
  68. # Discard wiki documentations blocks.
  69. if line.startswith("#ifdef SDL_WIKI_DOCUMENTATION_SECTION"):
  70. ignore_wiki_documentation = True
  71. continue
  72. # Discard pre-processor directives ^#.*
  73. if line.startswith("#"):
  74. continue
  75. # Discard "extern C" line
  76. match = reg_externC.match(line)
  77. if match:
  78. continue
  79. # Remove one line comment // ...
  80. # eg: extern SDL_DECLSPEC SDL_hid_device * SDLCALL SDL_hid_open_path(const char *path, int bExclusive /* = false */);
  81. line = reg_comment_remove_content.sub('', line)
  82. # Get the comment block /* ... */ across several lines
  83. match_start = "/*" in line
  84. match_end = "*/" in line
  85. if match_start and match_end:
  86. continue
  87. if match_start:
  88. parsing_comment = True
  89. current_comment = line
  90. continue
  91. if match_end:
  92. parsing_comment = False
  93. current_comment += line
  94. continue
  95. if parsing_comment:
  96. current_comment += line
  97. continue
  98. # Get the function prototype across several lines
  99. if parsing_function:
  100. # Append to the current function
  101. current_func += " "
  102. current_func += line.strip()
  103. else:
  104. # if is contains "extern", start grabbing
  105. if "extern" not in line:
  106. continue
  107. # Start grabbing the new function
  108. current_func = line.strip()
  109. parsing_function = True;
  110. # If it contains ';', then the function is complete
  111. if ";" not in current_func:
  112. continue
  113. # Got function/comment, reset vars
  114. parsing_function = False;
  115. func = current_func
  116. comment = current_comment
  117. current_func = ""
  118. current_comment = ""
  119. # Discard if it doesn't contain 'SDLCALL'
  120. if "SDLCALL" not in func:
  121. if args.debug:
  122. print(" Discard, doesn't have SDLCALL: " + func)
  123. continue
  124. # Discard if it contains 'SDLMAIN_DECLSPEC' (these are not SDL symbols).
  125. if "SDLMAIN_DECLSPEC" in func:
  126. if args.debug:
  127. print(" Discard, has SDLMAIN_DECLSPEC: " + func)
  128. continue
  129. if args.debug:
  130. print(" Raw data: " + func);
  131. # Replace unusual stuff...
  132. func = func.replace(" SDL_PRINTF_VARARG_FUNC(1)", "");
  133. func = func.replace(" SDL_PRINTF_VARARG_FUNC(2)", "");
  134. func = func.replace(" SDL_PRINTF_VARARG_FUNC(3)", "");
  135. func = func.replace(" SDL_PRINTF_VARARG_FUNCV(1)", "");
  136. func = func.replace(" SDL_PRINTF_VARARG_FUNCV(2)", "");
  137. func = func.replace(" SDL_PRINTF_VARARG_FUNCV(3)", "");
  138. func = func.replace(" SDL_WPRINTF_VARARG_FUNC(3)", "");
  139. func = func.replace(" SDL_WPRINTF_VARARG_FUNCV(3)", "");
  140. func = func.replace(" SDL_SCANF_VARARG_FUNC(2)", "");
  141. func = func.replace(" SDL_SCANF_VARARG_FUNCV(2)", "");
  142. func = func.replace(" SDL_ANALYZER_NORETURN", "");
  143. func = func.replace(" SDL_MALLOC", "");
  144. func = func.replace(" SDL_ALLOC_SIZE2(1, 2)", "");
  145. func = func.replace(" SDL_ALLOC_SIZE(2)", "");
  146. func = re.sub(r" SDL_ACQUIRE\(.*\)", "", func);
  147. func = re.sub(r" SDL_ACQUIRE_SHARED\(.*\)", "", func);
  148. func = re.sub(r" SDL_TRY_ACQUIRE\(.*\)", "", func);
  149. func = re.sub(r" SDL_TRY_ACQUIRE_SHARED\(.*\)", "", func);
  150. func = re.sub(r" SDL_RELEASE\(.*\)", "", func);
  151. func = re.sub(r" SDL_RELEASE_SHARED\(.*\)", "", func);
  152. func = re.sub(r" SDL_RELEASE_GENERIC\(.*\)", "", func);
  153. # Should be a valid function here
  154. match = reg_parsing_function.match(func)
  155. if not match:
  156. print("Cannot parse: "+ func)
  157. exit(-1)
  158. func_ret = match.group(1)
  159. func_name = match.group(2)
  160. func_params = match.group(3)
  161. #
  162. # Parse return value
  163. #
  164. func_ret = func_ret.replace('extern', ' ')
  165. func_ret = func_ret.replace('SDLCALL', ' ')
  166. func_ret = func_ret.replace('SDL_DECLSPEC', ' ')
  167. # Remove trailing spaces in front of '*'
  168. tmp = ""
  169. while func_ret != tmp:
  170. tmp = func_ret
  171. func_ret = func_ret.replace(' ', ' ')
  172. func_ret = func_ret.replace(' *', '*')
  173. func_ret = func_ret.strip()
  174. #
  175. # Parse parameters
  176. #
  177. func_params = func_params.strip()
  178. if func_params == "":
  179. func_params = "void"
  180. # Identify each function parameters with type and name
  181. # (eventually there are callbacks of several parameters)
  182. tmp = func_params.split(',')
  183. tmp2 = []
  184. param = ""
  185. for t in tmp:
  186. if param == "":
  187. param = t
  188. else:
  189. param = param + "," + t
  190. # Identify a callback or parameter when there is same count of '(' and ')'
  191. if param.count('(') == param.count(')'):
  192. tmp2.append(param.strip())
  193. param = ""
  194. # Process each parameters, separation name and type
  195. func_param_type = []
  196. func_param_name = []
  197. for t in tmp2:
  198. if t == "void":
  199. func_param_type.append(t)
  200. func_param_name.append("")
  201. continue
  202. if t == "...":
  203. func_param_type.append(t)
  204. func_param_name.append("")
  205. continue
  206. param_name = ""
  207. # parameter is a callback
  208. if '(' in t:
  209. match = reg_parsing_callback.match(t)
  210. if not match:
  211. print("cannot parse callback: " + t);
  212. exit(-1)
  213. a = match.group(1).strip()
  214. b = match.group(2).strip()
  215. c = match.group(3).strip()
  216. try:
  217. (param_type, param_name) = b.rsplit('*', 1)
  218. except:
  219. param_type = t;
  220. param_name = "param_name_not_specified"
  221. # bug rsplit ??
  222. if param_name == "":
  223. param_name = "param_name_not_specified"
  224. # reconstruct a callback name for future parsing
  225. func_param_type.append(a + " (" + param_type.strip() + " *REWRITE_NAME)" + c)
  226. func_param_name.append(param_name.strip())
  227. continue
  228. # array like "char *buf[]"
  229. has_array = False
  230. if t.endswith("[]"):
  231. t = t.replace("[]", "")
  232. has_array = True
  233. # pointer
  234. if '*' in t:
  235. try:
  236. (param_type, param_name) = t.rsplit('*', 1)
  237. except:
  238. param_type = t;
  239. param_name = "param_name_not_specified"
  240. # bug rsplit ??
  241. if param_name == "":
  242. param_name = "param_name_not_specified"
  243. val = param_type.strip() + "*REWRITE_NAME"
  244. # Remove trailing spaces in front of '*'
  245. tmp = ""
  246. while val != tmp:
  247. tmp = val
  248. val = val.replace(' ', ' ')
  249. val = val.replace(' *', '*')
  250. # first occurrence
  251. val = val.replace('*', ' *', 1)
  252. val = val.strip()
  253. else: # non pointer
  254. # cut-off last word on
  255. try:
  256. (param_type, param_name) = t.rsplit(' ', 1)
  257. except:
  258. param_type = t;
  259. param_name = "param_name_not_specified"
  260. val = param_type.strip() + " REWRITE_NAME"
  261. # set back array
  262. if has_array:
  263. val += "[]"
  264. func_param_type.append(val)
  265. func_param_name.append(param_name.strip())
  266. new_proc = {}
  267. # Return value type
  268. new_proc['retval'] = func_ret
  269. # List of parameters (type + anonymized param name 'REWRITE_NAME')
  270. new_proc['parameter'] = func_param_type
  271. # Real parameter name, or 'param_name_not_specified'
  272. new_proc['parameter_name'] = func_param_name
  273. # Function name
  274. new_proc['name'] = func_name
  275. # Header file
  276. new_proc['header'] = os.path.basename(filename)
  277. # Function comment
  278. new_proc['comment'] = comment
  279. full_API.append(new_proc)
  280. if args.debug:
  281. pprint.pprint(new_proc);
  282. print("\n")
  283. if func_name not in existing_procs:
  284. print("NEW " + func)
  285. add_dyn_api(new_proc)
  286. # For-End line in input
  287. input.close()
  288. # For-End parsing all files of sdl_list_includes
  289. # Dump API into a json file
  290. full_API_json()
  291. # Check comment formatting
  292. check_comment();
  293. # Dump API into a json file
  294. def full_API_json():
  295. if args.dump:
  296. filename = 'sdl.json'
  297. with open(filename, 'w', newline='') as f:
  298. json.dump(full_API, f, indent=4, sort_keys=True)
  299. print("dump API to '%s'" % filename);
  300. # Check public function comments are correct
  301. def check_comment_header():
  302. if not check_comment_header.done:
  303. check_comment_header.done = True
  304. print("")
  305. print("Please fix following warning(s):")
  306. print("-------------------------------")
  307. def check_comment():
  308. check_comment_header.done = False
  309. # Check \param
  310. for i in full_API:
  311. comment = i['comment']
  312. name = i['name']
  313. retval = i['retval']
  314. header = i['header']
  315. expected = len(i['parameter'])
  316. if expected == 1:
  317. if i['parameter'][0] == 'void':
  318. expected = 0;
  319. count = comment.count("\\param")
  320. if count != expected:
  321. # skip SDL_stdinc.h
  322. if header != 'SDL_stdinc.h':
  323. # Warning mismatch \param and function prototype
  324. check_comment_header()
  325. print(" In file %s: function %s() has %d '\\param' but expected %d" % (header, name, count, expected));
  326. # Warning check \param uses the correct parameter name
  327. # skip SDL_stdinc.h
  328. if header != 'SDL_stdinc.h':
  329. parameter_name = i['parameter_name']
  330. for n in parameter_name:
  331. if n != "" and "\\param " + n not in comment and "\\param[out] " + n not in comment:
  332. check_comment_header()
  333. print(" In file %s: function %s() missing '\\param %s'" % (header, name, n));
  334. # Check \returns
  335. for i in full_API:
  336. comment = i['comment']
  337. name = i['name']
  338. retval = i['retval']
  339. header = i['header']
  340. expected = 1
  341. if retval == 'void':
  342. expected = 0;
  343. count = comment.count("\\returns")
  344. if count != expected:
  345. # skip SDL_stdinc.h
  346. if header != 'SDL_stdinc.h':
  347. # Warning mismatch \param and function prototype
  348. check_comment_header()
  349. print(" In file %s: function %s() has %d '\\returns' but expected %d" % (header, name, count, expected));
  350. # Check \since
  351. for i in full_API:
  352. comment = i['comment']
  353. name = i['name']
  354. retval = i['retval']
  355. header = i['header']
  356. expected = 1
  357. count = comment.count("\\since")
  358. if count != expected:
  359. # skip SDL_stdinc.h
  360. if header != 'SDL_stdinc.h':
  361. # Warning mismatch \param and function prototype
  362. check_comment_header()
  363. print(" In file %s: function %s() has %d '\\since' but expected %d" % (header, name, count, expected));
  364. # Parse 'sdl_dynapi_procs_h' file to find existing functions
  365. def find_existing_procs():
  366. reg = re.compile(r'SDL_DYNAPI_PROC\([^,]*,([^,]*),.*\)')
  367. ret = []
  368. input = open(SDL_DYNAPI_PROCS_H)
  369. for line in input:
  370. match = reg.match(line)
  371. if not match:
  372. continue
  373. existing_func = match.group(1)
  374. ret.append(existing_func);
  375. # print(existing_func)
  376. input.close()
  377. return ret
  378. # Get list of SDL headers
  379. def get_header_list():
  380. reg = re.compile(r'^.*\.h$')
  381. ret = []
  382. tmp = os.listdir(SDL_INCLUDE_DIR)
  383. for f in tmp:
  384. # Only *.h files
  385. match = reg.match(f)
  386. if not match:
  387. if args.debug:
  388. print("Skip %s" % f)
  389. continue
  390. ret.append(SDL_INCLUDE_DIR / f)
  391. return ret
  392. # Write the new API in files: _procs.h _overrivides.h and .sym
  393. def add_dyn_api(proc):
  394. func_name = proc['name']
  395. func_ret = proc['retval']
  396. func_argtype = proc['parameter']
  397. # File: SDL_dynapi_procs.h
  398. #
  399. # Add at last
  400. # SDL_DYNAPI_PROC(SDL_EGLConfig,SDL_EGL_GetCurrentConfig,(void),(),return)
  401. f = open(SDL_DYNAPI_PROCS_H, "a", newline="")
  402. dyn_proc = "SDL_DYNAPI_PROC(" + func_ret + "," + func_name + ",("
  403. i = ord('a')
  404. remove_last = False
  405. for argtype in func_argtype:
  406. # Special case, void has no parameter name
  407. if argtype == "void":
  408. dyn_proc += "void"
  409. continue
  410. # Var name: a, b, c, ...
  411. varname = chr(i)
  412. i += 1
  413. tmp = argtype.replace("REWRITE_NAME", varname)
  414. dyn_proc += tmp + ", "
  415. remove_last = True
  416. # remove last 2 char ', '
  417. if remove_last:
  418. dyn_proc = dyn_proc[:-1]
  419. dyn_proc = dyn_proc[:-1]
  420. dyn_proc += "),("
  421. i = ord('a')
  422. remove_last = False
  423. for argtype in func_argtype:
  424. # Special case, void has no parameter name
  425. if argtype == "void":
  426. continue
  427. # Special case, '...' has no parameter name
  428. if argtype == "...":
  429. continue
  430. # Var name: a, b, c, ...
  431. varname = chr(i)
  432. i += 1
  433. dyn_proc += varname + ","
  434. remove_last = True
  435. # remove last char ','
  436. if remove_last:
  437. dyn_proc = dyn_proc[:-1]
  438. dyn_proc += "),"
  439. if func_ret != "void":
  440. dyn_proc += "return"
  441. dyn_proc += ")"
  442. f.write(dyn_proc + "\n")
  443. f.close()
  444. # File: SDL_dynapi_overrides.h
  445. #
  446. # Add at last
  447. # "#define SDL_DelayNS SDL_DelayNS_REAL
  448. f = open(SDL_DYNAPI_OVERRIDES_H, "a", newline="")
  449. f.write("#define " + func_name + " " + func_name + "_REAL\n")
  450. f.close()
  451. # File: SDL_dynapi.sym
  452. #
  453. # Add before "extra symbols go here" line
  454. input = open(SDL_DYNAPI_SYM)
  455. new_input = []
  456. for line in input:
  457. if "extra symbols go here" in line:
  458. new_input.append(" " + func_name + ";\n")
  459. new_input.append(line)
  460. input.close()
  461. f = open(SDL_DYNAPI_SYM, 'w', newline='')
  462. for line in new_input:
  463. f.write(line)
  464. f.close()
  465. if __name__ == '__main__':
  466. parser = argparse.ArgumentParser()
  467. parser.add_argument('--dump', help='output all SDL API into a .json file', action='store_true')
  468. parser.add_argument('--debug', help='add debug traces', action='store_true')
  469. args = parser.parse_args()
  470. try:
  471. main()
  472. except Exception as e:
  473. print(e)
  474. exit(-1)
  475. print("done!")
  476. exit(0)