functionalscript 0.38.0 → 0.39.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.
Files changed (75) hide show
  1. package/fjs/bnf/token_symbol/module.f.d.ts +38 -0
  2. package/fjs/bnf/token_symbol/module.f.js +48 -0
  3. package/fjs/bnf/token_symbol/proof.f.d.ts +10 -0
  4. package/fjs/bnf/token_symbol/proof.f.js +37 -0
  5. package/fjs/cas/cli/module.f.js +6 -9
  6. package/fjs/cas/evo/mcp/module.f.d.ts +9 -1
  7. package/fjs/cas/evo/mcp/module.f.js +52 -14
  8. package/fjs/cas/evo/mcp/proof.f.d.ts +2 -0
  9. package/fjs/cas/evo/mcp/proof.f.js +33 -2
  10. package/fjs/cas/evo/module.f.d.ts +76 -12
  11. package/fjs/cas/evo/module.f.js +129 -17
  12. package/fjs/cas/evo/proof.f.d.ts +7 -0
  13. package/fjs/cas/evo/proof.f.js +119 -0
  14. package/fjs/cas/mcp/module.f.js +22 -20
  15. package/fjs/cas/mcp/proof.f.d.ts +1 -1
  16. package/fjs/cas/mcp/proof.f.js +9 -9
  17. package/fjs/cas/module.f.js +64 -37
  18. package/fjs/cas/proof.f.d.ts +3 -9
  19. package/fjs/cas/proof.f.js +94 -74
  20. package/fjs/ci/bun/module.f.js +3 -3
  21. package/fjs/ci/common/module.f.d.ts +1 -2
  22. package/fjs/ci/common/module.f.js +1 -5
  23. package/fjs/ci/config/module.f.d.ts +5 -5
  24. package/fjs/ci/config/module.f.js +5 -5
  25. package/fjs/ci/deno/module.f.js +3 -3
  26. package/fjs/ci/module.f.js +3 -4
  27. package/fjs/ci/node/module.f.js +11 -9
  28. package/fjs/ci/proof.f.js +2 -0
  29. package/fjs/cli/module.f.js +2 -2
  30. package/fjs/common/monoid/module.f.d.ts +46 -2
  31. package/fjs/common/monoid/module.f.js +44 -0
  32. package/fjs/common/monoid/proof.f.d.ts +5 -0
  33. package/fjs/common/monoid/proof.f.js +27 -1
  34. package/fjs/dev/module.f.js +25 -25
  35. package/fjs/djs/module.f.js +5 -8
  36. package/fjs/djs/parser/module.f.d.ts +3 -0
  37. package/fjs/djs/parser/module.f.js +17 -0
  38. package/fjs/djs/transpiler/module.f.js +6 -6
  39. package/fjs/effects/eff/module.f.d.ts +72 -0
  40. package/fjs/effects/eff/module.f.js +46 -0
  41. package/fjs/effects/eff/proof.f.d.ts +11 -0
  42. package/fjs/effects/eff/proof.f.js +58 -0
  43. package/fjs/effects/list/module.f.d.ts +11 -5
  44. package/fjs/effects/list/module.f.js +2 -1
  45. package/fjs/effects/memory/proof.f.js +7 -8
  46. package/fjs/effects/module.f.d.ts +334 -52
  47. package/fjs/effects/module.f.js +253 -45
  48. package/fjs/effects/node/memory/proof.js +3 -2
  49. package/fjs/effects/node/module.f.d.ts +1 -1
  50. package/fjs/effects/node/module.f.js +9 -11
  51. package/fjs/effects/node/proof.f.js +18 -10
  52. package/fjs/effects/proof.f.d.ts +32 -6
  53. package/fjs/effects/proof.f.js +131 -39
  54. package/fjs/emergent_testing/module.f.js +55 -39
  55. package/fjs/emergent_testing/proof.f.d.ts +4 -0
  56. package/fjs/emergent_testing/proof.f.js +53 -20
  57. package/fjs/mcp/module.f.js +8 -8
  58. package/fjs/mcp/proof.f.js +5 -4
  59. package/fjs/mcp/stdio/module.f.d.ts +2 -2
  60. package/fjs/mcp/stdio/module.f.js +12 -12
  61. package/fjs/media/type/module.f.js +2 -2
  62. package/fjs/media/type/proof.f.js +7 -10
  63. package/fjs/module.f.js +4 -8
  64. package/fjs/types/bigint/module.f.js +4 -3
  65. package/fjs/types/bit_vec/module.f.js +5 -15
  66. package/fjs/types/btree/remove/module.f.d.ts +5 -0
  67. package/fjs/types/btree/remove/module.f.js +12 -0
  68. package/fjs/types/list/module.f.d.ts +21 -0
  69. package/fjs/types/list/module.f.js +17 -0
  70. package/fjs/types/list/proof.f.d.ts +1 -0
  71. package/fjs/types/list/proof.f.js +24 -1
  72. package/fjs/types/number/module.f.js +2 -1
  73. package/fjs/types/string/module.f.js +10 -2
  74. package/fjs/website/module.f.js +2 -3
  75. package/package.json +3 -3
