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
|
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include "aplwc_repl.h"
int
main(int argc, char *argv[])
{
struct aplwc *aplwc;
struct aplwc_line *line;
struct aplwc_value *value;
uint8_t *data;
char *input;
int ret, exit_code, line_number;
size_t memsize, input_size;
int opt, xflag, input_file;
FILE *f;
input = NULL;
line = NULL;
value = NULL;
xflag = 0;
input_file = 0;
exit_code = 0;
line_number = 0;
while((opt = getopt(argc, argv, "x")) != -1){
switch(opt){
case 'x':
xflag = 1;
break;
default:
usage:
fprintf(stderr, "Usage: %s [-x] [file]\n", argv[0]);
return 1;
}
}
if((optind+1) == argc){
input_file = 1;
f = fopen(argv[optind], "r");
if(f == NULL){
fprintf(stderr, "Could not open file: %s: %s\n", argv[optind], strerror(errno));
return 1;
}
}else if(optind == argc)
f = stdin;
else
goto usage;
memsize = getenv_ulong("APLWC_MEM", APLWC_MIN_MEM);
data = malloc(memsize);
if(data == NULL){
fprintf(stderr, "Couldn't allocate memory\n");
return 1;
}
ret = aplwc_new(&aplwc, data, memsize);
if(ret){
fprintf(stderr, "Couldn't create new aplwc instance: %s\n", aplwc_errstr_rc(ret));
free(data);
return 1;
}
if(xflag)
goto exit;
for(;;){
if(input)
free(input);
if(line)
aplwc_free_line(line);
if(value)
aplwc_free_value(value);
input = NULL;
if(getline(&input, &input_size, f) < 0){
free(input);
break;
}else{
line_number++;
if(input_file && (line_number == 1)){
if((strlen(input) > 2) && (input[0] == '#') && (input[1] == '!'))
continue;
}
line = aplwc_read(aplwc, input);
if(line == NULL){
line_error:
fprintf(stderr, "error on line %d: %s: %s\n", line_number, aplwc_errstr(aplwc), input);
if(input_file){
exit_code = 1;
goto exit;
}
continue;
}
value = aplwc_eval(line);
if(value == NULL)
goto line_error;
fprintf(stdout, "%s\n", aplwc_value_string(value));
}
}
exit:
if(input)
free(input);
if(line)
aplwc_free_line(line);
if(value)
aplwc_free_value(value);
aplwc_destroy(aplwc);
free(data);
return exit_code;
}
|