parse.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import os
  2. def parse_distributions_h(ffi, inc_dir):
  3. """
  4. Parse distributions.h located in inc_dir for CFFI, filling in the ffi.cdef
  5. Read the function declarations without the "#define ..." macros that will
  6. be filled in when loading the library.
  7. """
  8. with open(os.path.join(inc_dir, 'random', 'bitgen.h')) as fid:
  9. s = []
  10. for line in fid:
  11. # massage the include file
  12. if line.strip().startswith('#'):
  13. continue
  14. s.append(line)
  15. ffi.cdef('\n'.join(s))
  16. with open(os.path.join(inc_dir, 'random', 'distributions.h')) as fid:
  17. s = []
  18. in_skip = 0
  19. ignoring = False
  20. for line in fid:
  21. # check for and remove extern "C" guards
  22. if ignoring:
  23. if line.strip().startswith('#endif'):
  24. ignoring = False
  25. continue
  26. if line.strip().startswith('#ifdef __cplusplus'):
  27. ignoring = True
  28. # massage the include file
  29. if line.strip().startswith('#'):
  30. continue
  31. # skip any inlined function definition
  32. # which starts with 'static NPY_INLINE xxx(...) {'
  33. # and ends with a closing '}'
  34. if line.strip().startswith('static NPY_INLINE'):
  35. in_skip += line.count('{')
  36. continue
  37. elif in_skip > 0:
  38. in_skip += line.count('{')
  39. in_skip -= line.count('}')
  40. continue
  41. # replace defines with their value or remove them
  42. line = line.replace('DECLDIR', '')
  43. line = line.replace('NPY_INLINE', '')
  44. line = line.replace('RAND_INT_TYPE', 'int64_t')
  45. s.append(line)
  46. ffi.cdef('\n'.join(s))