lambdajson-js 1.1.8 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -3
- package/package.json +9 -3
- package/src/js-compiler.js +237 -71
- package/src/primitives.js +230 -60
package/README.md
CHANGED
|
@@ -5,13 +5,32 @@ LambdaJSON is a JSON based pure functional programming language: [https://github
|
|
|
5
5
|
## Quick start
|
|
6
6
|
|
|
7
7
|
```js
|
|
8
|
-
import { compile } from 'lambdajson-js';
|
|
8
|
+
import { compile, lint } from 'lambdajson-js';
|
|
9
9
|
|
|
10
10
|
const program = {
|
|
11
|
-
$
|
|
11
|
+
$map: {
|
|
12
|
+
over: '#.lines',
|
|
13
|
+
as: 'line',
|
|
14
|
+
fn: { $str: ['@line.name', ' x', { $multiply: ['@line.quantity', '#.factor'] }] }
|
|
15
|
+
}
|
|
12
16
|
};
|
|
13
17
|
const f = compile(program);
|
|
14
18
|
|
|
15
|
-
console.log(f(
|
|
19
|
+
console.log(f({ factor: 2, lines: [{ name: 'bolt', quantity: 3 }] })); // => ['bolt x6']
|
|
20
|
+
|
|
21
|
+
lint({ $str: ['\\ needless escape'] }); // => [{ severity: 'warning', code: 'needless-escape', … }]
|
|
16
22
|
```
|
|
17
23
|
|
|
24
|
+
`compile` throws a `LambdaJSONError` (with `code` and a JSON Pointer `path`) for a malformed program.
|
|
25
|
+
Problems found while a program runs throw a `LambdaJSONRuntimeError` (also with `code` and `path`).
|
|
26
|
+
See the language documentation for the full reference and the migration notes.
|
|
27
|
+
|
|
28
|
+
## Changes in 3.0
|
|
29
|
+
|
|
30
|
+
* **Breaking:** arithmetic (`$sum`, `$subtract`, `$multiply`, `$divide`) and ordering (`$lt`, `$lte`, `$gt`, `$gte`)
|
|
31
|
+
throw `LambdaJSONRuntimeError` (`missing-operand`) on a `null` or `undefined` operand instead of passing it on.
|
|
32
|
+
* **Breaking:** `$eq` and `$neq` compare deeply, by value.
|
|
33
|
+
* Functions with named parameters: `{ "$let": { "$f": { "$fn": { "as": ["a", "b"], "body": … } } }, "$f": [1, 2] }`;
|
|
34
|
+
`#` in the body stays the caller's input.
|
|
35
|
+
* New primitives: `$round`, `$min`, `$max`, `$count`, `$find`, `$unique`, `$pick`, `$omit`, `$lower`, `$upper`, `$trim`, `$isNil`.
|
|
36
|
+
* `signatureOf(name)` returns the declared types of a primitive; `typed(primitive, { takes, returns })` declares them for custom ones.
|
package/package.json
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lambdajson-js",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "LambdaJSON to JavaScript function compiler",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/js-compiler.js",
|
|
7
7
|
"module": "./src/js-compiler.js",
|
|
8
8
|
"files": [
|
|
9
9
|
"src",
|
|
10
|
-
"src/README.md",
|
|
11
10
|
"LICENSE"
|
|
12
11
|
],
|
|
13
12
|
"exports": {
|
|
@@ -34,7 +33,8 @@
|
|
|
34
33
|
"license": "MIT",
|
|
35
34
|
"author": "Benjamin Batistic",
|
|
36
35
|
"scripts": {
|
|
37
|
-
"test": "mocha"
|
|
36
|
+
"test": "mocha",
|
|
37
|
+
"prepublishOnly": "npm test"
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
40
|
"fast-printf": "^1.6.10",
|
|
@@ -46,5 +46,11 @@
|
|
|
46
46
|
"esbuild": "^0.27.0",
|
|
47
47
|
"globals": "^16.5.0",
|
|
48
48
|
"mocha": "^11.7.5"
|
|
49
|
+
},
|
|
50
|
+
"engines": {
|
|
51
|
+
"node": ">=18"
|
|
52
|
+
},
|
|
53
|
+
"publishConfig": {
|
|
54
|
+
"access": "public"
|
|
49
55
|
}
|
|
50
56
|
}
|
package/src/js-compiler.js
CHANGED
|
@@ -1,97 +1,257 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { primitives } from './primitives.js';
|
|
1
|
+
import { get, isArray, isPlainObject, isString, map, mapValues, zipObject } from 'lodash-es'
|
|
2
|
+
import { primitives, LambdaJSONRuntimeError } from './primitives.js';
|
|
3
3
|
|
|
4
4
|
export {
|
|
5
|
-
compile
|
|
5
|
+
compile,
|
|
6
|
+
lint,
|
|
7
|
+
signatureOf,
|
|
8
|
+
LambdaJSONError
|
|
6
9
|
}
|
|
10
|
+
export { primitives, named, special, call, typed, LambdaJSONRuntimeError } from './primitives.js';
|
|
7
11
|
|
|
8
12
|
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
|
|
13
|
+
* A problem in the structure of a program, found while compiling it.
|
|
14
|
+
* `path` is a JSON Pointer to the offending node, `code` a stable identifier.
|
|
15
|
+
*/
|
|
16
|
+
class LambdaJSONError extends Error {
|
|
17
|
+
constructor(code, path, message) {
|
|
18
|
+
super(`${message} (at ${path || '/'})`);
|
|
19
|
+
this.name = 'LambdaJSONError';
|
|
20
|
+
this.code = code;
|
|
21
|
+
this.path = path;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const LET = '$let';
|
|
26
|
+
const FN = '$fn';
|
|
27
|
+
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_-]*$/;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Converts a program written in pure JSON into a JavaScript function.
|
|
31
|
+
* Throws a LambdaJSONError when the program is malformed.
|
|
32
|
+
* @param {any} program
|
|
33
|
+
* @param {object} extendedPrimitives
|
|
12
34
|
* @returns {function}
|
|
13
35
|
*/
|
|
14
36
|
function compile(program, extendedPrimitives = {}) {
|
|
15
|
-
const f =
|
|
16
|
-
return input => f({input});
|
|
37
|
+
const f = compileProgram(program, extendedPrimitives, () => {});
|
|
38
|
+
return input => f({ input, vars: {} });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Lists the problems of a program without running it: the structural error
|
|
43
|
+
* that makes `compile` throw (if any) and warnings about needless escapes.
|
|
44
|
+
* @param {any} program
|
|
45
|
+
* @param {object} extendedPrimitives
|
|
46
|
+
* @returns {{ severity: 'error' | 'warning', code: string, path: string, message: string }[]}
|
|
47
|
+
*/
|
|
48
|
+
function lint(program, extendedPrimitives = {}) {
|
|
49
|
+
const problems = [];
|
|
50
|
+
const warn = (code, path, message) => problems.push({ severity: 'warning', code, path, message });
|
|
51
|
+
try {
|
|
52
|
+
compileProgram(program, extendedPrimitives, warn);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (!(error instanceof LambdaJSONError)) throw error;
|
|
55
|
+
problems.push({ severity: 'error', code: error.code, path: error.path, message: error.message });
|
|
56
|
+
}
|
|
57
|
+
return problems;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The declared types of a primitive: `{ takes, returns }`, or undefined when it declares none.
|
|
62
|
+
* @param {string} name
|
|
63
|
+
* @param {object} extendedPrimitives
|
|
64
|
+
*/
|
|
65
|
+
function signatureOf(name, extendedPrimitives = {}) {
|
|
66
|
+
return ({ ...primitives, ...extendedPrimitives })[name]?.signature;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function compileProgram(program, extendedPrimitives, warn) {
|
|
70
|
+
const scope = {
|
|
71
|
+
primitives: { ...primitives, ...extendedPrimitives },
|
|
72
|
+
functions: new Set(),
|
|
73
|
+
warn
|
|
74
|
+
};
|
|
75
|
+
return compileTree(scope, program, '');
|
|
17
76
|
}
|
|
18
77
|
|
|
19
|
-
|
|
20
|
-
|
|
78
|
+
const pointer = (path, key) => `${path}/${String(key).replace(/~/g, '~0').replace(/\//g, '~1')}`;
|
|
79
|
+
|
|
80
|
+
const fail = (code, path, message) => { throw new LambdaJSONError(code, path, message); };
|
|
81
|
+
|
|
82
|
+
function compileTree(scope, tree, path) {
|
|
83
|
+
if (isString(tree)) { return compileString(scope, tree, path); }
|
|
21
84
|
|
|
22
|
-
if (isArray(tree)) { return compileArray(
|
|
85
|
+
if (isArray(tree)) { return compileArray(scope, tree, path); }
|
|
23
86
|
|
|
24
|
-
if (
|
|
25
|
-
return
|
|
26
|
-
|
|
87
|
+
if (isPlainObject(tree)) {
|
|
88
|
+
return Object.keys(tree).some(k => k.startsWith('$'))
|
|
89
|
+
? compileCall(scope, tree, path)
|
|
90
|
+
: compileObject(scope, tree, path);
|
|
27
91
|
}
|
|
28
92
|
|
|
29
93
|
return () => tree;
|
|
30
94
|
}
|
|
31
95
|
|
|
32
|
-
|
|
33
|
-
|
|
96
|
+
/**
|
|
97
|
+
* Every object with a `$` key is a call: exactly one call key, optionally beside `$let`.
|
|
98
|
+
*/
|
|
99
|
+
function compileCall(scope, tree, path) {
|
|
100
|
+
const keys = Object.keys(tree);
|
|
101
|
+
const data = keys.filter(k => !k.startsWith('$'));
|
|
102
|
+
if (data.length > 0) {
|
|
103
|
+
const call = keys.find(k => k.startsWith('$'));
|
|
104
|
+
fail('mixed-call', path,
|
|
105
|
+
`'${call}' makes this object a call, so '${data.join("', '")}' can't stand beside it; ` +
|
|
106
|
+
`escape the key as '\\${call}' for a plain object`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const calls = keys.filter(k => k !== LET);
|
|
110
|
+
if (calls.length === 0) fail('missing-body', path, `'${LET}' needs a call beside it`);
|
|
111
|
+
if (calls.length > 1) fail('several-calls', path, `one call per object, found '${calls.join("', '")}'`);
|
|
112
|
+
const key = calls[0];
|
|
34
113
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
return _ => tree[valueDeclarationKey];
|
|
114
|
+
if (!keys.includes(LET)) {
|
|
115
|
+
return compileHead(scope, key, tree[key], path);
|
|
38
116
|
}
|
|
39
|
-
|
|
40
|
-
const
|
|
41
|
-
const
|
|
42
|
-
|
|
117
|
+
|
|
118
|
+
const declarations = tree[LET];
|
|
119
|
+
const letPath = pointer(path, LET);
|
|
120
|
+
if (!isPlainObject(declarations)) fail('invalid-let', letPath, `'${LET}' is an object of declarations`);
|
|
121
|
+
const inner = { ...scope, functions: new Set(scope.functions) };
|
|
122
|
+
for (const name of Object.keys(declarations)) {
|
|
123
|
+
if (name.startsWith('$')) {
|
|
124
|
+
if (scope.primitives[name] !== undefined) fail('shadowed-primitive', pointer(letPath, name), `'${name}' is a primitive and can't be redeclared`);
|
|
125
|
+
inner.functions.add(name);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const getLocalVars = compileVars(inner, declarations, letPath);
|
|
129
|
+
const f = compileHead(inner, key, tree[key], path);
|
|
43
130
|
return ({ vars, input }) => {
|
|
44
131
|
const extendedVars = { ...vars, ...getLocalVars({ vars, input }) };
|
|
45
132
|
return f({ vars: extendedVars, input });
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function compileHead(scope, key, value, path) {
|
|
137
|
+
const argPath = pointer(path, key);
|
|
138
|
+
const primitive = scope.primitives[key];
|
|
139
|
+
if (primitive !== undefined) {
|
|
140
|
+
return compilePrimitive(scope, key, primitive, value, argPath);
|
|
46
141
|
}
|
|
142
|
+
if (scope.functions.has(key)) {
|
|
143
|
+
return compileFunctionCall(scope, key, value, argPath);
|
|
144
|
+
}
|
|
145
|
+
return fail('unknown-function', argPath, `unknown function '${key}': neither a primitive nor declared in an enclosing '${LET}'`);
|
|
47
146
|
}
|
|
48
147
|
|
|
49
|
-
function
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
const functionKey = find(keys, k => k !== varsDeclarationKey);
|
|
53
|
-
const arg = compileTree(primitives, tree[functionKey]);
|
|
54
|
-
return ({ vars, input }) => {
|
|
55
|
-
const extendedVars = { ...vars, ...getLocalVars({ vars, input }) };
|
|
56
|
-
const f = extendedVars[functionKey];
|
|
57
|
-
return f({ vars: extendedVars, input: arg({ vars: extendedVars, input })});
|
|
148
|
+
function compilePrimitive(scope, key, primitive, value, path) {
|
|
149
|
+
if (typeof primitive === 'function') {
|
|
150
|
+
return primitive(compileTree(scope, value, path));
|
|
58
151
|
}
|
|
152
|
+
if (primitive.special) {
|
|
153
|
+
return primitive.special(value, specialContext(scope, key, path));
|
|
154
|
+
}
|
|
155
|
+
if (primitive.params) {
|
|
156
|
+
return primitive.impl(compileNamedArgs(scope, key, primitive.params, value, path));
|
|
157
|
+
}
|
|
158
|
+
return fail('invalid-primitive', path, `primitive '${key}' is neither a function nor a { params, impl } or { special } descriptor`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function specialContext(scope, key, path) {
|
|
162
|
+
return {
|
|
163
|
+
compile: (tree, ...steps) => compileTree(scope, tree, steps.reduce(pointer, path)),
|
|
164
|
+
fail: (message, ...steps) => fail('invalid-arguments', steps.reduce(pointer, path), `${key}: ${message}`),
|
|
165
|
+
warn: (code, message, ...steps) => scope.warn(code, steps.reduce(pointer, path), message),
|
|
166
|
+
path
|
|
167
|
+
};
|
|
59
168
|
}
|
|
60
169
|
|
|
61
|
-
|
|
62
|
-
|
|
170
|
+
/**
|
|
171
|
+
* Parameters are declared as names: `fn` is required, `over=#` defaults to the input,
|
|
172
|
+
* `as?` is optional. The parameter `as` is syntax: the names bound to a lambda's arguments.
|
|
173
|
+
*/
|
|
174
|
+
function parseParams(params) {
|
|
175
|
+
return params.map(spec => {
|
|
176
|
+
const name = spec.replace(/(=#|\?)$/, '');
|
|
177
|
+
return { name, required: spec === name, defaultsToInput: spec.endsWith('=#') };
|
|
178
|
+
});
|
|
179
|
+
}
|
|
63
180
|
|
|
64
|
-
|
|
181
|
+
const inputParam = ({ input }) => input;
|
|
65
182
|
|
|
66
|
-
|
|
67
|
-
|
|
183
|
+
function compileNamedArgs(scope, key, params, value, path) {
|
|
184
|
+
const declared = parseParams(params);
|
|
185
|
+
const names = declared.map(p => p.name);
|
|
186
|
+
const expected = `{ ${params.join(', ')} }`;
|
|
187
|
+
if (!isPlainObject(value) || Object.keys(value).some(k => k.startsWith('$'))) {
|
|
188
|
+
fail('named-arguments-expected', path, `'${key}' takes named arguments ${expected}`);
|
|
68
189
|
}
|
|
69
190
|
|
|
70
|
-
|
|
191
|
+
const args = {};
|
|
192
|
+
for (const [k, v] of Object.entries(value)) {
|
|
193
|
+
const argPath = pointer(path, k);
|
|
194
|
+
if (!names.includes(k)) {
|
|
195
|
+
const hint = k.startsWith('_') && names.includes(k.slice(1)) ? ` (write '${k.slice(1)}': parameters have no '_' prefix since version 2)` : '';
|
|
196
|
+
fail('unknown-parameter', argPath, `'${key}' has no parameter '${k}', expected ${expected}${hint}`);
|
|
197
|
+
}
|
|
198
|
+
args[k] = k === 'as' ? parseAs(v, argPath) : compileTree(scope, v, argPath);
|
|
199
|
+
}
|
|
200
|
+
for (const p of declared) {
|
|
201
|
+
if (p.name in args) continue;
|
|
202
|
+
if (p.required) fail('missing-parameter', path, `'${key}' requires '${p.name}', expected ${expected}`);
|
|
203
|
+
if (p.defaultsToInput) args[p.name] = inputParam;
|
|
204
|
+
}
|
|
205
|
+
return args;
|
|
71
206
|
}
|
|
72
207
|
|
|
73
|
-
function
|
|
74
|
-
const
|
|
75
|
-
|
|
208
|
+
function parseAs(value, path) {
|
|
209
|
+
const names = isArray(value) ? value : [value];
|
|
210
|
+
if (names.length === 0 || !names.every(n => isString(n) && IDENTIFIER.test(n))) {
|
|
211
|
+
fail('invalid-as', path, `'as' is a name or an array of names, e.g. "item" or ["total", "item"]`);
|
|
212
|
+
}
|
|
213
|
+
return names;
|
|
76
214
|
}
|
|
77
215
|
|
|
78
|
-
function
|
|
79
|
-
const
|
|
80
|
-
return
|
|
216
|
+
function compileFunctionCall(scope, key, value, path) {
|
|
217
|
+
const arg = compileTree(scope, value, path);
|
|
218
|
+
return ({ vars, input }) => vars[key]({ vars, input: arg({ vars, input }), outer: input });
|
|
81
219
|
}
|
|
82
220
|
|
|
83
|
-
function
|
|
84
|
-
|
|
221
|
+
function compileArray(scope, tree, path) {
|
|
222
|
+
const funks = map(tree, (n, i) => compileTree(scope, n, pointer(path, i)));
|
|
223
|
+
return x => map(funks, f => f(x));
|
|
85
224
|
}
|
|
86
225
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
226
|
+
/**
|
|
227
|
+
* `{ "$fn": { "as": names, "body": expression } }` declares a function with named parameters.
|
|
228
|
+
* The call's argument is bound to the name, or its items to the names of an array; `#` in the
|
|
229
|
+
* body stays the input of the caller.
|
|
230
|
+
*/
|
|
231
|
+
function compileFunction(scope, tree, path) {
|
|
232
|
+
const fnPath = pointer(path, FN);
|
|
233
|
+
const spec = tree[FN];
|
|
234
|
+
if (!isPlainObject(spec) || Object.keys(spec).some(k => k !== 'as' && k !== 'body') || !('as' in spec) || !('body' in spec)) {
|
|
235
|
+
fail('invalid-function', fnPath, `'${FN}' is an object { as, body }`);
|
|
236
|
+
}
|
|
237
|
+
const names = parseAs(spec.as, pointer(fnPath, 'as'));
|
|
238
|
+
const body = compileTree(scope, spec.body, pointer(fnPath, 'body'));
|
|
239
|
+
return ({ vars, input, outer }) => {
|
|
240
|
+
const args = isArray(spec.as) ? input : [input];
|
|
241
|
+
if (args.length !== names.length) {
|
|
242
|
+
throw new LambdaJSONRuntimeError('wrong-argument-count', fnPath, `the function takes ${names.length} argument(s), got ${args.length}`);
|
|
243
|
+
}
|
|
244
|
+
return body({ vars: { ...vars, ...zipObject(names, args) }, input: outer });
|
|
245
|
+
};
|
|
90
246
|
}
|
|
91
247
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
248
|
+
const isFunctionDeclaration = tree => isPlainObject(tree) && Object.keys(tree).length === 1 && FN in tree;
|
|
249
|
+
|
|
250
|
+
function compileVars(scope, obj, path) {
|
|
251
|
+
const funks = mapValues(obj, (n, k) => k.startsWith('$') && isFunctionDeclaration(n)
|
|
252
|
+
? compileFunction(scope, n, pointer(path, k))
|
|
253
|
+
: compileTree(scope, n, pointer(path, k)));
|
|
254
|
+
return ({ vars, input }) => {
|
|
95
255
|
const localVars = {};
|
|
96
256
|
const extendedVars = { ...vars };
|
|
97
257
|
for (const key in funks) {
|
|
@@ -101,38 +261,44 @@ function compileVars(primitives, obj) {
|
|
|
101
261
|
extendedVars[key] = localVars[key];
|
|
102
262
|
}
|
|
103
263
|
return localVars;
|
|
104
|
-
}
|
|
264
|
+
};
|
|
105
265
|
}
|
|
106
266
|
|
|
107
|
-
function compileObject(
|
|
108
|
-
const funks =
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
267
|
+
function compileObject(scope, obj, path) {
|
|
268
|
+
const funks = {};
|
|
269
|
+
for (const key of Object.keys(obj)) {
|
|
270
|
+
let outKey = key;
|
|
271
|
+
if (key.startsWith('\\')) {
|
|
272
|
+
outKey = key.slice(1);
|
|
273
|
+
if (!outKey.startsWith('$') && !outKey.startsWith('\\')) {
|
|
274
|
+
scope.warn('needless-escape', pointer(path, key), `the key '${outKey}' needs no escape`);
|
|
275
|
+
}
|
|
114
276
|
}
|
|
115
|
-
|
|
116
|
-
}
|
|
277
|
+
funks[outKey] = compileTree(scope, obj[key], pointer(path, key));
|
|
278
|
+
}
|
|
279
|
+
return x => mapValues(funks, f => f(x));
|
|
117
280
|
}
|
|
118
281
|
|
|
119
|
-
function compileString(str) {
|
|
282
|
+
function compileString(scope, str, path) {
|
|
120
283
|
if (str.startsWith('\\')) {
|
|
121
|
-
|
|
284
|
+
const value = str.slice(1);
|
|
285
|
+
if (!/^[#@\\]/.test(value)) {
|
|
286
|
+
scope.warn('needless-escape', path, `the string '${value}' needs no escape`);
|
|
287
|
+
}
|
|
288
|
+
return () => value;
|
|
122
289
|
}
|
|
123
290
|
if (str === '#') {
|
|
124
291
|
return ({ input }) => input;
|
|
125
292
|
}
|
|
126
293
|
if (str.startsWith('#')) {
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
return ({ input }) => get(input, pointer);
|
|
294
|
+
let p = str.slice(1);
|
|
295
|
+
p = /^\d/.test(p) ? `[${p[0]}]` + p.slice(1) : p;
|
|
296
|
+
p = p.startsWith('.') ? p.slice(1) : p;
|
|
297
|
+
return ({ input }) => get(input, p);
|
|
132
298
|
}
|
|
133
299
|
if (str.startsWith('@')) {
|
|
134
|
-
const
|
|
135
|
-
return ({ vars }) => get(vars,
|
|
300
|
+
const p = str.slice(1);
|
|
301
|
+
return ({ vars }) => get(vars, p);
|
|
136
302
|
}
|
|
137
303
|
return () => str;
|
|
138
304
|
}
|
package/src/primitives.js
CHANGED
|
@@ -1,77 +1,247 @@
|
|
|
1
1
|
import { printf } from 'fast-printf';
|
|
2
|
-
import { concat, divide,
|
|
3
|
-
orderBy, reduce, some, split, subtract, sum, tail, take, takeWhile, values, zipWith } from 'lodash-es'
|
|
2
|
+
import { concat, divide, every, filter, find, first, get, groupBy, gt, gte, includes, isArray, isEqual, isNil, join, keyBy, keys, lt, lte, map, mapValues, max, merge, min, multiply,
|
|
3
|
+
omit, orderBy, pick, reduce, round, some, split, subtract, sum, tail, take, takeWhile, uniqWith, values, zipObject, zipWith } from 'lodash-es'
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
/**
|
|
6
|
+
* A problem found while a program runs, e.g. an operand that is missing.
|
|
7
|
+
* `path` is a JSON Pointer to the offending node of the program, `code` a stable identifier.
|
|
8
|
+
*/
|
|
9
|
+
export class LambdaJSONRuntimeError extends Error {
|
|
10
|
+
constructor(code, path, message) {
|
|
11
|
+
super(`${message} (at ${path || '/'})`);
|
|
12
|
+
this.name = 'LambdaJSONRuntimeError';
|
|
13
|
+
this.code = code;
|
|
14
|
+
this.path = path;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Primitives come in three shapes:
|
|
20
|
+
* - a function `f => x => …`: the argument is compiled as one expression `f` (positional);
|
|
21
|
+
* - `{ params, impl }`: named arguments, `params` lists them (`fn` required, `over=#` defaults
|
|
22
|
+
* to the input, `as?` optional); `impl` receives an object of compiled arguments;
|
|
23
|
+
* - `{ special }`: a special form, `special(rawArgument, context)` compiles what it needs itself.
|
|
24
|
+
*/
|
|
25
|
+
export const named = (params, impl, extra = {}) => ({ params, impl, ...extra });
|
|
26
|
+
export const special = (form, extra = {}) => ({ special: form, ...extra });
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Calls a compiled lambda with the arguments of a callback. Without `as` the lambda's input `#`
|
|
30
|
+
* is `input` (by default the first argument); with `as` the arguments are bound to the names
|
|
31
|
+
* (read as `@name`) and `#` stays the input of the enclosing expression.
|
|
32
|
+
*/
|
|
33
|
+
export const call = (fn, as, x, args, input = args[0]) => as === undefined
|
|
34
|
+
? fn({ ...x, input })
|
|
35
|
+
: fn({ ...x, vars: { ...x.vars, ...zipObject(as, args) } });
|
|
36
|
+
|
|
37
|
+
const lambda = (fn, as, x) => (...args) => call(fn, as, x, args);
|
|
38
|
+
|
|
39
|
+
const toStr = v => v == null ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v);
|
|
40
|
+
|
|
41
|
+
const variadic = (name, empty, decides) => special((args, { compile }) => {
|
|
42
|
+
if (!isArray(args)) {
|
|
43
|
+
const f = compile(args);
|
|
44
|
+
return x => {
|
|
45
|
+
const vs = f(x);
|
|
46
|
+
return vs.length === 0 ? empty : vs.find(decides) ?? vs[vs.length - 1];
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
const fs = args.map((a, i) => compile(a, i));
|
|
50
|
+
return x => {
|
|
51
|
+
let v = empty;
|
|
52
|
+
for (const f of fs) {
|
|
53
|
+
v = f(x);
|
|
54
|
+
if (decides(v)) return v;
|
|
55
|
+
}
|
|
56
|
+
return v;
|
|
57
|
+
};
|
|
58
|
+
}, { description: `${name}: [a, b, …], short-circuits` });
|
|
6
59
|
|
|
7
|
-
|
|
60
|
+
/**
|
|
61
|
+
* Arithmetic and ordering need values: an operand that is null or undefined (typically a path
|
|
62
|
+
* missing in the input) fails with the path of the call instead of flowing on silently.
|
|
63
|
+
*/
|
|
64
|
+
const strict = (name, impl) => special((args, { compile, path }) => {
|
|
65
|
+
const f = compile(args);
|
|
66
|
+
return x => {
|
|
67
|
+
const operands = f(x);
|
|
68
|
+
const missing = isArray(operands) ? operands.findIndex(isNil) : isNil(operands) ? 0 : -1;
|
|
69
|
+
if (missing >= 0) {
|
|
70
|
+
throw new LambdaJSONRuntimeError('missing-operand', path,
|
|
71
|
+
`${name} got ${operands?.[missing] === null ? 'null' : 'undefined'} as ${isArray(operands) ? `operand ${missing}` : 'its operand'}; a path in the input is probably missing`);
|
|
72
|
+
}
|
|
73
|
+
return impl(operands);
|
|
74
|
+
};
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
const sort = direction => named(['by?', 'collection=#', 'as?'], ({ by, collection, as }) => x =>
|
|
78
|
+
orderBy(collection(x), by ? [v => call(by, as, x, [v])] : undefined, [direction]));
|
|
79
|
+
|
|
80
|
+
const primitiveTable = {
|
|
8
81
|
$let: true,
|
|
9
|
-
$literal:
|
|
10
|
-
$: f => x => v => f({ ...x, input: v}),
|
|
82
|
+
$literal: special(value => () => value),
|
|
83
|
+
$: f => x => v => f({ ...x, input: v }),
|
|
11
84
|
$in: f => x => f(x),
|
|
12
85
|
$return: f => x => f(x),
|
|
13
|
-
$apply: ({
|
|
86
|
+
$apply: named(['fn', 'to=#', 'as?'], ({ fn, to, as }) => x => call(fn, as, x, [to(x)])),
|
|
14
87
|
$pipeline: f => x => reduce(f(x), (a, g) => g(a), x.input),
|
|
15
|
-
|
|
16
|
-
$
|
|
17
|
-
|
|
88
|
+
|
|
89
|
+
$if: special((args, { compile, fail }) => {
|
|
90
|
+
if (!isArray(args) || args.length < 2 || args.length > 3) fail('takes [test, then] or [test, then, else]');
|
|
91
|
+
const [test, then, otherwise] = args.map((a, i) => compile(a, i));
|
|
92
|
+
return x => test(x) ? then(x) : otherwise ? otherwise(x) : null;
|
|
93
|
+
}),
|
|
94
|
+
$cond: special((args, { compile, fail }) => {
|
|
95
|
+
if (!isArray(args) || !args.every(c => isArray(c) && c.length === 2)) {
|
|
96
|
+
fail('takes clauses [[test, value], …]; a last clause ["else", value] always matches');
|
|
97
|
+
}
|
|
98
|
+
const clauses = args.map((c, i) => [compile(c[0], i, 0), compile(c[1], i, 1)]);
|
|
99
|
+
return x => {
|
|
100
|
+
for (const [test, value] of clauses) {
|
|
101
|
+
if (test(x)) return value(x);
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
};
|
|
105
|
+
}),
|
|
106
|
+
$and: variadic('$and', true, v => !v),
|
|
107
|
+
$or: variadic('$or', false, v => !!v),
|
|
108
|
+
$not: f => x => !f(x),
|
|
18
109
|
$negate: f => x => !f(x),
|
|
19
|
-
|
|
20
|
-
$
|
|
21
|
-
$
|
|
22
|
-
$
|
|
23
|
-
$
|
|
24
|
-
$
|
|
25
|
-
$
|
|
26
|
-
|
|
27
|
-
$
|
|
28
|
-
$
|
|
29
|
-
$
|
|
110
|
+
|
|
111
|
+
$eq: f => x => isEqual(...f(x)),
|
|
112
|
+
$neq: f => x => !isEqual(...f(x)),
|
|
113
|
+
$lt: strict('$lt', v => lt(...v)),
|
|
114
|
+
$lte: strict('$lte', v => lte(...v)),
|
|
115
|
+
$gt: strict('$gt', v => gt(...v)),
|
|
116
|
+
$gte: strict('$gte', v => gte(...v)),
|
|
117
|
+
|
|
118
|
+
$sum: strict('$sum', v => sum(v)),
|
|
119
|
+
$subtract: strict('$subtract', v => subtract(...v)),
|
|
120
|
+
$multiply: strict('$multiply', v => multiply(...v)),
|
|
121
|
+
$divide: strict('$divide', v => divide(...v)),
|
|
122
|
+
|
|
123
|
+
$map: named(['fn', 'over=#', 'as?'], ({ fn, over, as }) => x => map(over(x), lambda(fn, as, x))),
|
|
124
|
+
$mapValues: named(['fn', 'of=#', 'as?'], ({ fn, of, as }) => x => mapValues(of(x), lambda(fn, as, x))),
|
|
125
|
+
$filter: named(['predicate', 'collection=#', 'as?'], ({ predicate, collection, as }) => x => filter(collection(x), lambda(predicate, as, x))),
|
|
126
|
+
$any: named(['predicate', 'collection=#', 'as?'], ({ predicate, collection, as }) => x => some(collection(x), lambda(predicate, as, x))),
|
|
127
|
+
$all: named(['predicate', 'collection=#', 'as?'], ({ predicate, collection, as }) => x => every(collection(x), lambda(predicate, as, x))),
|
|
128
|
+
$group: named(['by', 'collection=#', 'as?'], ({ by, collection, as }) => x => groupBy(collection(x), v => call(by, as, x, [v]))),
|
|
129
|
+
$toDictionary: named(['by', 'collection=#', 'as?'], ({ by, collection, as }) => x => keyBy(collection(x), v => call(by, as, x, [v]))),
|
|
130
|
+
$take: named(['while?', 'count?', 'from=#', 'as?'], ({ while: whileFn, count, from, as }) => x => {
|
|
131
|
+
let y = from(x);
|
|
132
|
+
y = whileFn ? takeWhile(y, v => call(whileFn, as, x, [v])) : y;
|
|
133
|
+
y = count ? take(y, count(x)) : y;
|
|
134
|
+
return y;
|
|
135
|
+
}),
|
|
136
|
+
$zip: named(['with?', 'sequences=#', 'as?'], ({ with: withFn, sequences, as }) => x => {
|
|
137
|
+
const [as_, bs] = sequences(x);
|
|
138
|
+
return zipWith(as_, bs, (a, b) => withFn ? call(withFn, as, x, [a, b], [a, b]) : [a, b]);
|
|
139
|
+
}),
|
|
140
|
+
$fold: named(['with', 'init?', 'collection=#', 'as?'], ({ with: withFn, init, collection, as }) => {
|
|
141
|
+
const step = x => (a, v) => call(withFn, as, x, [a, v], [a, v]);
|
|
142
|
+
return init
|
|
143
|
+
? x => reduce(collection(x), step(x), init(x))
|
|
144
|
+
: x => reduce(collection(x), step(x));
|
|
145
|
+
}),
|
|
146
|
+
$ascending: sort('asc'),
|
|
147
|
+
$descending: sort('desc'),
|
|
148
|
+
|
|
30
149
|
$head: f => x => first(f(x)),
|
|
31
150
|
$tail: f => x => tail(f(x)),
|
|
32
151
|
$concat: f => x => concat(...f(x)),
|
|
33
|
-
$group: ({ _by, _collection = input }) => x => groupBy(_collection(x), v => _by({...x, input: v})),
|
|
34
|
-
$toDictionary: ({ _by, _collection = input }) => x => keyBy(_collection(x), v => _by({...x, input: v})),
|
|
35
152
|
$keys: f => x => keys(f(x)),
|
|
153
|
+
$values: f => x => values(f(x)),
|
|
36
154
|
$merge: f => x => merge({}, ...f(x)),
|
|
37
155
|
$coalesce: f => x => f(x).find(v => v != null),
|
|
38
|
-
$
|
|
39
|
-
$
|
|
40
|
-
|
|
41
|
-
$
|
|
42
|
-
$
|
|
43
|
-
$split: (
|
|
44
|
-
$match: (
|
|
45
|
-
$
|
|
46
|
-
$
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
$
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
},
|
|
60
|
-
$
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
: x => reduce(_collection(x), (a, v) => aggregator(x, [a, v]));
|
|
65
|
-
},
|
|
66
|
-
$replace: ({ _regex, _substitute, _string = input, _global }) => x => {
|
|
67
|
-
const pattern = _global?.(x) ? new RegExp(_regex(x), 'g') : _regex(x);
|
|
68
|
-
return _string(x).replace(pattern, _substitute(x));
|
|
69
|
-
},
|
|
70
|
-
$isMatch: ({ _pattern, _string = input }) => x => new RegExp(_pattern(x)).test(_string(x)),
|
|
156
|
+
$get: named(['object=#', 'path'], ({ object, path }) => x => get(object(x), path(x))),
|
|
157
|
+
$includes: named(['collection=#', 'value'], ({ collection, value }) => x => includes(collection(x), value(x))),
|
|
158
|
+
|
|
159
|
+
$str: f => x => { const v = f(x); return isArray(v) ? v.map(toStr).join('') : toStr(v); },
|
|
160
|
+
$join: named(['separator?', 'strings=#'], ({ separator = () => '', strings }) => x => join(strings(x), separator(x))),
|
|
161
|
+
$split: named(['separator', 'string=#'], ({ separator, string }) => x => split(string(x), separator(x))),
|
|
162
|
+
$match: named(['pattern', 'string=#'], ({ pattern, string }) => x => string(x).match(pattern(x))),
|
|
163
|
+
$isMatch: named(['pattern', 'string=#'], ({ pattern, string }) => x => new RegExp(pattern(x)).test(string(x))),
|
|
164
|
+
$replace: named(['regex', 'substitute', 'string=#', 'global?'], ({ regex, substitute, string, global }) => x => {
|
|
165
|
+
const p = global?.(x) ? new RegExp(regex(x), 'g') : regex(x);
|
|
166
|
+
return string(x).replace(p, substitute(x));
|
|
167
|
+
}),
|
|
168
|
+
$printf: named(['template', 'args=#'], ({ template, args }) => x => printf(template(x), ...args(x))),
|
|
169
|
+
$round: named(['value=#', 'digits?'], ({ value, digits }) => x => round(value(x), digits?.(x))),
|
|
170
|
+
$min: f => x => min(f(x)),
|
|
171
|
+
$max: f => x => max(f(x)),
|
|
172
|
+
$count: named(['predicate?', 'collection=#', 'as?'], ({ predicate, collection, as }) => x =>
|
|
173
|
+
predicate ? filter(collection(x), lambda(predicate, as, x)).length : collection(x).length),
|
|
174
|
+
$find: named(['predicate', 'collection=#', 'as?'], ({ predicate, collection, as }) => x => find(collection(x), lambda(predicate, as, x))),
|
|
175
|
+
$unique: f => x => uniqWith(f(x), isEqual),
|
|
176
|
+
$pick: named(['keys', 'object=#'], ({ keys, object }) => x => pick(object(x), keys(x))),
|
|
177
|
+
$omit: named(['keys', 'object=#'], ({ keys, object }) => x => omit(object(x), keys(x))),
|
|
178
|
+
$lower: f => x => toStr(f(x)).toLowerCase(),
|
|
179
|
+
$upper: f => x => toStr(f(x)).toUpperCase(),
|
|
180
|
+
$trim: f => x => toStr(f(x)).trim(),
|
|
181
|
+
$isNil: f => x => isNil(f(x)),
|
|
71
182
|
$parseInt: f => x => { const n = parseInt(f(x), 10); return isNaN(n) ? undefined : n; },
|
|
72
183
|
$parseFloat: f => x => { const n = parseFloat(f(x)); return isNaN(n) ? undefined : n; },
|
|
73
|
-
$ascending: ({ _by, _collection = input }) => x =>
|
|
74
|
-
orderBy(_collection(x), _by ? [v => _by({ ...x, input: v })] : undefined, ['asc']),
|
|
75
|
-
$descending: ({ _by, _collection = input }) => x =>
|
|
76
|
-
orderBy(_collection(x), _by ? [v => _by({ ...x, input: v })] : undefined, ['desc']),
|
|
77
184
|
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Types of the primitives, so that tools can infer what a program takes and returns.
|
|
188
|
+
* `takes` is the type of the expression argument, or an object of parameter types for
|
|
189
|
+
* named parameters; `returns` the type of the result. Types: `any`, `number`, `string`,
|
|
190
|
+
* `boolean`, `object`, `function` (a lambda), `names` (the `as` parameter), `array` or `array<T>`.
|
|
191
|
+
* A custom primitive declares its own with `typed`.
|
|
192
|
+
*/
|
|
193
|
+
export const typed = (primitive, signature) => typeof primitive === 'function'
|
|
194
|
+
? Object.assign(primitive, { signature })
|
|
195
|
+
: { ...primitive, signature };
|
|
196
|
+
|
|
197
|
+
const sig = (takes, returns) => ({ takes, returns });
|
|
198
|
+
const over = (fn, collection, returns, extra = {}) => sig({ [fn]: 'function', [collection]: collection === 'of' ? 'object' : 'array', ...extra, as: 'names' }, returns);
|
|
199
|
+
const numbers = 'array<number>';
|
|
200
|
+
|
|
201
|
+
const signatures = {
|
|
202
|
+
$literal: sig('any', 'any'), $: sig('any', 'function'), $in: sig('any', 'any'), $return: sig('any', 'any'),
|
|
203
|
+
$apply: sig({ fn: 'function', to: 'any', as: 'names' }, 'any'),
|
|
204
|
+
$pipeline: sig('array<function>', 'any'),
|
|
205
|
+
$if: sig('array', 'any'), $cond: sig('array', 'any'), $and: sig('array', 'any'), $or: sig('array', 'any'),
|
|
206
|
+
$not: sig('any', 'boolean'), $negate: sig('any', 'boolean'),
|
|
207
|
+
$eq: sig('array', 'boolean'), $neq: sig('array', 'boolean'),
|
|
208
|
+
$lt: sig(numbers, 'boolean'), $lte: sig(numbers, 'boolean'), $gt: sig(numbers, 'boolean'), $gte: sig(numbers, 'boolean'),
|
|
209
|
+
$sum: sig(numbers, 'number'), $subtract: sig(numbers, 'number'), $multiply: sig(numbers, 'number'), $divide: sig(numbers, 'number'),
|
|
210
|
+
$map: over('fn', 'over', 'array'),
|
|
211
|
+
$mapValues: over('fn', 'of', 'object'),
|
|
212
|
+
$filter: over('predicate', 'collection', 'array'),
|
|
213
|
+
$any: over('predicate', 'collection', 'boolean'),
|
|
214
|
+
$all: over('predicate', 'collection', 'boolean'),
|
|
215
|
+
$group: over('by', 'collection', 'object'),
|
|
216
|
+
$toDictionary: over('by', 'collection', 'object'),
|
|
217
|
+
$ascending: over('by', 'collection', 'array'),
|
|
218
|
+
$descending: over('by', 'collection', 'array'),
|
|
219
|
+
$take: sig({ while: 'function', count: 'number', from: 'array', as: 'names' }, 'array'),
|
|
220
|
+
$zip: sig({ with: 'function', sequences: 'array<array>', as: 'names' }, 'array'),
|
|
221
|
+
$fold: sig({ with: 'function', init: 'any', collection: 'array', as: 'names' }, 'any'),
|
|
222
|
+
$head: sig('array', 'any'), $tail: sig('array', 'array'), $concat: sig('array<array>', 'array'),
|
|
223
|
+
$keys: sig('object', 'array<string>'), $values: sig('object', 'array'), $merge: sig('array<object>', 'object'),
|
|
224
|
+
$coalesce: sig('array', 'any'),
|
|
225
|
+
$get: sig({ object: 'object', path: 'string' }, 'any'),
|
|
226
|
+
$includes: sig({ collection: 'array', value: 'any' }, 'boolean'),
|
|
227
|
+
$str: sig('any', 'string'),
|
|
228
|
+
$join: sig({ separator: 'string', strings: 'array' }, 'string'),
|
|
229
|
+
$split: sig({ separator: 'string', string: 'string' }, 'array<string>'),
|
|
230
|
+
$match: sig({ pattern: 'string', string: 'string' }, 'array'),
|
|
231
|
+
$isMatch: sig({ pattern: 'string', string: 'string' }, 'boolean'),
|
|
232
|
+
$replace: sig({ regex: 'string', substitute: 'string', string: 'string', global: 'boolean' }, 'string'),
|
|
233
|
+
$printf: sig({ template: 'string', args: 'array' }, 'string'),
|
|
234
|
+
$round: sig({ value: 'number', digits: 'number' }, 'number'),
|
|
235
|
+
$min: sig(numbers, 'number'), $max: sig(numbers, 'number'),
|
|
236
|
+
$count: over('predicate', 'collection', 'number'),
|
|
237
|
+
$find: over('predicate', 'collection', 'any'),
|
|
238
|
+
$unique: sig('array', 'array'),
|
|
239
|
+
$pick: sig({ keys: 'array<string>', object: 'object' }, 'object'),
|
|
240
|
+
$omit: sig({ keys: 'array<string>', object: 'object' }, 'object'),
|
|
241
|
+
$lower: sig('string', 'string'), $upper: sig('string', 'string'), $trim: sig('string', 'string'),
|
|
242
|
+
$isNil: sig('any', 'boolean'),
|
|
243
|
+
$parseInt: sig('string', 'number'), $parseFloat: sig('string', 'number'),
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
export const primitives = Object.fromEntries(Object.entries(primitiveTable).map(([name, primitive]) =>
|
|
247
|
+
[name, signatures[name] ? typed(primitive, signatures[name]) : primitive]));
|