trebol 0.1.0 → 0.1.2

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 (160) hide show
  1. package/README.md +18 -3
  2. package/dist/cli.js +13790 -11417
  3. package/dist/fonts/OFL.txt +93 -0
  4. package/dist/fonts/inter-cyrillic-ext.woff2 +0 -0
  5. package/dist/fonts/inter-cyrillic.woff2 +0 -0
  6. package/dist/fonts/inter-greek-ext.woff2 +0 -0
  7. package/dist/fonts/inter-greek.woff2 +0 -0
  8. package/dist/fonts/inter-latin-ext.woff2 +0 -0
  9. package/dist/fonts/inter-latin.woff2 +0 -0
  10. package/dist/fonts/inter-vietnamese.woff2 +0 -0
  11. package/dist/lib/core/access.d.ts +10 -0
  12. package/dist/lib/core/access.js +210 -0
  13. package/dist/lib/core/base.d.ts +4 -0
  14. package/dist/lib/core/base.js +50 -0
  15. package/dist/lib/core/bitset.d.ts +9 -0
  16. package/dist/lib/core/bitset.js +75 -0
  17. package/dist/lib/core/boot.d.ts +18 -0
  18. package/dist/lib/core/boot.js +73 -0
  19. package/dist/lib/core/compare.d.ts +9 -0
  20. package/dist/lib/core/compare.js +156 -0
  21. package/dist/lib/core/ctx.d.ts +36 -0
  22. package/dist/lib/core/ctx.js +251 -0
  23. package/dist/lib/core/dec.d.ts +28 -0
  24. package/dist/lib/core/dec.js +158 -0
  25. package/dist/lib/core/errors.d.ts +15 -0
  26. package/dist/lib/core/errors.js +44 -0
  27. package/dist/lib/core/escapes.d.ts +14 -0
  28. package/dist/lib/core/escapes.js +80 -0
  29. package/dist/lib/core/eval.d.ts +220 -0
  30. package/dist/lib/core/eval.js +666 -0
  31. package/dist/lib/core/func.d.ts +68 -0
  32. package/dist/lib/core/func.js +129 -0
  33. package/dist/lib/core/hash.d.ts +5 -0
  34. package/dist/lib/core/hash.js +155 -0
  35. package/dist/lib/core/index.d.ts +18 -0
  36. package/dist/lib/core/index.js +20 -0
  37. package/dist/lib/core/int64.d.ts +22 -0
  38. package/dist/lib/core/int64.js +113 -0
  39. package/dist/lib/core/kinds.d.ts +67 -0
  40. package/dist/lib/core/kinds.js +134 -0
  41. package/dist/lib/core/lexer.d.ts +13 -0
  42. package/dist/lib/core/lexer.js +702 -0
  43. package/dist/lib/core/mezz.d.ts +1 -0
  44. package/dist/lib/core/mezz.js +360 -0
  45. package/dist/lib/core/mold.d.ts +20 -0
  46. package/dist/lib/core/mold.js +434 -0
  47. package/dist/lib/core/natives/control.d.ts +1 -0
  48. package/dist/lib/core/natives/control.js +374 -0
  49. package/dist/lib/core/natives/csv.d.ts +15 -0
  50. package/dist/lib/core/natives/csv.js +315 -0
  51. package/dist/lib/core/natives/data.d.ts +11 -0
  52. package/dist/lib/core/natives/data.js +367 -0
  53. package/dist/lib/core/natives/define.d.ts +17 -0
  54. package/dist/lib/core/natives/define.js +47 -0
  55. package/dist/lib/core/natives/encode.d.ts +3 -0
  56. package/dist/lib/core/natives/encode.js +187 -0
  57. package/dist/lib/core/natives/json.d.ts +5 -0
  58. package/dist/lib/core/natives/json.js +273 -0
  59. package/dist/lib/core/natives/math.d.ts +3 -0
  60. package/dist/lib/core/natives/math.js +500 -0
  61. package/dist/lib/core/natives/parse.d.ts +1 -0
  62. package/dist/lib/core/natives/parse.js +600 -0
  63. package/dist/lib/core/natives/series.d.ts +4 -0
  64. package/dist/lib/core/natives/series.js +519 -0
  65. package/dist/lib/core/natives/text.d.ts +1 -0
  66. package/dist/lib/core/natives/text.js +487 -0
  67. package/dist/lib/core/natives/xml.d.ts +9 -0
  68. package/dist/lib/core/natives/xml.js +242 -0
  69. package/dist/lib/core/series.d.ts +26 -0
  70. package/dist/lib/core/series.js +73 -0
  71. package/dist/lib/core/symbols.d.ts +9 -0
  72. package/dist/lib/core/symbols.js +44 -0
  73. package/dist/lib/core/values.d.ts +206 -0
  74. package/dist/lib/core/values.js +223 -0
  75. package/dist/lib/host/browser.d.ts +4 -0
  76. package/dist/lib/host/browser.js +4974 -0
  77. package/dist/lib/host/chart.d.ts +26 -0
  78. package/dist/lib/host/chart.js +158 -0
  79. package/dist/lib/host/compress.d.ts +1 -0
  80. package/dist/lib/host/compress.js +37 -0
  81. package/dist/lib/host/devlog.d.ts +11 -0
  82. package/dist/lib/host/devlog.js +13 -0
  83. package/dist/lib/host/devtools.d.ts +23 -0
  84. package/dist/lib/host/devtools.js +626 -0
  85. package/dist/lib/host/draw.d.ts +31 -0
  86. package/dist/lib/host/draw.js +348 -0
  87. package/dist/lib/host/fonts/OFL.txt +93 -0
  88. package/dist/lib/host/fonts/inter-cyrillic-ext.woff2 +0 -0
  89. package/dist/lib/host/fonts/inter-cyrillic.woff2 +0 -0
  90. package/dist/lib/host/fonts/inter-greek-ext.woff2 +0 -0
  91. package/dist/lib/host/fonts/inter-greek.woff2 +0 -0
  92. package/dist/lib/host/fonts/inter-latin-ext.woff2 +0 -0
  93. package/dist/lib/host/fonts/inter-latin.woff2 +0 -0
  94. package/dist/lib/host/fonts/inter-vietnamese.woff2 +0 -0
  95. package/dist/lib/host/fonts.d.ts +11 -0
  96. package/dist/lib/host/fonts.js +29 -0
  97. package/dist/lib/host/icons.d.ts +3 -0
  98. package/dist/lib/host/icons.js +97 -0
  99. package/dist/lib/host/index.d.ts +40 -0
  100. package/dist/lib/host/index.js +192 -0
  101. package/dist/lib/host/js.d.ts +5 -0
  102. package/dist/lib/host/js.js +130 -0
  103. package/dist/lib/host/locale.d.ts +40 -0
  104. package/dist/lib/host/locale.js +241 -0
  105. package/dist/lib/host/markdown.d.ts +30 -0
  106. package/dist/lib/host/markdown.js +161 -0
  107. package/dist/lib/host/modules.d.ts +14 -0
  108. package/dist/lib/host/modules.js +300 -0
  109. package/dist/lib/host/natives.d.ts +6 -0
  110. package/dist/lib/host/natives.js +98 -0
  111. package/dist/lib/host/net.d.ts +12 -0
  112. package/dist/lib/host/net.js +549 -0
  113. package/dist/lib/host/orbit.d.ts +121 -0
  114. package/dist/lib/host/orbit.js +374 -0
  115. package/dist/lib/host/page.d.ts +9 -0
  116. package/dist/lib/host/page.js +55 -0
  117. package/dist/lib/host/rows.d.ts +29 -0
  118. package/dist/lib/host/rows.js +109 -0
  119. package/dist/lib/host/scheduler.d.ts +51 -0
  120. package/dist/lib/host/scheduler.js +197 -0
  121. package/dist/lib/host/theme.d.ts +58 -0
  122. package/dist/lib/host/theme.js +1667 -0
  123. package/dist/lib/ui/i18n.trb +117 -0
  124. package/dist/lib/ui/test.trb +565 -0
  125. package/dist/lib/ui/ui.trb +1678 -0
  126. package/dist/trebol.js +1427 -138
  127. package/editors/vscode/README.md +15 -0
  128. package/editors/vscode/language-configuration.json +28 -0
  129. package/editors/vscode/package.json +42 -0
  130. package/editors/vscode/syntaxes/trebol.tmLanguage.json +237 -0
  131. package/package.json +23 -7
  132. package/src/core/boot.ts +1 -1
  133. package/src/core/func.ts +4 -0
  134. package/src/core/natives/control.ts +1 -1
  135. package/src/core/natives/series.ts +9 -1
  136. package/src/core/natives/text.ts +2 -0
  137. package/src/host/browser.ts +1235 -83
  138. package/src/host/devlog.ts +16 -0
  139. package/src/host/devtools.ts +641 -0
  140. package/src/host/fonts/OFL.txt +93 -0
  141. package/src/host/fonts/inter-cyrillic-ext.woff2 +0 -0
  142. package/src/host/fonts/inter-cyrillic.woff2 +0 -0
  143. package/src/host/fonts/inter-greek-ext.woff2 +0 -0
  144. package/src/host/fonts/inter-greek.woff2 +0 -0
  145. package/src/host/fonts/inter-latin-ext.woff2 +0 -0
  146. package/src/host/fonts/inter-latin.woff2 +0 -0
  147. package/src/host/fonts/inter-vietnamese.woff2 +0 -0
  148. package/src/host/fonts.ts +39 -0
  149. package/src/host/index.ts +5 -3
  150. package/src/host/js.ts +127 -0
  151. package/src/host/markdown.ts +9 -0
  152. package/src/host/modules.ts +41 -2
  153. package/src/host/net.ts +9 -1
  154. package/src/host/orbit.ts +432 -0
  155. package/src/host/rows.ts +30 -0
  156. package/src/host/scheduler.ts +62 -36
  157. package/src/host/theme.ts +270 -6
  158. package/src/ui/i18n.trb +10 -0
  159. package/src/ui/test.trb +565 -0
  160. package/src/ui/ui.trb +564 -90
