| 1 |
import sys |
| 2 |
from itertools import izip |
| 3 |
from collections import OrderedDict |
| 4 |
|
| 5 |
from rpython.translator.tool.cbuild import ExternalCompilationInfo |
| 6 |
from rpython.rlib.rfile import FILEP |
| 7 |
from rpython.rtyper.lltypesystem import rffi, lltype |
| 8 |
from rpython.rtyper.tool import rfficache, rffi_platform |
| 9 |
from rpython.flowspace.model import Constant, const |
| 10 |
from rpython.flowspace.specialcase import register_flow_sc |
| 11 |
from rpython.flowspace.flowcontext import FlowingError |
| 12 |
|
| 13 |
from . import model |
| 14 |
from .cparser import Parser |
| 15 |
|
| 16 |
|
| 17 |
CNAME_TO_LLTYPE = { |
| 18 |
'char': rffi.CHAR, |
| 19 |
'double': rffi.DOUBLE, 'long double': rffi.LONGDOUBLE, |
| 20 |
'float': rffi.FLOAT, 'FILE': FILEP.TO} |
| 21 |
|
| 22 |
def add_inttypes(): |
| 23 |
for name in rffi.TYPES: |
| 24 |
if name.startswith('unsigned'): |
| 25 |
rname = 'u' + name[9:] |
| 26 |
else: |
| 27 |
rname = name |
| 28 |
rname = rname.replace(' ', '').upper() |
| 29 |
CNAME_TO_LLTYPE[name] = rfficache.platform.types[rname] |
| 30 |
|
| 31 |
add_inttypes() |
| 32 |
CNAME_TO_LLTYPE['int'] = rffi.INT_real |
| 33 |
CNAME_TO_LLTYPE['wchar_t'] = lltype.UniChar |
| 34 |
if 'ssize_t' not in CNAME_TO_LLTYPE: |
| 35 |
CNAME_TO_LLTYPE['ssize_t'] = rffi.SIGNED |
| 36 |
|
| 37 |
def cname_to_lltype(name): |
| 38 |
return CNAME_TO_LLTYPE[name] |
| 39 |
|
| 40 |
class DelayedStruct(object): |
| 41 |
def __init__(self, name, fields, TYPE): |
| 42 |
self.struct_name = name |
| 43 |
self.type_name = None |
| 44 |
self.fields = fields |
| 45 |
self.TYPE = TYPE |
| 46 |
|
| 47 |
def get_type_name(self): |
| 48 |
if self.type_name is not None: |
| 49 |
return self.type_name |
| 50 |
elif not self.struct_name.startswith('$'): |
| 51 |
return 'struct %s' % self.struct_name |
| 52 |
else: |
| 53 |
raise ValueError('Anonymous struct') |
| 54 |
|
| 55 |
def __repr__(self): |
| 56 |
return "<struct {struct_name}>".format(**vars(self)) |
| 57 |
|
| 58 |
|
| 59 |
class CTypeSpace(object): |
| 60 |
def __init__(self, parser=None, definitions=None, macros=None, |
| 61 |
headers=None, includes=None, include_dirs=None): |
| 62 |
self.definitions = definitions if definitions is not None else {} |
| 63 |
self.macros = macros if macros is not None else {} |
| 64 |
self.structs = {} |
| 65 |
self.ctx = parser if parser else Parser() |
| 66 |
self.headers = headers if headers is not None else ['sys/types.h'] |
| 67 |
self.parsed_headers = [] |
| 68 |
self.sources = [] |
| 69 |
self._config_entries = OrderedDict() |
| 70 |
self.includes = [] |
| 71 |
self.struct_typedefs = {} |
| 72 |
self._handled = set() |
| 73 |
self._frozen = False |
| 74 |
self._cdecl_type_cache = {} |
| 75 |
if includes is not None: |
| 76 |
for header in includes: |
| 77 |
self.include(header) |
| 78 |
if include_dirs is not None: |
| 79 |
self.include_dirs = include_dirs[:] |
| 80 |
else: |
| 81 |
self.include_dirs = [] |
| 82 |
|
| 83 |
def include(self, other): |
| 84 |
self.ctx.include(other.ctx) |
| 85 |
self.structs.update(other.structs) |
| 86 |
self.includes.append(other) |
| 87 |
|
| 88 |
def parse_source(self, source, configure=True): |
| 89 |
self.sources.append(source) |
| 90 |
self.ctx.parse(source) |
| 91 |
if configure: |
| 92 |
self.configure_types() |
| 93 |
|
| 94 |
def parse_header(self, header_path, configure=True): |
| 95 |
self.headers.append(str(header_path)) |
| 96 |
self.parsed_headers.append(header_path) |
| 97 |
self.ctx.parse(header_path.read()) |
| 98 |
if configure: |
| 99 |
self.configure_types() |
| 100 |
|
| 101 |
def add_typedef(self, name, obj, quals): |
| 102 |
assert name not in self.definitions |
| 103 |
tp = self.convert_type(obj, quals) |
| 104 |
if isinstance(tp, DelayedStruct): |
| 105 |
if tp.type_name is None: |
| 106 |
tp.type_name = name |
| 107 |
tp = self.realize_struct(tp) |
| 108 |
self.structs[obj.realtype] = tp |
| 109 |
self.definitions[name] = tp |
| 110 |
|
| 111 |
def add_macro(self, name, value): |
| 112 |
assert name not in self.macros |
| 113 |
self.macros[name] = value |
| 114 |
|
| 115 |
def add_struct(self, name, obj, quals): |
| 116 |
tp = self.convert_type(obj, quals) |
| 117 |
if isinstance(tp, DelayedStruct): |
| 118 |
tp = self.realize_struct(tp) |
| 119 |
self.structs[obj] = tp |
| 120 |
|
| 121 |
def new_struct(self, obj): |
| 122 |
if obj.name == '_IO_FILE': |
| 123 |
return cname_to_lltype('FILE') |
| 124 |
struct = DelayedStruct(obj.name, None, lltype.ForwardReference()) |
| 125 |
|
| 126 |
self.structs[obj] = struct |
| 127 |
if obj.fldtypes is not None: |
| 128 |
struct.fields = zip( |
| 129 |
obj.fldnames, |
| 130 |
[self.convert_field(field) for field in obj.fldtypes]) |
| 131 |
return struct |
| 132 |
|
| 133 |
def convert_field(self, obj): |
| 134 |
tp = self.convert_type(obj) |
| 135 |
if isinstance(tp, DelayedStruct): |
| 136 |
tp = tp.TYPE |
| 137 |
elif isinstance(tp, type) and issubclass(tp, Enum): |
| 138 |
tp = rffi.INT_real |
| 139 |
return tp |
| 140 |
|
| 141 |
def realize_struct(self, struct): |
| 142 |
type_name = struct.get_type_name() |
| 143 |
if struct.fields is None: |
| 144 |
raise ValueError('Missing definition for %s' % type_name) |
| 145 |
entry = rffi_platform.Struct(type_name, struct.fields) |
| 146 |
self._config_entries[entry] = struct.TYPE |
| 147 |
return struct.TYPE |
| 148 |
|
| 149 |
def build_eci(self): |
| 150 |
all_sources = [] |
| 151 |
for cts in self.includes: |
| 152 |
all_sources.extend(cts.sources) |
| 153 |
all_sources.extend(self.sources) |
| 154 |
all_headers = self.headers |
| 155 |
for x in self.includes: |
| 156 |
for hdr in x.headers: |
| 157 |
if hdr not in all_headers: |
| 158 |
all_headers.append(hdr) |
| 159 |
if sys.platform == 'win32': |
| 160 |
if sys.maxint > 2**32: |
| 161 |
compile_extra = ['-Dssize_t=__int64'] |
| 162 |
else: |
| 163 |
compile_extra = ['-Dssize_t=long'] |
| 164 |
else: |
| 165 |
compile_extra = [] |
| 166 |
return ExternalCompilationInfo( |
| 167 |
post_include_bits=all_sources, includes=all_headers, |
| 168 |
compile_extra=compile_extra, |
| 169 |
include_dirs=self.include_dirs) |
| 170 |
|
| 171 |
def configure_types(self): |
| 172 |
for name, (obj, quals) in self.ctx._declarations.iteritems(): |
| 173 |
if obj in self.ctx._included_declarations: |
| 174 |
continue |
| 175 |
if name in self._handled: |
| 176 |
continue |
| 177 |
self._handled.add(name) |
| 178 |
if name.startswith('typedef '): |
| 179 |
name = name[8:] |
| 180 |
self.add_typedef(name, obj, quals) |
| 181 |
elif name.startswith('macro '): |
| 182 |
name = name[6:] |
| 183 |
self.add_macro(name, obj) |
| 184 |
elif name.startswith('struct '): |
| 185 |
name = name[7:] |
| 186 |
self.add_struct(name, obj, quals) |
| 187 |
if not self._config_entries: |
| 188 |
return |
| 189 |
eci = self.build_eci() |
| 190 |
|
| 191 |
while self._config_entries: |
| 192 |
configure_now = [] |
| 193 |
for entry in self._config_entries: |
| 194 |
if self._can_configure(entry): |
| 195 |
configure_now.append(entry) |
| 196 |
if not configure_now: |
| 197 |
raise ValueError("configure_types() cannot make progress. " |
| 198 |
"Maybe the cdef is invalid?") |
| 199 |
result = rffi_platform.configure_entries(configure_now, eci) |
| 200 |
for entry, TYPE in izip(configure_now, result): |
| 201 |
|
| 202 |
del TYPE._hints['eci'] |
| 203 |
self._config_entries[entry].become(TYPE) |
| 204 |
del self._config_entries[entry] |
| 205 |
|
| 206 |
def _can_configure(self, entry): |
| 207 |
if isinstance(entry, rffi_platform.Struct): |
| 208 |
|
| 209 |
|
| 210 |
for fieldname, fieldtype in entry.interesting_fields: |
| 211 |
if isinstance(fieldtype, lltype.ForwardReference): |
| 212 |
return False |
| 213 |
return True |
| 214 |
|
| 215 |
def convert_type(self, obj, quals=0): |
| 216 |
if isinstance(obj, model.DefinedType): |
| 217 |
return self.convert_type(obj.realtype, obj.quals) |
| 218 |
if isinstance(obj, model.PrimitiveType): |
| 219 |
return cname_to_lltype(obj.name) |
| 220 |
elif isinstance(obj, model.StructType): |
| 221 |
if obj in self.structs: |
| 222 |
return self.structs[obj] |
| 223 |
return self.new_struct(obj) |
| 224 |
elif isinstance(obj, model.PointerType): |
| 225 |
TO = self.convert_type(obj.totype) |
| 226 |
if TO is lltype.Void: |
| 227 |
return rffi.VOIDP |
| 228 |
elif isinstance(TO, DelayedStruct): |
| 229 |
TO = TO.TYPE |
| 230 |
if isinstance(TO, lltype.ContainerType): |
| 231 |
return lltype.Ptr(TO) |
| 232 |
else: |
| 233 |
if obj.quals & model.Q_CONST: |
| 234 |
return lltype.Ptr(lltype.Array( |
| 235 |
TO, hints={'nolength': True, 'render_as_const': True})) |
| 236 |
else: |
| 237 |
return rffi.CArrayPtr(TO) |
| 238 |
elif isinstance(obj, model.FunctionPtrType): |
| 239 |
if obj.ellipsis: |
| 240 |
raise NotImplementedError |
| 241 |
args = [self.convert_type(arg) for arg in obj.args] |
| 242 |
res = self.convert_type(obj.result) |
| 243 |
return lltype.Ptr(lltype.FuncType(args, res)) |
| 244 |
elif isinstance(obj, model.VoidType): |
| 245 |
return lltype.Void |
| 246 |
elif isinstance(obj, model.ArrayType): |
| 247 |
return rffi.CFixedArray(self.convert_type(obj.item), obj.length) |
| 248 |
elif isinstance(obj, model.EnumType): |
| 249 |
enum = type(obj.forcename, (Enum,), {}) |
| 250 |
for key, value in zip(obj.enumerators, obj.enumvalues): |
| 251 |
setattr(enum, key, value) |
| 252 |
return enum |
| 253 |
else: |
| 254 |
raise NotImplementedError |
| 255 |
|
| 256 |
def gettype(self, cdecl): |
| 257 |
try: |
| 258 |
return self._cdecl_type_cache[cdecl] |
| 259 |
except KeyError: |
| 260 |
result = self._real_gettype(cdecl) |
| 261 |
self._cdecl_type_cache[cdecl] = result |
| 262 |
return result |
| 263 |
|
| 264 |
def _real_gettype(self, cdecl): |
| 265 |
obj = self.ctx.parse_type(cdecl) |
| 266 |
result = self.convert_type(obj) |
| 267 |
if isinstance(result, DelayedStruct): |
| 268 |
result = result.TYPE |
| 269 |
return result |
| 270 |
|
| 271 |
def cast(self, cdecl, value): |
| 272 |
return rffi.cast(self.gettype(cdecl), value) |
| 273 |
|
| 274 |
def parse_func(self, cdecl): |
| 275 |
cdecl = cdecl.strip() |
| 276 |
if cdecl[-1] != ';': |
| 277 |
cdecl += ';' |
| 278 |
ast, _, _ = self.ctx._parse(cdecl) |
| 279 |
decl = ast.ext[-1] |
| 280 |
tp, quals = self.ctx._get_type_and_quals(decl.type, name=decl.name) |
| 281 |
return FunctionDeclaration(decl.name, tp) |
| 282 |
|
| 283 |
def _freeze_(self): |
| 284 |
if self._frozen: |
| 285 |
return True |
| 286 |
|
| 287 |
@register_flow_sc(self.cast) |
| 288 |
def sc_cast(ctx, v_decl, v_arg): |
| 289 |
if not isinstance(v_decl, Constant): |
| 290 |
raise FlowingError( |
| 291 |
"The first argument of cts.cast() must be a constant.") |
| 292 |
TP = self.gettype(v_decl.value) |
| 293 |
return ctx.appcall(rffi.cast, const(TP), v_arg) |
| 294 |
|
| 295 |
@register_flow_sc(self.gettype) |
| 296 |
def sc_gettype(ctx, v_decl): |
| 297 |
if not isinstance(v_decl, Constant): |
| 298 |
raise FlowingError( |
| 299 |
"The argument of cts.gettype() must be a constant.") |
| 300 |
return const(self.gettype(v_decl.value)) |
| 301 |
|
| 302 |
self._frozen = True |
| 303 |
return True |
| 304 |
|
| 305 |
class Enum(object): |
| 306 |
pass |
| 307 |
|
| 308 |
class FunctionDeclaration(object): |
| 309 |
def __init__(self, name, tp): |
| 310 |
self.name = name |
| 311 |
self.tp = tp |
| 312 |
|
| 313 |
def get_llargs(self, cts): |
| 314 |
return [cts.convert_type(arg) for arg in self.tp.args] |
| 315 |
|
| 316 |
def get_llresult(self, cts): |
| 317 |
return cts.convert_type(self.tp.result) |
| 318 |
|
| 319 |
def parse_source(source, includes=None, headers=None, configure_now=True): |
| 320 |
cts = CTypeSpace(headers=headers, includes=includes) |
| 321 |
cts.parse_source(source) |
| 322 |
return cts |