@@ -5,38 +5,40 @@
5
5
  * @module
6
6
  */
7
7
  import { node } from '../config/module.f.js';
8
- import { clean, install, test, ubuntuArm, uses } from '../common/module.f.js';
8
+ import { install, test, ubuntuArm, uses } from '../common/module.f.js';
9
9
  export const major = (v) => v.split('.')[0];
10
10
  const installNode = (version) => uses('actions/setup-node', { 'node-version': version });
11
11
  const nodeInstall = (v) => [
12
12
  install(installNode(v)),
13
13
  test({ run: 'npm ci' }),
14
14
  ];
15
- export const basicNode = (version) => (extra) => clean([
15
+ export const basicNode = (version) => (extra) => [
16
16
  ...nodeInstall(version),
17
17
  ...extra,
18
- ]);
18
+ ];
19
19
  const fjsGlobalInstall = (version) => install({ run: `npm install -g functionalscript@${version}` });
20
20
  export const platformNodeSteps = (version) => [
21
21
  ...nodeInstall(node.default),
22
22
  fjsGlobalInstall(version),
23
23
  test({ run: 'fjs t' }),
24
24
  ];
25
- const node22Steps = (version) => clean([
25
+ const node22Steps = (version) => [
26
26
  ...nodeInstall(node.node22),
27
27
  fjsGlobalInstall(version),
28
28
  test({ run: 'fjs t' }),
29
- ]);
30
- const node24Steps = clean([
29
+ ];
30
+ const node24Steps = [
31
31
  ...nodeInstall(node.node24),
32
32
  test({ run: 'node --test' }),
33
- ]);
34
- const node26Steps = clean([
33
+ ];
34
+ const node26Steps = [
35
35
  ...nodeInstall(node.default),
36
+ test({ run: 'npm run ci-update' }),
37
+ test({ run: 'git add -A && git diff --cached --exit-code' }),
36
38
  test({ run: 'npx tsc' }),
37
39
  test({ run: 'npm run cov' }),
38
40
  test({ run: 'npm pack' }),
39
- ]);
41
+ ];
40
42
  const nodeJob = (steps) => ubuntuArm(steps);
