gendynapi.py 18 KB

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