-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpy_obj_parsing.js
385 lines (340 loc) · 13.2 KB
/
py_obj_parsing.js
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
import {None, isNone, EQ} from './hash_impl_common';
import {BigNumber} from 'bignumber.js';
class PyParsingError extends Error {
constructor(text, pos) {
// super(`${text} (at position ${pos})`);
const isStr = typeof text === 'string';
const textEn = isStr ? text : text.en;
super(textEn);
this.pos = pos;
this.text = isStr ? {en: textEn} : text;
}
}
const digitsMinusPlus = '-+0123456789';
const minusPlus = '-+';
// TODO: add mode for validating stuff: e.g. parseString() should throw on `"string contents" stuff after`
export class PyObjParser {
constructor(literal) {
this.s = literal;
this.pos = 0;
}
skipWhitespace() {
while (this.pos < this.s.length && /\s/.test(this.s[this.pos])) {
this.pos++;
}
}
current() {
return this.s[this.pos];
}
next() {
return this.s[this.pos + 1];
}
isWhiteSpaceOrEol(c) {
return c == null || /\s/.test(c);
}
isCurrentWhitespaceOrEol() {
return this.isWhiteSpaceOrEol(this.current());
}
consume(expectedChar) {
const c = this.current();
if (c == null) {
this.throwErr(
`Encountered unexpected EOL, expected ${expectedChar}`,
`Неожиданный конец данных, ожидается ${expectedChar}`
);
}
if (c !== expectedChar) {
this.throwErr(
`Expected \`${expectedChar}\`, got \`${c}\``,
`Ожидается \`${expectedChar}\` вместо \`${c}\``
);
}
this.pos++;
}
consumeWS(expectedChar) {
this.skipWhitespace();
this.consume(expectedChar);
}
maybeConsume(expectedChar) {
if (this.current() === expectedChar) {
this.consume(expectedChar);
}
}
maybeConsumeWS(expectedChar) {
this.skipWhitespace();
this.maybeConsume(expectedChar);
}
throwErr(textEn, textRu, pos) {
// TODO FIXME: pos computation looks way too complicated
let posToInclude = pos != null ? pos : this.pos;
posToInclude = Math.min(posToInclude, this.s.length - 1);
if (posToInclude < 0) posToInclude = 0;
throw new PyParsingError({en: textEn, ru: textRu}, posToInclude);
}
_parseStringOrNumberOrNone(allowedSeparators, fromDict, allowNonesInError) {
// TODO: The whole None parsing and error reporting for unwrapped strings
// TODO: is a bit of a mess
if (this.isNextNone(allowedSeparators)) {
return this._parseNoneOrThrowUnknownIdentifier(allowedSeparators);
}
return this._parseStringOrNumber(allowedSeparators, fromDict, allowNonesInError);
}
_parseStringOrNumber(allowedSeparators, fromDict = true, allowNonesInError = false) {
this.skipWhitespace();
let startPos = this.pos;
const c = this.current();
if (fromDict) {
if (c === '{' || c === '[') {
this.throwErr(
'Nested lists and dictionaries are not supported. Only strings and ints are.',
'Вложенные списки и словари не поддерживаются'
);
}
if (c == null) {
this.throwErr('Dict literal added abruptly - expected value', 'Неожиданный конец словаря');
}
}
if (digitsMinusPlus.includes(c)) {
return {res: this.parseNumber(allowedSeparators), startPos};
} else if (`"'`.includes(c)) {
return {res: this.parseString(), startPos};
} else {
this.throwErr(
`Expected value - string, integer${
allowNonesInError ? ' or None' : ''
}. If you wanted a string, wrap it in quotes`,
`Ожидается строка или целое${allowNonesInError ? ' или None' : ''}. Строки должны быть в кавычках.`
);
}
}
parseDict(minSize = null) {
const allowedSeparators = ',:}';
const c = this.current();
this.consumeWS('{');
let res = [];
this.skipWhitespace();
while (this.current() !== '}') {
if (this.current() == null) {
this.throwErr(
'Dict literal ended abruptly - no closing }',
'Неожиданный конец словаря, нет закрывающей }'
);
}
let key = this._parseStringOrNumberOrNone(allowedSeparators).res;
this.consumeWS(':');
let value = this._parseStringOrNumberOrNone(allowedSeparators).res;
res.push([key, value]);
this.skipWhitespace();
if (this.current() !== '}' && this.current() != null) this.consume(',');
}
this.consumeWS('}');
if (minSize != null) {
if (res.length < minSize) {
if (minSize > 1) {
this.throwErr(`There should be at least ${minSize} pairs`, `Должно быть не меньше ${minSize} пар`);
} else {
this.throwErr(`The data cannot be empty`, 'Пустые данные');
}
}
}
return res;
}
parseList(allowDuplicates = true, minSize = null, extraValueValidator) {
const allowedSeparators = ',]';
const c = this.current();
console.log('parseList', c, this.s);
this.maybeConsumeWS('[');
let res = [];
this.skipWhitespace();
while (this.current() !== ']') {
// if (this.current() == null) {
// this.throwErr('List literal ended abruptly - no closing ]');
// }
if (this.current() == null) {
break;
}
let {res: val, startPos: valStartPos} = this._parseStringOrNumberOrNone(allowedSeparators);
if (!allowDuplicates) {
for (let existingVal of res) {
if (EQ(val, existingVal)) {
this.throwErr(
'Duplicates are not allowed in this list',
'В списке не должно быть дублированных значений'
);
}
}
}
if (extraValueValidator) {
const error = extraValueValidator(val);
if (error) {
this.throwErr(error.en, error.ru, valStartPos);
}
}
res.push(val);
this.skipWhitespace();
if (this.current() !== ']' && this.current() != null) this.maybeConsume(',');
this.skipWhitespace();
}
this.maybeConsumeWS(']');
if (minSize != null) {
if (res.length < minSize) {
if (minSize > 1) {
this.throwErr(
`In this chapter, the list need to have length at least ${minSize}`,
`Список должен быть длиной не меньше ${minSize}`
);
} else {
this.throwErr(`In this chapter, the list cannot be empty`, 'Список не может быть пустым');
}
}
}
return res;
}
parseNumber(allowedSeparators = '') {
this.skipWhitespace();
if (this.current() == null) {
this.throwErr("Number can't be empty", 'Число не может быть пустым');
}
const originalPos = this.pos;
while (digitsMinusPlus.includes(this.current())) {
this.pos++;
}
if (this.current() === '.') {
this.throwErr('Floats are not supported', 'Флоаты пока не поддерживаются');
}
if (this.current() === 'e') {
this.throwErr('Floats in scientific notation are not supported', 'Флоаты пока не поддерживаются');
}
const nonDecimalErrorStringEn = 'Non-decimal bases are not supported';
const nonDecimalErrorStringRu = 'Поддерживаются только числа в десятичной системе счисления';
if (this.current() === 'x') {
this.throwErr(nonDecimalErrorStringEn, nonDecimalErrorStringRu);
}
if (!this.isCurrentWhitespaceOrEol() && (!allowedSeparators || !allowedSeparators.includes(this.current()))) {
// TODO: a bit more descriptive? and a bit less hacky?
this.throwErr('Invalid syntax: number with non-digit characters', 'В числе должны быть только цифры');
}
const num = this.s.slice(originalPos, this.pos);
if (num[0] === '0' && num.length > 1) {
this.throwErr(nonDecimalErrorStringEn, nonDecimalErrorStringRu);
}
// TODO: python parses numbers like ++1, -+--1, etc properly
if (isNaN(+num)) {
this.throwErr('Invalid number', 'Невалидное число', originalPos);
}
return BigNumber(num);
}
parseString() {
// TODO: handle escape characters
// TODO: handle/throw an error on triple-quoted strings
this.skipWhitespace();
const c = this.current();
if (c !== "'" && c !== '"') {
this.throwErr(
'String must be wrapped in quotation characters (either `\'` or `"`)',
'Строки должны быть в кавычках'
);
}
const quote = c;
this.consume(quote);
const originalPos = this.pos;
let res = [];
while (this.current() != null && this.current() !== quote) {
if (this.current() === '\\') {
if (this.next() !== '\\' && this.next() !== '"') {
this.throwErr(
'The only supported escape sequences are for \\\\ and \\"',
'Такие escape-последовательности не поддерживаются',
this.pos + 1
);
}
res.push(this.next());
this.pos += 2;
} else {
res.push(this.current());
this.pos++;
}
}
this.consume(quote);
return res.join('');
}
isNextNone(allowedSeparators = '') {
this.skipWhitespace();
return (
this.s.slice(this.pos, this.pos + 4) === 'None' &&
(this.isWhiteSpaceOrEol(this.s[this.pos + 4]) || allowedSeparators.includes(this.s[this.pos + 4]))
);
}
// Quite hacky
_parseNoneOrThrowUnknownIdentifier(allowedSeparators) {
this.skipWhitespace();
if (this.isNextNone(allowedSeparators)) {
const startPos = this.pos;
this.pos += 4;
return {res: None, startPos};
}
this.throwErr(
'Unknown identifier (if you wanted a string, wrap it in quotation marks - `"` or `\'`)',
'Строки должны быть в кавычках'
);
}
checkTrailingChars() {
this.skipWhitespace();
if (this.pos < this.s.length) {
this.throwErr('Trailing characters', 'Лишние символы');
}
}
}
function _checkTrailingChars(parser, parseFunc) {
const res = parseFunc();
parser.checkTrailingChars();
return res;
}
export function parsePyString(s) {
let parser = new PyObjParser(s);
return _checkTrailingChars(parser, () => parser.parseString());
}
export function parsePyNumber(s) {
let parser = new PyObjParser(s);
return _checkTrailingChars(parser, () => parser.parseNumber());
}
export function parsePyDict(s, minSize = null) {
let parser = new PyObjParser(s);
return _checkTrailingChars(parser, () => parser.parseDict(minSize));
}
export function parsePyList(s, allowDuplicates = true, minSize = null, extraValueValidator) {
let parser = new PyObjParser(s);
return _checkTrailingChars(parser, () => parser.parseList(allowDuplicates, minSize, extraValueValidator));
}
export function parsePyStringOrNumber(s) {
let parser = new PyObjParser(s);
return _checkTrailingChars(parser, () => parser._parseStringOrNumber(null, false).res);
}
export function parsePyStringOrNumberOrNone(s) {
let parser = new PyObjParser(s);
return _checkTrailingChars(parser, () => parser._parseStringOrNumberOrNone(null, false, true).res);
}
// TODO: Dump functions are very hacky right now
export function dumpSimplePyObj(o) {
if (isNone(o)) {
return 'None';
}
if (BigNumber.isBigNumber(o)) {
return o.toString();
}
return JSON.stringify(o);
}
export function dumpPyList(l) {
let strItems = [];
for (let item of l) {
strItems.push(dumpSimplePyObj(item));
}
return '[' + strItems.join(', ') + ']';
}
export function dumpPyDict(d) {
let strItems = [];
for (let [k, v] of d) {
strItems.push(`${dumpSimplePyObj(k)}: ${dumpSimplePyObj(v)}`);
}
return '{' + strItems.join(', ') + '}';
}