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
|
#include <stdio.h>
#include <string.h>
#ifdef _FUSPEL_CLI
#include <argp.h>
#include <stdbool.h>
#endif
#include "eval.h"
#include "lex.h"
#include "mem.h"
#include "parse.h"
#include "print.h"
#define LINE_LENGTH 139
fuspel* import(fuspel* already_parsed, char* fname) {
token_list* tokens = NULL;
fuspel* pgm;
FILE* f;
char* fname_;
fname_ = my_calloc(1, strlen(fname) + 6);
strcpy(fname_, fname);
strcat(fname_, ".fusp");
f = fopen(fname_, "r");
if (!f) {
fprintf(stderr, "Couldn't read %s\n", fname_);
exit(EXIT_FAILURE);
}
printf("Lexing %s...\n", fname_);
while (!feof(f)) {
char program[LINE_LENGTH];
if (!fgets(program, LINE_LENGTH, f)) {
if (feof(f))
break;
fprintf(stderr, "Couldn't read input.\n");
exit(EXIT_FAILURE);
}
tokens = lex(tokens, program);
if (!tokens) {
fprintf(stderr, "Couldn't lex program.\n");
exit(EXIT_FAILURE);
}
}
printf("Parsing %s...\n", fname_);
my_free(fname_);
pgm = parse(tokens);
free_token_list(tokens);
my_free(tokens);
concat_fuspel(pgm, already_parsed);
return pgm;
}
#ifdef _FUSPEL_CLI
const char *argp_prog_version = "fuspel";
const char *argp_prog_bugs = "<info@camilstaps.nl>";
static char doc[] = "Interpret a fuspel program";
static char args_doc[] = "MODULE [MODULE [MODULE [..]]]";
static struct argp_option options[] = {
{ "print-program", 'P', 0, 0, "Print the parsed program before execution" },
{ 0 }
};
struct environment {
fuspel* program;
bool printProgram;
};
static error_t parse_opt(int key, char *arg, struct argp_state *state) {
struct environment *env = state->input;
switch (key) {
case 'P':
env->printProgram = true;
break;
case ARGP_KEY_ARG:
env->program = import(env->program, arg);
return 0;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static struct argp argp = { options, parse_opt, args_doc, doc, 0, 0, 0 };
int main(int argc, char* argv[]) {
expression* result;
int i;
struct environment env;
env.printProgram = false;
env.program = NULL;
argp_parse(&argp, argc, argv, 0, 0, &env);
if (!env.program) {
fprintf(stderr, "Couldn't parse program.\n");
exit(EXIT_FAILURE);
}
if (env.printProgram) {
printf("\n");
print_fuspel(env.program);
printf("\n\n");
}
result = eval_main(env.program);
if (result) {
print_expression(result);
printf("\n");
free_expression(result);
my_free(result);
}
free_fuspel(env.program);
my_free(env.program);
return 0;
}
#endif
|