1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
#include <string.h>
#include <stdio.h>
#include <dynamic_typing.h>
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("<function>");
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("<union>");
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);
}
|