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,367 @@
1
+ // Data natives: making values, words and contexts, load/mold, and the few
2
+ // series natives the core needs before the full series set arrives.
3
+ import { K, isAnyBlock, isAnyString, isAnyWord, kindName } from "../kinds.js";
4
+ import { intern, spell, canon } from "../symbols.js";
5
+ import { splice } from "../series.js";
6
+ import * as I64 from "../int64.js";
7
+ import { ownMeta, NONE, UNSET, TRUE, FALSE, string, codePoints, text, datatype, typeset, context, object, blockOf, wordOf, pair, } from "../values.js";
8
+ import { bindSeries, bindSelf, collectSetWords, copyDeep, ctxFind, getWord, setWord } from "../ctx.js";
9
+ import { makeError } from "../errors.js";
10
+ import { makeFunc, typesOf, P } from "../func.js";
11
+ import { load, LoadError } from "../lexer.js";
12
+ import { mold, form } from "../mold.js";
13
+ import { pick, poke, blockFind } from "../access.js";
14
+ import { native, value, fail, doBlock, hostCall } from "./define.js";
15
+ /** Loads a string into a block bound to the user context. */
16
+ const TREBOL = canon(intern('trebol'));
17
+ /**
18
+ * Where the code of a script starts: after a `Trebol [...]` header if it has
19
+ * one. Returns the header block too (null without one).
20
+ */
21
+ export function scriptStart(code) {
22
+ const d = code.s.data;
23
+ const head = d[code.i];
24
+ const hdr = d[code.i + 1];
25
+ if (head?.t === K.Word && canon(head.sym) === TREBOL && hdr?.t === K.Block)
26
+ return { header: hdr, start: code.i + 2 };
27
+ return { header: null, start: code.i };
28
+ }
29
+ /** Takes a script header off freshly loaded code, as R3's load and do. */
30
+ function dropHeader(b) {
31
+ const { start } = scriptStart(b);
32
+ if (start === b.i)
33
+ return;
34
+ splice(b.s, b.i, start - b.i, []);
35
+ if (b.s.nl !== undefined && b.s.nl.length > b.i)
36
+ b.s.nl[b.i] = false;
37
+ }
38
+ export function loadUser(rt, src) {
39
+ let b;
40
+ try {
41
+ b = load(text(src));
42
+ }
43
+ catch (e) {
44
+ // LoadError is the one exception on the normal path; it becomes a value here.
45
+ if (e instanceof LoadError)
46
+ return fail('syntax', 'load', e.message);
47
+ throw e;
48
+ }
49
+ dropHeader(b);
50
+ bindSeries(b.s, rt.user, true);
51
+ return value(b);
52
+ }
53
+ // As in R3 and Red, text holding one value loads as that value; /all always gives a block.
54
+ native('load', '["Reads Trebol source text, or a file of it, into values: the value itself, or a block when there are several." source [string! binary! file! url!] /all "Gives a block even for one value"]', (t, f, v) => {
55
+ let src = f.args[0];
56
+ // bytes are UTF-8 text, as save gives them
57
+ if (src.t === K.Binary)
58
+ src = string(new TextDecoder().decode(new Uint8Array(src.s.data.slice(src.i))));
59
+ if (f.phase === 0 && src.t !== K.String) {
60
+ f.phase = 1;
61
+ return hostCall(t, 'read', [src], 'read files');
62
+ }
63
+ const r = loadUser(t.rt, (f.phase === 1 ? v : src));
64
+ if (r.k !== 'value' || f.args[1] === TRUE)
65
+ return r;
66
+ const b = r.v;
67
+ return b.s.data.length === 1 ? value(b.s.data[0]) : r;
68
+ });
69
+ native('mold', '["The value as Trebol source text, the way you would type it." value [any-type!] /only /all]', (_t, f) => value(string(mold(f.args[0], { only: f.args[1] === TRUE, all: f.args[2] === TRUE }))));
70
+ native('form', '["The value as text for people to read." value [any-type!]]', (_t, f) => value(string(form(f.args[0]))));
71
+ // --- make ------------------------------------------------------------------------
72
+ /**
73
+ * A new object from an optional prototype and a body. The prototype's
74
+ * blocks and function bodies are copied and rebound to the new context, so
75
+ * methods see the new object's fields; its strings are copied too.
76
+ */
77
+ function makeObject(proto, spec, kind) {
78
+ const ctx = context();
79
+ if (proto !== null) {
80
+ ctx.keys.push(...proto.keys);
81
+ for (const v of proto.vals)
82
+ ctx.vals.push(rebindValue(v, proto, ctx));
83
+ }
84
+ collectSetWords(spec.s, spec.i, ctx);
85
+ const body = copyDeep(spec.s, spec.i);
86
+ bindSeries(body, ctx);
87
+ if (kind === K.Object) {
88
+ ctx.self = true;
89
+ bindSelf(body, ctx);
90
+ }
91
+ return { obj: { t: kind, ctx }, body };
92
+ }
93
+ function rebindValue(v, from, to) {
94
+ if (isAnyBlock(v.t)) {
95
+ const b = v;
96
+ return { t: b.t, s: copyDeep(b.s, 0, from, to), i: b.i };
97
+ }
98
+ if (v.t === K.Function) {
99
+ const def = v.p;
100
+ return { t: K.Function, p: { ...def, body: copyDeep(def.body, 0, from, to) } };
101
+ }
102
+ // as R3: strings and binaries are copied too, so no two objects share one
103
+ if (isAnyString(v.t) || v.t === K.Binary) {
104
+ const s = v;
105
+ return { t: s.t, s: { data: s.s.data.slice() }, i: s.i };
106
+ }
107
+ return v;
108
+ }
109
+ function makeOf(k, spec) {
110
+ switch (k) {
111
+ case K.Function: {
112
+ if (spec.t !== K.Block)
113
+ break;
114
+ const [s, b] = spec.s.data.slice(spec.i);
115
+ if (s?.t !== K.Block || b?.t !== K.Block)
116
+ return 'make function! needs [spec body]';
117
+ const def = makeFunc(s, b);
118
+ return typeof def === 'string' ? `bad function spec: ${def}` : { t: K.Function, p: def };
119
+ }
120
+ case K.Op: {
121
+ if (spec.t !== K.Function && spec.t !== K.Native)
122
+ break;
123
+ return { t: K.Op, p: { fn: spec } };
124
+ }
125
+ case K.Map: {
126
+ if (spec.t !== K.Block)
127
+ break;
128
+ const items = spec.s.data.slice(spec.i);
129
+ if (items.length % 2 !== 0)
130
+ return 'make map! needs key value pairs';
131
+ return {
132
+ t: K.Map,
133
+ s: { data: items.map((c, i) => i % 2 === 0 && isAnyWord(c.t) ? { t: K.Word, sym: c.sym, bind: null } : c) },
134
+ };
135
+ }
136
+ case K.Block:
137
+ case K.Paren:
138
+ if (spec.t === K.Integer)
139
+ return { t: k, s: { data: [] }, i: 0 };
140
+ if (isAnyBlock(spec.t))
141
+ return { t: k, s: { data: spec.s.data.slice(spec.i) }, i: 0 };
142
+ break;
143
+ case K.String:
144
+ case K.File:
145
+ case K.Email:
146
+ case K.Url:
147
+ case K.Tag:
148
+ if (spec.t === K.Integer)
149
+ return { t: k, s: { data: [] }, i: 0 };
150
+ return { t: k, s: { data: codePoints(form(spec)) }, i: 0 };
151
+ case K.Pair: {
152
+ // make pair! [3 4], as R3
153
+ if (spec.t !== K.Block)
154
+ break;
155
+ const [a, b] = spec.s.data.slice(spec.i);
156
+ const n = (c) => (c?.t === K.Integer ? I64.toNumber(c.v) : c?.t === K.Decimal ? c.v : null);
157
+ const x = n(a);
158
+ const y = n(b);
159
+ if (x === null || y === null)
160
+ return 'make pair! needs two numbers';
161
+ return pair(x, y);
162
+ }
163
+ case K.Typeset: {
164
+ if (spec.t !== K.Block)
165
+ break;
166
+ const bits = typesOf(spec);
167
+ return typeof bits === 'string' ? bits : typeset(bits);
168
+ }
169
+ case K.Error:
170
+ if (spec.t === K.String)
171
+ return makeError('user', 'message', text(spec));
172
+ break;
173
+ }
174
+ return `cannot make ${kindName(k)} from ${kindName(spec.t)}`;
175
+ }
176
+ native('make', '["Makes a new value of a type, or from a prototype object." type [any-value!] spec [any-value!]]', (_t, f) => {
177
+ if (f.phase === 1)
178
+ return value(f.data);
179
+ const type = f.args[0];
180
+ const spec = f.args[1];
181
+ let proto = null;
182
+ let kind = K.Object;
183
+ if (type.t === K.Datatype && (type.k === K.Object || (type.k === K.Error && spec.t === K.Block))) {
184
+ if (type.k === K.Error) {
185
+ proto = makeError('user', 'message', '').ctx;
186
+ kind = K.Error;
187
+ }
188
+ }
189
+ else if (type.t === K.Object || type.t === K.Error) {
190
+ proto = type.ctx;
191
+ kind = type.t;
192
+ }
193
+ else if (type.t === K.Datatype) {
194
+ const made = makeOf(type.k, spec);
195
+ return typeof made === 'string' ? fail('script', 'bad-make', made) : value(made);
196
+ }
197
+ else {
198
+ return fail('script', 'bad-make', `cannot make from ${kindName(type.t)}`);
199
+ }
200
+ if (spec.t !== K.Block)
201
+ return fail('script', 'bad-make', `make ${kindName(kind)} needs a block`);
202
+ const { obj, body } = makeObject(proto, spec, kind);
203
+ f.phase = 1;
204
+ f.data = obj;
205
+ return { k: 'do', s: body, i: 0 };
206
+ });
207
+ // --- words and contexts ----------------------------------------------------------
208
+ native('get', '["The value a word refers to." word [any-word!] /any]', (_t, f) => {
209
+ const w = f.args[0];
210
+ const v = getWord(w);
211
+ if (v === null)
212
+ return fail('script', 'not-bound', `${spell(w.sym)} is not bound to a context`);
213
+ if (v.t === K.Unset && f.args[1] !== TRUE)
214
+ return fail('script', 'no-value', `${spell(w.sym)} has no value`);
215
+ return value(v);
216
+ });
217
+ native('set', '["Sets a word, or each word of a block, to a value." word [any-word! block!] value [any-type!]]', (_t, f) => {
218
+ const target = f.args[0];
219
+ const v = f.args[1];
220
+ const words = target.t === K.Block ? target.s.data.slice(target.i) : [target];
221
+ for (let i = 0; i < words.length; i++) {
222
+ const w = words[i];
223
+ if (!isAnyWord(w.t))
224
+ return fail('script', 'bad-set', `cannot set ${mold(w)}`);
225
+ const x = target.t === K.Block && v.t === K.Block ? v.s.data[v.i + i] ?? NONE : v;
226
+ if (!setWord(w, x))
227
+ return fail('script', 'not-bound', `${spell(w.sym)} is not bound to a context`);
228
+ }
229
+ return value(v);
230
+ });
231
+ native('value?', '["True if the word has a value." word [any-word!]]', (_t, f) => {
232
+ const v = getWord(f.args[0]);
233
+ return value(v !== null && v.t !== K.Unset ? TRUE : FALSE);
234
+ });
235
+ native('type?', '["The datatype of a value." value [any-type!]]', (_t, f) => value(datatype(f.args[0].t)));
236
+ // --- reflection: what help and source are written with ---------------------
237
+ /** The function an op! calls, or the value itself. */
238
+ const underOp = (c) => (c.t === K.Op ? c.p.fn : c);
239
+ native('spec-of', '["A copy of a function\'s spec block." value [any-function!]]', (_t, f) => {
240
+ const c = underOp(f.args[0]);
241
+ const p = c.p;
242
+ const spec = c.t === K.Function ? p.specBlock : p.specBlock;
243
+ return value({ t: K.Block, s: copyDeep(spec.s, spec.i), i: 0 });
244
+ });
245
+ native('body-of', '["A copy of a function\'s body block, or none for a native." value [any-function!]]', (_t, f) => {
246
+ const c = underOp(f.args[0]);
247
+ return value(c.t === K.Function ? { t: K.Block, s: copyDeep(c.p.body), i: 0 } : NONE);
248
+ });
249
+ native('words-of', '["The words of an object or map, or the arguments, refinements and local words of a function." value [any-object! map! any-function!]]', (_t, f) => {
250
+ const c = underOp(f.args[0]);
251
+ if (c.t === K.Object || c.t === K.Error)
252
+ return value(blockOf(K.Block, c.ctx.keys.map(k => wordOf(K.Word, k))));
253
+ if (c.t === K.Map)
254
+ return value(blockOf(K.Block, c.s.data.filter((_v, i) => i % 2 === 0)));
255
+ // a function's arguments, refinements and local words, as its spec names them (R3)
256
+ const p = c.p;
257
+ const spec = c.t === K.Function ? p.spec : p.spec;
258
+ const out = [];
259
+ let locals = false;
260
+ for (const x of spec.params) {
261
+ if (x.kind === P.Local && !locals) {
262
+ out.push(wordOf(K.Refinement, intern('local')));
263
+ locals = true;
264
+ }
265
+ out.push(wordOf(x.kind === P.Ref ? K.Refinement : K.Word, x.sym));
266
+ }
267
+ return value(blockOf(K.Block, out));
268
+ });
269
+ native('values-of', '["The values of an object or map." value [any-object! map!]]', (_t, f) => {
270
+ const c = f.args[0];
271
+ if (c.t === K.Map)
272
+ return value(blockOf(K.Block, c.s.data.filter((_v, i) => i % 2 === 1)));
273
+ return value(blockOf(K.Block, c.ctx.vals.slice()));
274
+ });
275
+ native('bind', '["Binds the words of a block to a context." words [block! any-word!] context [any-word! any-object!] /new /copy "Binds a deep copy and leaves the block as it was"]', (_t, f) => {
276
+ let x = f.args[0];
277
+ const c = f.args[1];
278
+ const ctx = c.t === K.Object || c.t === K.Error ? c.ctx : c.bind;
279
+ if (ctx === null)
280
+ return fail('script', 'not-bound', `${mold(c)} is not bound to a context`);
281
+ const all = f.args[2] === TRUE;
282
+ if (x.t !== K.Block) {
283
+ const w = x;
284
+ if (!all && ctxFind(ctx, w.sym) < 0)
285
+ return value(w);
286
+ return value({ t: w.t, sym: w.sym, bind: ctx });
287
+ }
288
+ if (f.args[3] === TRUE)
289
+ x = { t: x.t, s: copyDeep(x.s, x.i), i: 0 };
290
+ bindSeries(x.s, ctx, all);
291
+ return value(x);
292
+ });
293
+ native('context?', '["The context a word is bound to, or none." word [any-word!]]', (_t, f) => {
294
+ const ctx = f.args[0].bind;
295
+ return value(ctx === null ? NONE : object(ctx));
296
+ });
297
+ native('unset', '["Takes the value away from a word, or from each word of a block." word [any-word! block!]]', (_t, f) => {
298
+ const target = f.args[0];
299
+ const words = target.t === K.Block ? target.s.data.slice(target.i) : [target];
300
+ for (const w of words) {
301
+ if (!isAnyWord(w.t))
302
+ return fail('script', 'bad-set', `cannot unset ${mold(w)}`);
303
+ if (!setWord(w, UNSET))
304
+ return fail('script', 'not-bound', `${spell(w.sym)} is not bound to a context`);
305
+ }
306
+ return value(UNSET);
307
+ });
308
+ native('in', '["The word of an object, bound to it, or none if the object has no such word." object [any-object!] word [any-word!]]', (_t, f) => {
309
+ const obj = f.args[0];
310
+ const w = f.args[1];
311
+ return value(ctxFind(obj.ctx, w.sym) >= 0 ? { t: K.Word, sym: w.sym, bind: obj.ctx } : NONE);
312
+ });
313
+ native('use', '["Evaluates a block with words of its own, which exist only inside it." words [block! word!] body [block!]]', (_t, f, v) => {
314
+ if (f.phase === 1)
315
+ return value(v);
316
+ const words = f.args[0];
317
+ const list = words.t === K.Block ? words.s.data.slice(words.i) : [words];
318
+ if (list.some(w => !isAnyWord(w.t)))
319
+ return fail('script', 'bad-words', 'use needs a block of words');
320
+ const ctx = context(list.map(w => w.sym), list.map(() => NONE));
321
+ const body = f.args[1];
322
+ const s = copyDeep(body.s, body.i);
323
+ bindSeries(s, ctx);
324
+ f.phase = 1;
325
+ return doBlock({ t: K.Block, s, i: 0 });
326
+ });
327
+ // --- minimal series ----------------------------------------------------------------
328
+ native('length?', '["The number of values from the series\' position to its tail." series [series! map! object!]]', (_t, f) => {
329
+ const x = f.args[0];
330
+ if (x.t === K.Map)
331
+ return value({ t: K.Integer, v: x.s.data.length / 2 });
332
+ if (x.t === K.Object || x.t === K.Error)
333
+ return value({ t: K.Integer, v: x.ctx.keys.length });
334
+ const s = x;
335
+ return value({ t: K.Integer, v: Math.max(0, s.s.data.length - s.i) });
336
+ });
337
+ native('pick', '["The value at a position or key." series [any-value!] index [any-value!]]', (_t, f) => {
338
+ const r = pick(f.args[0], f.args[1]);
339
+ return typeof r === 'string' ? fail('script', 'bad-pick', r) : value(r);
340
+ });
341
+ native('poke', '["Sets the value at a position or key; gives the value." series [any-value!] index [any-value!] value [any-value!]]', (_t, f) => {
342
+ const msg = poke(f.args[0], f.args[1], f.args[2]);
343
+ return msg !== null ? fail('script', 'bad-poke', msg) : value(f.args[2]);
344
+ });
345
+ // put, as in R3 and Red: a map or object gets the key set; a block has the value
346
+ // after the key replaced, or the key and value appended when the key is missing.
347
+ native('put', '["Sets the value of a key; gives the value." series [map! object! block!] key [any-value!] value [any-value!]]', (_t, f) => {
348
+ const [x, key, v] = f.args;
349
+ if (x.t === K.Block) {
350
+ const at = blockFind(x.s, x.i, key);
351
+ if (at < 0 || at + 1 >= x.s.data.length) {
352
+ const items = at < 0 ? [key, v] : [v];
353
+ ownMeta(x.s);
354
+ x.s.data.push(...items);
355
+ if (x.s.nl)
356
+ x.s.nl.push(...items.map(() => false));
357
+ if (x.s.pos)
358
+ x.s.pos.push(...items.map(() => -1));
359
+ }
360
+ else {
361
+ x.s.data[at + 1] = v;
362
+ }
363
+ return value(v);
364
+ }
365
+ const msg = poke(x, key, v);
366
+ return msg !== null ? fail('script', 'bad-poke', msg) : value(v);
367
+ });
@@ -0,0 +1,17 @@
1
+ import { throwError, type NativeFn, type Step, type Task } from '../eval.ts';
2
+ import type { Cell, BlockCell } from '../values.ts';
3
+ export declare function native(name: string, spec: string, fn: NativeFn): void;
4
+ /** Infix operators: the op's name and the two-argument native it calls. */
5
+ export declare const OPS: Array<[op: string, fn: string]>;
6
+ export declare function op(name: string, fn: string): void;
7
+ export declare const value: (v: Cell) => Step;
8
+ export declare const fail: typeof throwError;
9
+ /** none and false are false; everything else is true. */
10
+ export declare function truthy(c: Cell): boolean;
11
+ /** `do` this block and come back. */
12
+ export declare function doBlock(b: BlockCell): Step;
13
+ /**
14
+ * Calls a function the host sets in lib, such as `read` or `do-file`: the core
15
+ * cannot reach files or the network itself. An error when this host has none.
16
+ */
17
+ export declare function hostCall(t: Task, name: string, args: Cell[], what: string): Step;
@@ -0,0 +1,47 @@
1
+ // Helpers to declare natives.
2
+ //
3
+ // native('append', '[series [series!] value /only]', (t, f) => ...)
4
+ //
5
+ // The spec is Trebol source, parsed by the same code as `func` specs, so
6
+ // natives and functions take arguments, refinements and types identically.
7
+ // `f.args` follows the spec order: refinements and their arguments included.
8
+ import { K } from "../kinds.js";
9
+ import { load } from "../lexer.js";
10
+ import { parseSpec } from "../func.js";
11
+ import { registerNative, throwError } from "../eval.js";
12
+ import { ctxFind } from "../ctx.js";
13
+ import { intern } from "../symbols.js";
14
+ export function native(name, spec, fn) {
15
+ const specBlock = load(spec).s.data[0];
16
+ const parsed = parseSpec(specBlock);
17
+ // A malformed spec here is a bug in Trebol itself, found at startup.
18
+ if (typeof parsed === 'string')
19
+ throw new Error(`bad spec for native ${name}: ${parsed}`);
20
+ registerNative({ name, spec: parsed, specBlock }, fn);
21
+ }
22
+ /** Infix operators: the op's name and the two-argument native it calls. */
23
+ export const OPS = [];
24
+ export function op(name, fn) {
25
+ OPS.push([name, fn]);
26
+ }
27
+ export const value = (v) => ({ k: 'value', v });
28
+ export const fail = throwError;
29
+ /** none and false are false; everything else is true. */
30
+ export function truthy(c) {
31
+ return !(c.t === K.None || (c.t === K.Logic && !c.v));
32
+ }
33
+ /** `do` this block and come back. */
34
+ export function doBlock(b) {
35
+ return { k: 'do', s: b.s, i: b.i };
36
+ }
37
+ /**
38
+ * Calls a function the host sets in lib, such as `read` or `do-file`: the core
39
+ * cannot reach files or the network itself. An error when this host has none.
40
+ */
41
+ export function hostCall(t, name, args, what) {
42
+ const i = ctxFind(t.rt.lib, intern(name));
43
+ const fn = i < 0 ? undefined : t.rt.lib.vals[i];
44
+ if (fn === undefined || (fn.t !== K.Native && fn.t !== K.Function))
45
+ return throwError('access', 'no-host', `this host cannot ${what}`);
46
+ return { k: 'call', fn, args };
47
+ }
@@ -0,0 +1,3 @@
1
+ import { type Cell } from '../values.ts';
2
+ /** The names and values of a map, an object or a block, as a query writes them; null when one is not a name. */
3
+ export declare function queryText(c: Cell): string | null;
@@ -0,0 +1,187 @@
1
+ // Bytes as text and back, hex numbers, URL escapes and checksums, as in R3
2
+ // and Red: enbase debase to-hex enhex dehex checksum; and the query of a URL
3
+ // as a map and back: load-query to-query.
4
+ import { K } from "../kinds.js";
5
+ import { intern, canon, spell } from "../symbols.js";
6
+ import * as I64 from "../int64.js";
7
+ import { TRUE, integer, codePoints, text, string, map, block, fromCodePoints, } from "../values.js";
8
+ import { decodeBase, encodeBase } from "../base.js";
9
+ import { crc32, adler32, md5, sha1, sha256 } from "../hash.js";
10
+ import { utf8 } from "../series.js";
11
+ import { fieldText } from "./csv.js";
12
+ import { native, value, fail } from "./define.js";
13
+ /** The bytes of a binary, or the UTF-8 bytes of a string. */
14
+ function bytesOf(v) {
15
+ if (v.t === K.Binary)
16
+ return v.s.data.slice(v.i);
17
+ return utf8(text(v));
18
+ }
19
+ function baseOf(f, at) {
20
+ if (f.args[at] !== TRUE)
21
+ return 64;
22
+ const b = I64.toNumber(f.args[at + 1].v);
23
+ return b === 2 || b === 16 || b === 64 ? b : null;
24
+ }
25
+ native('enbase', '["Writes bytes as text in base 64, or another base." value [binary! any-string!] /base "2, 16 or 64" base-value [integer!]]', (_t, f) => {
26
+ const base = baseOf(f, 1);
27
+ if (base === null)
28
+ return fail('script', 'bad-base', 'the base must be 2, 16 or 64');
29
+ return value({ t: K.String, s: { data: codePoints(encodeBase(bytesOf(f.args[0]), base)) }, i: 0 });
30
+ });
31
+ native('debase', '["Reads bytes written as text in base 64, or another base." value [any-string! binary!] /base "2, 16 or 64" base-value [integer!]]', (_t, f) => {
32
+ const base = baseOf(f, 1);
33
+ if (base === null)
34
+ return fail('script', 'bad-base', 'the base must be 2, 16 or 64');
35
+ const v = f.args[0];
36
+ const src = v.t === K.Binary ? new TextDecoder().decode(new Uint8Array(v.s.data.slice(v.i))) : text(v);
37
+ const bytes = decodeBase(src, base);
38
+ if (bytes === null)
39
+ return fail('script', 'bad-base', `the text is not valid base ${base}`);
40
+ return value({ t: K.Binary, s: { data: bytes }, i: 0 });
41
+ });
42
+ native('to-hex', '["The value in hexadecimal, as an issue." value [integer! tuple!] /size "Use this many digits" len [integer!]]', (_t, f) => {
43
+ const v = f.args[0];
44
+ let hex;
45
+ if (v.t === K.Tuple) {
46
+ hex = v.v.map(b => b.toString(16).toUpperCase().padStart(2, '0')).join('');
47
+ }
48
+ else {
49
+ hex = BigInt.asUintN(64, BigInt(v.v)).toString(16).toUpperCase().padStart(16, '0');
50
+ }
51
+ if (f.args[1] === TRUE) {
52
+ const n = Math.max(1, I64.toNumber(f.args[2].v));
53
+ hex = hex.length > n ? hex.slice(hex.length - n) : hex.padStart(n, '0');
54
+ }
55
+ return value({ t: K.Issue, sym: intern(hex), bind: null });
56
+ });
57
+ /** Code points with %xx escapes turned back into the characters their UTF-8 bytes spell. */
58
+ function unhex(cps) {
59
+ const out = [];
60
+ let bytes = [];
61
+ const flush = () => {
62
+ if (bytes.length > 0)
63
+ out.push(...codePoints(new TextDecoder().decode(new Uint8Array(bytes))));
64
+ bytes = [];
65
+ };
66
+ for (let i = 0; i < cps.length; i++) {
67
+ const h = i + 2 < cps.length ? String.fromCodePoint(cps[i + 1], cps[i + 2]) : '';
68
+ if (cps[i] === 0x25 && /^[0-9A-Fa-f]{2}$/.test(h)) {
69
+ bytes.push(parseInt(h, 16));
70
+ i += 2;
71
+ }
72
+ else {
73
+ flush();
74
+ out.push(cps[i]);
75
+ }
76
+ }
77
+ flush();
78
+ return out;
79
+ }
80
+ native('dehex', '["Turns %xx escapes in a string or URL back into characters." value [any-string!]]', (_t, f) => {
81
+ const v = f.args[0];
82
+ return value({ t: v.t, s: { data: unhex(v.s.data.slice(v.i)) }, i: 0 });
83
+ });
84
+ // What enhex leaves as it is: in a URL or file name, what may stand in one (as
85
+ // encodeURI); in other text, only what needs no escape in a part of one (as
86
+ // encodeURIComponent), as R3 does.
87
+ const COMPONENT = /^[A-Za-z0-9\-_.!~*'()]$/;
88
+ const URI = /^[A-Za-z0-9\-_.!~*'();/?:@&=+$,#]$/;
89
+ /** Code points with every one the test refuses written as %xx escapes of its UTF-8 bytes. */
90
+ function enhexed(cps, keep, plus) {
91
+ let s = '';
92
+ for (const cp of cps) {
93
+ const c = String.fromCodePoint(cp);
94
+ if (plus && cp === 0x20)
95
+ s += '+';
96
+ else if (keep.test(c))
97
+ s += c;
98
+ else
99
+ for (const b of utf8(c))
100
+ s += '%' + b.toString(16).toUpperCase().padStart(2, '0');
101
+ }
102
+ return s;
103
+ }
104
+ native('enhex', '["Writes the characters a URL cannot hold as %xx escapes." value [any-string!] /uri "Write spaces as +, as forms send them"]', (_t, f) => {
105
+ const v = f.args[0];
106
+ const keep = v.t === K.Url || v.t === K.File ? URI : COMPONENT;
107
+ return value({ t: v.t, s: { data: codePoints(enhexed(v.s.data.slice(v.i), keep, f.args[1] === TRUE)) }, i: 0 });
108
+ });
109
+ /** The names and values of a map, an object or a block, as a query writes them; null when one is not a name. */
110
+ export function queryText(c) {
111
+ const pairs = [];
112
+ if (c.t === K.Map)
113
+ pairs.push(...c.s.data);
114
+ else if (c.t === K.Block)
115
+ pairs.push(...c.s.data.slice(c.i));
116
+ else if (c.t === K.Object)
117
+ c.ctx.keys.forEach((k, j) => pairs.push({ t: K.Word, sym: k, bind: null }, c.ctx.vals[j]));
118
+ const parts = [];
119
+ const part = (name, v) => {
120
+ if (v.t !== K.None)
121
+ parts.push(enhexed(codePoints(name), COMPONENT, false) + '=' + enhexed(codePoints(fieldText(v)), COMPONENT, false));
122
+ };
123
+ for (let k = 0; k + 1 < pairs.length; k += 2) {
124
+ const key = pairs[k];
125
+ if (!(key.t >= K.Word && key.t <= K.Issue) && key.t !== K.String)
126
+ return null;
127
+ const name = fieldText(key);
128
+ const v = pairs[k + 1];
129
+ if (v.t === K.Block)
130
+ for (const each of v.s.data.slice(v.i))
131
+ part(name, each);
132
+ else
133
+ part(name, v);
134
+ }
135
+ return parts.join('&');
136
+ }
137
+ native('to-query', '["Writes names and values as the query of a URL: q=caf%C3%A9&page=2." values [map! object! block!]]', (_t, f) => {
138
+ const s = queryText(f.args[0]);
139
+ return s === null ? fail('script', 'bad-query', 'a query takes words or strings as names') : value(string(s));
140
+ });
141
+ const KEY_WORD = /^[A-Za-z_][A-Za-z0-9_-]*$/;
142
+ native('load-query', '["Reads the query of a URL as a map of strings; a name given twice holds a block." source [any-string!]]', (_t, f) => {
143
+ const v = f.args[0];
144
+ let s = fromCodePoints(v.s.data, v.i);
145
+ if (v.t === K.Url)
146
+ s = s.includes('?') ? s.slice(s.indexOf('?') + 1) : '';
147
+ if (s.includes('#'))
148
+ s = s.slice(0, s.indexOf('#'));
149
+ if (s.startsWith('?'))
150
+ s = s.slice(1);
151
+ const names = [];
152
+ const vals = [];
153
+ for (const part of s.split('&')) {
154
+ if (part === '')
155
+ continue;
156
+ const at = part.indexOf('=');
157
+ const read = (t) => fromCodePoints(unhex(codePoints(t.replace(/\+/g, ' '))));
158
+ const name = read(at < 0 ? part : part.slice(0, at));
159
+ const val = string(at < 0 ? '' : read(part.slice(at + 1)));
160
+ const n = names.indexOf(name);
161
+ if (n < 0) {
162
+ names.push(name);
163
+ vals.push([val]);
164
+ }
165
+ else
166
+ vals[n].push(val);
167
+ }
168
+ const pairs = [];
169
+ names.forEach((name, n) => {
170
+ pairs.push(KEY_WORD.test(name) ? { t: K.Word, sym: intern(name), bind: null } : string(name));
171
+ pairs.push(vals[n].length === 1 ? vals[n][0] : block(vals[n]));
172
+ });
173
+ return value(map(pairs));
174
+ });
175
+ const HASHES = { md5, sha1, sha256 };
176
+ native('checksum', '["A checksum or hash of the bytes: md5 sha1 sha256 give a binary, crc32 adler32 an integer." data [binary! any-string!] method [word!]]', (_t, f) => {
177
+ const bytes = bytesOf(f.args[0]);
178
+ const name = spell(canon(f.args[1].sym)).toLowerCase();
179
+ if (name === 'crc32')
180
+ return value(integer(crc32(bytes)));
181
+ if (name === 'adler32')
182
+ return value(integer(adler32(bytes)));
183
+ const hash = HASHES[name];
184
+ if (hash === undefined)
185
+ return fail('script', 'bad-method', `checksum has no method ${name}: use md5 sha1 sha256 crc32 adler32`);
186
+ return value({ t: K.Binary, s: { data: hash(bytes) }, i: 0 });
187
+ });
@@ -0,0 +1,5 @@
1
+ import { type Cell } from '../values.ts';
2
+ /** Parses JSON text; returns the value or an error message. */
3
+ export declare function parseJson(src: string): Cell | string;
4
+ /** Serializes a value as JSON. Cycles, and functions in a block, become null. */
5
+ export declare function toJson(v: Cell, seen?: Set<unknown>): string;