-
Notifications
You must be signed in to change notification settings - Fork 2
/
jsonlexer.d
248 lines (223 loc) · 5.15 KB
/
jsonlexer.d
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
/**
* JSON lexer.
* Authors: Brian Schott
* Standards: $(LINK2 http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf, ECMA-404)
*/
module jsonlexer;
import std.file;
import std.algorithm;
import stdx.lexer;
import std.stdio;
// JSON is pretty simple. These are the only fixed-representation tokens.
// Normally things like "true", and "false" would be possible default tokens,
// but JSON has no identifiers that they could be confused with.
private enum fixedTokens = [
"{", "}", "[", "]", ",", ":", "true", "false", "null"
];
// Empty. JSON has no keywords that could be confused with any sort of dynamic
// token.
private enum keywords = [];
// Very simple
private enum dynamicTokens = [
"string", "number", "whitespace"
];
// Map the beginning of the dynamic tokens to their handling functions
private enum tokenHandlers = [
"\"", "lexStringLiteral",
"0", "lexNumber",
"1", "lexNumber",
"2", "lexNumber",
"3", "lexNumber",
"4", "lexNumber",
"5", "lexNumber",
"6", "lexNumber",
"7", "lexNumber",
"8", "lexNumber",
"9", "lexNumber",
" ", "lexWhitespace",
"\t", "lexWhitespace",
"\r", "lexWhitespace",
"\n", "lexWhitespace"
];
alias IdType = TokenIdType!(fixedTokens, dynamicTokens, keywords);
public alias str = tokenStringRepresentation!(IdType, fixedTokens, dynamicTokens, keywords);
template tok(string token)
{
alias tok = TokenId!(IdType, fixedTokens, dynamicTokens, keywords, token);
}
enum extraFields = "";
alias Token = TokenStructure!(IdType, extraFields);
struct JSONLexer
{
mixin Lexer!(Token, lexError, isSeparating, fixedTokens,
dynamicTokens, keywords, tokenHandlers);
this(ubyte[] source, StringCache* cache)
{
this.range = LexerRange(source);
this.cache = cache;
popFront();
}
void popFront() pure
{
_popFront();
}
private:
Token lexWhitespace() pure nothrow @safe
{
import std.ascii;
mixin (tokenStart);
while (!range.empty && isWhite(range.front))
range.popFront();
string text = cache.cacheGet(range.slice(mark));
return Token(tok!"whitespace", text, line, column, index);
}
Token lexError() pure nothrow @safe
{
range.popFront();
return Token(tok!"", null, 0, 0, 0);
}
Token lexStringLiteral() pure nothrow @safe
{
mixin (tokenStart);
ubyte quote = range.front;
range.popFront();
while (true)
{
if (range.empty)
return Token(tok!"", null, 0, 0, 0);
if (range.front == '\\')
{
range.popFront();
if (range.empty)
return Token(tok!"", null, 0, 0, 0);
range.popFront();
}
else if (range.front == quote)
{
range.popFront();
break;
}
else
range.popFront();
}
return Token(tok!"string", cache.cacheGet(range.slice(mark)), line,
column, index);
}
Token lexNumber() pure nothrow
{
mixin (tokenStart);
bool foundDot = range.front == '.';
if (foundDot)
range.popFront();
decimalLoop: while (!range.empty)
{
switch (range.front)
{
case '0': .. case '9':
range.popFront();
break;
case 'e':
case 'E':
lexExponent();
break decimalLoop;
case '.':
if (foundDot || !range.canPeek(1) || range.peekAt(1) == '.')
break decimalLoop;
else
{
// The following bit of silliness tries to tell the
// difference between "int dot identifier" and
// "double identifier".
if (range.canPeek(1))
{
switch (range.peekAt(1))
{
case '0': .. case '9':
goto doubleLiteral;
default:
break decimalLoop;
}
}
else
{
doubleLiteral:
range.popFront();
foundDot = true;
}
}
break;
default:
break decimalLoop;
}
}
return Token(tok!"number", cache.cacheGet(range.slice(mark)),
line, column, index);
}
void lexExponent() pure nothrow @safe
{
range.popFront();
bool foundSign = false;
bool foundDigit = false;
while (!range.empty)
{
switch (range.front)
{
case '-':
case '+':
if (foundSign)
return;
foundSign = true;
range.popFront();
break;
case '0': .. case '9':
foundDigit = true;
range.popFront();
break;
default:
return;
}
}
}
// JSON has no valid default token such as an identifier, so the JSON lexer
// will never need to determine if it is at the end of an identifier.
// Therefore, this always returns false.
bool isSeparating(size_t offset) pure nothrow @safe
{
return true;
}
private enum tokenStart = q{
size_t line = range.line;
size_t column = range.column;
size_t index = range.index;
auto mark = range.mark();
};
StringCache* cache;
}
void main(string[] args)
{
import std.array;
ubyte[] source = readFile(args[1]);
StringCache* cache = new StringCache(StringCache.defaultBucketCount);
auto lexer = JSONLexer(source, cache);
while (!lexer.empty)
{
auto token = lexer.front();
writeln("<<", token.text is null ? str(token.type) : token.text, ">>");
lexer.popFront();
}
writeln("done");
}
ubyte[] readFile(string fileName)
{
import std.array;
import std.conv;
if (!exists(fileName))
{
stderr.writefln("%s does not exist", fileName);
return [];
}
File f = File(fileName);
ubyte[] sourceCode = uninitializedArray!(ubyte[])(to!size_t(f.size));
f.rawRead(sourceCode);
return sourceCode;
}