gendynapi.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. #!/usr/bin/env python3
  2. # Simple DirectMedia Layer
  3. # Copyright (C) 1997-2023 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 __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('.*extern[ "]*C[ "].*')
  47. reg_comment_remove_content = re.compile('\/\*.*\*/')
  48. reg_parsing_function = re.compile('(.*SDLCALL[^\(\)]*) ([a-zA-Z0-9_]+) *\((.*)\) *;.*')
  49. #eg:
  50. # void (SDLCALL *callback)(void*, int)
  51. # \1(\2)\3
  52. reg_parsing_callback = re.compile('([^\(\)]*)\(([^\(\)]+)\)(.*)')
  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. for line in input:
  62. # Discard pre-processor directives ^#.*
  63. if line.startswith("#"):
  64. continue
  65. # Discard "extern C" line
  66. match = reg_externC.match(line)
  67. if match:
  68. continue
  69. # Remove one line comment /* ... */
  70. # eg: extern DECLSPEC SDL_hid_device * SDLCALL SDL_hid_open_path(const char *path, int bExclusive /* = false */);
  71. line = reg_comment_remove_content.sub('', line)
  72. # Get the comment block /* ... */ across several lines
  73. match_start = "/*" in line
  74. match_end = "*/" in line
  75. if match_start and match_end:
  76. continue
  77. if match_start:
  78. parsing_comment = True
  79. current_comment = line
  80. continue
  81. if match_end:
  82. parsing_comment = False
  83. current_comment += line
  84. continue
  85. if parsing_comment:
  86. current_comment += line
  87. continue
  88. # Get the function prototype across several lines
  89. if parsing_function:
  90. # Append to the current function
  91. current_func += " "
  92. current_func += line.strip()
  93. else:
  94. # if is contains "extern", start grabbing
  95. if "extern" not in line:
  96. continue
  97. # Start grabbing the new function
  98. current_func = line.strip()
  99. parsing_function = True;
  100. # If it contains ';', then the function is complete
  101. if ";" not in current_func:
  102. continue
  103. # Got function/comment, reset vars
  104. parsing_function = False;
  105. func = current_func
  106. comment = current_comment
  107. current_func = ""
  108. current_comment = ""
  109. # Discard if it doesn't contain 'SDLCALL'
  110. if "SDLCALL" not in func:
  111. if args.debug:
  112. print(" Discard, doesn't have SDLCALL: " + func)
  113. continue
  114. # Discard if it contains 'SDLMAIN_DECLSPEC' (these are not SDL symbols).
  115. if "SDLMAIN_DECLSPEC" in func:
  116. if args.debug:
  117. print(" Discard, has SDLMAIN_DECLSPEC: " + func)
  118. continue
  119. if args.debug:
  120. print(" Raw data: " + func);
  121. # Replace unusual stuff...
  122. func = func.replace(" SDL_PRINTF_VARARG_FUNC(1)", "");
  123. func = func.replace(" SDL_PRINTF_VARARG_FUNC(2)", "");
  124. func = func.replace(" SDL_PRINTF_VARARG_FUNC(3)", "");
  125. func = func.replace(" SDL_WPRINTF_VARARG_FUNC(3)", "");
  126. func = func.replace(" SDL_SCANF_VARARG_FUNC(2)", "");
  127. func = func.replace(" __attribute__((analyzer_noreturn))", "");
  128. func = func.replace(" SDL_MALLOC", "");
  129. func = func.replace(" SDL_ALLOC_SIZE2(1, 2)", "");
  130. func = func.replace(" SDL_ALLOC_SIZE(2)", "");
  131. func = re.sub(" SDL_ACQUIRE\(.*\)", "", func);
  132. func = re.sub(" SDL_ACQUIRE_SHARED\(.*\)", "", func);
  133. func = re.sub(" SDL_TRY_ACQUIRE\(.*\)", "", func);
  134. func = re.sub(" SDL_TRY_ACQUIRE_SHARED\(.*\)", "", func);
  135. func = re.sub(" SDL_RELEASE\(.*\)", "", func);
  136. func = re.sub(" SDL_RELEASE_SHARED\(.*\)", "", func);
  137. func = re.sub(" SDL_RELEASE_GENERIC\(.*\)", "", func);
  138. # Should be a valid function here
  139. match = reg_parsing_function.match(func)
  140. if not match:
  141. print("Cannot parse: "+ func)
  142. exit(-1)
  143. func_ret = match.group(1)
  144. func_name = match.group(2)
  145. func_params = match.group(3)
  146. #
  147. # Parse return value
  148. #
  149. func_ret = func_ret.replace('extern', ' ')
  150. func_ret = func_ret.replace('SDLCALL', ' ')
  151. func_ret = func_ret.replace('DECLSPEC', ' ')
  152. # Remove trailing spaces in front of '*'
  153. tmp = ""
  154. while func_ret != tmp:
  155. tmp = func_ret
  156. func_ret = func_ret.replace(' ', ' ')
  157. func_ret = func_ret.replace(' *', '*')
  158. func_ret = func_ret.strip()
  159. #
  160. # Parse parameters
  161. #
  162. func_params = func_params.strip()
  163. if func_params == "":
  164. func_params = "void"
  165. # Identify each function parameters with type and name
  166. # (eventually there are callbacks of several parameters)
  167. tmp = func_params.split(',')
  168. tmp2 = []
  169. param = ""
  170. for t in tmp:
  171. if param == "":
  172. param = t
  173. else:
  174. param = param + "," + t
  175. # Identify a callback or parameter when there is same count of '(' and ')'
  176. if param.count('(') == param.count(')'):
  177. tmp2.append(param.strip())
  178. param = ""
  179. # Process each parameters, separation name and type
  180. func_param_type = []
  181. func_param_name = []
  182. for t in tmp2:
  183. if t == "void":
  184. func_param_type.append(t)
  185. func_param_name.append("")
  186. continue
  187. if t == "...":
  188. func_param_type.append(t)
  189. func_param_name.append("")
  190. continue
  191. param_name = ""
  192. # parameter is a callback
  193. if '(' in t:
  194. match = reg_parsing_callback.match(t)
  195. if not match:
  196. print("cannot parse callback: " + t);
  197. exit(-1)
  198. a = match.group(1).strip()
  199. b = match.group(2).strip()
  200. c = match.group(3).strip()
  201. try:
  202. (param_type, param_name) = b.rsplit('*', 1)
  203. except:
  204. param_type = t;
  205. param_name = "param_name_not_specified"
  206. # bug rsplit ??
  207. if param_name == "":
  208. param_name = "param_name_not_specified"
  209. # reconstruct a callback name for future parsing
  210. func_param_type.append(a + " (" + param_type.strip() + " *REWRITE_NAME)" + c)
  211. func_param_name.append(param_name.strip())
  212. continue
  213. # array like "char *buf[]"
  214. has_array = False
  215. if t.endswith("[]"):
  216. t = t.replace("[]", "")
  217. has_array = True
  218. # pointer
  219. if '*' in t:
  220. try:
  221. (param_type, param_name) = t.rsplit('*', 1)
  222. except:
  223. param_type = t;
  224. param_name = "param_name_not_specified"
  225. # bug rsplit ??
  226. if param_name == "":
  227. param_name = "param_name_not_specified"
  228. val = param_type.strip() + "*REWRITE_NAME"
  229. # Remove trailing spaces in front of '*'
  230. tmp = ""
  231. while val != tmp:
  232. tmp = val
  233. val = val.replace(' ', ' ')
  234. val = val.replace(' *', '*')
  235. # first occurrence
  236. val = val.replace('*', ' *', 1)
  237. val = val.strip()
  238. else: # non pointer
  239. # cut-off last word on
  240. try:
  241. (param_type, param_name) = t.rsplit(' ', 1)
  242. except:
  243. param_type = t;
  244. param_name = "param_name_not_specified"
  245. val = param_type.strip() + " REWRITE_NAME"
  246. # set back array
  247. if has_array:
  248. val += "[]"
  249. func_param_type.append(val)
  250. func_param_name.append(param_name.strip())
  251. new_proc = {}
  252. # Return value type
  253. new_proc['retval'] = func_ret
  254. # List of parameters (type + anonymized param name 'REWRITE_NAME')
  255. new_proc['parameter'] = func_param_type
  256. # Real parameter name, or 'param_name_not_specified'
  257. new_proc['parameter_name'] = func_param_name
  258. # Function name
  259. new_proc['name'] = func_name
  260. # Header file
  261. new_proc['header'] = os.path.basename(filename)
  262. # Function comment
  263. new_proc['comment'] = comment
  264. full_API.append(new_proc)
  265. if args.debug:
  266. pprint.pprint(new_proc);
  267. print("\n")
  268. if func_name not in existing_procs:
  269. print("NEW " + func)
  270. add_dyn_api(new_proc)
  271. # For-End line in input
  272. input.close()
  273. # For-End parsing all files of sdl_list_includes
  274. # Dump API into a json file
  275. full_API_json()
  276. # Check comment formatting
  277. check_comment();
  278. # Dump API into a json file
  279. def full_API_json():
  280. if args.dump:
  281. filename = 'sdl.json'
  282. with open(filename, 'w') as f:
  283. json.dump(full_API, f, indent=4, sort_keys=True)
  284. print("dump API to '%s'" % filename);
  285. # Check public function comments are correct
  286. def check_comment_header():
  287. if not check_comment_header.done:
  288. check_comment_header.done = True
  289. print("")
  290. print("Please fix following warning(s):")
  291. print("-------------------------------")
  292. def check_comment():
  293. check_comment_header.done = False
  294. # Check \param
  295. for i in full_API:
  296. comment = i['comment']
  297. name = i['name']
  298. retval = i['retval']
  299. header = i['header']
  300. expected = len(i['parameter'])
  301. if expected == 1:
  302. if i['parameter'][0] == 'void':
  303. expected = 0;
  304. count = comment.count("\\param")
  305. if count != expected:
  306. # skip SDL_stdinc.h
  307. if header != 'SDL_stdinc.h':
  308. # Warning mismatch \param and function prototype
  309. check_comment_header()
  310. print(" In file %s: function %s() has %d '\\param' but expected %d" % (header, name, count, expected));
  311. # Warning check \param uses the correct parameter name
  312. # skip SDL_stdinc.h
  313. if header != 'SDL_stdinc.h':
  314. parameter_name = i['parameter_name']
  315. for n in parameter_name:
  316. if n != "" and "\\param " + n not in comment:
  317. check_comment_header()
  318. print(" In file %s: function %s() missing '\\param %s'" % (header, name, n));
  319. # Check \returns
  320. for i in full_API:
  321. comment = i['comment']
  322. name = i['name']
  323. retval = i['retval']
  324. header = i['header']
  325. expected = 1
  326. if retval == 'void':
  327. expected = 0;
  328. count = comment.count("\\returns")
  329. if count != expected:
  330. # skip SDL_stdinc.h
  331. if header != 'SDL_stdinc.h':
  332. # Warning mismatch \param and function prototype
  333. check_comment_header()
  334. print(" In file %s: function %s() has %d '\\returns' but expected %d" % (header, name, count, expected));
  335. # Check \since
  336. for i in full_API:
  337. comment = i['comment']
  338. name = i['name']
  339. retval = i['retval']
  340. header = i['header']
  341. expected = 1
  342. count = comment.count("\\since")
  343. if count != expected:
  344. # skip SDL_stdinc.h
  345. if header != 'SDL_stdinc.h':
  346. # Warning mismatch \param and function prototype
  347. check_comment_header()
  348. print(" In file %s: function %s() has %d '\\since' but expected %d" % (header, name, count, expected));
  349. # Parse 'sdl_dynapi_procs_h' file to find existing functions
  350. def find_existing_procs():
  351. reg = re.compile('SDL_DYNAPI_PROC\([^,]*,([^,]*),.*\)')
  352. ret = []
  353. input = open(SDL_DYNAPI_PROCS_H)
  354. for line in input:
  355. match = reg.match(line)
  356. if not match:
  357. continue
  358. existing_func = match.group(1)
  359. ret.append(existing_func);
  360. # print(existing_func)
  361. input.close()
  362. return ret
  363. # Get list of SDL headers
  364. def get_header_list():
  365. reg = re.compile('^.*\.h$')
  366. ret = []
  367. tmp = os.listdir(SDL_INCLUDE_DIR)
  368. for f in tmp:
  369. # Only *.h files
  370. match = reg.match(f)
  371. if not match:
  372. if args.debug:
  373. print("Skip %s" % f)
  374. continue
  375. ret.append(SDL_INCLUDE_DIR / f)
  376. return ret
  377. # Write the new API in files: _procs.h _overrivides.h and .sym
  378. def add_dyn_api(proc):
  379. func_name = proc['name']
  380. func_ret = proc['retval']
  381. func_argtype = proc['parameter']
  382. # File: SDL_dynapi_procs.h
  383. #
  384. # Add at last
  385. # SDL_DYNAPI_PROC(SDL_EGLConfig,SDL_EGL_GetCurrentEGLConfig,(void),(),return)
  386. f = open(SDL_DYNAPI_PROCS_H, "a")
  387. dyn_proc = "SDL_DYNAPI_PROC(" + func_ret + "," + func_name + ",("
  388. i = ord('a')
  389. remove_last = False
  390. for argtype in func_argtype:
  391. # Special case, void has no parameter name
  392. if argtype == "void":
  393. dyn_proc += "void"
  394. continue
  395. # Var name: a, b, c, ...
  396. varname = chr(i)
  397. i += 1
  398. tmp = argtype.replace("REWRITE_NAME", varname)
  399. dyn_proc += tmp + ", "
  400. remove_last = True
  401. # remove last 2 char ', '
  402. if remove_last:
  403. dyn_proc = dyn_proc[:-1]
  404. dyn_proc = dyn_proc[:-1]
  405. dyn_proc += "),("
  406. i = ord('a')
  407. remove_last = False
  408. for argtype in func_argtype:
  409. # Special case, void has no parameter name
  410. if argtype == "void":
  411. continue
  412. # Special case, '...' has no parameter name
  413. if argtype == "...":
  414. continue
  415. # Var name: a, b, c, ...
  416. varname = chr(i)
  417. i += 1
  418. dyn_proc += varname + ","
  419. remove_last = True
  420. # remove last char ','
  421. if remove_last:
  422. dyn_proc = dyn_proc[:-1]
  423. dyn_proc += "),"
  424. if func_ret != "void":
  425. dyn_proc += "return"
  426. dyn_proc += ")"
  427. f.write(dyn_proc + "\n")
  428. f.close()
  429. # File: SDL_dynapi_overrides.h
  430. #
  431. # Add at last
  432. # "#define SDL_DelayNS SDL_DelayNS_REAL
  433. f = open(SDL_DYNAPI_OVERRIDES_H, "a")
  434. f.write("#define " + func_name + " " + func_name + "_REAL\n")
  435. f.close()
  436. # File: SDL_dynapi.sym
  437. #
  438. # Add before "extra symbols go here" line
  439. input = open(SDL_DYNAPI_SYM)
  440. new_input = []
  441. for line in input:
  442. if "extra symbols go here" in line:
  443. new_input.append(" " + func_name + ";\n")
  444. new_input.append(line)
  445. input.close()
  446. f = open(SDL_DYNAPI_SYM, 'w')
  447. for line in new_input:
  448. f.write(line)
  449. f.close()
  450. if __name__ == '__main__':
  451. parser = argparse.ArgumentParser()
  452. parser.add_argument('--dump', help='output all SDL API into a .json file', action='store_true')
  453. parser.add_argument('--debug', help='add debug traces', action='store_true')
  454. args = parser.parse_args()
  455. try:
  456. main()
  457. except Exception as e:
  458. print(e)
  459. exit(-1)
  460. print("done!")
  461. exit(0)