Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cparser.py 43KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. from . import model
  2. from .commontypes import COMMON_TYPES, resolve_common_type
  3. from .error import FFIError, CDefError
  4. try:
  5. from . import _pycparser as pycparser
  6. except ImportError:
  7. import pycparser
  8. import weakref, re, sys
  9. try:
  10. if sys.version_info < (3,):
  11. import thread as _thread
  12. else:
  13. import _thread
  14. lock = _thread.allocate_lock()
  15. except ImportError:
  16. lock = None
  17. def _workaround_for_static_import_finders():
  18. # Issue #392: packaging tools like cx_Freeze can not find these
  19. # because pycparser uses exec dynamic import. This is an obscure
  20. # workaround. This function is never called.
  21. import pycparser.yacctab
  22. import pycparser.lextab
  23. CDEF_SOURCE_STRING = "<cdef source string>"
  24. _r_comment = re.compile(r"/\*.*?\*/|//([^\n\\]|\\.)*?$",
  25. re.DOTALL | re.MULTILINE)
  26. _r_define = re.compile(r"^\s*#\s*define\s+([A-Za-z_][A-Za-z_0-9]*)"
  27. r"\b((?:[^\n\\]|\\.)*?)$",
  28. re.DOTALL | re.MULTILINE)
  29. _r_line_directive = re.compile(r"^[ \t]*#[ \t]*(?:line|\d+)\b.*$", re.MULTILINE)
  30. _r_partial_enum = re.compile(r"=\s*\.\.\.\s*[,}]|\.\.\.\s*\}")
  31. _r_enum_dotdotdot = re.compile(r"__dotdotdot\d+__$")
  32. _r_partial_array = re.compile(r"\[\s*\.\.\.\s*\]")
  33. _r_words = re.compile(r"\w+|\S")
  34. _parser_cache = None
  35. _r_int_literal = re.compile(r"-?0?x?[0-9a-f]+[lu]*$", re.IGNORECASE)
  36. _r_stdcall1 = re.compile(r"\b(__stdcall|WINAPI)\b")
  37. _r_stdcall2 = re.compile(r"[(]\s*(__stdcall|WINAPI)\b")
  38. _r_cdecl = re.compile(r"\b__cdecl\b")
  39. _r_extern_python = re.compile(r'\bextern\s*"'
  40. r'(Python|Python\s*\+\s*C|C\s*\+\s*Python)"\s*.')
  41. _r_star_const_space = re.compile( # matches "* const "
  42. r"[*]\s*((const|volatile|restrict)\b\s*)+")
  43. _r_int_dotdotdot = re.compile(r"(\b(int|long|short|signed|unsigned|char)\s*)+"
  44. r"\.\.\.")
  45. _r_float_dotdotdot = re.compile(r"\b(double|float)\s*\.\.\.")
  46. def _get_parser():
  47. global _parser_cache
  48. if _parser_cache is None:
  49. _parser_cache = pycparser.CParser()
  50. return _parser_cache
  51. def _workaround_for_old_pycparser(csource):
  52. # Workaround for a pycparser issue (fixed between pycparser 2.10 and
  53. # 2.14): "char*const***" gives us a wrong syntax tree, the same as
  54. # for "char***(*const)". This means we can't tell the difference
  55. # afterwards. But "char(*const(***))" gives us the right syntax
  56. # tree. The issue only occurs if there are several stars in
  57. # sequence with no parenthesis inbetween, just possibly qualifiers.
  58. # Attempt to fix it by adding some parentheses in the source: each
  59. # time we see "* const" or "* const *", we add an opening
  60. # parenthesis before each star---the hard part is figuring out where
  61. # to close them.
  62. parts = []
  63. while True:
  64. match = _r_star_const_space.search(csource)
  65. if not match:
  66. break
  67. #print repr(''.join(parts)+csource), '=>',
  68. parts.append(csource[:match.start()])
  69. parts.append('('); closing = ')'
  70. parts.append(match.group()) # e.g. "* const "
  71. endpos = match.end()
  72. if csource.startswith('*', endpos):
  73. parts.append('('); closing += ')'
  74. level = 0
  75. i = endpos
  76. while i < len(csource):
  77. c = csource[i]
  78. if c == '(':
  79. level += 1
  80. elif c == ')':
  81. if level == 0:
  82. break
  83. level -= 1
  84. elif c in ',;=':
  85. if level == 0:
  86. break
  87. i += 1
  88. csource = csource[endpos:i] + closing + csource[i:]
  89. #print repr(''.join(parts)+csource)
  90. parts.append(csource)
  91. return ''.join(parts)
  92. def _preprocess_extern_python(csource):
  93. # input: `extern "Python" int foo(int);` or
  94. # `extern "Python" { int foo(int); }`
  95. # output:
  96. # void __cffi_extern_python_start;
  97. # int foo(int);
  98. # void __cffi_extern_python_stop;
  99. #
  100. # input: `extern "Python+C" int foo(int);`
  101. # output:
  102. # void __cffi_extern_python_plus_c_start;
  103. # int foo(int);
  104. # void __cffi_extern_python_stop;
  105. parts = []
  106. while True:
  107. match = _r_extern_python.search(csource)
  108. if not match:
  109. break
  110. endpos = match.end() - 1
  111. #print
  112. #print ''.join(parts)+csource
  113. #print '=>'
  114. parts.append(csource[:match.start()])
  115. if 'C' in match.group(1):
  116. parts.append('void __cffi_extern_python_plus_c_start; ')
  117. else:
  118. parts.append('void __cffi_extern_python_start; ')
  119. if csource[endpos] == '{':
  120. # grouping variant
  121. closing = csource.find('}', endpos)
  122. if closing < 0:
  123. raise CDefError("'extern \"Python\" {': no '}' found")
  124. if csource.find('{', endpos + 1, closing) >= 0:
  125. raise NotImplementedError("cannot use { } inside a block "
  126. "'extern \"Python\" { ... }'")
  127. parts.append(csource[endpos+1:closing])
  128. csource = csource[closing+1:]
  129. else:
  130. # non-grouping variant
  131. semicolon = csource.find(';', endpos)
  132. if semicolon < 0:
  133. raise CDefError("'extern \"Python\": no ';' found")
  134. parts.append(csource[endpos:semicolon+1])
  135. csource = csource[semicolon+1:]
  136. parts.append(' void __cffi_extern_python_stop;')
  137. #print ''.join(parts)+csource
  138. #print
  139. parts.append(csource)
  140. return ''.join(parts)
  141. def _warn_for_string_literal(csource):
  142. if '"' not in csource:
  143. return
  144. for line in csource.splitlines():
  145. if '"' in line and not line.lstrip().startswith('#'):
  146. import warnings
  147. warnings.warn("String literal found in cdef() or type source. "
  148. "String literals are ignored here, but you should "
  149. "remove them anyway because some character sequences "
  150. "confuse pre-parsing.")
  151. break
  152. def _warn_for_non_extern_non_static_global_variable(decl):
  153. if not decl.storage:
  154. import warnings
  155. warnings.warn("Global variable '%s' in cdef(): for consistency "
  156. "with C it should have a storage class specifier "
  157. "(usually 'extern')" % (decl.name,))
  158. def _remove_line_directives(csource):
  159. # _r_line_directive matches whole lines, without the final \n, if they
  160. # start with '#line' with some spacing allowed, or '#NUMBER'. This
  161. # function stores them away and replaces them with exactly the string
  162. # '#line@N', where N is the index in the list 'line_directives'.
  163. line_directives = []
  164. def replace(m):
  165. i = len(line_directives)
  166. line_directives.append(m.group())
  167. return '#line@%d' % i
  168. csource = _r_line_directive.sub(replace, csource)
  169. return csource, line_directives
  170. def _put_back_line_directives(csource, line_directives):
  171. def replace(m):
  172. s = m.group()
  173. if not s.startswith('#line@'):
  174. raise AssertionError("unexpected #line directive "
  175. "(should have been processed and removed")
  176. return line_directives[int(s[6:])]
  177. return _r_line_directive.sub(replace, csource)
  178. def _preprocess(csource):
  179. # First, remove the lines of the form '#line N "filename"' because
  180. # the "filename" part could confuse the rest
  181. csource, line_directives = _remove_line_directives(csource)
  182. # Remove comments. NOTE: this only work because the cdef() section
  183. # should not contain any string literals (except in line directives)!
  184. def replace_keeping_newlines(m):
  185. return ' ' + m.group().count('\n') * '\n'
  186. csource = _r_comment.sub(replace_keeping_newlines, csource)
  187. # Remove the "#define FOO x" lines
  188. macros = {}
  189. for match in _r_define.finditer(csource):
  190. macroname, macrovalue = match.groups()
  191. macrovalue = macrovalue.replace('\\\n', '').strip()
  192. macros[macroname] = macrovalue
  193. csource = _r_define.sub('', csource)
  194. #
  195. if pycparser.__version__ < '2.14':
  196. csource = _workaround_for_old_pycparser(csource)
  197. #
  198. # BIG HACK: replace WINAPI or __stdcall with "volatile const".
  199. # It doesn't make sense for the return type of a function to be
  200. # "volatile volatile const", so we abuse it to detect __stdcall...
  201. # Hack number 2 is that "int(volatile *fptr)();" is not valid C
  202. # syntax, so we place the "volatile" before the opening parenthesis.
  203. csource = _r_stdcall2.sub(' volatile volatile const(', csource)
  204. csource = _r_stdcall1.sub(' volatile volatile const ', csource)
  205. csource = _r_cdecl.sub(' ', csource)
  206. #
  207. # Replace `extern "Python"` with start/end markers
  208. csource = _preprocess_extern_python(csource)
  209. #
  210. # Now there should not be any string literal left; warn if we get one
  211. _warn_for_string_literal(csource)
  212. #
  213. # Replace "[...]" with "[__dotdotdotarray__]"
  214. csource = _r_partial_array.sub('[__dotdotdotarray__]', csource)
  215. #
  216. # Replace "...}" with "__dotdotdotNUM__}". This construction should
  217. # occur only at the end of enums; at the end of structs we have "...;}"
  218. # and at the end of vararg functions "...);". Also replace "=...[,}]"
  219. # with ",__dotdotdotNUM__[,}]": this occurs in the enums too, when
  220. # giving an unknown value.
  221. matches = list(_r_partial_enum.finditer(csource))
  222. for number, match in enumerate(reversed(matches)):
  223. p = match.start()
  224. if csource[p] == '=':
  225. p2 = csource.find('...', p, match.end())
  226. assert p2 > p
  227. csource = '%s,__dotdotdot%d__ %s' % (csource[:p], number,
  228. csource[p2+3:])
  229. else:
  230. assert csource[p:p+3] == '...'
  231. csource = '%s __dotdotdot%d__ %s' % (csource[:p], number,
  232. csource[p+3:])
  233. # Replace "int ..." or "unsigned long int..." with "__dotdotdotint__"
  234. csource = _r_int_dotdotdot.sub(' __dotdotdotint__ ', csource)
  235. # Replace "float ..." or "double..." with "__dotdotdotfloat__"
  236. csource = _r_float_dotdotdot.sub(' __dotdotdotfloat__ ', csource)
  237. # Replace all remaining "..." with the same name, "__dotdotdot__",
  238. # which is declared with a typedef for the purpose of C parsing.
  239. csource = csource.replace('...', ' __dotdotdot__ ')
  240. # Finally, put back the line directives
  241. csource = _put_back_line_directives(csource, line_directives)
  242. return csource, macros
  243. def _common_type_names(csource):
  244. # Look in the source for what looks like usages of types from the
  245. # list of common types. A "usage" is approximated here as the
  246. # appearance of the word, minus a "definition" of the type, which
  247. # is the last word in a "typedef" statement. Approximative only
  248. # but should be fine for all the common types.
  249. look_for_words = set(COMMON_TYPES)
  250. look_for_words.add(';')
  251. look_for_words.add(',')
  252. look_for_words.add('(')
  253. look_for_words.add(')')
  254. look_for_words.add('typedef')
  255. words_used = set()
  256. is_typedef = False
  257. paren = 0
  258. previous_word = ''
  259. for word in _r_words.findall(csource):
  260. if word in look_for_words:
  261. if word == ';':
  262. if is_typedef:
  263. words_used.discard(previous_word)
  264. look_for_words.discard(previous_word)
  265. is_typedef = False
  266. elif word == 'typedef':
  267. is_typedef = True
  268. paren = 0
  269. elif word == '(':
  270. paren += 1
  271. elif word == ')':
  272. paren -= 1
  273. elif word == ',':
  274. if is_typedef and paren == 0:
  275. words_used.discard(previous_word)
  276. look_for_words.discard(previous_word)
  277. else: # word in COMMON_TYPES
  278. words_used.add(word)
  279. previous_word = word
  280. return words_used
  281. class Parser(object):
  282. def __init__(self):
  283. self._declarations = {}
  284. self._included_declarations = set()
  285. self._anonymous_counter = 0
  286. self._structnode2type = weakref.WeakKeyDictionary()
  287. self._options = {}
  288. self._int_constants = {}
  289. self._recomplete = []
  290. self._uses_new_feature = None
  291. def _parse(self, csource):
  292. csource, macros = _preprocess(csource)
  293. # XXX: for more efficiency we would need to poke into the
  294. # internals of CParser... the following registers the
  295. # typedefs, because their presence or absence influences the
  296. # parsing itself (but what they are typedef'ed to plays no role)
  297. ctn = _common_type_names(csource)
  298. typenames = []
  299. for name in sorted(self._declarations):
  300. if name.startswith('typedef '):
  301. name = name[8:]
  302. typenames.append(name)
  303. ctn.discard(name)
  304. typenames += sorted(ctn)
  305. #
  306. csourcelines = []
  307. csourcelines.append('# 1 "<cdef automatic initialization code>"')
  308. for typename in typenames:
  309. csourcelines.append('typedef int %s;' % typename)
  310. csourcelines.append('typedef int __dotdotdotint__, __dotdotdotfloat__,'
  311. ' __dotdotdot__;')
  312. # this forces pycparser to consider the following in the file
  313. # called <cdef source string> from line 1
  314. csourcelines.append('# 1 "%s"' % (CDEF_SOURCE_STRING,))
  315. csourcelines.append(csource)
  316. fullcsource = '\n'.join(csourcelines)
  317. if lock is not None:
  318. lock.acquire() # pycparser is not thread-safe...
  319. try:
  320. ast = _get_parser().parse(fullcsource)
  321. except pycparser.c_parser.ParseError as e:
  322. self.convert_pycparser_error(e, csource)
  323. finally:
  324. if lock is not None:
  325. lock.release()
  326. # csource will be used to find buggy source text
  327. return ast, macros, csource
  328. def _convert_pycparser_error(self, e, csource):
  329. # xxx look for "<cdef source string>:NUM:" at the start of str(e)
  330. # and interpret that as a line number. This will not work if
  331. # the user gives explicit ``# NUM "FILE"`` directives.
  332. line = None
  333. msg = str(e)
  334. match = re.match(r"%s:(\d+):" % (CDEF_SOURCE_STRING,), msg)
  335. if match:
  336. linenum = int(match.group(1), 10)
  337. csourcelines = csource.splitlines()
  338. if 1 <= linenum <= len(csourcelines):
  339. line = csourcelines[linenum-1]
  340. return line
  341. def convert_pycparser_error(self, e, csource):
  342. line = self._convert_pycparser_error(e, csource)
  343. msg = str(e)
  344. if line:
  345. msg = 'cannot parse "%s"\n%s' % (line.strip(), msg)
  346. else:
  347. msg = 'parse error\n%s' % (msg,)
  348. raise CDefError(msg)
  349. def parse(self, csource, override=False, packed=False, pack=None,
  350. dllexport=False):
  351. if packed:
  352. if packed != True:
  353. raise ValueError("'packed' should be False or True; use "
  354. "'pack' to give another value")
  355. if pack:
  356. raise ValueError("cannot give both 'pack' and 'packed'")
  357. pack = 1
  358. elif pack:
  359. if pack & (pack - 1):
  360. raise ValueError("'pack' must be a power of two, not %r" %
  361. (pack,))
  362. else:
  363. pack = 0
  364. prev_options = self._options
  365. try:
  366. self._options = {'override': override,
  367. 'packed': pack,
  368. 'dllexport': dllexport}
  369. self._internal_parse(csource)
  370. finally:
  371. self._options = prev_options
  372. def _internal_parse(self, csource):
  373. ast, macros, csource = self._parse(csource)
  374. # add the macros
  375. self._process_macros(macros)
  376. # find the first "__dotdotdot__" and use that as a separator
  377. # between the repeated typedefs and the real csource
  378. iterator = iter(ast.ext)
  379. for decl in iterator:
  380. if decl.name == '__dotdotdot__':
  381. break
  382. else:
  383. assert 0
  384. current_decl = None
  385. #
  386. try:
  387. self._inside_extern_python = '__cffi_extern_python_stop'
  388. for decl in iterator:
  389. current_decl = decl
  390. if isinstance(decl, pycparser.c_ast.Decl):
  391. self._parse_decl(decl)
  392. elif isinstance(decl, pycparser.c_ast.Typedef):
  393. if not decl.name:
  394. raise CDefError("typedef does not declare any name",
  395. decl)
  396. quals = 0
  397. if (isinstance(decl.type.type, pycparser.c_ast.IdentifierType) and
  398. decl.type.type.names[-1].startswith('__dotdotdot')):
  399. realtype = self._get_unknown_type(decl)
  400. elif (isinstance(decl.type, pycparser.c_ast.PtrDecl) and
  401. isinstance(decl.type.type, pycparser.c_ast.TypeDecl) and
  402. isinstance(decl.type.type.type,
  403. pycparser.c_ast.IdentifierType) and
  404. decl.type.type.type.names[-1].startswith('__dotdotdot')):
  405. realtype = self._get_unknown_ptr_type(decl)
  406. else:
  407. realtype, quals = self._get_type_and_quals(
  408. decl.type, name=decl.name, partial_length_ok=True,
  409. typedef_example="*(%s *)0" % (decl.name,))
  410. self._declare('typedef ' + decl.name, realtype, quals=quals)
  411. elif decl.__class__.__name__ == 'Pragma':
  412. pass # skip pragma, only in pycparser 2.15
  413. else:
  414. raise CDefError("unexpected <%s>: this construct is valid "
  415. "C but not valid in cdef()" %
  416. decl.__class__.__name__, decl)
  417. except CDefError as e:
  418. if len(e.args) == 1:
  419. e.args = e.args + (current_decl,)
  420. raise
  421. except FFIError as e:
  422. msg = self._convert_pycparser_error(e, csource)
  423. if msg:
  424. e.args = (e.args[0] + "\n *** Err: %s" % msg,)
  425. raise
  426. def _add_constants(self, key, val):
  427. if key in self._int_constants:
  428. if self._int_constants[key] == val:
  429. return # ignore identical double declarations
  430. raise FFIError(
  431. "multiple declarations of constant: %s" % (key,))
  432. self._int_constants[key] = val
  433. def _add_integer_constant(self, name, int_str):
  434. int_str = int_str.lower().rstrip("ul")
  435. neg = int_str.startswith('-')
  436. if neg:
  437. int_str = int_str[1:]
  438. # "010" is not valid oct in py3
  439. if (int_str.startswith("0") and int_str != '0'
  440. and not int_str.startswith("0x")):
  441. int_str = "0o" + int_str[1:]
  442. pyvalue = int(int_str, 0)
  443. if neg:
  444. pyvalue = -pyvalue
  445. self._add_constants(name, pyvalue)
  446. self._declare('macro ' + name, pyvalue)
  447. def _process_macros(self, macros):
  448. for key, value in macros.items():
  449. value = value.strip()
  450. if _r_int_literal.match(value):
  451. self._add_integer_constant(key, value)
  452. elif value == '...':
  453. self._declare('macro ' + key, value)
  454. else:
  455. raise CDefError(
  456. 'only supports one of the following syntax:\n'
  457. ' #define %s ... (literally dot-dot-dot)\n'
  458. ' #define %s NUMBER (with NUMBER an integer'
  459. ' constant, decimal/hex/octal)\n'
  460. 'got:\n'
  461. ' #define %s %s'
  462. % (key, key, key, value))
  463. def _declare_function(self, tp, quals, decl):
  464. tp = self._get_type_pointer(tp, quals)
  465. if self._options.get('dllexport'):
  466. tag = 'dllexport_python '
  467. elif self._inside_extern_python == '__cffi_extern_python_start':
  468. tag = 'extern_python '
  469. elif self._inside_extern_python == '__cffi_extern_python_plus_c_start':
  470. tag = 'extern_python_plus_c '
  471. else:
  472. tag = 'function '
  473. self._declare(tag + decl.name, tp)
  474. def _parse_decl(self, decl):
  475. node = decl.type
  476. if isinstance(node, pycparser.c_ast.FuncDecl):
  477. tp, quals = self._get_type_and_quals(node, name=decl.name)
  478. assert isinstance(tp, model.RawFunctionType)
  479. self._declare_function(tp, quals, decl)
  480. else:
  481. if isinstance(node, pycparser.c_ast.Struct):
  482. self._get_struct_union_enum_type('struct', node)
  483. elif isinstance(node, pycparser.c_ast.Union):
  484. self._get_struct_union_enum_type('union', node)
  485. elif isinstance(node, pycparser.c_ast.Enum):
  486. self._get_struct_union_enum_type('enum', node)
  487. elif not decl.name:
  488. raise CDefError("construct does not declare any variable",
  489. decl)
  490. #
  491. if decl.name:
  492. tp, quals = self._get_type_and_quals(node,
  493. partial_length_ok=True)
  494. if tp.is_raw_function:
  495. self._declare_function(tp, quals, decl)
  496. elif (tp.is_integer_type() and
  497. hasattr(decl, 'init') and
  498. hasattr(decl.init, 'value') and
  499. _r_int_literal.match(decl.init.value)):
  500. self._add_integer_constant(decl.name, decl.init.value)
  501. elif (tp.is_integer_type() and
  502. isinstance(decl.init, pycparser.c_ast.UnaryOp) and
  503. decl.init.op == '-' and
  504. hasattr(decl.init.expr, 'value') and
  505. _r_int_literal.match(decl.init.expr.value)):
  506. self._add_integer_constant(decl.name,
  507. '-' + decl.init.expr.value)
  508. elif (tp is model.void_type and
  509. decl.name.startswith('__cffi_extern_python_')):
  510. # hack: `extern "Python"` in the C source is replaced
  511. # with "void __cffi_extern_python_start;" and
  512. # "void __cffi_extern_python_stop;"
  513. self._inside_extern_python = decl.name
  514. else:
  515. if self._inside_extern_python !='__cffi_extern_python_stop':
  516. raise CDefError(
  517. "cannot declare constants or "
  518. "variables with 'extern \"Python\"'")
  519. if (quals & model.Q_CONST) and not tp.is_array_type:
  520. self._declare('constant ' + decl.name, tp, quals=quals)
  521. else:
  522. _warn_for_non_extern_non_static_global_variable(decl)
  523. self._declare('variable ' + decl.name, tp, quals=quals)
  524. def parse_type(self, cdecl):
  525. return self.parse_type_and_quals(cdecl)[0]
  526. def parse_type_and_quals(self, cdecl):
  527. ast, macros = self._parse('void __dummy(\n%s\n);' % cdecl)[:2]
  528. assert not macros
  529. exprnode = ast.ext[-1].type.args.params[0]
  530. if isinstance(exprnode, pycparser.c_ast.ID):
  531. raise CDefError("unknown identifier '%s'" % (exprnode.name,))
  532. return self._get_type_and_quals(exprnode.type)
  533. def _declare(self, name, obj, included=False, quals=0):
  534. if name in self._declarations:
  535. prevobj, prevquals = self._declarations[name]
  536. if prevobj is obj and prevquals == quals:
  537. return
  538. if not self._options.get('override'):
  539. raise FFIError(
  540. "multiple declarations of %s (for interactive usage, "
  541. "try cdef(xx, override=True))" % (name,))
  542. assert '__dotdotdot__' not in name.split()
  543. self._declarations[name] = (obj, quals)
  544. if included:
  545. self._included_declarations.add(obj)
  546. def _extract_quals(self, type):
  547. quals = 0
  548. if isinstance(type, (pycparser.c_ast.TypeDecl,
  549. pycparser.c_ast.PtrDecl)):
  550. if 'const' in type.quals:
  551. quals |= model.Q_CONST
  552. if 'volatile' in type.quals:
  553. quals |= model.Q_VOLATILE
  554. if 'restrict' in type.quals:
  555. quals |= model.Q_RESTRICT
  556. return quals
  557. def _get_type_pointer(self, type, quals, declname=None):
  558. if isinstance(type, model.RawFunctionType):
  559. return type.as_function_pointer()
  560. if (isinstance(type, model.StructOrUnionOrEnum) and
  561. type.name.startswith('$') and type.name[1:].isdigit() and
  562. type.forcename is None and declname is not None):
  563. return model.NamedPointerType(type, declname, quals)
  564. return model.PointerType(type, quals)
  565. def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False,
  566. typedef_example=None):
  567. # first, dereference typedefs, if we have it already parsed, we're good
  568. if (isinstance(typenode, pycparser.c_ast.TypeDecl) and
  569. isinstance(typenode.type, pycparser.c_ast.IdentifierType) and
  570. len(typenode.type.names) == 1 and
  571. ('typedef ' + typenode.type.names[0]) in self._declarations):
  572. tp, quals = self._declarations['typedef ' + typenode.type.names[0]]
  573. quals |= self._extract_quals(typenode)
  574. return tp, quals
  575. #
  576. if isinstance(typenode, pycparser.c_ast.ArrayDecl):
  577. # array type
  578. if typenode.dim is None:
  579. length = None
  580. else:
  581. length = self._parse_constant(
  582. typenode.dim, partial_length_ok=partial_length_ok)
  583. # a hack: in 'typedef int foo_t[...][...];', don't use '...' as
  584. # the length but use directly the C expression that would be
  585. # generated by recompiler.py. This lets the typedef be used in
  586. # many more places within recompiler.py
  587. if typedef_example is not None:
  588. if length == '...':
  589. length = '_cffi_array_len(%s)' % (typedef_example,)
  590. typedef_example = "*" + typedef_example
  591. #
  592. tp, quals = self._get_type_and_quals(typenode.type,
  593. partial_length_ok=partial_length_ok,
  594. typedef_example=typedef_example)
  595. return model.ArrayType(tp, length), quals
  596. #
  597. if isinstance(typenode, pycparser.c_ast.PtrDecl):
  598. # pointer type
  599. itemtype, itemquals = self._get_type_and_quals(typenode.type)
  600. tp = self._get_type_pointer(itemtype, itemquals, declname=name)
  601. quals = self._extract_quals(typenode)
  602. return tp, quals
  603. #
  604. if isinstance(typenode, pycparser.c_ast.TypeDecl):
  605. quals = self._extract_quals(typenode)
  606. type = typenode.type
  607. if isinstance(type, pycparser.c_ast.IdentifierType):
  608. # assume a primitive type. get it from .names, but reduce
  609. # synonyms to a single chosen combination
  610. names = list(type.names)
  611. if names != ['signed', 'char']: # keep this unmodified
  612. prefixes = {}
  613. while names:
  614. name = names[0]
  615. if name in ('short', 'long', 'signed', 'unsigned'):
  616. prefixes[name] = prefixes.get(name, 0) + 1
  617. del names[0]
  618. else:
  619. break
  620. # ignore the 'signed' prefix below, and reorder the others
  621. newnames = []
  622. for prefix in ('unsigned', 'short', 'long'):
  623. for i in range(prefixes.get(prefix, 0)):
  624. newnames.append(prefix)
  625. if not names:
  626. names = ['int'] # implicitly
  627. if names == ['int']: # but kill it if 'short' or 'long'
  628. if 'short' in prefixes or 'long' in prefixes:
  629. names = []
  630. names = newnames + names
  631. ident = ' '.join(names)
  632. if ident == 'void':
  633. return model.void_type, quals
  634. if ident == '__dotdotdot__':
  635. raise FFIError(':%d: bad usage of "..."' %
  636. typenode.coord.line)
  637. tp0, quals0 = resolve_common_type(self, ident)
  638. return tp0, (quals | quals0)
  639. #
  640. if isinstance(type, pycparser.c_ast.Struct):
  641. # 'struct foobar'
  642. tp = self._get_struct_union_enum_type('struct', type, name)
  643. return tp, quals
  644. #
  645. if isinstance(type, pycparser.c_ast.Union):
  646. # 'union foobar'
  647. tp = self._get_struct_union_enum_type('union', type, name)
  648. return tp, quals
  649. #
  650. if isinstance(type, pycparser.c_ast.Enum):
  651. # 'enum foobar'
  652. tp = self._get_struct_union_enum_type('enum', type, name)
  653. return tp, quals
  654. #
  655. if isinstance(typenode, pycparser.c_ast.FuncDecl):
  656. # a function type
  657. return self._parse_function_type(typenode, name), 0
  658. #
  659. # nested anonymous structs or unions end up here
  660. if isinstance(typenode, pycparser.c_ast.Struct):
  661. return self._get_struct_union_enum_type('struct', typenode, name,
  662. nested=True), 0
  663. if isinstance(typenode, pycparser.c_ast.Union):
  664. return self._get_struct_union_enum_type('union', typenode, name,
  665. nested=True), 0
  666. #
  667. raise FFIError(":%d: bad or unsupported type declaration" %
  668. typenode.coord.line)
  669. def _parse_function_type(self, typenode, funcname=None):
  670. params = list(getattr(typenode.args, 'params', []))
  671. for i, arg in enumerate(params):
  672. if not hasattr(arg, 'type'):
  673. raise CDefError("%s arg %d: unknown type '%s'"
  674. " (if you meant to use the old C syntax of giving"
  675. " untyped arguments, it is not supported)"
  676. % (funcname or 'in expression', i + 1,
  677. getattr(arg, 'name', '?')))
  678. ellipsis = (
  679. len(params) > 0 and
  680. isinstance(params[-1].type, pycparser.c_ast.TypeDecl) and
  681. isinstance(params[-1].type.type,
  682. pycparser.c_ast.IdentifierType) and
  683. params[-1].type.type.names == ['__dotdotdot__'])
  684. if ellipsis:
  685. params.pop()
  686. if not params:
  687. raise CDefError(
  688. "%s: a function with only '(...)' as argument"
  689. " is not correct C" % (funcname or 'in expression'))
  690. args = [self._as_func_arg(*self._get_type_and_quals(argdeclnode.type))
  691. for argdeclnode in params]
  692. if not ellipsis and args == [model.void_type]:
  693. args = []
  694. result, quals = self._get_type_and_quals(typenode.type)
  695. # the 'quals' on the result type are ignored. HACK: we absure them
  696. # to detect __stdcall functions: we textually replace "__stdcall"
  697. # with "volatile volatile const" above.
  698. abi = None
  699. if hasattr(typenode.type, 'quals'): # else, probable syntax error anyway
  700. if typenode.type.quals[-3:] == ['volatile', 'volatile', 'const']:
  701. abi = '__stdcall'
  702. return model.RawFunctionType(tuple(args), result, ellipsis, abi)
  703. def _as_func_arg(self, type, quals):
  704. if isinstance(type, model.ArrayType):
  705. return model.PointerType(type.item, quals)
  706. elif isinstance(type, model.RawFunctionType):
  707. return type.as_function_pointer()
  708. else:
  709. return type
  710. def _get_struct_union_enum_type(self, kind, type, name=None, nested=False):
  711. # First, a level of caching on the exact 'type' node of the AST.
  712. # This is obscure, but needed because pycparser "unrolls" declarations
  713. # such as "typedef struct { } foo_t, *foo_p" and we end up with
  714. # an AST that is not a tree, but a DAG, with the "type" node of the
  715. # two branches foo_t and foo_p of the trees being the same node.
  716. # It's a bit silly but detecting "DAG-ness" in the AST tree seems
  717. # to be the only way to distinguish this case from two independent
  718. # structs. See test_struct_with_two_usages.
  719. try:
  720. return self._structnode2type[type]
  721. except KeyError:
  722. pass
  723. #
  724. # Note that this must handle parsing "struct foo" any number of
  725. # times and always return the same StructType object. Additionally,
  726. # one of these times (not necessarily the first), the fields of
  727. # the struct can be specified with "struct foo { ...fields... }".
  728. # If no name is given, then we have to create a new anonymous struct
  729. # with no caching; in this case, the fields are either specified
  730. # right now or never.
  731. #
  732. force_name = name
  733. name = type.name
  734. #
  735. # get the type or create it if needed
  736. if name is None:
  737. # 'force_name' is used to guess a more readable name for
  738. # anonymous structs, for the common case "typedef struct { } foo".
  739. if force_name is not None:
  740. explicit_name = '$%s' % force_name
  741. else:
  742. self._anonymous_counter += 1
  743. explicit_name = '$%d' % self._anonymous_counter
  744. tp = None
  745. else:
  746. explicit_name = name
  747. key = '%s %s' % (kind, name)
  748. tp, _ = self._declarations.get(key, (None, None))
  749. #
  750. if tp is None:
  751. if kind == 'struct':
  752. tp = model.StructType(explicit_name, None, None, None)
  753. elif kind == 'union':
  754. tp = model.UnionType(explicit_name, None, None, None)
  755. elif kind == 'enum':
  756. if explicit_name == '__dotdotdot__':
  757. raise CDefError("Enums cannot be declared with ...")
  758. tp = self._build_enum_type(explicit_name, type.values)
  759. else:
  760. raise AssertionError("kind = %r" % (kind,))
  761. if name is not None:
  762. self._declare(key, tp)
  763. else:
  764. if kind == 'enum' and type.values is not None:
  765. raise NotImplementedError(
  766. "enum %s: the '{}' declaration should appear on the first "
  767. "time the enum is mentioned, not later" % explicit_name)
  768. if not tp.forcename:
  769. tp.force_the_name(force_name)
  770. if tp.forcename and '$' in tp.name:
  771. self._declare('anonymous %s' % tp.forcename, tp)
  772. #
  773. self._structnode2type[type] = tp
  774. #
  775. # enums: done here
  776. if kind == 'enum':
  777. return tp
  778. #
  779. # is there a 'type.decls'? If yes, then this is the place in the
  780. # C sources that declare the fields. If no, then just return the
  781. # existing type, possibly still incomplete.
  782. if type.decls is None:
  783. return tp
  784. #
  785. if tp.fldnames is not None:
  786. raise CDefError("duplicate declaration of struct %s" % name)
  787. fldnames = []
  788. fldtypes = []
  789. fldbitsize = []
  790. fldquals = []
  791. for decl in type.decls:
  792. if (isinstance(decl.type, pycparser.c_ast.IdentifierType) and
  793. ''.join(decl.type.names) == '__dotdotdot__'):
  794. # XXX pycparser is inconsistent: 'names' should be a list
  795. # of strings, but is sometimes just one string. Use
  796. # str.join() as a way to cope with both.
  797. self._make_partial(tp, nested)
  798. continue
  799. if decl.bitsize is None:
  800. bitsize = -1
  801. else:
  802. bitsize = self._parse_constant(decl.bitsize)
  803. self._partial_length = False
  804. type, fqual = self._get_type_and_quals(decl.type,
  805. partial_length_ok=True)
  806. if self._partial_length:
  807. self._make_partial(tp, nested)
  808. if isinstance(type, model.StructType) and type.partial:
  809. self._make_partial(tp, nested)
  810. fldnames.append(decl.name or '')
  811. fldtypes.append(type)
  812. fldbitsize.append(bitsize)
  813. fldquals.append(fqual)
  814. tp.fldnames = tuple(fldnames)
  815. tp.fldtypes = tuple(fldtypes)
  816. tp.fldbitsize = tuple(fldbitsize)
  817. tp.fldquals = tuple(fldquals)
  818. if fldbitsize != [-1] * len(fldbitsize):
  819. if isinstance(tp, model.StructType) and tp.partial:
  820. raise NotImplementedError("%s: using both bitfields and '...;'"
  821. % (tp,))
  822. tp.packed = self._options.get('packed')
  823. if tp.completed: # must be re-completed: it is not opaque any more
  824. tp.completed = 0
  825. self._recomplete.append(tp)
  826. return tp
  827. def _make_partial(self, tp, nested):
  828. if not isinstance(tp, model.StructOrUnion):
  829. raise CDefError("%s cannot be partial" % (tp,))
  830. if not tp.has_c_name() and not nested:
  831. raise NotImplementedError("%s is partial but has no C name" %(tp,))
  832. tp.partial = True
  833. def _parse_constant(self, exprnode, partial_length_ok=False):
  834. # for now, limited to expressions that are an immediate number
  835. # or positive/negative number
  836. if isinstance(exprnode, pycparser.c_ast.Constant):
  837. s = exprnode.value
  838. if '0' <= s[0] <= '9':
  839. s = s.rstrip('uUlL')
  840. try:
  841. if s.startswith('0'):
  842. return int(s, 8)
  843. else:
  844. return int(s, 10)
  845. except ValueError:
  846. if len(s) > 1:
  847. if s.lower()[0:2] == '0x':
  848. return int(s, 16)
  849. elif s.lower()[0:2] == '0b':
  850. return int(s, 2)
  851. raise CDefError("invalid constant %r" % (s,))
  852. elif s[0] == "'" and s[-1] == "'" and (
  853. len(s) == 3 or (len(s) == 4 and s[1] == "\\")):
  854. return ord(s[-2])
  855. else:
  856. raise CDefError("invalid constant %r" % (s,))
  857. #
  858. if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and
  859. exprnode.op == '+'):
  860. return self._parse_constant(exprnode.expr)
  861. #
  862. if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and
  863. exprnode.op == '-'):
  864. return -self._parse_constant(exprnode.expr)
  865. # load previously defined int constant
  866. if (isinstance(exprnode, pycparser.c_ast.ID) and
  867. exprnode.name in self._int_constants):
  868. return self._int_constants[exprnode.name]
  869. #
  870. if (isinstance(exprnode, pycparser.c_ast.ID) and
  871. exprnode.name == '__dotdotdotarray__'):
  872. if partial_length_ok:
  873. self._partial_length = True
  874. return '...'
  875. raise FFIError(":%d: unsupported '[...]' here, cannot derive "
  876. "the actual array length in this context"
  877. % exprnode.coord.line)
  878. #
  879. if isinstance(exprnode, pycparser.c_ast.BinaryOp):
  880. left = self._parse_constant(exprnode.left)
  881. right = self._parse_constant(exprnode.right)
  882. if exprnode.op == '+':
  883. return left + right
  884. elif exprnode.op == '-':
  885. return left - right
  886. elif exprnode.op == '*':
  887. return left * right
  888. elif exprnode.op == '/':
  889. return self._c_div(left, right)
  890. elif exprnode.op == '%':
  891. return left - self._c_div(left, right) * right
  892. elif exprnode.op == '<<':
  893. return left << right
  894. elif exprnode.op == '>>':
  895. return left >> right
  896. elif exprnode.op == '&':
  897. return left & right
  898. elif exprnode.op == '|':
  899. return left | right
  900. elif exprnode.op == '^':
  901. return left ^ right
  902. #
  903. raise FFIError(":%d: unsupported expression: expected a "
  904. "simple numeric constant" % exprnode.coord.line)
  905. def _c_div(self, a, b):
  906. result = a // b
  907. if ((a < 0) ^ (b < 0)) and (a % b) != 0:
  908. result += 1
  909. return result
  910. def _build_enum_type(self, explicit_name, decls):
  911. if decls is not None:
  912. partial = False
  913. enumerators = []
  914. enumvalues = []
  915. nextenumvalue = 0
  916. for enum in decls.enumerators:
  917. if _r_enum_dotdotdot.match(enum.name):
  918. partial = True
  919. continue
  920. if enum.value is not None:
  921. nextenumvalue = self._parse_constant(enum.value)
  922. enumerators.append(enum.name)
  923. enumvalues.append(nextenumvalue)
  924. self._add_constants(enum.name, nextenumvalue)
  925. nextenumvalue += 1
  926. enumerators = tuple(enumerators)
  927. enumvalues = tuple(enumvalues)
  928. tp = model.EnumType(explicit_name, enumerators, enumvalues)
  929. tp.partial = partial
  930. else: # opaque enum
  931. tp = model.EnumType(explicit_name, (), ())
  932. return tp
  933. def include(self, other):
  934. for name, (tp, quals) in other._declarations.items():
  935. if name.startswith('anonymous $enum_$'):
  936. continue # fix for test_anonymous_enum_include
  937. kind = name.split(' ', 1)[0]
  938. if kind in ('struct', 'union', 'enum', 'anonymous', 'typedef'):
  939. self._declare(name, tp, included=True, quals=quals)
  940. for k, v in other._int_constants.items():
  941. self._add_constants(k, v)
  942. def _get_unknown_type(self, decl):
  943. typenames = decl.type.type.names
  944. if typenames == ['__dotdotdot__']:
  945. return model.unknown_type(decl.name)
  946. if typenames == ['__dotdotdotint__']:
  947. if self._uses_new_feature is None:
  948. self._uses_new_feature = "'typedef int... %s'" % decl.name
  949. return model.UnknownIntegerType(decl.name)
  950. if typenames == ['__dotdotdotfloat__']:
  951. # note: not for 'long double' so far
  952. if self._uses_new_feature is None:
  953. self._uses_new_feature = "'typedef float... %s'" % decl.name
  954. return model.UnknownFloatType(decl.name)
  955. raise FFIError(':%d: unsupported usage of "..." in typedef'
  956. % decl.coord.line)
  957. def _get_unknown_ptr_type(self, decl):
  958. if decl.type.type.type.names == ['__dotdotdot__']:
  959. return model.unknown_ptr_type(decl.name)
  960. raise FFIError(':%d: unsupported usage of "..." in typedef'
  961. % decl.coord.line)