Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

956 rindas
41 KiB

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