summaryrefslogtreecommitdiff
path: root/types.c
blob: be5083a6539530e1afe65ba6feb2ae800862ed19 (plain)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>

#include <clang-c/Index.h>

#include "util.h"
#include "mcbind.h"

Type *mktype(Ty ty)
{
	Type *t;

	t = zalloc(sizeof(Type));
	t->type = ty;
	return t;
}

Type *mktyarray(Type *sub, size_t sz)
{
	Type *t;
	t = mktype(Tyarray);
	lappend(&t->sub, &t->nsub, sub);
	t->arraysz = sz;
	return t;
}

Type *mktyptr(Type *sub)
{
	Type *t;
	t = mktype(Typtr);
	lappend(&t->sub, &t->nsub, sub);
	return t;
}

Type *mktyname(char *name)
{
	Type *t;
	t = mktype(Tyname);
	t->defname = name;
	return t;
}

Type *mktystruct(char *name, Dcl **dcls, size_t ndcls)
{
	Type *t;
	t = mktype(Tystruct);
	t->defname = name;
	return t;
}

Type *mktyunion(char *name, Dcl **dcls, size_t ndcls)
{
	Type *t;
	t = mktype(Tyunion);
	t->defname = name;
	return t;
}

Type *mktyopaque(char *name, size_t sz)
{
	Type *t;
	t = mktype(Tyname);
	t->arraysz = sz;
	t->defname = name;
	return t;
}

Type *tybase(Pkg *pkg, Type *orig)
{
	Type *ty, *sub;

	ty = orig;
	while (ty->type == Tyname) {
		if (!ty->sub || !ty->sub[0]) {
			sub = htget(pkg->tydefs, ty->defname);
			if (!ty->sub)
				lappend(&ty->sub, &ty->nsub, sub);
			else
				ty->sub[0] = sub;
		}
		if (!ty->sub || !ty->sub[0]) {
			fprintf(stderr, "no type definition for %s\n", ty->defname);
			return NULL;
		}
		ty = ty->sub[0];
	}
	assert(ty != NULL);
	return ty;
}

bool needswrapper(Pkg *pkg, Type *orig)
{
	Type *ty;

	ty = tybase(pkg, orig);
	switch (ty->type) {
	case Tystruct:	return 1;
	case Tyunion:	return 1;
	case Tyarray:	return 1;
	default:	return 0;
	}
}

bool funcneedswrapper(Pkg *pkg, Type *ty)
{
	size_t i;

	ty = tybase(pkg, ty);
	if (ty->type != Tyfunc)
		return 0;
	for (i = 0; i < ty->nsub; i++)
		if (needswrapper(pkg, ty->sub[i]))
			return 1;
	return 0;
}

Type *wrappedtype(Pkg *pkg, Type *ty)
{
	Type *w;
	size_t i;

	w = mktype(Tyfunc);
	if (needswrapper(pkg, ty->sub[0])) {
		lappend(&w->sub, &w->nsub, mktype(Tyvoid));
		lappend(&w->subname, &w->nsubname, NULL);
	}
	for (i = 0; i < ty->nsub; i++) {
		if (needswrapper(pkg, ty->sub[i]))
			lappend(&w->sub, &w->nsub, mktyptr(ty->sub[i]));
		else 
			lappend(&w->sub, &w->nsub, ty->sub[i]);
		lappend(&w->subname, &w->nsubname, NULL);
	}
	return w;
}