- Make struct into a type constuctor - Rework placeholders - Got rid of 'PrimitiveType' as a concept Still in idea form [skip-ci]
65 lines
1.9 KiB
Python
65 lines
1.9 KiB
Python
from .type3 import types as type3types
|
|
|
|
|
|
def calculate_alloc_size(typ: type3types.Type3, is_member: bool = False) -> int:
|
|
if typ in (type3types.u8, type3types.i8, ):
|
|
return 4 # FIXME: We allocate 4 bytes for every u8 since you load them into an i32
|
|
|
|
if typ in (type3types.u32, type3types.i32, type3types.f32, ):
|
|
return 4
|
|
|
|
if typ in (type3types.u64, type3types.i64, type3types.f64, ):
|
|
return 8
|
|
|
|
if typ == type3types.bytes_:
|
|
if is_member:
|
|
return 4
|
|
|
|
raise NotImplementedError # When does this happen?
|
|
|
|
st_args = type3types.struct.did_construct(typ)
|
|
if st_args is not None:
|
|
if is_member:
|
|
# Structs referred to by other structs or tuples are pointers
|
|
return 4
|
|
|
|
return sum(
|
|
calculate_alloc_size(x, is_member=True)
|
|
for x in st_args.values()
|
|
)
|
|
|
|
sa_args = type3types.static_array.did_construct(typ)
|
|
if sa_args is not None:
|
|
if is_member:
|
|
# tuples referred to by other structs or tuples are pointers
|
|
return 4
|
|
|
|
sa_type, sa_len = sa_args
|
|
|
|
return sa_len.value * calculate_alloc_size(sa_type, is_member=True)
|
|
|
|
tp_args = type3types.tuple_.did_construct(typ)
|
|
if tp_args is not None:
|
|
if is_member:
|
|
# tuples referred to by other structs or tuples are pointers
|
|
return 4
|
|
|
|
size = 0
|
|
for arg in tp_args:
|
|
size += calculate_alloc_size(arg, is_member=True)
|
|
|
|
return size
|
|
|
|
raise NotImplementedError(calculate_alloc_size, typ)
|
|
|
|
def calculate_member_offset(st_name: str, st_args: dict[str, type3types.Type3], needle: str) -> int:
|
|
result = 0
|
|
|
|
for memnam, memtyp in st_args.items():
|
|
if needle == memnam:
|
|
return result
|
|
|
|
result += calculate_alloc_size(memtyp, is_member=True)
|
|
|
|
raise Exception(f'{needle} not in {st_name}')
|