-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathto-python.ts
More file actions
765 lines (671 loc) · 18.7 KB
/
Copy pathto-python.ts
File metadata and controls
765 lines (671 loc) · 18.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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
import { SheetDocumentSchema } from '../sheet-model/schema.ts';
import type {
SheetDocument,
SheetLiteral,
SheetSymbol,
SheetValueNode,
SheetValueTree,
} from '../sheet-model/types.ts';
import { assertNever } from '../shared/assertNever.ts';
import {
createSheetFromValueTreeJson,
type Calculation,
type ValueTreeSheetOptions,
} from '../value-tree-json/to-sheet.ts';
export interface PythonExportOptions {
readonly functionName?: string;
}
export type PythonFromValueTreeJsonOptions = ValueTreeSheetOptions &
PythonExportOptions;
type PythonExpression = {
readonly code: string;
readonly precedence: number;
readonly usesMath: boolean;
};
type PythonRenderContext = {
readonly pythonNameBySymbolId: ReadonlyMap<string, string>;
};
const PythonPrecedence = {
Conditional: 1,
LogicalOr: 2,
LogicalAnd: 3,
Compare: 4,
AddSubtract: 5,
MultiplyDivide: 6,
Unary: 7,
Power: 8,
Call: 9,
Atom: 10,
} as const;
const leadingDigitPattern = /^[0-9]/;
const pythonReservedWords = new Set([
'False',
'None',
'True',
'and',
'as',
'assert',
'async',
'await',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'nonlocal',
'not',
'or',
'pass',
'raise',
'return',
'try',
'while',
'with',
'yield',
]);
const toPythonIdentifier = (value: string, fallback: string): string => {
const sanitized = value
.toLowerCase()
.replace(/[^a-z0-9_]+/g, '_')
.replace(/^_+|_+$/g, '')
.replace(/_+/g, '_');
const withFallback = sanitized || fallback;
const safeLeadingCharacter = leadingDigitPattern.test(withFallback)
? `_${withFallback}`
: withFallback;
return pythonReservedWords.has(safeLeadingCharacter)
? `${safeLeadingCharacter}_value`
: safeLeadingCharacter;
};
const buildUniquePythonName = (
baseName: string,
usedNames: Set<string>,
): string => {
if (!usedNames.has(baseName)) {
usedNames.add(baseName);
return baseName;
}
let suffix = 2;
let candidate = `${baseName}_${suffix}`;
while (usedNames.has(candidate)) {
suffix += 1;
candidate = `${baseName}_${suffix}`;
}
usedNames.add(candidate);
return candidate;
};
const buildPythonNameBySymbolId = (
symbols: readonly SheetSymbol[],
): ReadonlyMap<string, string> => {
const usedNames = new Set<string>();
const pythonNameBySymbolId = new Map<string, string>();
symbols.forEach((symbol, symbolIndex) => {
const baseName = toPythonIdentifier(
symbol.glyphCodeName ?? symbol.id,
`symbol_${symbolIndex + 1}`,
);
pythonNameBySymbolId.set(
symbol.id,
buildUniquePythonName(baseName, usedNames),
);
});
return pythonNameBySymbolId;
};
const literalToPython = (literal: SheetLiteral): PythonExpression => {
switch (literal.kind) {
case 'boolean':
return {
code: literal.value ? 'True' : 'False',
precedence: PythonPrecedence.Atom,
usesMath: false,
};
case 'empty':
return {
code: 'None',
precedence: PythonPrecedence.Atom,
usesMath: false,
};
case 'number':
return {
code: Number.isNaN(literal.value) ? 'math.nan' : `${literal.value}`,
precedence: PythonPrecedence.Atom,
usesMath: Number.isNaN(literal.value),
};
case 'string':
return {
code: JSON.stringify(literal.value),
precedence: PythonPrecedence.Atom,
usesMath: false,
};
default:
return assertNever(literal);
}
};
const parenthesize = (
expression: PythonExpression,
requiredPrecedence: number,
): string =>
expression.precedence < requiredPrecedence
? `(${expression.code})`
: expression.code;
const parenthesizeBinaryOperand = ({
expression,
parentPrecedence,
parenthesizeEqualPrecedence,
}: {
readonly expression: PythonExpression;
readonly parentPrecedence: number;
readonly parenthesizeEqualPrecedence: boolean;
}): string =>
expression.precedence < parentPrecedence ||
(parenthesizeEqualPrecedence && expression.precedence === parentPrecedence)
? `(${expression.code})`
: expression.code;
const combineMathUsage = (expressions: readonly PythonExpression[]): boolean =>
expressions.some((expression) => expression.usesMath);
const requireArgCount = (
functionId: string,
args: readonly PythonExpression[],
expected: number,
): void => {
if (args.length !== expected) {
throw new Error(
`Cannot export function '${functionId}' with ${args.length} args to Python`,
);
}
};
const binaryExpression = (
functionId: string,
args: readonly PythonExpression[],
operator: string,
precedence: number,
options: {
readonly parenthesizeEqualLeft?: boolean;
readonly parenthesizeEqualRight?: boolean;
} = {},
): PythonExpression => {
requireArgCount(functionId, args, 2);
const [left, right] = args;
return {
code: `${parenthesizeBinaryOperand({
expression: left,
parentPrecedence: precedence,
parenthesizeEqualPrecedence: options.parenthesizeEqualLeft ?? false,
})} ${operator} ${parenthesizeBinaryOperand({
expression: right,
parentPrecedence: precedence,
parenthesizeEqualPrecedence: options.parenthesizeEqualRight ?? false,
})}`,
precedence,
usesMath: combineMathUsage(args),
};
};
const requireAtLeastOneArg = (
functionId: string,
args: readonly PythonExpression[],
): void => {
if (args.length === 0) {
throw new Error(
`Cannot export function '${functionId}' with 0 args to Python`,
);
}
};
const logicalExpression = (
functionId: string,
args: readonly PythonExpression[],
operator: string,
precedence: number,
): PythonExpression => {
requireAtLeastOneArg(functionId, args);
if (args.length === 1) {
return args[0];
}
return {
code: args
.map((arg) =>
parenthesizeBinaryOperand({
expression: arg,
parentPrecedence: precedence,
parenthesizeEqualPrecedence: false,
}),
)
.join(` ${operator} `),
precedence,
usesMath: combineMathUsage(args),
};
};
const mathSingleArgCall = (
functionId: string,
args: readonly PythonExpression[],
name: string,
): PythonExpression => {
requireArgCount(functionId, args, 1);
return {
code: `math.${name}(${args[0].code})`,
precedence: PythonPrecedence.Call,
usesMath: true,
};
};
const pythonCallExpression = (
functionId: string,
args: readonly PythonExpression[],
name: string,
): PythonExpression => {
requireAtLeastOneArg(functionId, args);
return {
code: `${name}(${args.map((arg) => arg.code).join(', ')})`,
precedence: PythonPrecedence.Call,
usesMath: combineMathUsage(args),
};
};
const optionalSecondArgCallExpression = (
functionId: string,
args: readonly PythonExpression[],
name: string,
usesMath: boolean,
): PythonExpression => {
if (args.length === 0 || args.length > 2) {
throw new Error(
`Cannot export function '${functionId}' with ${args.length} args to Python`,
);
}
return {
code: `${name}(${args.map((arg) => arg.code).join(', ')})`,
precedence: PythonPrecedence.Call,
usesMath,
};
};
const passthroughExpression = (
args: readonly PythonExpression[],
): PythonExpression => {
if (args.length === 0) {
return {
code: 'None',
precedence: PythonPrecedence.Atom,
usesMath: false,
};
}
if (args.length === 1) {
return args[0];
}
return {
code: `(${args.map((arg) => arg.code).join(', ')})`,
precedence: PythonPrecedence.Atom,
usesMath: combineMathUsage(args),
};
};
type FunctionExpressionRenderer = (
args: readonly PythonExpression[],
) => PythonExpression;
const comparisonOptions = {
parenthesizeEqualLeft: true,
parenthesizeEqualRight: true,
} as const;
const functionExpressionRenderers: Readonly<
Record<string, FunctionExpressionRenderer>
> = {
'fg.add': (args) =>
binaryExpression('fg.add', args, '+', PythonPrecedence.AddSubtract),
'fg.and': (args) =>
logicalExpression('fg.and', args, 'and', PythonPrecedence.LogicalAnd),
'fg.ceil': (args) => mathSingleArgCall('fg.ceil', args, 'ceil'),
'fg.cnd': (args) => {
requireArgCount('fg.cnd', args, 3);
return {
code: `${args[1].code} if ${args[0].code} else ${args[2].code}`,
precedence: PythonPrecedence.Conditional,
usesMath: combineMathUsage(args),
};
},
'fg.deg': (args) => mathSingleArgCall('fg.deg', args, 'degrees'),
'fg.divide': (args) =>
binaryExpression('fg.divide', args, '/', PythonPrecedence.MultiplyDivide, {
parenthesizeEqualRight: true,
}),
'fg.eq': (args) =>
binaryExpression('fg.eq', args, '==', PythonPrecedence.Compare, {
...comparisonOptions,
}),
'fg.exp': (args) => mathSingleArgCall('fg.exp', args, 'exp'),
'fg.ge': (args) =>
binaryExpression('fg.ge', args, '>=', PythonPrecedence.Compare, {
...comparisonOptions,
}),
'fg.gt': (args) =>
binaryExpression('fg.gt', args, '>', PythonPrecedence.Compare, {
...comparisonOptions,
}),
'fg.le': (args) =>
binaryExpression('fg.le', args, '<=', PythonPrecedence.Compare, {
...comparisonOptions,
}),
'fg.log': (args) =>
optionalSecondArgCallExpression('fg.log', args, 'math.log', true),
'fg.lt': (args) =>
binaryExpression('fg.lt', args, '<', PythonPrecedence.Compare, {
...comparisonOptions,
}),
'fg.max': (args) => pythonCallExpression('fg.max', args, 'max'),
'fg.min': (args) => pythonCallExpression('fg.min', args, 'min'),
'fg.multiply': (args) =>
binaryExpression('fg.multiply', args, '*', PythonPrecedence.MultiplyDivide),
'fg.ne': (args) =>
binaryExpression('fg.ne', args, '!=', PythonPrecedence.Compare, {
...comparisonOptions,
}),
'fg.noop': passthroughExpression,
'fg.or': (args) =>
logicalExpression('fg.or', args, 'or', PythonPrecedence.LogicalOr),
'fg.pi': (args) => {
requireArgCount('fg.pi', args, 0);
return {
code: 'math.pi',
precedence: PythonPrecedence.Atom,
usesMath: true,
};
},
'fg.pow': (args) =>
binaryExpression('fg.pow', args, '**', PythonPrecedence.Power, {
parenthesizeEqualLeft: true,
}),
'fg.round': (args) =>
optionalSecondArgCallExpression(
'fg.round',
args,
'round',
combineMathUsage(args),
),
'fg.sqrt': (args) => mathSingleArgCall('fg.sqrt', args, 'sqrt'),
'fg.stub': passthroughExpression,
'fg.subtract': (args) =>
binaryExpression('fg.subtract', args, '-', PythonPrecedence.AddSubtract, {
parenthesizeEqualRight: true,
}),
'fg.uminus': (args) => {
requireArgCount('fg.uminus', args, 1);
return {
code: `-${parenthesize(args[0], PythonPrecedence.Unary)}`,
precedence: PythonPrecedence.Unary,
usesMath: args[0].usesMath,
};
},
};
const renderFunctionExpression = (
functionId: string,
args: readonly PythonExpression[],
): PythonExpression => {
const renderer = functionExpressionRenderers[functionId];
if (!renderer) {
throw new Error(`Cannot export unsupported function '${functionId}'`);
}
return renderer(args);
};
const nodeByKey = (tree: SheetValueTree): ReadonlyMap<string, SheetValueNode> =>
new Map(tree.nodes.map((node) => [node.key, node]));
const renderValueNode = ({
context,
node,
nodeLookup,
stack,
}: {
readonly context: PythonRenderContext;
readonly node: SheetValueNode;
readonly nodeLookup: ReadonlyMap<string, SheetValueNode>;
readonly stack: readonly string[];
}): PythonExpression => {
if (stack.includes(node.key)) {
throw new Error(
`Cycle inside value tree at node '${node.key}' while exporting Python`,
);
}
switch (node.kind) {
case 'literal':
return literalToPython(node.value);
case 'symbol': {
const pythonName = context.pythonNameBySymbolId.get(node.symbolId);
if (!pythonName) {
throw new Error(
`Symbol reference '${node.symbolId}' does not resolve for Python export`,
);
}
return {
code: pythonName,
precedence: PythonPrecedence.Atom,
usesMath: false,
};
}
case 'function': {
if (
node.functionId === 'fg.stub' &&
node.argKeys.length === 0 &&
node.result
) {
return literalToPython(node.result);
}
const args = node.argKeys.map((argKey) => {
const argNode = nodeLookup.get(argKey);
if (!argNode) {
throw new Error(
`Function argument '${argKey}' does not resolve for Python export`,
);
}
return renderValueNode({
context,
node: argNode,
nodeLookup,
stack: [...stack, node.key],
});
});
return renderFunctionExpression(node.functionId, args);
}
default:
return assertNever(node);
}
};
const renderSymbolExpression = (
symbol: SheetSymbol,
context: PythonRenderContext,
): PythonExpression => {
const nodeLookup = nodeByKey(symbol.valueTree);
const rootNode = nodeLookup.get(symbol.valueTree.rootKey);
if (!rootNode) {
throw new Error(
`Root node '${symbol.valueTree.rootKey}' does not resolve for Python export`,
);
}
return renderValueNode({
context,
node: rootNode,
nodeLookup,
stack: [],
});
};
const collectReachableSymbolIds = (
tree: SheetValueTree,
node: SheetValueNode,
nodeLookup: ReadonlyMap<string, SheetValueNode>,
visitedNodeKeys: Set<string>,
): ReadonlySet<string> => {
if (visitedNodeKeys.has(node.key)) {
return new Set();
}
visitedNodeKeys.add(node.key);
if (node.kind === 'symbol') {
return new Set([node.symbolId]);
}
if (node.kind !== 'function') {
return new Set();
}
const symbolIds = new Set<string>();
for (const argKey of node.argKeys) {
const argNode = nodeLookup.get(argKey);
if (!argNode) {
throw new Error(
`Function argument '${argKey}' does not resolve for Python export`,
);
}
for (const symbolId of collectReachableSymbolIds(
tree,
argNode,
nodeLookup,
visitedNodeKeys,
)) {
symbolIds.add(symbolId);
}
}
return symbolIds;
};
const collectSymbolDependencies = (
symbol: SheetSymbol,
): ReadonlySet<string> => {
const lookup = nodeByKey(symbol.valueTree);
const rootNode = lookup.get(symbol.valueTree.rootKey);
if (!rootNode) {
throw new Error(
`Root node '${symbol.valueTree.rootKey}' does not resolve for Python export`,
);
}
return collectReachableSymbolIds(
symbol.valueTree,
rootNode,
lookup,
new Set(),
);
};
const orderSymbolsForPython = (
symbols: readonly SheetSymbol[],
): readonly SheetSymbol[] => {
const symbolById = new Map(symbols.map((symbol) => [symbol.id, symbol]));
const dependenciesBySymbolId = new Map(
symbols.map((symbol) => [
symbol.id,
new Set(
[...collectSymbolDependencies(symbol)].filter(
(symbolId) => symbolId !== symbol.id,
),
),
]),
);
const orderedSymbols: SheetSymbol[] = [];
const resolvedSymbolIds = new Set<string>();
const remainingSymbolIds = new Set(symbols.map((symbol) => symbol.id));
while (remainingSymbolIds.size > 0) {
let progressed = false;
for (const symbol of symbols) {
if (!remainingSymbolIds.has(symbol.id)) {
continue;
}
const dependencies = dependenciesBySymbolId.get(symbol.id) ?? new Set();
const dependenciesResolved = [...dependencies].every((symbolId) =>
resolvedSymbolIds.has(symbolId),
);
if (!dependenciesResolved) {
continue;
}
orderedSymbols.push(symbol);
resolvedSymbolIds.add(symbol.id);
remainingSymbolIds.delete(symbol.id);
progressed = true;
}
if (!progressed) {
throw new Error(
`Could not resolve Python export order for symbols: ${[
...remainingSymbolIds,
].join(', ')}`,
);
}
}
return orderedSymbols.map((symbol) => {
const resolvedSymbol = symbolById.get(symbol.id);
if (!resolvedSymbol) {
throw new Error(`Symbol '${symbol.id}' does not resolve`);
}
return resolvedSymbol;
});
};
const sanitizeCommentLine = (value: string): string =>
value.replace(/\s+/g, ' ').trim();
const renderSymbolComment = (symbol: SheetSymbol): string | undefined => {
const parts = [
sanitizeCommentLine(symbol.description),
symbol.unit ? `[${sanitizeCommentLine(symbol.unit)}]` : '',
].filter(Boolean);
return parts.length > 0 ? ` # ${parts.join(' ')}` : undefined;
};
export const createPythonFromSheetDocument = (
source: SheetDocument,
options: PythonExportOptions = {},
): string => {
const sheet = SheetDocumentSchema.parse(source);
const functionName = toPythonIdentifier(
options.functionName ?? `calculate_${sheet.id}`,
'calculate_sheet',
);
const pythonNameBySymbolId = buildPythonNameBySymbolId(sheet.symbols);
const context: PythonRenderContext = { pythonNameBySymbolId };
const orderedSymbols = orderSymbolsForPython(sheet.symbols);
const assignments: string[] = [];
let usesMath = false;
for (const symbol of orderedSymbols) {
const pythonName = pythonNameBySymbolId.get(symbol.id);
if (!pythonName) {
throw new Error(
`Symbol '${symbol.id}' does not have a Python identifier`,
);
}
const comment = renderSymbolComment(symbol);
const expression = renderSymbolExpression(symbol, context);
usesMath = usesMath || expression.usesMath;
if (comment) {
assignments.push(comment);
}
assignments.push(` ${pythonName} = ${expression.code}`);
}
const returnEntries = sheet.symbols.map((symbol) => {
const pythonName = pythonNameBySymbolId.get(symbol.id);
if (!pythonName) {
throw new Error(
`Symbol '${symbol.id}' does not have a Python identifier`,
);
}
return ` ${JSON.stringify(symbol.id)}: ${pythonName},`;
});
const lines = [
'from __future__ import annotations',
...(usesMath ? ['', 'import math'] : []),
'',
'',
`def ${functionName}() -> dict[str, object]:`,
` """Generated from FormulaSheet sheet: ${sheet.title}."""`,
...assignments,
' return {',
...returnEntries,
' }',
'',
];
return `${lines.join('\n')}`;
};
export const createPythonFromValueTreeJson = (
source: unknown,
options: PythonFromValueTreeJsonOptions,
): string => {
const { functionName, ...sheetOptions } = options;
const valueTreeSheet = createSheetFromValueTreeJson(source, sheetOptions);
return createPythonFromSheetDocument(valueTreeSheet.sheet, { functionName });
};
export const createPythonFromCalculation = (
calculation: Calculation,
options?: PythonExportOptions,
): string => createPythonFromSheetDocument(calculation.sheet, options);