-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
377 lines (325 loc) · 11.7 KB
/
index.js
File metadata and controls
377 lines (325 loc) · 11.7 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
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
import { preprocessExpression } from './preprocess.js';
function tokenize(input) {
const tokens = [];
const re = /\s*([A-Za-z_][A-Za-z0-9_]*|\d+(?:\.\d+)?|[()+\-*/=,^!])/g;
let m;
while ((m = re.exec(input)) !== null) tokens.push(m[1]);
return tokens;
}
function parse(input) {
const tokens = tokenize(input);
let i = 0;
function peek() { return tokens[i]; }
function next() { return tokens[i++]; }
function isNumber(tok) { return /^(\d+(\.\d+)?)$/.test(tok); }
function isIdent(tok) { return /^[A-Za-z_][A-Za-z0-9_]*$/.test(tok); }
function parseExpression() {
if (isIdent(peek()) && tokens[i + 1] === '=') {
const target = next();
next();
const expr = parseAddSub();
return { type: 'assign', target, expr };
}
return parseAddSub();
}
function parseAddSub() {
let node = parseMulDiv();
while (peek() === '+' || peek() === '-') {
const op = next();
const right = parseMulDiv();
node = { type: 'binary', op, left: node, right };
}
return node;
}
function parseMulDiv() {
let node = parsePower();
while (peek() === '*' || peek() === '/') {
const op = next();
const right = parsePower();
node = { type: 'binary', op, left: node, right };
}
return node;
}
function parsePower() {
let node = parseUnary();
if (peek() === '^') {
next();
const right = parsePower();
node = { type: 'binary', op: '^', left: node, right };
}
return node;
}
function parseUnary() {
const tok = peek();
if (tok === '+' || tok === '-') {
const op = next();
const expr = parseUnary();
return op === '-' ? { type: 'unary', op: 'neg', expr } : expr;
}
if (isIdent(tok) && tokens[i + 1] === '(') {
const func = next().toLowerCase();
next();
const arg = parseExpression();
if (peek() !== ')') throw new Error('Expected ) after function arg');
next();
const nameMap = { 'abs': 'abs', 'round': 'rnd', 'rnd': 'rnd', 'floor': 'flr', 'ceil': 'ceil' };
const opType = nameMap[func] || func;
return { type: 'unary', op: opType, expr: arg };
}
return parsePrimary();
}
function parsePrimary() {
const tok = peek();
if (!tok) throw new Error('Unexpected end of input');
if (tok === '(') { next(); const node = parseExpression(); if (peek() !== ')') throw new Error('Missing )'); next(); return node; }
if (isNumber(tok)) { next(); return { type: 'number', value: parseFloat(tok) }; }
if (isIdent(tok)) { next(); return { type: 'ident', name: tok }; }
throw new Error('Unexpected token: ' + tok);
}
const ast = parseExpression();
if (i < tokens.length) throw new Error('Unexpected token leftover: ' + peek());
return ast;
}
function match(op) {
if (op === '*') return MUL;
if (op === '/') return DIV;
if (op === '+') return ADD;
if (op === '-') return SUB;
if (op === '=') return EQ;
if (op === '^') throw new Error('Power operator "^" should have been lowered by gen() (exponentiation-by-squaring).');
throw new Error('Unsupported op in match: ' + op);
}
function lowerToInstances(ast) {
const instances = [];
function makeTemp() { return float_counter(); }
function pushInstance(obj) {
instances.push({
item_target: obj.item_target,
item_1: obj.item_1,
item_2: obj.item_2,
mod: obj.mod === undefined ? 1 : obj.mod,
target_op: obj.target_op || EQ,
op_1: obj.op_1 || ADD,
op_2: obj.op_2 || MUL,
abs_neg_1: obj.abs_neg_1 || null,
rnd_1: obj.rnd_1 || null,
abs_neg_2: obj.abs_neg_2 || null,
rnd_2: obj.rnd_2 || null
});
}
function standardBinaryLowering(node, desiredTarget, attachUnary) {
const leftRef = gen(node.left);
const rightRef = gen(node.right);
const out = desiredTarget || makeTemp();
pushInstance({
item_target: out,
item_1: leftRef,
item_2: rightRef,
mod: 1,
target_op: EQ,
op_1: match(node.op),
op_2: MUL,
abs_neg_1: attachUnary?.abs_neg_1 || null,
rnd_1: attachUnary?.rnd_1 || null
});
return out;
}
function lowerIntPower(baseRef, exponent, desiredTarget = null, attachUnary = null) {
const memo = new Map();
function keyFor(ref, exp) {
return `${String(ref)}|${exp}`;
}
function build(ref, exp) {
const key = keyFor(ref, exp);
if (memo.has(key)) return memo.get(key);
if (exp === 0) {
memo.set(key, 1);
return 1;
}
if (exp === 1) {
memo.set(key, ref);
return ref;
}
if (exp % 2 === 0) {
const half = build(ref, exp / 2);
const out = makeTemp();
pushInstance({
item_target: out,
item_1: half,
item_2: half,
mod: 1,
target_op: EQ,
op_1: match('*'),
op_2: MUL,
abs_neg_1: null,
rnd_1: null
});
memo.set(key, out);
return out;
} else {
const rest = build(ref, exp - 1);
const out = makeTemp();
pushInstance({
item_target: out,
item_1: ref,
item_2: rest,
mod: 1,
target_op: EQ,
op_1: match('*'),
op_2: MUL,
abs_neg_1: null,
rnd_1: null
});
memo.set(key, out);
return out;
}
}
const resultRef = build(baseRef, exponent);
if (attachUnary && (attachUnary.abs_neg_1 || attachUnary.rnd_1)) {
for (let i = instances.length - 1; i >= 0; i--) {
if (instances[i].item_target === resultRef) {
if (attachUnary.abs_neg_1) instances[i].abs_neg_1 = attachUnary.abs_neg_1;
if (attachUnary.rnd_1) instances[i].rnd_1 = attachUnary.rnd_1;
break;
}
}
}
if (desiredTarget && resultRef !== desiredTarget) {
pushInstance({
item_target: desiredTarget,
item_1: resultRef,
item_2: 0,
mod: 1,
target_op: EQ,
op_1: match('+'),
op_2: MUL,
abs_neg_1: null,
rnd_1: null
});
return desiredTarget;
}
return resultRef;
}
function gen(node, desiredTarget = null, attachUnary = null) {
if (node.type === 'number') return node.value;
if (node.type === 'ident') return node.name;
if (node.type === 'unary') {
const flags = {};
if (node.op === 'neg') flags.abs_neg_1 = NEG;
else if (node.op === 'abs') flags.abs_neg_1 = ABS;
else if (node.op === 'rnd') flags.rnd_1 = RND;
else if (node.op === 'flr') flags.rnd_1 = FLR;
else if (node.op === 'ceil') flags.rnd_1 = CEI;
if (node.expr && node.expr.type === 'binary') {
return gen(node.expr, desiredTarget, flags);
}
const inRef = gen(node.expr);
const out = desiredTarget || makeTemp();
pushInstance({
item_target: out,
item_1: inRef,
item_2: 0,
mod: 1,
target_op: EQ,
op_1: match('+'),
abs_neg_1: flags.abs_neg_1 || null,
rnd_1: flags.rnd_1 || null
});
return out;
}
if (node.type === 'binary') {
if (node.op === '^') {
if (node.right && node.right.type === 'number' && Number.isInteger(node.right.value) && node.right.value >= 0) {
const baseRef = gen(node.left);
const exponent = node.right.value;
return lowerIntPower(baseRef, exponent, desiredTarget, attachUnary);
} else {
return standardBinaryLowering(node, desiredTarget, attachUnary);
}
}
if ((node.op === '*' || node.op === '/') && node.left && node.left.type === 'binary') {
const inner = node.left;
if (!['+', '-', '*', '/'].includes(inner.op)) {
return standardBinaryLowering(node, desiredTarget, attachUnary);
}
if (node.right.type !== 'number') {
return standardBinaryLowering(node, desiredTarget, attachUnary);
}
const item1Ref = gen(inner.left);
const item2Ref = gen(inner.right);
const modLiteral = node.right.value;
const out = desiredTarget || makeTemp();
pushInstance({
item_target: out,
item_1: item1Ref,
item_2: item2Ref,
mod: modLiteral,
target_op: EQ,
op_1: match(inner.op),
op_2: match(node.op),
abs_neg_1: attachUnary?.abs_neg_1 || null,
rnd_1: attachUnary?.rnd_1 || null
});
return out;
}
return standardBinaryLowering(node, desiredTarget, attachUnary);
}
if (node.type === 'assign') {
gen(node.expr, node.target);
return node.target;
}
throw new Error('Unknown node type in gen: ' + JSON.stringify(node));
}
gen(ast);
return instances;
}
function decomposeExpressionToInstances(input) {
const ast = parse(input);
const instances = lowerToInstances(ast);
return { ast, instances };
}
let variables = {}
let setVariables = (dict) => {
for (let i in dict) {
variables[i] = dict[i]
}
}
function equation(expression) {
expression = preprocessExpression(expression);
const { instances } = decomposeExpressionToInstances(expression);
const literalCache = {};
function resolveRef(ref) {
if (typeof ref === 'number') {
if (!(ref in literalCache)) {
literalCache[ref] = counter(ref);
}
return literalCache[ref];
}
if (typeof ref === 'string') {
if (!(ref in variables)) {
variables[ref] = counter();
}
return variables[ref];
}
return ref;
}
for (let inst of instances) {
const targetObj = resolveRef(inst.item_target);
const leftObj = resolveRef(inst.item_1);
const rightObj = resolveRef(inst.item_2);
const target_type = targetObj.type;
const type_1 = leftObj.type;
const type_2 = rightObj.type;
item_edit(
leftObj.item,
rightObj.item,
targetObj.item,
type_1, type_2, target_type,
inst.target_op, inst.op_1, inst.op_2,
inst.mod,
inst.abs_neg_1, inst.abs_neg_2,
inst.rnd_1, inst.rnd_2
).add()
}
}
export { decomposeExpressionToInstances, parse, setVariables, equation };