-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader.js
More file actions
88 lines (82 loc) · 2.06 KB
/
reader.js
File metadata and controls
88 lines (82 loc) · 2.06 KB
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
const Reader = function (tokens) {
this.tokens = tokens;
this.position = 0;
this.next = () => {
const currentToken = this.tokens[this.position];
this.position += 1;
return currentToken;
}
this.peek = () => {
return this.tokens[this.position];
}
}
function read_str (input) {
input = input.replace(/\\\\/g, '\\');
const reader = new Reader(tokenize(input));
return read_form(reader);
}
function tokenize (input) {
const regex = /[\s,]*(~@|[\[\]{}()'`~^@]|"(?:\\.|[^\\"])*"?|;.*|[^\s\[\]{}('"`,;)]+)/g;
return [...input.matchAll(regex)].map(match => match[1]);
}
function read_form (reader) {
const token = reader.peek();
switch (token) {
case '(':
reader.next();
return read_list(reader);
case '@':
reader.next();
return ['deref', read_form(reader)];
case "'":
reader.next();
return ['quote', read_form(reader)]
case "`":
reader.next();
return ['quasiquote', read_form(reader)]
case "~":
reader.next();
return ['unquote', read_form(reader)]
case "~@":
reader.next();
return ['splice-unquote', read_form(reader)]
default:
return read_atom(reader);
}
}
function read_list (reader, results) {
if (results === undefined) {
return read_list(reader, [])
} else {
if (reader.peek() === undefined){
throw new Error('Error: unbalanced parentheses')
}
const token = read_form(reader);
if (token === ')') {
return results;
} else {
results.push(token);
return read_list(reader, results);
}
}
}
function read_atom (reader) {
let token = reader.next();
const float = parseFloat(token);
if (!isNaN(float)){
return float;
} else if (token === 'nil'){
return null;
} else if (token === 'true') {
return true;
} else if (token === 'false') {
return false;
} else if (/^".*"$/g.test(token)) {
token = token.slice(1, -1);
token = token.replace(/\\"/g, '"').replace(/\\n/g, '\n');
return `"${token}"`;
} else {
return token;
}
}
exports.read_str = read_str;