/
reader.zig
341 lines (302 loc) · 10.3 KB
/
reader.zig
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
const fmt = @import("std").fmt;
const warn = @import("std").debug.warn;
pub const pcre = @cImport({
@cInclude("pcre.h");
});
const MalType = @import("types.zig").MalType;
const MalData = @import("types.zig").MalData;
const MalTypeValue = @import("types.zig").MalTypeValue;
const MalError = @import("error.zig").MalError;
const MalLinkedList = @import("linked_list.zig").MalLinkedList;
const printer = @import("printer.zig");
const Allocator = @import("std").heap.c_allocator;
const string_eql = @import("utils.zig").string_eql;
const linked_list = @import("linked_list.zig");
const match: [*]const u8 =
c\\[\s,]*(~@|[\[\]{}()'`~^@]|"(?:\\.|[^\\"])*"?|;.*|[^\s\[\]{}('"`,;)]*)
;
var error_msg: [*c]const u8 = undefined;
var erroroffset: c_int = 0;
var re: ?*pcre.pcre = null;
const Reader = struct {
position: u32,
string: [] const u8,
tokens: [] usize,
pub fn init(string: [] const u8, tokens: [] usize) Reader {
return Reader {
.position = 0,
.string = string,
.tokens = tokens,
};
}
pub fn next(self: *Reader) []const u8 {
const this_token = self.peek();
self.position += 1;
return this_token;
}
pub fn peek(self: *Reader) []const u8 {
while(!self.eol()) {
const start = self.tokens[2*self.position];
const end = self.tokens[2*self.position+1];
if(self.string[start] == ';') {
self.position += 1;
continue;
}
return self.string[start..end];
}
return "";
}
pub fn eol(self: *Reader) bool {
return (2 * self.position >= self.tokens.len);
}
};
const AliasPair = struct {
name: []const u8,
value: []const u8,
count: u8,
};
const alias_pairs = [_] AliasPair {
AliasPair {.name="@", .value="deref", .count=1},
AliasPair {.name="\'", .value="quote", .count=1},
AliasPair {.name="`", .value="quasiquote", .count=1},
AliasPair {.name="~", .value="unquote", .count=1},
AliasPair {.name="~@", .value="splice-unquote", .count=1},
AliasPair {.name="^", .value="with-meta", .count=2},
};
pub fn read_form(reader: *Reader) MalError!?*MalType {
if(reader.eol()) {
return null;
}
const token = reader.peek();
if(token.len == 0) {
return MalType.new_nil(Allocator);
}
if(token[0] == '(') {
return try read_list(reader);
}
else if(token[0] == '[') {
return try read_vector(reader);
}
else if(token[0] == ':') {
const keyword = reader.next();
return MalType.new_keyword(Allocator, keyword[1..keyword.len]);
}
else if(token[0] == '{') {
return try read_hashmap(reader);
}
for(alias_pairs) |pair| {
const name = pair.name;
const value = pair.value;
const count = pair.count;
if(!string_eql(token, name)) {
continue;
}
var new_ll = MalLinkedList.init(Allocator);
const new_generic = try MalType.new_generic(Allocator, value);
const tmp = reader.next();
var num_read: u8 = 0;
while(num_read < count) {
const next_read = (try read_form(reader)) orelse return MalError.ArgError;
try linked_list.prepend_mal(Allocator, &new_ll, next_read);
num_read += 1;
}
try linked_list.prepend_mal(Allocator, &new_ll, new_generic);
const new_list = try MalType.new_nil(Allocator);
new_list.data = MalData {.List = new_ll};
return new_list;
}
return try read_atom(reader);
}
pub fn read_list(reader: *Reader) MalError!*MalType {
const first_token = reader.next();
var new_ll = MalLinkedList.init(Allocator);
const mal_list: *MalType = try MalType.new_nil(Allocator);
while(!reader.eol()) {
var next_token = reader.peek();
if(next_token.len == 0) {
return MalError.ReaderUnmatchedParen;
}
if(next_token[0] == ')') {
const right_paren = reader.next();
mal_list.data = MalData{.List = new_ll};
return mal_list;
}
const mal = (try read_form(reader)) orelse return MalError.ArgError;
try linked_list.append_mal(Allocator, &new_ll, mal);
}
return MalError.ReaderUnmatchedParen;
}
pub fn read_vector(reader: *Reader) MalError!*MalType {
const first_token = reader.next();
var new_ll = MalLinkedList.init(Allocator);
const mal_list: *MalType = try MalType.new_nil(Allocator);
while(!reader.eol()) {
var next_token = reader.peek();
if(next_token.len == 0) {
return MalError.ReaderUnmatchedParen;
}
if(next_token[0] == ']') {
const right_paren = reader.next();
mal_list.data = MalData{.Vector = new_ll};
return mal_list;
}
const mal = (try read_form(reader)) orelse return MalError.ArgError;
try linked_list.append_mal(Allocator, &new_ll, mal);
}
return MalError.ReaderUnmatchedParen;
}
pub fn read_hashmap(reader: *Reader) MalError!*MalType {
const first_token = reader.next();
const new_hashmap = try MalType.new_hashmap(Allocator);
while(!reader.eol()) {
var next_token = reader.peek();
if(next_token.len == 0) {
return MalError.ReaderUnmatchedParen;
}
if(next_token[0] == '}') {
const right_paren = reader.next();
return new_hashmap;
}
const mal = (try read_form(reader)) orelse return MalError.ArgError;
const key = switch(mal.data) {
.String => |s| s,
.Keyword => |kwd| kwd,
else => return MalError.TypeError,
};
if(next_token.len == 0 or next_token[0] == '}') {
return MalError.ReaderBadHashmap;
}
const val = (try read_form(reader)) orelse return MalError.ArgError;
try new_hashmap.hashmap_insert(key, val);
}
return MalError.ReaderUnmatchedParen;
}
fn char_is_int(c: u8) bool {
return (c >= '0' and c <= '9');
}
fn token_is_int(token: []const u8) bool {
if(char_is_int(token[0]))
return true;
if(token.len >= 2 and token[0] == '-' and char_is_int(token[1]))
return true;
return false;
}
pub fn read_atom(reader: *Reader) MalError!*MalType {
const token = reader.next();
if(token_is_int(token)) {
var mal_atom = try MalType.new_nil(Allocator);
try read_atom_int(mal_atom, token);
return mal_atom;
}
else if(string_eql(token, "nil")) {
return MalType.new_nil(Allocator);
}
else if(string_eql(token, "true")) {
return MalType.new_bool(Allocator, true);
}
else if(string_eql(token, "false")) {
return MalType.new_bool(Allocator, false);
}
else if(token[0] == '"') {
var mal_atom = try MalType.new_nil(Allocator);
try read_atom_string(mal_atom, token);
return mal_atom;
}
else {
var mal_atom = try MalType.new_generic(Allocator, token);
return mal_atom;
}
}
fn read_atom_int(mal_atom: *MalType, token: []const u8) MalError!void {
// TODO: extract int type from union
mal_atom.data = MalData {.Int = fmt.parseInt(i32, token, 10)
catch |err| return MalError.SystemError };
}
fn read_atom_string(mal_atom: *MalType, token: []const u8) MalError!void {
const n = token.len;
if(token[0] != '"' or token[n-1] != '"' or n <= 1) {
return MalError.ReaderUnmatchedString;
}
if(n <= 2) {
// We get here when the token is an empty string.
// We encode this as MalTypeValue.String, with null .string_value
var string = Allocator.alloc(u8, 0) catch return MalError.SystemError;
mal_atom.data = MalData {.String = string};
return;
}
var tmp_buffer = Allocator.alloc(u8, n-2) catch return MalError.SystemError;
defer Allocator.free(tmp_buffer);
var i: usize = 1;
var j: usize = 0;
const escape_char: u8 = '\\'; //TODO: remove this comment required by bad emacs config '
while(i < n-1) {
if(token[i] != escape_char) {
tmp_buffer[j] = token[i];
j += 1;
i += 1;
}
else {
if(i==n-2) {
return MalError.ReaderUnmatchedString;
}
if(token[i+1] == 'n') {
tmp_buffer[j] = '\n';
} else {
tmp_buffer[j] = token[i+1];
}
j += 1;
i += 2;
}
}
var string = Allocator.alloc(u8, j) catch return MalError.SystemError;
i = 0;
while(i < j) {
string[i] = tmp_buffer[i];
i += 1;
}
mal_atom.data = MalData {.String = string};
}
pub fn read_str(string: [] const u8) MalError!Reader {
if(re == null) {
re = pcre.pcre_compile(&match[0], 0, &error_msg, &erroroffset, 0);
}
const tokens = try tokenize(re, string);
return Reader.init(string, tokens);
}
// Allocates an array of matches. Caller is becomes owner of memory.
pub fn tokenize(regex: ?*pcre.pcre, string: [] const u8) MalError![] usize {
// TODO: pass in allocator
const buffer_size: usize = 3 * string.len + 10;
var indices: [] c_int = Allocator.alloc(c_int, buffer_size)
catch return MalError.SystemError;
defer Allocator.free(indices);
var match_buffer: [] usize = Allocator.alloc(usize, buffer_size)
catch return MalError.SystemError;
defer Allocator.free(match_buffer);
var current_match: usize = 0;
var start_pos: c_int = 0;
var rc: c_int = 0;
var start_match: usize = 0;
var end_match: usize = 0;
const subject_size: c_int = @intCast(c_int, string.len);
while(start_pos < subject_size) {
rc = pcre.pcre_exec(regex, 0, &string[0], subject_size, start_pos, 0,
&indices[0], @intCast(c_int,buffer_size));
if(rc <= 0)
break;
start_pos = indices[1];
start_match = @intCast(usize, indices[2]);
end_match = @intCast(usize, indices[3]);
match_buffer[current_match] = start_match;
match_buffer[current_match+1] = end_match;
current_match += 2;
}
var matches: [] usize = Allocator.alloc(usize, current_match)
catch return MalError.SystemError;
var i: usize = 0;
while(i < current_match) {
matches[i] = match_buffer[i];
i += 1;
}
return matches;
}