-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVirtualMachine.h
450 lines (400 loc) · 13.2 KB
/
VirtualMachine.h
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
#if 1
/* Function: tp_deinit
* Destroys a VM instance.
*
* When you no longer need an instance of tinypy, you can use this to free all
* memory used by it. Even when you are using only a single tinypy instance, it
* may be good practice to call this function on shutdown.
*/
inline void tp_deinit(tp_vm *tp) {
while (tp->root.list.val->len) {
_tp_list_pop(tp, tp->root.list.val, 0, "tp_deinit");
}
tp_full(tp); tp_full(tp);
tp_delete(tp, tp->root);
tp_gc_deinit(tp);
free(tp);
}
/* tp_frame_*/
inline void tp_frame(tp_vm *tp, tp_obj globals, tp_obj code, tp_obj *ret_dest) {
tp_frame_ f;
f.globals = globals;
f.code = code;
f.cur = (tp_code*)f.code.string.val;
f.jmp = 0;
/* fprintf(stderr,"tp->cur: %d\n",tp->cur);*/
f.regs = (tp->cur <= 0 ? tp->regs : tp->frames[tp->cur].regs + tp->frames[tp->cur].cregs);
f.regs[0] = f.globals;
f.regs[1] = f.code;
f.regs += TP_REGS_EXTRA;
f.ret_dest = ret_dest;
f.lineno = 0;
f.line = tp_string("");
f.name = tp_string("?");
f.fname = tp_string("?");
f.cregs = 0;
/* return f;*/
if (f.regs + (256 + TP_REGS_EXTRA) >= tp->regs + TP_REGS || tp->cur >= TP_FRAMES - 1) {
tp_raise(, tp_string("(tp_frame) RuntimeError: stack overflow"));
}
tp->cur += 1;
tp->frames[tp->cur] = f;
}
inline void _tp_raise(tp_vm *tp, tp_obj e)
{
/*char *x = 0; x[0]=0;*/
if (!tp || !tp->jmp) {
printf("\nException:\n"); tp_echo(tp, e); printf("\n");
exit(-1);
}
if (e.type != TP_NONE) { tp->ex = e; }
tp_grey(tp, e);
longjmp(tp->buf, 1);
}
inline void tp_print_stack(tp_vm *tp)
{
int i;
printf("\n");
for (i = 0; i <= tp->cur; i++) {
if (!tp->frames[i].lineno) { continue; }
printf("File \""); tp_echo(tp, tp->frames[i].fname); printf("\", ");
printf("line %d, in ", tp->frames[i].lineno);
tp_echo(tp, tp->frames[i].name); printf("\n ");
tp_echo(tp, tp->frames[i].line); printf("\n");
}
printf("\nException:\n"); tp_echo(tp, tp->ex); printf("\n");
}
inline void tp_handle(tp_vm *tp)
{
int i;
for (i = tp->cur; i >= 0; i--) {
if (tp->frames[i].jmp) { break; }
}
if (i >= 0) {
tp->cur = i;
tp->frames[i].cur = tp->frames[i].jmp;
tp->frames[i].jmp = 0;
return;
}
tp_print_stack(tp);
exit(-1);
}
/* Function: tp_call
* Calls a tinypy function.
*
* Use this to call a tinypy function.
*
* Parameters:
* tp - The VM instance.
* self - The object to call.
* params - Parameters to pass.
*
* Example:
* > tp_call(tp,
* > tp_get(tp, tp->builtins, tp_string("foo")),
* > tp_params_v(tp, tp_string("hello")))
* This will look for a global function named "foo", then call it with a single
* positional parameter containing the string "hello".
*/
inline tp_obj tp_call(tp_vm *tp, tp_obj self, tp_obj params) {
/* I'm not sure we should have to do this, but
just for giggles we will. */
tp->params = params;
if (self.type == TP_DICT) {
if (self.dict.dtype == 1) {
tp_obj meta; if (_tp_lookup(tp, self, tp_string("__new__"), &meta)) {
_tp_list_insert(tp, params.list.val, 0, self);
return tp_call(tp, meta, params);
}
}
else if (self.dict.dtype == 2) {
TP_META_BEGIN(self, "__call__");
return tp_call(tp, meta, params);
TP_META_END;
}
}
if (self.type == TP_FNC && !(self.fnc.ftype & 1)) {
tp_obj r = _tp_tcall(tp, self);
tp_grey(tp, r);
return r;
}
if (self.type == TP_FNC) {
tp_obj dest = tp_None;
tp_frame(tp, self.fnc.info->globals, self.fnc.info->code, &dest);
if ((self.fnc.ftype & 2)) {
tp->frames[tp->cur].regs[0] = params;
_tp_list_insert(tp, params.list.val, 0, self.fnc.info->self);
}
else {
tp->frames[tp->cur].regs[0] = params;
}
tp_run(tp, tp->cur);
return dest;
}
tp_params_v(tp, 1, self); tp_print(tp);
tp_raise(tp_None, tp_string("(tp_call) TypeError: object is not callable"));
}
inline void tp_return(tp_vm *tp, tp_obj v) {
tp_obj *dest = tp->frames[tp->cur].ret_dest;
if (dest) { *dest = v; tp_grey(tp, v); }
memset(tp->frames[tp->cur].regs - TP_REGS_EXTRA, 0, (TP_REGS_EXTRA + tp->frames[tp->cur].cregs) * sizeof(tp_obj));
tp->cur -= 1;
}
enum {
TP_IEOF, TP_IADD, TP_ISUB, TP_IMUL, TP_IDIV, TP_IPOW, TP_IBITAND, TP_IBITOR, TP_ICMP, TP_IGET, TP_ISET,
TP_INUMBER, TP_ISTRING, TP_IGGET, TP_IGSET, TP_IMOVE, TP_IDEF, TP_IPASS, TP_IJUMP, TP_ICALL,
TP_IRETURN, TP_IIF, TP_IDEBUG, TP_IEQ, TP_ILE, TP_ILT, TP_IDICT, TP_ILIST, TP_INONE, TP_ILEN,
TP_ILINE, TP_IPARAMS, TP_IIGET, TP_IFILE, TP_INAME, TP_INE, TP_IHAS, TP_IRAISE, TP_ISETJMP,
TP_IMOD, TP_ILSH, TP_IRSH, TP_IITER, TP_IDEL, TP_IREGS, TP_IBITXOR, TP_IIFN,
TP_INOT, TP_IBITNOT,
TP_ITOTAL
};
/* char *tp_strings[TP_ITOTAL] = {
"EOF","ADD","SUB","MUL","DIV","POW","BITAND","BITOR","CMP","GET","SET","NUM",
"STR","GGET","GSET","MOVE","DEF","PASS","JUMP","CALL","RETURN","IF","DEBUG",
"EQ","LE","LT","DICT","LIST","NONE","LEN","LINE","PARAMS","IGET","FILE",
"NAME","NE","HAS","RAISE","SETJMP","MOD","LSH","RSH","ITER","DEL","REGS",
"BITXOR", "IFN", "NOT", "BITNOT",
};*/
#define VA ((int)e.regs.a)
#define VB ((int)e.regs.b)
#define VC ((int)e.regs.c)
#define RA regs[e.regs.a]
#define RB regs[e.regs.b]
#define RC regs[e.regs.c]
#define UVBC (unsigned short)(((VB<<8)+VC))
#define SVBC (short)(((VB<<8)+VC))
#define GA tp_grey(tp,RA)
#define SR(v) f->cur = cur; return(v);
inline int tp_step(tp_vm *tp)
{
tp_frame_ *f = &tp->frames[tp->cur];
tp_obj *regs = f->regs;
tp_code *cur = f->cur;
while (1)
{
tp_code e = *cur;
switch (e.i)
{
case TP_IEOF: tp_return(tp, tp_None); SR(0); break;
case TP_IADD: RA = tp_add(tp, RB, RC); break;
case TP_ISUB: RA = tp_sub(tp, RB, RC); break;
case TP_IMUL: RA = tp_mul(tp, RB, RC); break;
case TP_IDIV: RA = tp_div(tp, RB, RC); break;
case TP_IPOW: RA = tp_pow(tp, RB, RC); break;
case TP_IBITAND: RA = tp_bitwise_and(tp, RB, RC); break;
case TP_IBITOR: RA = tp_bitwise_or(tp, RB, RC); break;
case TP_IBITXOR: RA = tp_bitwise_xor(tp, RB, RC); break;
case TP_IMOD: RA = tp_mod(tp, RB, RC); break;
case TP_ILSH: RA = tp_lsh(tp, RB, RC); break;
case TP_IRSH: RA = tp_rsh(tp, RB, RC); break;
case TP_ICMP: RA = tp_number(tp_cmp(tp, RB, RC)); break;
case TP_INE: RA = tp_number(tp_cmp(tp, RB, RC) != 0); break;
case TP_IEQ: RA = tp_number(tp_cmp(tp, RB, RC) == 0); break;
case TP_ILE: RA = tp_number(tp_cmp(tp, RB, RC) <= 0); break;
case TP_ILT: RA = tp_number(tp_cmp(tp, RB, RC) < 0); break;
case TP_IBITNOT: RA = tp_bitwise_not(tp, RB); break;
case TP_INOT: RA = tp_number(!tp_bool(tp, RB)); break;
case TP_IPASS: break;
case TP_IIF: if (tp_bool(tp, RA)) { cur += 1; } break;
case TP_IIFN: if (!tp_bool(tp, RA)) { cur += 1; } break;
case TP_IGET: RA = tp_get(tp, RB, RC); GA; break;
case TP_IITER:
if (RC.number.val < tp_len(tp, RB).number.val)
{
RA = tp_iter(tp, RB, RC); GA;
RC.number.val += 1;
cur += 1;
}
break;
case TP_IHAS: RA = tp_has(tp, RB, RC); break;
case TP_IIGET: tp_iget(tp, &RA, RB, RC); break;
case TP_ISET: tp_set(tp, RA, RB, RC); break;
case TP_IDEL: tp_del(tp, RA, RB); break;
case TP_IMOVE: RA = RB; break;
case TP_INUMBER:
{
RA = tp_number(*(double*)(*++cur).string.val);
cur += sizeof(double) / 4;
continue;
}
case TP_ISTRING:
{
int a = (*(cur + 1)).string.val - f->code.string.val;
RA = tp_string_sub(tp, f->code, a, a + UVBC), cur += (UVBC / 4) + 1;
break;
}
case TP_IDICT: RA = tp_dict_n(tp, VC / 2, &RB); break;
case TP_ILIST: RA = tp_list_n(tp, VC, &RB); break;
case TP_IPARAMS: RA = tp_params_n(tp, VC, &RB); break;
case TP_ILEN: RA = tp_len(tp, RB); break;
case TP_IJUMP: cur += SVBC; continue; break;
case TP_ISETJMP: f->jmp = SVBC ? cur + SVBC : 0; break;
case TP_ICALL:
{
f->cur = cur + 1; RA = tp_call(tp, RB, RC); GA;
return 0;
}
case TP_IGGET:
{
if (!tp_iget(tp, &RA, f->globals, RB)) {
RA = tp_get(tp, tp->builtins, RB); GA;
}
break;
}
case TP_IGSET:
tp_set(tp, f->globals, RA, RB);
break;
case TP_IDEF:
{
int a = (*(cur + 1)).string.val - f->code.string.val;
RA = tp_def(tp, tp_string_sub(tp, f->code, a, a + (SVBC - 1) * 4), f->globals);
cur += SVBC;
continue;
}
case TP_IRETURN: tp_return(tp, RA); SR(0); break;
case TP_IRAISE: _tp_raise(tp, RA); SR(0); break;
case TP_IDEBUG: tp_params_v(tp, 3, tp_string("DEBUG:"), tp_number(VA), RA); tp_print(tp); break;
case TP_INONE: RA = tp_None; break;
case TP_ILINE:
{
int a = (*(cur + 1)).string.val - f->code.string.val;
f->line = tp_string_sub(tp, f->code, a, a + VA * 4 - 1);
cur += VA; f->lineno = UVBC;
break;
}
case TP_IFILE: f->fname = RA; break;
case TP_INAME: f->name = RA; break;
case TP_IREGS: f->cregs = VA; break;
default:
tp_raise(0, tp_string("(tp_step) RuntimeError: invalid instruction"));
break;
}
cur += 1;
}
SR(0);
}
//////////////////////////////////////////////////////////
inline void _tp_run(tp_vm *tp, int cur) {
tp->jmp += 1; if (setjmp(tp->buf)) { tp_handle(tp); }
while (tp->cur >= cur && tp_step(tp) != -1);
tp->jmp -= 1;
}
inline void tp_run(tp_vm *tp, int cur) {
jmp_buf tmp;
memcpy(tmp, tp->buf, sizeof(jmp_buf));
_tp_run(tp, cur);
memcpy(tp->buf, tmp, sizeof(jmp_buf));
}
inline tp_obj tp_ez_call(tp_vm *tp, const char *mod, const char *fnc, tp_obj params) {
tp_obj tmp;
tmp = tp_get(tp, tp->modules, tp_string(mod));
tmp = tp_get(tp, tmp, tp_string(fnc));
return tp_call(tp, tmp, params);
}
inline tp_obj _tp_import(tp_vm *tp, tp_obj fname, tp_obj name, tp_obj code) {
tp_obj g;
if (!((fname.type != TP_NONE && _tp_str_index(fname, tp_string(".tpc")) != -1) || code.type != TP_NONE)) {
return tp_ez_call(tp, "py2bc", "import_fname", tp_params_v(tp, 2, fname, name));
}
if (code.type == TP_NONE) {
tp_params_v(tp, 1, fname);
code = tp_load(tp);
}
g = tp_dict(tp);
tp_set(tp, g, tp_string("__name__"), name);
tp_set(tp, g, tp_string("__code__"), code);
tp_set(tp, g, tp_string("__dict__"), g);
tp_frame(tp, g, code, 0);
tp_set(tp, tp->modules, name, g);
if (!tp->jmp) { tp_run(tp, tp->cur); }
return g;
}
/* Function: tp_import
* Imports a module.
*
* Parameters:
* fname - The filename of a file containing the module's code.
* name - The name of the module.
* codes - The module's code. If this is given, fname is ignored.
* len - The length of the bytecode.
*
* Returns:
* The module object.
*/
inline tp_obj tp_import(tp_vm *tp, const char * fname, const char * name, void *codes, int len) {
tp_obj f = fname ? tp_string(fname) : tp_None;
tp_obj bc = codes ? tp_string_n((const char*)codes, len) : tp_None;
return _tp_import(tp, f, tp_string(name), bc);
}
inline tp_obj tp_exec_(tp_vm *tp) {
tp_obj code = TP_OBJ();
tp_obj globals = TP_OBJ();
tp_obj r = tp_None;
tp_frame(tp, globals, code, &r);
tp_run(tp, tp->cur);
return r;
}
inline tp_obj tp_import_(tp_vm *tp) {
tp_obj mod = TP_OBJ();
tp_obj r;
if (tp_has(tp, tp->modules, mod).number.val) {
return tp_get(tp, tp->modules, mod);
}
r = _tp_import(tp, tp_add(tp, mod, tp_string(".tpc")), mod, tp_None);
return r;
}
inline void tp_builtins(tp_vm *tp) {
tp_obj o;
struct { const char *s; void *f; } b[] = {
{ "print",tp_print },{ "range",tp_range },{ "min",tp_min },
{ "max",tp_max },{ "bind",tp_bind },{ "copy",tp_copy },
{ "import",tp_import_ },{ "len",tp_len_ },{ "assert",tp_assert },
{ "str",tp_str2 },{ "float",tp_float },{ "system",tp_system },
{ "istype",tp_istype },{ "chr",tp_chr },{ "save",tp_save },
{ "load",tp_load },{ "fpack",tp_fpack },{ "abs",tp_abs },
{ "int",tp_int },{ "exec",tp_exec_ },{ "exists",tp_exists },
{ "mtime",tp_mtime },{ "number",tp_float },{ "round",tp_round },
{ "ord",tp_ord },{ "merge",tp_merge },{ "getraw",tp_getraw },
{ "setmeta",tp_setmeta },{ "getmeta",tp_getmeta },
{ "bool", tp_builtins_bool },
{ 0,0 },
};
int i; for (i = 0; b[i].s; i++) {
tp_set(tp, tp->builtins, tp_string(b[i].s), tp_fnc(tp, (tp_obj(*)(tp_vm *))b[i].f));
}
o = tp_object(tp);
tp_set(tp, o, tp_string("__call__"), tp_fnc(tp, tp_object_call));
tp_set(tp, o, tp_string("__new__"), tp_fnc(tp, tp_object_new));
tp_set(tp, tp->builtins, tp_string("object"), o);
}
inline void tp_args(tp_vm *tp, int argc, char *argv[]) {
tp_obj self = tp_list(tp);
int i;
for (i = 1; i < argc; i++) { _tp_list_append(tp, self.list.val, tp_string(argv[i])); }
tp_set(tp, tp->builtins, tp_string("ARGV"), self);
}
inline tp_obj tp_main(tp_vm *tp, char *fname, void *code, int len) {
return tp_import(tp, fname, "__main__", code, len);
}
/* Function: tp_compile
* Compile some tinypy code.
*
*/
inline tp_obj tp_compile(tp_vm *tp, tp_obj text, tp_obj fname) {
return tp_ez_call(tp, "BUILTINS", "compile", tp_params_v(tp, 2, text, fname));
}
/* Function: tp_exec
* Execute VM code.
*/
inline tp_obj tp_exec(tp_vm *tp, tp_obj code, tp_obj globals) {
tp_obj r = tp_None;
tp_frame(tp, globals, code, &r);
tp_run(tp, tp->cur);
return r;
}
inline tp_obj tp_eval(tp_vm *tp, const char *text, tp_obj globals) {
tp_obj code = tp_compile(tp, tp_string(text), tp_string("<eval>"));
return tp_exec(tp, code, globals);
}
#endif