Debian Codegraph @

rpython/tool/cparser/cparser.py

raw symbols SCIP
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 # Issue #392: packaging tools like cx_Freeze can not find these
15 # because pycparser uses exec dynamic import. This is an obscure
16 # workaround. This function is never called.
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( # matches "* const "
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 # Workaround for a pycparser issue (fixed between pycparser 2.10 and
59 # 2.14): "char*const***" gives us a wrong syntax tree, the same as
60 # for "char***(*const)". This means we can't tell the difference
61 # afterwards. But "char(*const(***))" gives us the right syntax
62 # tree. The issue only occurs if there are several stars in
63 # sequence with no parenthesis inbetween, just possibly qualifiers.
64 # Attempt to fix it by adding some parentheses in the source: each
65 # time we see "* const" or "* const *", we add an opening
66 # parenthesis before each star---the hard part is figuring out where
67 # to close them.
68 parts = []
69 while True:
70 match = _r_star_const_space.search(csource)
71 if not match:
72 break
73 #print repr(''.join(parts)+csource), '=>',
74 parts.append(csource[:match.start()])
75 parts.append('('); closing = ')'
76 parts.append(match.group()) # e.g. "* const "
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 #print repr(''.join(parts)+csource)
96 parts.append(csource)
97 return ''.join(parts)
98
99 def _preprocess_extern_python(csource):
100 # input: `extern "Python" int foo(int);` or
101 # `extern "Python" { int foo(int); }`
102 # output:
103 # void __cffi_extern_python_start;
104 # int foo(int);
105 # void __cffi_extern_python_stop;
106 #
107 # input: `extern "Python+C" int foo(int);`
108 # output:
109 # void __cffi_extern_python_plus_c_start;
110 # int foo(int);
111 # void __cffi_extern_python_stop;
112 parts = []
113 while True:
114 match = _r_extern_python.search(csource)
115 if not match:
116 break
117 endpos = match.end() - 1
118 #print
119 #print ''.join(parts)+csource
120 #print '=>'
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 # grouping variant
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 # non-grouping variant
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 #print ''.join(parts)+csource
145 #print
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 # _r_line_directive matches whole lines, without the final \n, if they
170 # start with '#line' with some spacing allowed, or '#NUMBER'. This
171 # function stores them away and replaces them with exactly the string
172 # '#line@N', where N is the index in the list 'line_directives'.
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 # First, remove the lines of the form '#line N "filename"' because
192 # the "filename" part could confuse the rest
193 csource, line_directives = _remove_line_directives(csource)
194 # Remove comments. NOTE: this only work because the cdef() section
195 # should not contain any string literals (except in line directives)!
196 def replace_keeping_newlines(m):
197 return ' ' + m.group().count('\n') * '\n'
198 csource = _r_comment.sub(replace_keeping_newlines, csource)
199 # Remove the "#define FOO x" lines
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 # Process "#ifdef _WIN64 ... #else ... #endif" blocks.
206 # This is used in cpyext_object.h to define Py_ssize_t
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 # BIG HACK: replace WINAPI or __stdcall with "volatile const".
216 # It doesn't make sense for the return type of a function to be
217 # "volatile volatile const", so we abuse it to detect __stdcall...
218 # Hack number 2 is that "int(volatile *fptr)();" is not valid C
219 # syntax, so we place the "volatile" before the opening parenthesis.
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 # Replace `extern "Python"` with start/end markers
225 csource = _preprocess_extern_python(csource)
226 #
227 # Now there should not be any string literal left; warn if we get one
228 _warn_for_string_literal(csource)
229 #
230 # Replace "[...]" with "[__dotdotdotarray__]"
231 csource = _r_partial_array.sub('[__dotdotdotarray__]', csource)
232 #
233 # Replace "...}" with "__dotdotdotNUM__}". This construction should
234 # occur only at the end of enums; at the end of structs we have "...;}"
235 # and at the end of vararg functions "...);". Also replace "=...[,}]"
236 # with ",__dotdotdotNUM__[,}]": this occurs in the enums too, when
237 # giving an unknown value.
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 # Replace "int ..." or "unsigned long int..." with "__dotdotdotint__"
251 csource = _r_int_dotdotdot.sub(' __dotdotdotint__ ', csource)
252 # Replace "float ..." or "double..." with "__dotdotdotfloat__"
253 csource = _r_float_dotdotdot.sub(' __dotdotdotfloat__ ', csource)
254 # Replace all remaining "..." with the same name, "__dotdotdot__",
255 # which is declared with a typedef for the purpose of C parsing.
256 csource = csource.replace('...', ' __dotdotdot__ ')
257 # Finally, put back the line directives
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 # Look in the source for what looks like usages of types from the
267 # list of common types. A "usage" is approximated here as the
268 # appearance of the word, minus a "definition" of the type, which
269 # is the last word in a "typedef" statement. Approximative only
270 # but should be fine for all the common types.
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: # word in COMMON_TYPES
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 # modifies self._macros in-place
319 csource, macros = _preprocess(csource, self._macros)
320 # XXX: for more efficiency we would need to poke into the
321 # internals of CParser... the following registers the
322 # typedefs, because their presence or absence influences the
323 # parsing itself (but what they are typedef'ed to plays no role)
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 # this forces pycparser to consider the following in the file
340 # called <cdef source string> from line 1
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 # csource will be used to find buggy source text
350 return ast, macros, csource
351
352 def _convert_pycparser_error(self, e, csource):
353 # xxx look for "<cdef source string>:NUM:" at the start of str(e)
354 # and interpret that as a line number. This will not work if
355 # the user gives explicit ``# NUM "FILE"`` directives.
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 # add the macros
403 self._process_macros(macros)
404 # find the first "__dotdotdot__" and use that as a separator
405 # between the repeated typedefs and the real csource
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 # TODO: check that the pragma matches the kwarg
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 # ignore identical double declarations
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 # "010" is not valid oct in py3
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 # hack: `extern "Python"` in the C source is replaced
536 # with "void __cffi_extern_python_start;" and
537 # "void __cffi_extern_python_stop;"
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 # first, dereference typedefs, if we have it already parsed, we're good
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 # array type
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 # a hack: in 'typedef int foo_t[...][...];', don't use '...' as
614 # the length but use directly the C expression that would be
615 # generated by recompiler.py. This lets the typedef be used in
616 # many more places within recompiler.py
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 # pointer type
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 # assume a primitive type. get it from .names, but reduce
639 # synonyms to a single chosen combination
640 names = list(type.names)
641 if names != ['signed', 'char']: # keep this unmodified
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 # ignore the 'signed' prefix below, and reorder the others
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'] # implicitly
657 if names == ['int']: # but kill it if 'short' or 'long'
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 # 'struct foobar'
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 # 'union foobar'
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 # 'enum foobar'
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 # a function type
687 return self._parse_function_type(typenode, name), 0
688 #
689 # nested anonymous structs or unions end up here
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 # the 'quals' on the result type are ignored. HACK: we absure them
727 # to detect __stdcall functions: we textually replace "__stdcall"
728 # with "volatile volatile const" above.
729 abi = None
730 if hasattr(typenode.type, 'quals'): # else, probable syntax error anyway
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 # First, a level of caching on the exact 'type' node of the AST.
745 # This is obscure, but needed because pycparser "unrolls" declarations
746 # such as "typedef struct { } foo_t, *foo_p" and we end up with
747 # an AST that is not a tree, but a DAG, with the "type" node of the
748 # two branches foo_t and foo_p of the trees being the same node.
749 # It's a bit silly but detecting "DAG-ness" in the AST tree seems
750 # to be the only way to distinguish this case from two independent
751 # structs. See test_struct_with_two_usages.
752 try:
753 return self._structnode2type[type]
754 except KeyError:
755 pass
756 #
757 # Note that this must handle parsing "struct foo" any number of
758 # times and always return the same StructType object. Additionally,
759 # one of these times (not necessarily the first), the fields of
760 # the struct can be specified with "struct foo { ...fields... }".
761 # If no name is given, then we have to create a new anonymous struct
762 # with no caching; in this case, the fields are either specified
763 # right now or never.
764 #
765 force_name = name
766 name = type.name
767 #
768 # get the type or create it if needed
769 if name is None:
770 # 'force_name' is used to guess a more readable name for
771 # anonymous structs, for the common case "typedef struct { } foo".
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 # enums: done here
809 if kind == 'enum':
810 return tp
811 #
812 # is there a 'type.decls'? If yes, then this is the place in the
813 # C sources that declare the fields. If no, then just return the
814 # existing type, possibly still incomplete.
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 # XXX pycparser is inconsistent: 'names' should be a list
828 # of strings, but is sometimes just one string. Use
829 # str.join() as a way to cope with both.
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: # must be re-completed: it is not opaque any more
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 # for now, limited to expressions that are an immediate number
870 # or positive/negative number
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 # load previously defined int constant
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: # opaque enum
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 # fix for test_anonymous_enum_include
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