From 578531395ecbabd8179e31520c2832ac7d6d3765 Mon Sep 17 00:00:00 2001 From: Matthew Sotoudeh Date: Thu, 27 Jul 2023 12:06:17 -0700 Subject: add dynamic typing example --- python/examples/dynamic_typing/test.c | 76 +++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 python/examples/dynamic_typing/test.c (limited to 'python/examples/dynamic_typing/test.c') diff --git a/python/examples/dynamic_typing/test.c b/python/examples/dynamic_typing/test.c new file mode 100644 index 0000000..86e2229 --- /dev/null +++ b/python/examples/dynamic_typing/test.c @@ -0,0 +1,76 @@ +#include +#include +#include + +void pprint_(void *obj, struct type *type) { + switch (type->kind) { + case TY_BASIC: + switch (type->size) { + case sizeof(char): + printf("(%s)%lu", type->basic, (unsigned long)*(unsigned char *)obj); + break; + case sizeof(short): + printf("(%s)%lu", type->basic, (unsigned long)*(unsigned short *)obj); + break; + case sizeof(int): + printf("(%s)%lu", type->basic, (unsigned long)*(unsigned int *)obj); + break; + case sizeof(long): + printf("(%s)%lu", type->basic, (unsigned long)*(unsigned long *)obj); + break; + default: + printf("?"); + break; + } + break; + case TY_ARRAY: + printf("{ "); + void *ptr = obj; + for (unsigned long i = 0; i < type->length; i++) { + pprint_(obj, type->base); + obj += type->base->size; + if (i + 1 < type->length) printf(", "); + else printf(" "); + } + printf("}"); + break; + case TY_POINTER: + printf("%p[%ld]", *(void **)obj, type->length); + break; + case TY_FUNCTION: + printf(""); + break; + case TY_STRUCT: + printf("{ "); + for (struct type *member = type->members; member; member = member->next_member) { + printf(".%s = ", member->field_name); + pprint_((void*)obj + member->offset, member); + if (member->next_member) printf(", "); + else printf(" "); + } + printf("}"); + break; + case TY_UNION: + printf(""); + break; + } +} + +void pprint(void *obj) { + pprint_(obj, dynamic_typeof(obj)->base); + printf("\n"); +} + +int main() { + struct { + char x; + int y; + int z[3]; + } foo = {1, 2, {3, 4, 5}}; + pprint(&foo); + struct { + char a; + int b; + } bar = {100, 200}; + pprint(&bar); +} -- cgit v1.2.3