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
|
#include "pez.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>
#include <readline/history.h>
#define CHECK(x) do { \
if (!(x)) { \
fprintf(stderr, "%s\n", pez_geterr(cx)); \
assert(!#x); \
} \
} while (0)
static bool
printtop(PezContext *cx)
{
assert(pez_top(cx) >= 2);
return
pez_push(cx, 0) // printf was stored here
&& pez_pushstring(cx, "%a", 2)
&& pez_push(cx, -3)
&& pez_apply(cx, 2)
&& (pez_pop(cx), pez_pop(cx), 1);
}
static void
help(void)
{
printf("Usage: pez [OPTION]... [FILE] [ARG]...\n"
"With no FILE, enter repl.\n"
"\n"
" -h, --help show this help message\n"
" -db debug: print bytecode\n"
" -dG debug: stress GC\n"
" -dg debug: print GC info\n"
"\n");
}
int
main(int argc, char **argv) {
PezContext *cx = pez_new(NULL, NULL, 8*1024 /* 8KiB stack */);
FILE *fp = NULL;
int i, ret = 0;
assert(cx != NULL && "no context");
for (i = 1; i < argc; ++i) {
const char *arg = argv[i];
if (*arg == '-') {
if (!strcmp(arg, "-h") || !strcmp(arg, "--help")) {
help();
goto Bye;
} else if (arg[1] == 'd' && arg[2]) {
pez_debug(cx, arg + 2);
} else {
printf("pez: Invalid option '%s'\n", arg);
help();
ret = 1;
goto Bye;
}
} else {
fp = fopen(arg, "r");
if (!fp) {
perror(arg);
ret = 1;
goto Bye;
}
break;
}
}
if (!fp) {
char *src;
using_history();
CHECK(pez_pushglobal(cx, "printf"));
CHECK(pez_pushvoid(cx) && pez_setglobal(cx, "_"));
while ((src = readline("> "))) {
add_history(src);
if (!pez_eval_str(cx, "<repl>", src)) {
fprintf(stderr, "error: %s\n", pez_geterr(cx));
} else {
assert(pez_top(cx) == 2);
CHECK(pez_push(cx, -1));
CHECK(pez_setglobal(cx, "_"));
CHECK(printtop(cx));
printf("\n");
}
free(src);
}
} else {
if (!pez_eval_file(cx, argv[i], fp)) {
fprintf(stderr, "error: %s\n", pez_geterr(cx));
ret = 1;
goto Bye;
}
assert(pez_top(cx) == 1);
}
Bye:
if (fp) {
fclose(fp);
}
pez_del(cx);
return ret;
}
|