@@ -0,0 +1,156 @@
1
+ // Loose equality (`=`, equal?) and ordering (`<`, sort).
2
+ //
3
+ // `equal?` is what people mean by "the same": numbers compare by value across
4
+ // integer!, decimal!, percent! and money!, text and chars ignore case, words
5
+ // compare by symbol whatever their type. `strictEqual` in values.ts is `==`.
6
+ import { K, isAnyBlock, isAnyString, isAnyWord } from "./kinds.js";
7
+ import { canon, spell } from "./symbols.js";
8
+ import * as I64 from "./int64.js";
9
+ import { decCmp, decFromNumber, decFromBig } from "./dec.js";
10
+ import { strictEqual } from "./values.js";
11
+ const isNumeric = (c) => c.t === K.Integer || c.t === K.Decimal || c.t === K.Percent || c.t === K.Money;
12
+ /** An exact decimal for any numeric cell (null for NaN/infinity). */
13
+ export function toDec(c) {
14
+ switch (c.t) {
15
+ case K.Integer: return typeof c.v === 'bigint' ? decFromBig(c.v) : decFromNumber(c.v);
16
+ case K.Decimal:
17
+ case K.Percent: return decFromNumber(c.v);
18
+ case K.Money: return c.v;
19
+ }
20
+ return null;
21
+ }
22
+ function numCmp(a, b) {
23
+ if (a.t === K.Integer && b.t === K.Integer)
24
+ return I64.cmp(a.v, b.v);
25
+ if (a.t === K.Money && b.t === K.Money && a.cur !== '' && b.cur !== '' &&
26
+ a.cur.toUpperCase() !== b.cur.toUpperCase())
27
+ return null;
28
+ const x = toDec(a);
29
+ const y = toDec(b);
30
+ if (x === null || y === null) {
31
+ const fx = a.t === K.Decimal || a.t === K.Percent ? a.v : NaN;
32
+ const fy = b.t === K.Decimal || b.t === K.Percent ? b.v : NaN;
33
+ if (Number.isNaN(fx) || Number.isNaN(fy))
34
+ return null;
35
+ return fx < fy ? -1 : fx > fy ? 1 : 0;
36
+ }
37
+ return decCmp(x, y);
38
+ }
39
+ function textCmp(a, b) {
40
+ const x = a.s.data;
41
+ const y = b.s.data;
42
+ const n = Math.min(x.length - a.i, y.length - b.i);
43
+ for (let k = 0; k < n; k++) {
44
+ const p = foldCase(x[a.i + k]);
45
+ const q = foldCase(y[b.i + k]);
46
+ if (p !== q)
47
+ return p < q ? -1 : 1;
48
+ }
49
+ const la = x.length - a.i;
50
+ const lb = y.length - b.i;
51
+ return la < lb ? -1 : la > lb ? 1 : 0;
52
+ }
53
+ /** Lowercase code point for case-insensitive comparison. */
54
+ export function foldCase(cp) {
55
+ if (cp >= 65 && cp <= 90)
56
+ return cp + 32;
57
+ if (cp < 128)
58
+ return cp;
59
+ const lower = String.fromCodePoint(cp).toLowerCase();
60
+ return lower.length === 1 || lower.codePointAt(0) > 0xffff ? lower.codePointAt(0) : cp;
61
+ }
62
+ // Decimals are binary fractions, so as in R3 two of them are equal when they
63
+ // are at most 10 representable numbers apart: 0.1 + 0.2 = 0.3. `==` stays exact.
64
+ const ULPS = 10n;
65
+ const f64 = new Float64Array(1);
66
+ const i64 = new BigInt64Array(f64.buffer);
67
+ /** Position of a float on a line where neighbouring floats are 1 apart. */
68
+ function ordinal(x) {
69
+ f64[0] = x;
70
+ const n = i64[0];
71
+ return n < 0n ? -(n & 0x7fffffffffffffffn) : n;
72
+ }
73
+ function almostEqual(x, y) {
74
+ if (x === y)
75
+ return true;
76
+ if (!Number.isFinite(x) || !Number.isFinite(y))
77
+ return false;
78
+ const d = ordinal(x) - ordinal(y);
79
+ return (d < 0n ? -d : d) <= ULPS;
80
+ }
81
+ const isFloat = (c) => c.t === K.Decimal || c.t === K.Percent;
82
+ export function isEqual(a, b) {
83
+ if (a === b)
84
+ return true;
85
+ if (isNumeric(a) && isNumeric(b)) {
86
+ if ((isFloat(a) || isFloat(b)) && a.t !== K.Money && b.t !== K.Money) {
87
+ const n = (c) => (c.t === K.Integer ? I64.toNumber(c.v) : c.v);
88
+ return almostEqual(n(a), n(b));
89
+ }
90
+ return numCmp(a, b) === 0;
91
+ }
92
+ if (isAnyString(a.t) && isAnyString(b.t))
93
+ return textCmp(a, b) === 0;
94
+ if (a.t === K.Char && b.t === K.Char)
95
+ return foldCase(a.v) === foldCase(b.v);
96
+ if (isAnyWord(a.t) && isAnyWord(b.t))
97
+ return canon(a.sym) === canon(b.sym);
98
+ if (isAnyBlock(a.t) && a.t === b.t) {
99
+ const x = a;
100
+ const y = b;
101
+ const n = x.s.data.length - x.i;
102
+ if (n !== y.s.data.length - y.i)
103
+ return false;
104
+ for (let k = 0; k < n; k++)
105
+ if (!isEqual(x.s.data[x.i + k], y.s.data[y.i + k]))
106
+ return false;
107
+ return true;
108
+ }
109
+ return strictEqual(a, b);
110
+ }
111
+ /** Ordering for `<`, `>` and sort; null when the two cannot be ordered. */
112
+ export function compare(a, b) {
113
+ if (isNumeric(a) && isNumeric(b))
114
+ return numCmp(a, b);
115
+ if (isAnyString(a.t) && isAnyString(b.t))
116
+ return textCmp(a, b);
117
+ if (a.t === K.Char && b.t === K.Char) {
118
+ const x = foldCase(a.v);
119
+ const y = foldCase(b.v);
120
+ return x < y ? -1 : x > y ? 1 : 0;
121
+ }
122
+ if (a.t === K.Time && b.t === K.Time)
123
+ return a.v < b.v ? -1 : a.v > b.v ? 1 : 0;
124
+ if (a.t === K.Date && b.t === K.Date) {
125
+ const x = dateKey(a.v);
126
+ const y = dateKey(b.v);
127
+ return x < y ? -1 : x > y ? 1 : 0;
128
+ }
129
+ if (a.t === K.Pair && b.t === K.Pair) {
130
+ if (a.y !== b.y)
131
+ return a.y < b.y ? -1 : 1;
132
+ return a.x < b.x ? -1 : a.x > b.x ? 1 : 0;
133
+ }
134
+ if (a.t === K.Tuple && b.t === K.Tuple) {
135
+ const n = Math.max(a.v.length, b.v.length);
136
+ for (let k = 0; k < n; k++) {
137
+ const x = a.v[k] ?? 0;
138
+ const y = b.v[k] ?? 0;
139
+ if (x !== y)
140
+ return x < y ? -1 : 1;
141
+ }
142
+ return 0;
143
+ }
144
+ if (a.t === K.Logic && b.t === K.Logic)
145
+ return a.v === b.v ? 0 : a.v ? 1 : -1;
146
+ if (isAnyWord(a.t) && isAnyWord(b.t)) {
147
+ const x = spell(canon(a.sym));
148
+ const y = spell(canon(b.sym));
149
+ return x < y ? -1 : x > y ? 1 : 0;
150
+ }
151
+ return null;
152
+ }
153
+ /** UTC milliseconds for ordering dates; a date without zone counts as UTC. */
154
+ function dateKey(d) {
155
+ return Date.UTC(d.y, d.m - 1, d.d) + (d.time ?? 0) / 1e6 - (d.zone ?? 0) * 60000;
156
+ }
@@ -0,0 +1,36 @@
1
+ import { type Sym } from './symbols.ts';
2
+ import { type Cell, type Ctx, type Series, type WordCell } from './values.ts';
3
+ /** Index of `sym` in `ctx` (case-insensitive), or -1. Ignores the parent. */
4
+ export declare function ctxFind(ctx: Ctx, sym: Sym): number;
5
+ /** Appends a key (which must not exist yet) and returns its index. */
6
+ export declare function ctxAdd(ctx: Ctx, sym: Sym, v?: Cell): number;
7
+ /** Index of `sym`, adding it (unset) when missing. */
8
+ export declare function ctxEnsure(ctx: Ctx, sym: Sym): number;
9
+ /** The value of a bound word, following the parent chain; null if unbound or absent. */
10
+ export declare function getWord(w: WordCell): Cell | null;
11
+ /** Binds every `self` word in a block, deeply, to an object context. */
12
+ export declare function bindSelf(s: Series<Cell>, ctx: Ctx, seen?: Set<Series<Cell>>): void;
13
+ /** Sets the value at `i`, marking a watched context dirty. */
14
+ export declare function ctxSet(ctx: Ctx, i: number, v: Cell): void;
15
+ /** Sets a bound word in its own context, adding the key if needed. False if unbound. */
16
+ export declare function setWord(w: WordCell, v: Cell): boolean;
17
+ export declare function isBindable(c: Cell): c is WordCell;
18
+ /**
19
+ * Binds the words of a block, deeply and in place.
20
+ * With `all`, every word is bound to `ctx`; otherwise only words whose
21
+ * symbol is a key of `ctx`.
22
+ */
23
+ export declare function bindSeries(s: Series<Cell>, ctx: Ctx, all?: boolean, seen?: Set<Series<Cell>>): void;
24
+ /** Adds every top-level set-word of a block to `ctx` (unset), as `make object!` does. */
25
+ export declare function collectSetWords(s: Series<Cell>, from: number, ctx: Ctx): void;
26
+ /**
27
+ * The body of a function for one call: a deep copy with the words of `tmpl`
28
+ * rebound to `ctx`, which has the same keys in the same order.
29
+ */
30
+ export declare function instantiate(body: Series<Cell>, tmpl: Ctx, ctx: Ctx): Series<Cell>;
31
+ /**
32
+ * Deep copy of the block-like series reachable from `s[from..]`; strings and
33
+ * other series are shared. Words bound to `from` are rebound to `to` on the
34
+ * way, which is how a function body is instantiated for each call.
35
+ */
36
+ export declare function copyDeep(s: Series<Cell>, start?: number, rebindFrom?: Ctx | null, rebindTo?: Ctx | null): Series<Cell>;
@@ -0,0 +1,251 @@
1
+ // Contexts and definitional binding.
2
+ //
3
+ // A word carries a reference to the context it is bound to, fixed when code
4
+ // is loaded or when a function or object is made, never at evaluation time.
5
+ // Binding a block replaces its word cells with bound copies in place: the
6
+ // series is mutable, the cells are not.
7
+ //
8
+ // Only the user context has a parent (lib). Binding a word to user with `all`
9
+ // adds its key there, with lib's value at that moment, as R3 imports lib words
10
+ // into user: user code can then shadow or unset a lib word without touching
11
+ // lib. A bound word also records where its key is (`idx`), so reading it is one
12
+ // array access; a word bound without an index still finds its key by name, and
13
+ // a word bound to user without a key there is still looked up in lib.
14
+ import { K, isAnyBlock } from "./kinds.js";
15
+ import { canon, intern } from "./symbols.js";
16
+ import { UNSET } from "./values.js";
17
+ /** Below this many keys a linear scan beats building a hash index. */
18
+ const SCAN_LIMIT = 8;
19
+ /** Index of `sym` in `ctx` (case-insensitive), or -1. Ignores the parent. */
20
+ export function ctxFind(ctx, sym) {
21
+ const c = canon(sym);
22
+ const keys = ctx.keys;
23
+ if (keys.length <= SCAN_LIMIT && ctx.idx === undefined) {
24
+ for (let i = 0; i < keys.length; i++)
25
+ if (canon(keys[i]) === c)
26
+ return i;
27
+ return -1;
28
+ }
29
+ let idx = ctx.idx;
30
+ let n = ctx.idxN ?? 0;
31
+ if (idx === undefined) {
32
+ idx = new Map();
33
+ ctx.idx = idx;
34
+ n = 0;
35
+ }
36
+ for (; n < keys.length; n++) {
37
+ const k = canon(keys[n]);
38
+ if (!idx.has(k))
39
+ idx.set(k, n);
40
+ }
41
+ ctx.idxN = n;
42
+ return idx.get(c) ?? -1;
43
+ }
44
+ /** Appends a key (which must not exist yet) and returns its index. */
45
+ export function ctxAdd(ctx, sym, v = UNSET) {
46
+ ctx.keys.push(sym);
47
+ ctx.vals.push(v);
48
+ return ctx.keys.length - 1;
49
+ }
50
+ /** Index of `sym`, adding it (unset) when missing. */
51
+ export function ctxEnsure(ctx, sym) {
52
+ const i = ctxFind(ctx, sym);
53
+ return i >= 0 ? i : ctxAdd(ctx, sym);
54
+ }
55
+ /** The value of a bound word, following the parent chain; null if unbound or absent. */
56
+ export function getWord(w) {
57
+ const b = w.bind;
58
+ if (b !== null && w.idx !== undefined)
59
+ return b.vals[w.idx];
60
+ for (let ctx = b; ctx !== null; ctx = ctx.parent) {
61
+ const i = ctxFind(ctx, w.sym);
62
+ if (i >= 0)
63
+ return ctx.vals[i];
64
+ if (ctx.self === true && canon(w.sym) === SELF)
65
+ return { t: K.Object, ctx };
66
+ }
67
+ return null;
68
+ }
69
+ const SELF = canon(intern('self'));
70
+ /** Binds every `self` word in a block, deeply, to an object context. */
71
+ export function bindSelf(s, ctx, seen = new Set()) {
72
+ if (seen.has(s))
73
+ return;
74
+ seen.add(s);
75
+ const data = s.data;
76
+ for (let i = 0; i < data.length; i++) {
77
+ const c = data[i];
78
+ if (isBindable(c) && canon(c.sym) === SELF)
79
+ data[i] = { t: c.t, sym: c.sym, bind: ctx };
80
+ else if (isAnyBlock(c.t))
81
+ bindSelf(c.s, ctx, seen);
82
+ }
83
+ }
84
+ /** Sets the value at `i`, marking a watched context dirty. */
85
+ export function ctxSet(ctx, i, v) {
86
+ ctx.vals[i] = v;
87
+ if (ctx.watch !== undefined && ctx.dirty !== true) {
88
+ ctx.dirty = true;
89
+ ctx.watch.push(ctx);
90
+ }
91
+ }
92
+ /** Sets a bound word in its own context, adding the key if needed. False if unbound. */
93
+ export function setWord(w, v) {
94
+ const ctx = w.bind;
95
+ if (ctx === null)
96
+ return false;
97
+ ctxSet(ctx, w.idx ?? ctxEnsure(ctx, w.sym), v);
98
+ return true;
99
+ }
100
+ // --- binding -----------------------------------------------------------------
101
+ export function isBindable(c) {
102
+ return c.t === K.Word || c.t === K.SetWord || c.t === K.GetWord || c.t === K.LitWord;
103
+ }
104
+ /**
105
+ * Binds the words of a block, deeply and in place.
106
+ * With `all`, every word is bound to `ctx`; otherwise only words whose
107
+ * symbol is a key of `ctx`.
108
+ */
109
+ export function bindSeries(s, ctx, all = false, seen = new Set()) {
110
+ if (seen.has(s))
111
+ return;
112
+ seen.add(s);
113
+ const data = s.data;
114
+ for (let i = 0; i < data.length; i++) {
115
+ const c = data[i];
116
+ if (isBindable(c)) {
117
+ if (c.bind === ctx && c.idx !== undefined)
118
+ continue;
119
+ let at = ctxFind(ctx, c.sym);
120
+ if (at < 0 && all)
121
+ at = ctxAdd(ctx, c.sym, imported(ctx, c.sym));
122
+ if (at >= 0)
123
+ data[i] = { t: c.t, sym: c.sym, bind: ctx, idx: at };
124
+ }
125
+ else if (isAnyBlock(c.t)) {
126
+ bindSeries(c.s, ctx, all, seen);
127
+ }
128
+ }
129
+ }
130
+ /** The value a new key of `ctx` starts with: its parent's (lib's, for user), or unset. */
131
+ function imported(ctx, sym) {
132
+ for (let p = ctx.parent; p !== null; p = p.parent) {
133
+ const i = ctxFind(p, sym);
134
+ if (i >= 0)
135
+ return p.vals[i];
136
+ }
137
+ return UNSET;
138
+ }
139
+ /** Adds every top-level set-word of a block to `ctx` (unset), as `make object!` does. */
140
+ export function collectSetWords(s, from, ctx) {
141
+ const data = s.data;
142
+ for (let i = from; i < data.length; i++) {
143
+ const c = data[i];
144
+ if (c.t === K.SetWord)
145
+ ctxEnsure(ctx, c.sym);
146
+ }
147
+ }
148
+ const PLANS = new WeakMap();
149
+ function callPlan(body, tmpl) {
150
+ const plan = new Map();
151
+ const seen = new Set();
152
+ let twice = false;
153
+ const visit = (s) => {
154
+ if (seen.has(s)) {
155
+ twice = true;
156
+ return;
157
+ }
158
+ seen.add(s);
159
+ const words = [];
160
+ const blocks = [];
161
+ s.data.forEach((c, i) => {
162
+ if (isBindable(c) && c.bind === tmpl)
163
+ words.push(i);
164
+ else if (isAnyBlock(c.t)) {
165
+ blocks.push(i);
166
+ visit(c.s);
167
+ }
168
+ });
169
+ plan.set(s, { words, blocks });
170
+ };
171
+ visit(body);
172
+ return twice ? null : plan;
173
+ }
174
+ /**
175
+ * The body of a function for one call: a deep copy with the words of `tmpl`
176
+ * rebound to `ctx`, which has the same keys in the same order.
177
+ */
178
+ export function instantiate(body, tmpl, ctx) {
179
+ let plan = PLANS.get(body);
180
+ if (plan === undefined) {
181
+ plan = callPlan(body, tmpl);
182
+ PLANS.set(body, plan);
183
+ }
184
+ if (plan === null)
185
+ return copyDeep(body, 0, tmpl, ctx);
186
+ const p = plan;
187
+ const copy = (s) => {
188
+ const at = p.get(s);
189
+ const out = { data: s.data.slice() };
190
+ // newline markers and source positions are shared until an edit (see ownMeta)
191
+ if (s.nl || s.pos) {
192
+ out.nl = s.nl;
193
+ out.pos = s.pos;
194
+ out.sharedMeta = true;
195
+ }
196
+ if (s.file !== undefined)
197
+ out.file = s.file;
198
+ const d = out.data;
199
+ for (const i of at.words) {
200
+ const w = d[i];
201
+ d[i] = w.idx === undefined ? { t: w.t, sym: w.sym, bind: ctx } : { t: w.t, sym: w.sym, bind: ctx, idx: w.idx };
202
+ }
203
+ for (const i of at.blocks) {
204
+ const b = d[i];
205
+ d[i] = { t: b.t, s: copy(b.s), i: b.i };
206
+ }
207
+ return out;
208
+ };
209
+ return copy(body);
210
+ }
211
+ /**
212
+ * Deep copy of the block-like series reachable from `s[from..]`; strings and
213
+ * other series are shared. Words bound to `from` are rebound to `to` on the
214
+ * way, which is how a function body is instantiated for each call.
215
+ */
216
+ export function copyDeep(s, start = 0, rebindFrom = null, rebindTo = null) {
217
+ return copyRec(s, start, rebindFrom, rebindTo, new Map());
218
+ }
219
+ function copyRec(s, start, from, to, done) {
220
+ const whole = start === 0;
221
+ if (whole) {
222
+ const prev = done.get(s);
223
+ if (prev !== undefined)
224
+ return prev;
225
+ }
226
+ const out = { data: [] };
227
+ if (whole)
228
+ done.set(s, out);
229
+ if (s.nl)
230
+ out.nl = s.nl.slice(start);
231
+ if (s.pos)
232
+ out.pos = s.pos.slice(start);
233
+ if (s.file !== undefined)
234
+ out.file = s.file;
235
+ const data = s.data;
236
+ for (let i = start; i < data.length; i++) {
237
+ const c = data[i];
238
+ if (from !== null && isBindable(c) && c.bind === from) {
239
+ // `to` has the keys of `from` in the same order (a call frame, or an object made from a proto)
240
+ out.data.push(c.idx === undefined ? { t: c.t, sym: c.sym, bind: to } : { t: c.t, sym: c.sym, bind: to, idx: c.idx });
241
+ }
242
+ else if (isAnyBlock(c.t)) {
243
+ const b = c;
244
+ out.data.push({ t: b.t, s: copyRec(b.s, 0, from, to, done), i: b.i });
245
+ }
246
+ else {
247
+ out.data.push(c);
248
+ }
249
+ }
250
+ return out;
251
+ }
@@ -0,0 +1,28 @@
1
+ export interface Dec {
2
+ readonly d: bigint;
3
+ readonly e: number;
4
+ }
5
+ export declare function dec(d: bigint, e: number): Dec;
6
+ /** Parses "12", "-12.50", "1'000,25" (comma or dot as decimal mark). */
7
+ export declare function parseDec(text: string): Dec | null;
8
+ /** Formats with at least `minFrac` fractional digits. */
9
+ export declare function formatDec(v: Dec, minFrac?: number): string;
10
+ export declare function decEqual(a: Dec, b: Dec): boolean;
11
+ export declare function decToNumber(v: Dec): number;
12
+ export declare function decAdd(a: Dec, b: Dec): Dec;
13
+ export declare function decSub(a: Dec, b: Dec): Dec;
14
+ export declare function decMul(a: Dec, b: Dec): Dec;
15
+ /** Digits kept after the point by division, rounded half to even. */
16
+ export declare const DIV_SCALE = 18;
17
+ /** a / b with DIV_SCALE fractional digits; null when b is zero. */
18
+ export declare function decDiv(a: Dec, b: Dec): Dec | null;
19
+ export declare function decCmp(a: Dec, b: Dec): -1 | 0 | 1;
20
+ /** The exact decimal of a finite JS number's shortest representation. */
21
+ export declare function decFromNumber(n: number): Dec | null;
22
+ export declare function decFromBig(n: bigint): Dec;
23
+ /** Remainder with the sign of `a`, as `a - b × trunc(a / b)`; null when b is zero. */
24
+ export declare function decRem(a: Dec, b: Dec): Dec | null;
25
+ /** How `round` breaks a value between two multiples of the scale. */
26
+ export type Rounding = 'half-away' | 'half-down' | 'half-ceiling' | 'even' | 'down' | 'floor' | 'ceiling';
27
+ /** The multiple of `scale` nearest to `a` by `mode`, computed exactly; null when scale is zero. */
28
+ export declare function decRound(a: Dec, scale: Dec, mode: Rounding): Dec | null;
@@ -0,0 +1,158 @@
1
+ // Exact decimals, used by money!.
2
+ //
3
+ // A value is `d × 10^-e` with `d` a bigint and `e >= 0`, always normalized
4
+ // (no trailing zeros in `d` when e > 0), so two equal amounts have the same
5
+ // representation and can be compared field by field.
6
+ export function dec(d, e) {
7
+ while (e > 0 && d % 10n === 0n) {
8
+ d /= 10n;
9
+ e--;
10
+ }
11
+ if (d === 0n)
12
+ e = 0;
13
+ return { d, e };
14
+ }
15
+ /** Parses "12", "-12.50", "1'000,25" (comma or dot as decimal mark). */
16
+ export function parseDec(text) {
17
+ const clean = text.replace(/'/g, '').replace(',', '.');
18
+ const m = /^([+-]?)(\d*)(?:\.(\d*))?$/.exec(clean);
19
+ if (!m)
20
+ return null;
21
+ const int = m[2] ?? '';
22
+ const frac = m[3] ?? '';
23
+ if (int === '' && frac === '')
24
+ return null;
25
+ const digits = BigInt((int || '0') + frac);
26
+ return dec(m[1] === '-' ? -digits : digits, frac.length);
27
+ }
28
+ /** Formats with at least `minFrac` fractional digits. */
29
+ export function formatDec(v, minFrac = 0) {
30
+ const neg = v.d < 0n;
31
+ let digits = (neg ? -v.d : v.d).toString();
32
+ const e = Math.max(v.e, minFrac);
33
+ digits = digits + '0'.repeat(e - v.e);
34
+ if (e > 0) {
35
+ digits = digits.padStart(e + 1, '0');
36
+ digits = digits.slice(0, digits.length - e) + '.' + digits.slice(digits.length - e);
37
+ }
38
+ return (neg ? '-' : '') + digits;
39
+ }
40
+ export function decEqual(a, b) {
41
+ return a.d === b.d && a.e === b.e;
42
+ }
43
+ export function decToNumber(v) {
44
+ return Number(v.d) / 10 ** v.e;
45
+ }
46
+ // --- arithmetic ------------------------------------------------------------------
47
+ function align(a, b) {
48
+ const e = Math.max(a.e, b.e);
49
+ return [a.d * 10n ** BigInt(e - a.e), b.d * 10n ** BigInt(e - b.e), e];
50
+ }
51
+ export function decAdd(a, b) {
52
+ const [x, y, e] = align(a, b);
53
+ return dec(x + y, e);
54
+ }
55
+ export function decSub(a, b) {
56
+ const [x, y, e] = align(a, b);
57
+ return dec(x - y, e);
58
+ }
59
+ export function decMul(a, b) {
60
+ return dec(a.d * b.d, a.e + b.e);
61
+ }
62
+ /** Digits kept after the point by division, rounded half to even. */
63
+ export const DIV_SCALE = 18;
64
+ /** a / b with DIV_SCALE fractional digits; null when b is zero. */
65
+ export function decDiv(a, b) {
66
+ if (b.d === 0n)
67
+ return null;
68
+ // a.d·10^-a.e / b.d·10^-b.e = (a.d·10^(S+b.e) / (b.d·10^a.e)) · 10^-S
69
+ let num = a.d * 10n ** BigInt(DIV_SCALE + b.e);
70
+ let den = b.d * 10n ** BigInt(a.e);
71
+ if (den < 0n) {
72
+ num = -num;
73
+ den = -den;
74
+ }
75
+ let q = num / den;
76
+ const r = num % den;
77
+ const twice = (r < 0n ? -r : r) * 2n;
78
+ if (twice > den || (twice === den && q % 2n !== 0n))
79
+ q += num < 0n ? -1n : 1n;
80
+ return dec(q, DIV_SCALE);
81
+ }
82
+ export function decCmp(a, b) {
83
+ const [x, y] = align(a, b);
84
+ return x < y ? -1 : x > y ? 1 : 0;
85
+ }
86
+ /** The exact decimal of a finite JS number's shortest representation. */
87
+ export function decFromNumber(n) {
88
+ if (!Number.isFinite(n))
89
+ return null;
90
+ const m = /^(-?)(\d+)(?:\.(\d+))?(?:e([+-]\d+))?$/.exec(String(n));
91
+ if (!m)
92
+ return null;
93
+ const frac = m[3] ?? '';
94
+ let d = BigInt(m[2] + frac);
95
+ let e = frac.length - Number(m[4] ?? 0);
96
+ if (e < 0) {
97
+ d *= 10n ** BigInt(-e);
98
+ e = 0;
99
+ }
100
+ return dec(m[1] === '-' ? -d : d, e);
101
+ }
102
+ export function decFromBig(n) {
103
+ return dec(n, 0);
104
+ }
105
+ /** Remainder with the sign of `a`, as `a - b × trunc(a / b)`; null when b is zero. */
106
+ export function decRem(a, b) {
107
+ if (b.d === 0n)
108
+ return null;
109
+ const [x, y, e] = align(a, b);
110
+ return dec(x % y, e);
111
+ }
112
+ /** The multiple of `scale` nearest to `a` by `mode`, computed exactly; null when scale is zero. */
113
+ export function decRound(a, scale, mode) {
114
+ if (scale.d === 0n)
115
+ return null;
116
+ // a / scale = num / den exactly
117
+ let num = a.d * 10n ** BigInt(scale.e);
118
+ let den = scale.d * 10n ** BigInt(a.e);
119
+ if (den < 0n) {
120
+ num = -num;
121
+ den = -den;
122
+ }
123
+ let k = num / den;
124
+ const r = num % den;
125
+ if (r !== 0n) {
126
+ const away = num < 0n ? -1n : 1n;
127
+ const twice = (r < 0n ? -r : r) * 2n;
128
+ const half = twice > den ? 1 : twice === den ? 0 : -1;
129
+ switch (mode) {
130
+ case 'half-away':
131
+ if (half >= 0)
132
+ k += away;
133
+ break;
134
+ case 'half-down':
135
+ if (half > 0)
136
+ k += away;
137
+ break;
138
+ case 'half-ceiling':
139
+ if (half > 0 || (half === 0 && num > 0n))
140
+ k += away;
141
+ break;
142
+ case 'even':
143
+ if (half > 0 || (half === 0 && k % 2n !== 0n))
144
+ k += away;
145
+ break;
146
+ case 'down': break;
147
+ case 'floor':
148
+ if (num < 0n)
149
+ k -= 1n;
150
+ break;
151
+ case 'ceiling':
152
+ if (num > 0n)
153
+ k += 1n;
154
+ break;
155
+ }
156
+ }
157
+ return dec(k * scale.d, scale.e);
158
+ }
@@ -0,0 +1,15 @@
1
+ import { type Cell, type ObjectCell } from './values.ts';
2
+ /** Field order of every error! context. */
3
+ export declare const ERROR_FIELDS: readonly ["type", "id", "message", "near", "where", "at"];
4
+ export type ErrorField = (typeof ERROR_FIELDS)[number];
5
+ /**
6
+ * Error types, as in Rebol: `script` for misuse of the language, `math` for
7
+ * arithmetic, `user` for errors made by programs, `access` for the host
8
+ * (network, storage), `syntax` for load failures, `internal` for bugs.
9
+ */
10
+ export declare function makeError(type: string, id: string, message: string): ObjectCell;
11
+ export declare function errorField(e: ObjectCell, f: ErrorField): Cell;
12
+ /** Sets a field only when it is still none, so the innermost location wins. */
13
+ export declare function fillErrorField(e: ObjectCell, f: ErrorField, v: Cell): void;
14
+ /** One-line message, e.g. "Script error: x has no value". */
15
+ export declare function errorMessage(e: ObjectCell): string;
@@ -0,0 +1,44 @@
1
+ // Errors are values.
2
+ //
3
+ // An error! is an object-like context with fixed fields. Natives create them
4
+ // and hand them to the evaluator inside a `throw` Step; nothing on the normal
5
+ // path uses JS exceptions. The evaluator fills `near`, `where` and `at` while
6
+ // unwinding, from the innermost expression and function it passes through.
7
+ import { K } from "./kinds.js";
8
+ import { intern, spell } from "./symbols.js";
9
+ import { NONE, string, wordOf, text } from "./values.js";
10
+ import { ctxFind } from "./ctx.js";
11
+ /** Field order of every error! context. */
12
+ export const ERROR_FIELDS = ['type', 'id', 'message', 'near', 'where', 'at'];
13
+ const FIELD_SYMS = ERROR_FIELDS.map(f => intern(f));
14
+ /**
15
+ * Error types, as in Rebol: `script` for misuse of the language, `math` for
16
+ * arithmetic, `user` for errors made by programs, `access` for the host
17
+ * (network, storage), `syntax` for load failures, `internal` for bugs.
18
+ */
19
+ export function makeError(type, id, message) {
20
+ const ctx = {
21
+ keys: [...FIELD_SYMS],
22
+ vals: [wordOf(K.Word, type), wordOf(K.Word, id), string(message), NONE, NONE, NONE],
23
+ parent: null,
24
+ };
25
+ return { t: K.Error, ctx };
26
+ }
27
+ export function errorField(e, f) {
28
+ const i = ctxFind(e.ctx, intern(f));
29
+ return i >= 0 ? e.ctx.vals[i] : NONE;
30
+ }
31
+ /** Sets a field only when it is still none, so the innermost location wins. */
32
+ export function fillErrorField(e, f, v) {
33
+ const i = ctxFind(e.ctx, intern(f));
34
+ if (i >= 0 && e.ctx.vals[i].t === K.None)
35
+ e.ctx.vals[i] = v;
36
+ }
37
+ /** One-line message, e.g. "Script error: x has no value". */
38
+ export function errorMessage(e) {
39
+ const type = errorField(e, 'type');
40
+ const msg = errorField(e, 'message');
41
+ const name = type.t === K.Word ? spell(type.sym) : 'user';
42
+ const body = msg.t === K.String ? text(msg) : '';
43
+ return `${name.charAt(0).toUpperCase()}${name.slice(1)} error: ${body}`;
44
+ }