-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.c
564 lines (477 loc) · 16 KB
/
main.c
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
/*
* MUSL standalone interpreter.
* This file implements a standalone scripting language
* built on top of the MUSL.
* It is also intended to serve as an example of how to
* embed MUSL in your own application, and adds some
* file handling functions to demonstrate adding your own
* functions to the interpreter.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef WITH_REGEX
#include <sys/types.h>
#include <regex.h>
#endif
#include "musl.h"
#define INPUT_BUFFER_SIZE 80
#define NUM_FILES 10
/* This structure shows how we can store arbitrary user data in a musl structure.
* User data is useful if you have several interpreters in the same program that
* needs to store their own state.
*/
struct user_data {
FILE * files[NUM_FILES];
};
/* These functions are declared at the bottom of this file.
* They are additional functions that this program adds to the
* interpreter.
* Note that they conform to the mu_func prototype.
* Look at the comments in the definitions below to see how to
* add your own functions to a musl interpreter.
*/
static struct mu_par my_print(struct musl *m, int argc, struct mu_par argv[]);
static struct mu_par my_input_s(struct musl *m, int argc, struct mu_par argv[]);
static struct mu_par my_input(struct musl *m, int argc, struct mu_par argv[]);
static struct mu_par my_fopen(struct musl *m, int argc, struct mu_par argv[]);
static struct mu_par my_fclose(struct musl *m, int argc, struct mu_par argv[]);
static struct mu_par my_feof(struct musl *m, int argc, struct mu_par argv[]);
static struct mu_par my_fread(struct musl *m, int argc, struct mu_par argv[]);
static struct mu_par my_fwrite(struct musl *m, int argc, struct mu_par argv[]);
static struct mu_par my_srand(struct musl *m, int argc, struct mu_par argv[]);
static struct mu_par my_rand(struct musl *m, int argc, struct mu_par argv[]);
static struct mu_par my_time(struct musl *m, int argc, struct mu_par argv[]);
static struct mu_par my_regex(struct musl *m, int argc, struct mu_par argv[]);
static struct mu_par my_call(struct musl *m, int argc, struct mu_par argv[]);
static struct mu_par my_halt(struct musl *m, int argc, struct mu_par argv[]);
static struct mu_par my_dump(struct musl *m, int argc, struct mu_par argv[]);
int main(int argc, char *argv[]) {
char *s;
int r, i;
struct musl *m;
struct user_data data;
srand(time(NULL)); /* For in case */
for(r = 0; r < NUM_FILES; r++)
data.files[r] = NULL;
if(argc <= 1) {
fprintf(stderr, "Usage: %s FILE1 FILE2 ...\n", argv[0]);
return 1;
}
if(!(m = mu_create())) {
fprintf(stderr, "ERROR: Couldn't create MUSL structure\n");
exit(EXIT_FAILURE);
}
/* Store a pointer to our user data in the musl structure */
mu_set_data(m, &data);
/* Add the custom functions to the interpreter here.
* Function names must be in lowercase.
*/
mu_add_func(m, "print", my_print);
mu_add_func(m, "input$", my_input_s);
mu_add_func(m, "input", my_input);
mu_add_func(m, "open", my_fopen);
mu_add_func(m, "close", my_fclose);
mu_add_func(m, "eof", my_feof);
/* Note that functions that return strings' names must end with '$' */
mu_add_func(m, "read$", my_fread);
mu_add_func(m, "write", my_fwrite);
mu_add_func(m, "randomize", my_srand);
mu_add_func(m, "random", my_rand);
mu_add_func(m, "time", my_time);
mu_add_func(m, "regex", my_regex);
mu_add_func(m, "call", my_call);
mu_add_func(m, "halt", my_halt);
mu_add_func(m, "dump", my_dump);
/* You can replace built-in functions with new ones.
* You can also disable built-in functions by replacing them
* with NULL as in mu_add_func(m, "print", NULL);
*/
/* This is how you can set the values of variables */
mu_set_str(m, "mystr$", "fnord");
mu_set_int(m, "mynum", 12345);
/* You can also access array variables like this: */
mu_set_str(m, "myarray$[foo]", "XYZZY");
for(i = 1; i < argc; i++) {
/* mu_readfile() is a helper function to read an entire
* script file into memory
*/
if(!(s = mu_readfile(argv[i]))) {
fprintf(stderr, "ERROR: Unable to read \"%s\"\n", argv[i]);
break;
}
#ifdef TEST
printf("============\n%s\n============\n", s);
#endif
/* Run the script from the string */
if(!mu_run(m, s)) {
/* This is how you retrieve info about interpreter errors: */
fprintf(stderr, "ERROR:Line %d: %s:\n>> %s\n", mu_cur_line(m), mu_error_msg(m),
mu_error_text(m));
mu_dump(m, stderr);
}
/* The return value of mu_readfile() also needs to be free()'ed.
* Just don't free() it if you're still going to call mu_cur_line()
*/
free(s);
}
#ifdef TEST
/* This is how you retrieve variable values from the interpreter: */
printf("============\nmystr$= \"%s\"\nmynum= %d\nmyarray$[foo]= \"%s\"\n",
mu_get_str(m, "mystr$"), mu_get_int(m, "mynum"), mu_get_str(m, "myarray$[foo]"));
#endif
/* Destroy the interpreter when we're done with it */
mu_cleanup(m);
for(i = 0; i < NUM_FILES; i++)
if(data.files[i])
fclose(data.files[i]);
return 0;
}
/*3 Extended Functions
*# These functions are available to programs run using the
*# standalone interpreter:
*#
*/
/*@ ##PRINT(exp1, exp2, ...)
*# Prints all its parameters, followed by a newline
*/
static struct mu_par my_print(struct musl *m, int argc, struct mu_par argv[]) {
struct mu_par rv = {mu_int, {argc}};
int i;
for(i = 0; i < argc; i++) {
if(i > 0)
fputc(' ', stdout);
if(argv[i].type == mu_str)
fputs(argv[i].v.s, stdout);
else
printf("%d", argv[i].v.i);
}
fputs("\n", stdout);
return rv;
}
/*@ ##INPUT$([prompt], [@var]) INPUT([prompt], [@var])
*# Reads a string from the keyboard, with an optional prompt.\n
*# The first form returns the input value as a string, while
*# the second form converts the value to an integer internally.\n
*# Trailing newline characters are removed.\n
*# It returns the input string. If the optional {{@var}} parameter
*# is specified, {{var}} is also set to the input string.
*/
static struct mu_par my_input_s(struct musl *m, int argc, struct mu_par argv[]) {
struct mu_par rv;
char *c;
if(argc == 0)
fputs("> ", stdout);
else {
fputs(mu_par_str(m, 0, argc, argv), stdout);
fputc(' ', stdout);
}
fflush(stdout);
rv.type = mu_str;
rv.v.s = malloc(INPUT_BUFFER_SIZE + 1);
if(!rv.v.s) {
mu_throw(m, "Out of memory");
}
rv.v.s[0] = '\0';
if(fgets(rv.v.s, INPUT_BUFFER_SIZE, stdin))
for(c=rv.v.s;c[0];c++)
if(strchr("\r\n",c[0]))
c[0] = '\0';
if(argc > 1) {
const char * name = mu_par_str(m, 1, argc, argv);
mu_set_str(m, name, rv.v.s);
}
return rv;
}
static struct mu_par my_input(struct musl *m, int argc, struct mu_par argv[]) {
struct mu_par rv;
char buffer[50];
if(argc == 0)
fputs("> ", stdout);
else {
fputs(mu_par_str(m, 0, argc, argv), stdout);
fputc(' ', stdout);
}
fflush(stdout);
rv.type = mu_int;
rv.v.i = 0;
if(fgets(buffer, sizeof buffer - 1, stdin))
rv.v.i = atoi(buffer);
if(argc > 1) {
const char * name = mu_par_str(m, 1, argc, argv);
mu_set_int(m, name, rv.v.i);
}
return rv;
}
/*@ ##OPEN(path, mode)
*# Opens a given file in a specific mode.\n
*# {{mode}} can be "r" for reading, "w" for writing, "a" for appending.\n
*# It returns a number that should be used with {{~~CLOSE()}}, {{~~READ$()}} and {{~~WRITE()}}.
*/
static struct mu_par my_fopen(struct musl *m, int argc, struct mu_par argv[]) {
const char *path, *mode;
struct mu_par rv; /* Stores the return value of our function */
struct user_data *data = mu_get_data(m);
path = mu_par_str(m, 0, argc, argv); /* Get the path from the first parameter */
mode = mu_par_str(m, 1, argc, argv); /* Get the path from the second parameter */
/* Our function returns an index into the file table */
rv.type = mu_int;
/* Find the first available file handle */
for(rv.v.i = 0; rv.v.i < NUM_FILES && data->files[rv.v.i]; rv.v.i++);
if(rv.v.i == NUM_FILES)
mu_throw(m, "Too many open files");
data->files[rv.v.i] = fopen(path, mode);
if(!data->files[rv.v.i])
mu_throw(m, "Unable to OPEN() file");
return rv;
}
/*@ ##CLOSE(f)
*# Closes a previously opened file.\n
*# {{f}} is the number of the file previously opened with {{~~OPEN()}}.
*/
static struct mu_par my_fclose(struct musl *m, int argc, struct mu_par argv[]) {
struct mu_par rv = {mu_int, {0}};
int index;
struct user_data *data = mu_get_data(m);
index = mu_par_int(m, 0, argc, argv);
if(index < 0 || index > NUM_FILES || !data->files[index])
mu_throw(m, "Invalid file handle in CLOSE()");
fclose(data->files[index]);
data->files[index] = NULL;
return rv;
}
/*@ ##EOF(f)
*# Returns 1 if the end of a file has been reached.\n
*# {{f}} is the number of the file previously opened with {{~~OPEN()}}.
*/
static struct mu_par my_feof(struct musl *m, int argc, struct mu_par argv[]) {
struct mu_par rv = {mu_int, {0}};
int index;
struct user_data *data = mu_get_data(m);
index = mu_par_int(m, 0, argc, argv);
if(index < 0 || index > NUM_FILES || !data->files[index])
mu_throw(m, "Invalid file handle in EOF()");
rv.v.i = feof(data->files[index]);
return rv;
}
/*@ ##READ$(f)
*# Reads a line of text from a file.\n
*# {{f}} is the number of the file previously opened with {{~~OPEN()}}.\n
*# It trims the trailing newline.
*/
static struct mu_par my_fread(struct musl *m, int argc, struct mu_par argv[]) {
struct mu_par rv;
int index, i;
char buffer[INPUT_BUFFER_SIZE];
struct user_data *data = mu_get_data(m);
index = mu_par_int(m, 0, argc, argv);
if(index < 0 || index > NUM_FILES || !data->files[index])
mu_throw(m, "Invalid file handle in READ$()");
if(!fgets(buffer, INPUT_BUFFER_SIZE, data->files[index]))
{
if(feof(data->files[index]))
buffer[0] = '\0';
else
mu_throw(m, "Couldn't READ$() from file");
}
for(i = 0; buffer[i]; i++)
if(buffer[i] == '\r' || buffer[i] == '\n')
buffer[i] = '\0';
/* NOTE that functions returning strings must allocate those
* strings on the heap because musl will try to free() them
* when they're no longer in use. Hence the strdup() below.
*/
rv.type = mu_str;
rv.v.s = strdup(buffer);
if(!rv.v.s)
mu_throw(m, "Out of memory");
return rv;
}
/*@ ##WRITE(f, par1, par2, par, ...)
*# Writes all its parameters to a file, followed by a newline.\n
*# {{f}} is the number of the file previously opened with {{~~OPEN()}}.\n
*# The remaining parameters can be numbers or strings, and will be
*# separated by spaces.
*/
static struct mu_par my_fwrite(struct musl *m, int argc, struct mu_par argv[]) {
struct mu_par rv = {mu_int, {0}};
int index, i;
struct user_data *data = mu_get_data(m);
index = mu_par_int(m, 0, argc, argv);
if(index < 0 || index > NUM_FILES || !data->files[index])
mu_throw(m, "Invalid file handle in EOF()");
for(i = 1; i < argc; i++)
{
if(argv[i].type == mu_str)
fputs(argv[i].v.s, data->files[index]);
else
fprintf(data->files[index], "%d", argv[i].v.i);
fputs(i == argc-1?"\n":" ", data->files[index]);
}
return rv;
}
/*@ ##RANDOMIZE([seed])
*# Initializes the system random number generator with an optional 'seed'
*/
static struct mu_par my_srand(struct musl *m, int argc, struct mu_par argv[]) {
struct mu_par rv = {mu_int, {0}};
srand(argc?mu_par_int(m, 0, argc, argv):time(NULL));
return rv;
}
/*@ ##RANDOM() RANDOM(N) RANDOM(N,M)
*{
** {{RANDOM()}} - Chooses a random number
** {{RANDOM(N)}} - Chooses a random number in the range [1, N]
** {{RANDOM(N,M)}} - Chooses a random number in the range [N, M]
*}
*/
static struct mu_par my_rand(struct musl *m, int argc, struct mu_par argv[]) {
struct mu_par rv = {mu_int, {0}};
rv.v.i = rand();
if(argc == 1) {
int f = mu_par_int(m,0, argc, argv);
if(f <= 0)
mu_throw(m, "Parameter to RANDOM(N) must be greater than 0");
rv.v.i = (rv.v.i % f) + 1;
} else if(argc == 2) {
int f = (mu_par_int(m,1, argc, argv) - mu_par_int(m,0, argc, argv) + 1);
if(f <= 0)
mu_throw(m, "Parameters to RANDOM(N,M) must satisfy M-N+1 > 0");
rv.v.i = (rv.v.i % f) + mu_par_int(m,0, argc, argv);
}
return rv;
}
/*@ ##TIME([fmt])
*# Returns the current time as a formatted string.\n
*# The optional {{fmt}} parameter specifies the output
*# format, using the same notation as {{strftime()}} in
*# the C standard library.
*# The default format is {{"%Y/%m/%d %H:%M:%S"}}.
*/
static struct mu_par my_time(struct musl *m, int argc, struct mu_par argv[]) {
struct mu_par rv = {mu_str, {0}};
time_t t;
struct tm *tmp;
const char *fmt = "%Y/%m/%d %H:%M:%S";
char buffer[50];
if(argc > 0)
fmt = mu_par_str(m,0, argc, argv);
time(&t);
tmp = localtime(&t);
if(!tmp) {
mu_throw(m, "localtime() error in TIME()");
}
if(!strftime(buffer, sizeof buffer,fmt,tmp)) {
mu_throw(m, "Unable to format time in TIME('%s')", fmt);
}
rv.v.s = strdup(buffer);
return rv;
}
/*
* The regex function requires the POSIX regular expression functions
* regcomp, regexec, regerror, regfree, which may not be available on
* all platforms.
*/
/*@ ##REGEX(pattern$, string$)
*# Matches the regex {{pattern$}} to {{string$}}.\n
*# It uses the POSIX Extended regular expression syntax
*# described in {{'man 7 regex'}}.\n
*# It returns the number of matches/submatches or 0 if {{string$}}
*# does not match the {{pattern$}}.\n
*# On a successful match, the array {{_M$[]}} will be filled with
*# the submatches. Note that {{_M$[]}} is zero indexed: {{_M$[0]}} will
*# contain the entire string that matched the regex.\n
*# This implies that on a successful match, the largest index in
*# {{_M$[]}} will be one less than the return value of {{REGEX()}}
*/
static struct mu_par my_regex(struct musl *m, int argc, struct mu_par argv[])
{
struct mu_par rv = {mu_int, {0}};
#ifdef WITH_REGEX
#define NAME_SIZE 80
const char *pat = mu_par_str(m, 0, argc, argv);
const char *str = mu_par_str(m, 1, argc, argv);
regex_t preg;
regmatch_t sm[10];
int r;
char errbuf[128];
if((r = regcomp(&preg, pat, REG_EXTENDED)) != 0) {
regerror(r, &preg, errbuf, sizeof errbuf);
regfree(&preg);
mu_throw(m, "In REGEX(): %s", errbuf);
}
if((r = regexec(&preg, str, 10, sm, 0)) != 0) {
if(r != REG_NOMATCH) {
regerror(r, &preg, errbuf, sizeof errbuf);
regfree(&preg);
mu_throw(m, "In REGEX(): %s", errbuf);
}
rv.v.i = 0;
} else {
for(r = 0; r < 10; r++) {
const char *c, *start;
char *match, name[30];
if(sm[r].rm_so < 0)
break;
match = malloc(sm[r].rm_eo + 1);
if(!match)
mu_throw(m, "Out of memory");
start = str + sm[r].rm_so;
for(c = start; c - str < sm[r].rm_eo; c++)
match[c - start] = *c;
match[c - start] = '\0';
snprintf(name, sizeof name, "_m$[%d]", r);
if(!mu_set_str(m, name, match))
mu_throw(m, "Out of memory");
free(match);
}
if(!mu_set_int(m, "_m$[length]", r))
mu_throw(m, "Out of memory");
rv.v.i = r;
}
regfree(&preg);
#else
mu_throw(m, "This version of Musl was compiled without Regex support");
#endif
return rv;
}
/*@ ##CALL(label$)
*# {{CALL("label")}} is the same as {{GOSUB label}}.\n
*# {/It is mainly here to test and demo the {{~~mu_gosub()}} API function./}
*/
static struct mu_par my_call(struct musl *m, int argc, struct mu_par argv[]) {
struct mu_par rv = {mu_int, {0}};
const char *label = mu_par_str(m, 0, argc, argv);
rv.v.i = mu_gosub(m, label);
if(!rv.v.i) {
/* You really should call mu_throw(), but you get an opportunity first to
* clean up after yourself.
* The NULL parameter to mu_throw() lets it keep the current value of m->error_msg
*/
/* FIXME: This call to mu_throw() causes the parameter to CALL() to be leaked.
devnotes.txt explains the situation.
*/
mu_throw(m, NULL);
}
return rv;
}
/*@ ##HALT()
*# Halts the interpreter immediately.\n
*# Calling this is equivalent to executing an {{END}} statement.\n
*# {/It is mainly here to test and demo the {{~~mu_halt()}} API function./}
*/
static struct mu_par my_halt(struct musl *m, int argc, struct mu_par argv[]) {
struct mu_par rv = {mu_int, {0}};
mu_halt(m);
return rv;
}
/*@ ##DUMP()
*# Dumps the contents of the interpreter's memory to the standard error stream.\n
*# This is the closest that Musl is going to come to a debugger.
*/
static struct mu_par my_dump(struct musl *m, int argc, struct mu_par argv[]) {
struct mu_par rv = {mu_int, {0}};
mu_dump(m, stderr);
return rv;
}