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