41
43
  export const nodeVersionJobs = (version) => ({
42
44
  [`node${major(node.node22)}`]: nodeJob(node22Steps(version)),
package/fjs/ci/proof.f.js CHANGED
@@ -62,6 +62,8 @@ export const proof = {
62
62
  assert(!hasExactRunInJob('wasm', 'cargo test --target wasm32-wasip1-threads --release')(gha), 'unexpected Wasmtime WASM threads release check');
63
63
  assert(hasRunInJob('node22', 'fjs t')(gha), 'expected Node 22 FunctionalScript smoke test');
64
64
  assert(hasRunInJob('node26', 'npm pack')(gha), 'expected Node 26 package check');
65
+ assert(hasRunInJob('node26', 'npm run ci-update')(gha), 'expected Node 26 workflow regeneration');
66
+ assert(hasRunInJob('node26', 'git add -A && git diff --cached --exit-code')(gha), 'expected Node 26 generated-file drift check');
65
67
  assert(!hasRun('npm publish --dry-run')(gha), 'unexpected npm publish dry-run');
66
68
  for (const id of [
67
69
  'ubuntu-intel',
@@ -1,5 +1,5 @@
1
1
  import { errorExit, log } from '../effects/node/module.f.js';
2
- import { pure } from '../effects/module.f.js';
2
+ import { pure, step } from '../effects/module.f.js';
3
3
  import { at, fromEntries } from '../types/object/module.f.js';
4
4
  const helpMeta = { names: ['help', 'h', '?'], description: 'Print this help message' };
5
5
  export const dispatch = (commands) => (options) => {
@@ -23,7 +23,7 @@ export const dispatch = (commands) => (options) => {
23
23
  return dispatch(targetCmd.handler)({ ...options, args: ['help'] });
24
24
  }
25
25
  }
26
- return log(helpText).step(() => pure(0));
26
+ return step(log(helpText), () => pure(0));
27
27
  }
28
28
  const found = at(cmd)(map);
29
29
  if (found === null) {
@@ -1,11 +1,13 @@
1
1
  /**
2
2
  * Monoids: the `Monoid<T>` algebraic structure (identity plus associative
3
- * binary operation) and `repeat`, which applies the operation `n` times using
4
- * exponentiation by squaring.
3
+ * binary operation), `repeat`, which applies the operation `n` times using
4
+ * exponentiation by squaring, and `fold`, which applies it across every element
5
+ * of a list.
5
6
  *
6
7
  * @module
7
8
  */
8
9
  import type { Fold, Reduce } from '../../types/function/operator/module.f.ts';
10
+ import { type List } from '../../types/list/module.f.ts';
9
11
  /**
10
12
  * Represents a monoid, an algebraic structure with a binary operation
11
13
  * and an identity (neutral) element.
@@ -80,3 +82,45 @@ export type Monoid<T> = {
80
82
  * ```
81
83
  */
82
84
  export declare const repeat: <T>({ identity, operation }: Monoid<T>) => Fold<bigint, T>;
85
+ /**
86
+ * Reduces a `List<T>` with the monoid's associative `operation`, seeded at its
87
+ * `identity`. An empty list folds to `identity`.
88
+ *
89
+ * `fold` is the reduction companion of {@link repeat}: where `repeat` applies
90
+ * the operation a fixed number of times to a single element, `fold` applies it
91
+ * across every element of a list. Together they let list reductions such as
92
+ * `sum`, `product`, and string `concat` be expressed directly as monoid folds,
93
+ * so the identity paired with each operation is stated once at the call site
94
+ * instead of hand-seeding a raw `reduce`.
95
+ *
96
+ * Like `repeat`, `fold` applies the operation **accumulator-first**:
97
+ * `operation(accumulator)(element)`, seeded at `identity`, so
98
+ * `[a, b, c]` folds to `((identity op a) op b) op c`. Left-to-right order is
99
+ * therefore preserved and `fold` is correct for non-commutative monoids (e.g.
100
+ * string concatenation as `a => b => a + b`). `list.reduce` calls its reducer
101
+ * element-first, so the operation is `flip`ped before it is handed over.
102
+ *
103
+ * @template T The type of the elements in the monoid.
104
+ * @param monoid The monoid structure, including the identity and binary operation.
105
+ * @returns A function that reduces a `List<T>` to a single `T`.
106
+ *
107
+ * @example
108
+ *
109
+ * ```ts
110
+ * const add: Monoid<number> = {
111
+ * identity: 0,
112
+ * operation: a => b => a + b,
113
+ * };
114
+ *
115
+ * fold(add)([1, 2, 3, 4]) // 10
116
+ * fold(add)([]) // 0
117
+ *
118
+ * const concat: Monoid<string> = {
119
+ * identity: '',
120
+ * operation: a => b => a + b,
121
+ * };
122
+ *
123
+ * fold(concat)(['a', 'b', 'c']) // 'abc' — order preserved
124
+ * ```
125
+ */
126
+ export declare const fold: <T>({ identity, operation }: Monoid<T>) => (list: List<T>) => T;
@@ -1,3 +1,5 @@
1
+ import { reduce } from '../../types/list/module.f.js';
2
+ import { flip } from '../../types/function/module.f.js';
1
3
  /**
2
4
  * Repeats a monoid operation `n` times on the given element `a`.
3
5
  * This function efficiently performs the operation using exponentiation by squaring.
@@ -42,3 +44,45 @@ export const repeat = ({ identity, operation }) => n => a => {
42
44
  ai = operation(ai)(ai);
43
45
  }
44
46
  };
47
+ /**
48
+ * Reduces a `List<T>` with the monoid's associative `operation`, seeded at its
49
+ * `identity`. An empty list folds to `identity`.
50
+ *
51
+ * `fold` is the reduction companion of {@link repeat}: where `repeat` applies
52
+ * the operation a fixed number of times to a single element, `fold` applies it
53
+ * across every element of a list. Together they let list reductions such as
54
+ * `sum`, `product`, and string `concat` be expressed directly as monoid folds,
55
+ * so the identity paired with each operation is stated once at the call site
56
+ * instead of hand-seeding a raw `reduce`.
57
+ *
58
+ * Like `repeat`, `fold` applies the operation **accumulator-first**:
59
+ * `operation(accumulator)(element)`, seeded at `identity`, so
60
+ * `[a, b, c]` folds to `((identity op a) op b) op c`. Left-to-right order is
61
+ * therefore preserved and `fold` is correct for non-commutative monoids (e.g.
62
+ * string concatenation as `a => b => a + b`). `list.reduce` calls its reducer
63
+ * element-first, so the operation is `flip`ped before it is handed over.
64
+ *
65
+ * @template T The type of the elements in the monoid.
66
+ * @param monoid The monoid structure, including the identity and binary operation.
67
+ * @returns A function that reduces a `List<T>` to a single `T`.
68
+ *
69
+ * @example
70
+ *
71
+ * ```ts
72
+ * const add: Monoid<number> = {
73
+ * identity: 0,
74
+ * operation: a => b => a + b,
75
+ * };
76
+ *
77
+ * fold(add)([1, 2, 3, 4]) // 10
78
+ * fold(add)([]) // 0
79
+ *
80
+ * const concat: Monoid<string> = {
81
+ * identity: '',
82
+ * operation: a => b => a + b,
83
+ * };
84
+ *
85
+ * fold(concat)(['a', 'b', 'c']) // 'abc' — order preserved
86
+ * ```
87
+ */
88
+ export const fold = ({ identity, operation }) => reduce(flip(operation))(identity);
@@ -1,4 +1,9 @@
1
1
  export declare const proof: {
2
2
  numberAdd: () => void;
3
3
  stringConcat: () => void;
4
+ fold: {
5
+ nonEmpty: () => void;
6
+ order: () => void;
7
+ empty: () => void;
8
+ };
4
9
  };
@@ -1,4 +1,4 @@
1
- import { repeat } from "./module.f.js";
1
+ import { repeat, fold } from "./module.f.js";
2
2
  import { assertEq } from '../../asserts/module.f.js';
3
3
  export const proof = {
4
4
  numberAdd: () => {
@@ -18,5 +18,31 @@ export const proof = {
18
18
  };
19
19
  const resultConcat = repeat(concat)(3n)('ha'); // 'hahaha'
20
20
  assertEq(resultConcat, 'hahaha');
21
+ },
22
+ fold: {
23
+ nonEmpty: () => {
24
+ const add = {
25
+ identity: 0,
26
+ operation: a => b => a + b,
27
+ };
28
+ assertEq(fold(add)([1, 2, 3, 4]), 10);
29
+ },
30
+ order: () => {
31
+ // a non-commutative monoid: `fold` must preserve left-to-right order
32
+ // (`((('' + 'a') + 'b') + 'c')`), not reverse it to `'cba'`.
33
+ const concat = {
34
+ identity: '',
35
+ operation: a => b => a + b,
36
+ };
37
+ assertEq(fold(concat)(['a', 'b', 'c']), 'abc');
38
+ },
39
+ empty: () => {
40
+ const concat = {
41
+ identity: '',
42
+ operation: a => b => a + b,
43
+ };
44
+ // an empty list folds to the identity
45
+ assertEq(fold(concat)([]), '');
46
+ },
21
47
  }
22
48
  };
@@ -6,7 +6,7 @@
6
6
  import { all, import_, readdir } from '../effects/node/module.f.js';
7
7
  import { cmp as strCmp } from '../types/string/module.f.js';
8
8
  import { unwrap } from '../types/result/module.f.js';
9
- import { pure } from '../effects/module.f.js';
9
+ import { pure, step } from '../effects/module.f.js';
10
10
  import { join, relativize, toPosix } from '../path/module.f.js';
11
11
  import { assert } from '../asserts/module.f.js';
12
12
  /**
@@ -25,32 +25,33 @@ export const shouldLoad = (s) => s.endsWith('.f.ts') || s.endsWith('.f.js') ||
25
25
  s.endsWith('proof.mts') || s.endsWith('proof.mjs');
26
26
  const isSourceFile = (path) => path.endsWith('.js') || path.endsWith('.ts') || path.endsWith('.mts') || path.endsWith('.mjs');
27
27
  const allFiles = (s, predicate) => {
28
- const load = (p) => readdir(p, {})
29
- .step(d => {
30
- let result = [];
31
- for (const i of unwrap(d)) {
32
- const { name } = i;
33
- if (name.startsWith('.')) {
34
- continue;
35
- }
36
- const file = join(p, name);
37
- if (!i.isFile) {
38
- if (name === 'node_modules') {
28
+ const load = (p) => {
29
+ const x0 = step(readdir(p, {}), d => {
30
+ let result = [];
31
+ for (const i of unwrap(d)) {
32
+ const { name } = i;
33
+ if (name.startsWith('.')) {
39
34
  continue;
40
35
  }
41
- result = [...result, load(file)];
42
- continue;
43
- }
44
- if (predicate(file)) {
45
- result = [...result, pure([file])];
36
+ const file = join(p, name);
37
+ if (!i.isFile) {
38
+ if (name === 'node_modules') {
39
+ continue;
40
+ }
41
+ result = [...result, load(file)];
42
+ continue;
43
+ }
44
+ if (predicate(file)) {
45
+ result = [...result, pure([file])];
46
+ }
46
47
  }
47
- }
48
- return all(...result);
49
- })
50
- .step(v => pure(v.flat()));
48
+ return all(...result);
49
+ });
50
+ return step(x0, v => pure(v.flat()));
51
+ };
51
52
  return load(s);
52
53
  };
53
- const loadFile = (f) => import_(f).step(r => pure([[f, unwrap(r)]]));
54
+ const loadFile = (f) => step(import_(f), r => pure([[f, unwrap(r)]]));
54
55
  const { fromEntries } = Object;
55
56
  /**
56
57
  * Discovers all source files under `INIT_CWD` (or `.` if unset) that match
@@ -74,9 +75,8 @@ export const loadModuleMap = (env) => {
74
75
  // we should consider optimize them by ALIQ technique or something similar.
75
76
  // For example, we should be able to write it like `allFiles(s).flatMap(loadFile)`,
76
77
  // then an effect runner can batch all file loading operations together.
77
- return allFiles(s, shouldLoad)
78
- .step(files => all(...files.map(loadFile)))
79
- .step(entries => pure(fromEntries(entries
78
+ const x0 = step(allFiles(s, shouldLoad), files => all(...files.map(loadFile)));
79
+ return step(x0, entries => pure(fromEntries(entries
80
80
  .flat()
81
81
  .map(([k, v]) => [relativize(prefix, k), v])
82
82
  .toSorted(([a], [b]) => strCmp(a)(b)))));
@@ -1,25 +1,22 @@
1
1
  import { transpile } from './transpiler/module.f.js';
2
2
  import { stringify, stringifyAsTree } from './serializer/module.f.js';
3
3
  import { sort } from '../types/object/module.f.js';
4
- import { pure } from '../effects/module.f.js';
4
+ import { pure, step } from '../effects/module.f.js';
5
5
  import { writeUtf8File, error, } from '../effects/node/module.f.js';
6
6
  export const compile = args => {
7
7
  if (args.length < 2) {
8
- return error('Error: Requires 2 or more arguments')
9
- .step(() => pure(1));
8
+ return step(error('Error: Requires 2 or more arguments'), () => pure(1));
10
9
  }
11
10
  const inputFileName = args[0];
12
11
  const outputFileName = args[1];
13
- return transpile(inputFileName).step((result) => {
12
+ return step(transpile(inputFileName), (result) => {
14
13
  if (result[0] === 'error') {
15
14
  const metadata = result[1].metadata;
16
- return error(`${metadata?.path}:${metadata?.line}:${metadata?.column} - error: ${result[1].message}`)
17
- .step(() => pure(0));
15
+ return step(error(`${metadata?.path}:${metadata?.line}:${metadata?.column} - error: ${result[1].message}`), () => pure(0));
18
16
  }
19
17
  const content = outputFileName.endsWith('.json')
20
18
  ? stringifyAsTree(sort)(result[1])
21
19
  : stringify(sort)(result[1]);
22
- return writeUtf8File(outputFileName, content)
23
- .step(() => pure(0));
20
+ return step(writeUtf8File(outputFileName, content), () => pure(0));
24
21
  });
25
22
  };
@@ -17,4 +17,7 @@ export declare const proof: {
17
17
  pushKey: {
18
18
  nonObjectTop: () => void;
19
19
  };
20
+ endArray: {
21
+ nonArrayTop: () => void;
22
+ };
20
23
  };
@@ -380,4 +380,21 @@ export const proof = {
380
380
  assertEq(result.state, 'error');
381
381
  },
382
382
  },
383
+ endArray: {
384
+ // `endArray` is only ever invoked while `state.top` is an array (the
385
+ // `'['`/`'[v'`/`'[,'` value-states guarantee it), so its non-array
386
+ // guard is a defensive branch unreachable through `parseFromTokens`.
387
+ // Call it directly to cover that branch.
388
+ nonArrayTop: () => {
389
+ const state = {
390
+ state: 'exportValue',
391
+ module: { refs: null, modules: null, consts: null },
392
+ valueState: '[,',
393
+ top: null,
394
+ stack: null,
395
+ };
396
+ const result = endArray(state);
397
+ assertEq(result.state, 'result');
398
+ },
399
+ },
383
400
  };
@@ -12,7 +12,7 @@ import { stringToList } from '../../text/utf16/module.f.js';
12
12
  import { concat as pathConcat } from '../../path/module.f.js';
13
13
  import { parseFromTokens } from '../parser/module.f.js';
14
14
  import { run } from '../ast/module.f.js';
15
- import { foldStep, pure } from '../../effects/module.f.js';
15
+ import { foldStep, pure, step } from '../../effects/module.f.js';
16
16
  import { readUtf8File } from '../../effects/node/module.f.js';
17
17
  const mapDjs = context => path => {
18
18
  const res = at(path)(context.complete);
@@ -21,7 +21,7 @@ const mapDjs = context => path => {
21
21
  }
22
22
  return res.djs;
23
23
  };
24
- const parseModule = path => readUtf8File(path).step(result => {
24
+ const parseModule = path => step(readUtf8File(path), result => {
25
25
  if (result[0] === 'error') {
26
26
  return pure(error({ message: 'file not found', metadata: null }));
27
27
  }
@@ -34,8 +34,8 @@ const transpileWithImports = path => parseModuleResult => context => {
34
34
  const pathsCombine = listMap(pathConcat(dir))(parseModuleResult[1][0]);
35
35
  const pathsArray = toArray(pathsCombine);
36
36
  const contextWithStack = { ...context, stack: { first: path, tail: context.stack } };
37
- return foldStep(foldNextModuleOp)(contextWithStack)(pathsArray)
38
- .step(contextWithImports => {
37
+ const x0 = foldStep(pure(pathsArray), contextWithStack, foldNextModuleOp);
38
+ return step(x0, contextWithImports => {
39
39
  if (contextWithImports.error !== null) {
40
40
  return pure(contextWithImports);
41
41
  }
@@ -60,7 +60,7 @@ const foldNextModuleOp = path => context => {
60
60
  if (at(path)(context.complete) !== null) {
61
61
  return pure(context);
62
62
  }
63
- return parseModule(path).step(parseModuleResult => transpileWithImports(path)(parseModuleResult)(context));
63
+ return step(parseModule(path), parseModuleResult => transpileWithImports(path)(parseModuleResult)(context));
64
64
  };
65
65
  /**
66
66
  * Transpiles a DJS module graph rooted at `path` into a single `Unknown` value.
@@ -69,7 +69,7 @@ const foldNextModuleOp = path => context => {
69
69
  * evaluates the AST. Returns `['ok', value]` on success, or `['error', ParseError]`
70
70
  * on a parse failure or circular dependency.
71
71
  */
72
- export const transpile = path => foldNextModuleOp(path)({ stack: null, complete: null, error: null }).step((context) => {
72
+ export const transpile = path => step(foldNextModuleOp(path)({ stack: null, complete: null, error: null }), (context) => {
73
73
  if (context.error !== null) {
74
74
  return pure(error(context.error));
75
75
  }
@@ -0,0 +1,72 @@
1
+ import { type Effect, type Operation } from '../module.f.ts';
2
+ /**
3
+ * A fluent, method-chaining monad over a raw {@link Effect} that also
4
+ * accumulates the history of every value the chain has produced. `.step(f)`
5
+ * is bind — `f` receives the current value followed by every prior value,
6
+ * most recent first (`f(t, ...p)`), and returns a raw `Effect`; `.step`
7
+ * re-wraps the result together with that history so `.step(f).step(g)`
8
+ * chains and stays in the `Eff` world throughout. `.map(f)` is the functor
9
+ * map — the same thing for an `f` that returns a plain value rather than an
10
+ * effect, so it is exactly `.step((...tp) => pure(f(...tp)))`. `P` is the
11
+ * tuple of prior values available to the *next* `.step` call; it grows by one
12
+ * element (the current `T`) on every step, starting empty at {@link eff}.
13
+ * `.value` is the exit back to a raw `Effect`, discarding the history. An
14
+ * `Eff` is not assignable to `Effect`; unwrap through `.value`.
15
+ *
16
+ * **`.map` grows the history just as `.step` does, and does not widen `O`.**
17
+ * Both follow from it being that `.step` call and nothing else: a chain
18
+ * rewritten from `.step(v => pure(f(v)))` to `.map(f)` must hand later
19
+ * callbacks the same prior values it did before, and a projection performs no
20
+ * command, so it contributes no operation for a runner to interpret.
21
+ *
22
+ * **The history is positional, so every parameter a callback declares is
23
+ * meaningful.** `f` is applied as `f(...tp)`, so a callback written
24
+ * `(v, n = 1) => …` or `(v, ...rest) => …` receives prior chain values in `n` /
25
+ * `rest` rather than the default or an empty rest — and where the types line up,
26
+ * TypeScript will not object. Declare exactly as many parameters as the callback
27
+ * intends to read; a defaulted or rest parameter after the current value is a
28
+ * bug, not a convenience. This is what makes `.map(g)` a *different* call from
29
+ * `.step(v => pure(g(v)))` whenever `g` is not genuinely unary — the lambda
30
+ * pins the arity at one, while passing `g` point-free exposes it to the prior
31
+ * values, the way `['1', '2', '3'].map(parseInt)` does.
32
+ *
33
+ * **`.value` is always an already-built `Effect`.** Reading it composes
34
+ * nothing: the projection that drops the history tuple to its current value is
35
+ * performed by the `.step` that produced the link, not deferred to the read.
36
+ * An `Eff` is a record to look into, not an object with a method that quietly
37
+ * does work when called.
38
+ *
39
+ * That costs one projection per link, paid whether or not the link is ever
40
+ * unwrapped — an n-link chain builds n of them where a deferred `.result()`
41
+ * method would build one. It is a constant factor on construction, with no
42
+ * extra forcing of the wrapped effect and no change in growth rate, bought in
43
+ * exchange for a uniform rule at the boundary every caller touches.
44
+ *
45
+ * At the entry it costs nothing at all: `eff(e).value` **is** `e`, because
46
+ * {@link eff} stores what it was handed rather than rebuilding it from the
47
+ * history, so wrapping and unwrapping round-trip to identity. `h` is still a
48
+ * thunk, so `eff(e)` composes nothing and never forces `e`: an `Eff` that is
49
+ * built and only read does no work at all.
50
+ *
51
+ * **`P` has no default, on purpose.** A default of `readonly[]` would make
52
+ * `Eff<O, T>` a spelling that silently erases history: an
53
+ * `Eff<O, T, readonly[A]>` is assignable to it, because `f` sits in a
54
+ * contravariant position and TypeScript accepts a callback declaring fewer
55
+ * parameters than the type it is checked against. The next `.step` callback
56
+ * would then be typed as receiving no prior values while the runtime still
57
+ * passes them, and any callback destructuring a rest parameter would be handed
58
+ * entries its type says cannot exist. Requiring the third argument means that
59
+ * erasure cannot be written at all, rather than merely being discouraged;
60
+ * {@link eff} spells `readonly[]` itself.
61
+ */
62
+ export type Eff<O extends Operation, T, P extends readonly unknown[]> = {
63
+ readonly value: Effect<O, T>;
64
+ readonly step: <Q extends Operation, R>(f: (...tp: readonly [T, ...P]) => Effect<Q, R>) => Eff<O | Q, R, readonly [T, ...P]>;
65
+ readonly map: <R>(f: (...tp: readonly [T, ...P]) => R) => Eff<O, R, readonly [T, ...P]>;
66
+ };
67
+ /**
68
+ * Wraps a raw {@link Effect}; the bridge into the `Eff` world, with an empty
69
+ * history. The empty tuple is spelled out because {@link Eff} deliberately has
70
+ * no default for `P` — see its docs.
71
+ */
72
+ export declare const eff: <O extends Operation, T>(value: Effect<O, T>) => Eff<O, T, readonly []>;
@@ -0,0 +1,46 @@
1
+ import { history, historyStep, mapStep, pure } from '../module.f.js';
2
+ /**
3
+ * Builds an `Eff` from two views of the same chain: `value`, the effect for the
4
+ * current value alone, and `h`, a thunk for the `[current, ...history]` tuple.
5
+ *
6
+ * **The two must denote the same computation** — `value` has to be what `h()`
7
+ * produces with the history dropped. Nothing enforces it. The
8
+ * redundancy is deliberate: `value` used to be derived from `h` on demand,
9
+ * which made disagreement impossible but also forced the entry case to rebuild
10
+ * an effect it was already holding. Passing it in is what lets {@link eff} hand
11
+ * the original back.
12
+ *
13
+ * The asymmetry between the two — one built, one deferred — is the point.
14
+ * `value` is either already in hand ({@link eff} was given it) or already built
15
+ * (`.step` has just composed the chain it projects from), so storing it costs
16
+ * no more than the projection itself. `h` is different: nothing needs the
17
+ * history tuple until a later `.step` asks for it, and composing effects is
18
+ * eager, so holding a thunk is the only way to not compose it yet. That keeps
19
+ * `eff(e)` free of work entirely.
20
+ *
21
+ * `.step` calls `h()` once and closes over the effect, so everything built
22
+ * from that link shares it. `eff`'s thunk is not memoized, so calling `.step`
23
+ * twice on the same `eff(e)` rebuilds and re-forces `e` — harmless under
24
+ * `Pure`'s contract, which requires the thunk to be pure and to tolerate
25
+ * repeat calls.
26
+ */
27
+ const create = (value, h) => {
28
+ // `self` is named so `.map` can be *defined* as the `.step` call it is
29
+ // documented to equal, rather than as a second copy of `.step`'s body that
30
+ // has to be re-checked against it.
31
+ const self = {
32
+ value,
33
+ step: f => {
34
+ const x1 = historyStep(h(), f);
35
+ return create(mapStep(x1, ([t]) => t), () => x1);
36
+ },
37
+ map: f => self.step((...tp) => pure(f(...tp)))
38
+ };
39
+ return self;
40
+ };
41
+ /**
42
+ * Wraps a raw {@link Effect}; the bridge into the `Eff` world, with an empty
43
+ * history. The empty tuple is spelled out because {@link Eff} deliberately has
44
+ * no default for `P` — see its docs.
45
+ */
46
+ export const eff = (value) => create(value, () => history(value));
@@ -0,0 +1,11 @@
1
+ export declare const proof: {
2
+ value: () => void;
3
+ pure: () => void;
4
+ chain: () => void;
5
+ overDo: () => void;
6
+ map: {
7
+ chain: () => void;
8
+ growsHistory: () => void;
9
+ overDo: () => void;
10
+ };
11
+ };
@@ -0,0 +1,58 @@
1
+ import { do_, match, pure } from '../module.f.js';
2
+ import { assert, assertEq } from '../../asserts/module.f.js';
3
+ import { assertPure } from '../proof.f.js';
4
+ import { eff } from './module.f.js';
5
+ const next = match({ add: (a, b) => a + b });
6
+ export const proof = {
7
+ value: () => {
8
+ assertPure(eff(pure(5)).value, 5);
9
+ },
10
+ pure: () => {
11
+ assertPure(pure(5), 5);
12
+ },
13
+ chain: () => {
14
+ const x = eff(pure(5))
15
+ .step(v => pure(v + 1))
16
+ .step(v => pure(v * 2))
17
+ .value;
18
+ assertPure(x, 12);
19
+ },
20
+ overDo: () => {
21
+ const e = eff(do_('add')(2, 3))
22
+ .step(r => pure(r + 1))
23
+ .value;
24
+ const r = next(e);
25
+ assert(r[0] === 'cont', r);
26
+ assertEq(r[1], 5);
27
+ assertPure(r[2](r[1]), 6);
28
+ },
29
+ map: {
30
+ chain: () => {
31
+ const x = eff(pure(5))
32
+ .map(v => v + 1)
33
+ .map(v => v * 2)
34
+ .value;
35
+ assertPure(x, 12);
36
+ },
37
+ // `.map` grows the history exactly as `.step` does, so a callback after
38
+ // it still reaches the pre-`map` value. This is the contract that makes
39
+ // rewriting `.step(v => pure(f(v)))` into `.map(f)` a pure readability
40
+ // change rather than one that alters what later callbacks receive.
41
+ growsHistory: () => {
42
+ const x = eff(pure(5))
43
+ .map(v => v + 1)
44
+ .step((v, prev) => pure(`${prev}${v}`))
45
+ .value;
46
+ assertPure(x, '56');
47
+ },
48
+ overDo: () => {
49
+ const e = eff(do_('add')(2, 3))
50
+ .map(r => r + 1)
51
+ .value;
52
+ const r = next(e);
53
+ assert(r[0] === 'cont', r);
54
+ assertEq(r[1], 5);
55
+ assertPure(r[2](r[1]), 6);
56
+ },
57
+ },
58
+ };
@@ -7,10 +7,15 @@ export type NonEmpty<O extends Operation, T> = {
7
7
  * The payload of a `List` effect: the next cons cell, or `undefined` at
8
8
  * end-of-stream.
9
9
  *
10
- * Since `Pure<T>` is now itself a lazy thunk (`() => T`), the effect alone is the
11
- * suspension point and the cell needs no extra wrapping thunk. `Effect<O, Next<O, T>>`
12
- * is used directly in places where `List<O, T>` cannot be written as a return type
13
- * (see {@link empty}).
10
+ * A `List` suspends only where a `Do` node does. `Pure` is a thunk, but that
11
+ * thunk is a discriminator rather than a suspension, and {@link nonEmpty} takes
12
+ * `tail` as an ordinary argument already evaluated by the time the cell is
13
+ * built. A chain of pure cells is therefore constructed in full, up front;
14
+ * streaming comes from cells produced inside a command's continuation, where
15
+ * the tail is not reached until a runner performs the command.
16
+ *
17
+ * `Effect<O, Next<O, T>>` is used directly in places where `List<O, T>` cannot
18
+ * be written as a return type (see {@link empty}).
14
19
  */
15
20
  export type Next<O extends Operation, T> = NonEmpty<O, T> | undefined;
16
21
  export type List<O extends Operation, T> = Effect<O, Next<O, T>>;
@@ -26,6 +31,7 @@ export type List<O extends Operation, T> = Effect<O, Next<O, T>>;
26
31
  */
27
32
  export declare const empty: <O extends Operation, T>() => Effect<O, Next<O, T>>;
28
33
  /**
29
- * Prepends `head` to a `ListEffect` `tail`, as a pure cons cell. See {@link empty}.
34
+ * Prepends `first` to a {@link List} `tail`, as a pure cons cell. `tail` is an
35
+ * ordinary argument, so it is built before the cell is — see {@link Next}.
30
36
  */
31
37
  export declare const nonEmpty: <O extends Operation, T>(first: T, tail: List<O, T>) => Effect<O, Next<O, T>>;
@@ -11,6 +11,7 @@ import { pure } from "../module.f.js";
11
11
  */
12
12
  export const empty = () => pure(undefined);
13
13
  /**
14
- * Prepends `head` to a `ListEffect` `tail`, as a pure cons cell. See {@link empty}.
14
+ * Prepends `first` to a {@link List} `tail`, as a pure cons cell. `tail` is an
15
+ * ordinary argument, so it is built before the cell is — see {@link Next}.
15
16
  */
16
17
  export const nonEmpty = (first, tail) => pure({ first, tail });