basedpl 0.1.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,242 @@
1
+ # BasedPL
2
+
3
+
4
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
+
6
+ BasedPL, the Based-array Programming Language, is an array language derived from APL, with ideas from J and BQN. Its notation aims to be simple and consistent. Most of this documentation calls it BPL. BPL is written in Rust and comes as a native executable, a Jupyter kernel and a Python API.
7
+
8
+ LLMs: read [llms.txt](https://answerdotai.github.io/basedpl/llms.txt) first. It is the primary reference index and concise overview.
9
+
10
+ ## Install and try it
11
+
12
+ ``` sh
13
+ pip install basedpl
14
+ bpl
15
+ ```
16
+
17
+ Each release also has a standalone `bpl` that needs no Python, for macOS on Apple silicon and for Linux on x86-64 and arm64. On a Mac:
18
+
19
+ ``` sh
20
+ curl -Lo bpl https://github.com/AnswerDotAI/basedpl/releases/latest/download/bpl-macos-arm64
21
+ chmod +x bpl
22
+ ```
23
+
24
+ On Linux, download `bpl-linux-x86_64` or `bpl-linux-arm64` instead.
25
+
26
+ At the prompt, define a mean and apply it:
27
+
28
+ ``` bpl
29
+ avg←+/÷≢
30
+ avg 2 4 9
31
+ ```
32
+
33
+ 5
34
+
35
+ Use `bpl -e 'avg←+/÷≢ ⋄ avg 2 4 9'` for a shell command. The [command-line guide](https://answerdotai.github.io/basedpl/cli.html) covers source files and pipes.
36
+
37
+ ## Interactive use
38
+
39
+ In the REPL, type a backtick followed by a glyph name. For example, `` `iota `` becomes `⍳` when you press Tab or type a non-letter. Abbreviations and Alt-key shortcuts are available. `]help +` shows help for `+`. [`•prefs`](https://answerdotai.github.io/basedpl/system-functions.html#prefs) changes display settings, such as boxes and how much of a large array shows. See [REPL](https://answerdotai.github.io/basedpl/repl.html) and the [glyph reference](https://answerdotai.github.io/basedpl/glyphs.html), which lists each glyph’s key.
40
+
41
+ In Jupyter, select the installed **BasedPL** kernel. Cells share definitions and support completion, Shift-Tab help and interruption. You can also use `%%bpl` cells in a Python notebook. See [Using BPL notebooks](https://answerdotai.github.io/basedpl/notebooks.html).
42
+
43
+ ## New to APL?
44
+
45
+ APL is a language built around operations on whole arrays and notation for combining functions. Here is a taste of that style in BPL.
46
+
47
+ Numbers separated by spaces form a vector. Arithmetic applies to every element:
48
+
49
+ ``` bpl
50
+ 10+1 2 3
51
+ ```
52
+
53
+ 11 12 13
54
+
55
+ Operators modify or combine functions. Reduce (`/`) turns addition into summation. `⍳10` generates 0…9:
56
+
57
+ ``` bpl
58
+ +/⍳10
59
+ ```
60
+
61
+ 45
62
+
63
+ Functions can also be combined without naming their arguments. In `avg←+/÷≢`, sum (`+/`) divided by tally (`≢`) defines the mean:
64
+
65
+ ``` bpl
66
+ avg 1 2 3 4
67
+ ```
68
+
69
+ 2.5
70
+
71
+ To see how these ideas express an algorithm, start from “a prime has exactly two positive divisors”. Form all remainders of 1 to 50 (`|⊗⍨1+⍳50`), count the zeros down each column (`+⌿0=`), and find the positions (`⍸`) whose count is two. Positions count from 0. `1+` turns each position back into its number:
72
+
73
+ ``` bpl
74
+ 1+⍸2=+⌿0=|⊗⍨1+⍳50
75
+ ```
76
+
77
+ 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
78
+
79
+ [Getting started](https://answerdotai.github.io/basedpl/getting-started.html#example-algorithms) builds a primes function from the same divisor count, step by step, and displays the divisibility matrix along the way.
80
+
81
+ ## What’s distinctive?
82
+
83
+ For APL users, some key differences are:
84
+
85
+ - [Based arrays](https://answerdotai.github.io/basedpl/arrays.html), as in BQN: numbers, characters and functions are atoms; enclosure always adds a layer.
86
+ - **Vectors in brackets, and grouping by spaces.** `[a b c]` is a vector, and `a+b × c+d` is `(a+b)×(c+d)`. A run that ends in a function is a train. For example, `+/÷≢ x` is the mean of `x`, and `2×` doubles its argument. `0⌷v` and `v₀` both select the first item of `v`.
87
+ - **Leading-axis broadcasting**, including expansion of length-1 axes, plus string keys and names on axes.
88
+ - **Exact integers and rationals** alongside approximate real and complex numbers.
89
+ - Dfns, trains and operators, with additions such as Under, iteration histories, windows and function arrays.
90
+
91
+ Positions and axes count from 0, as in BQN and Python. Approximate comparisons use tolerance `1E¯14`. See the [language principles](https://answerdotai.github.io/basedpl/principles.html) for why BPL works this way, the [glyph reference](https://answerdotai.github.io/basedpl/glyphs.html) for Dyalog differences and [Arrays](https://answerdotai.github.io/basedpl/arrays.html) for the array model.
92
+
93
+ ### Numbers
94
+
95
+ Bare numbers are approximate. Use `ₓ` for exact integers and `r` for exact fractions:
96
+
97
+ ``` bpl
98
+ 1r3+1r6
99
+ ```
100
+
101
+ 1ᵣ2
102
+
103
+ Complex numbers use `j` between real and imaginary parts. Functions such as square root extend into the complex domain:
104
+
105
+ ``` bpl
106
+ √¯4
107
+ ```
108
+
109
+ 0ⱼ2
110
+
111
+ See [Numbers](https://answerdotai.github.io/basedpl/numbers.html) for conversion and mixed arithmetic.
112
+
113
+ ### Array literals and broadcasting
114
+
115
+ Write matrix rows directly in an array literal. Leading-axis agreement lets a vector supply one offset per row:
116
+
117
+ ``` bpl
118
+ m←[1 2 3
119
+ 4 5 6]
120
+ m+10 20
121
+ ```
122
+
123
+ 11 12 13
124
+ 24 25 26
125
+
126
+ See [array notation](https://answerdotai.github.io/basedpl/glyphs/brackets.html) and [broadcasting](https://answerdotai.github.io/basedpl/evaluation.html#agreement-and-pervasion).
127
+
128
+ ### Keys and named axes
129
+
130
+ Axes can have names, and positions along them can have string keys. Describe the axes once, then select by key or reduce by axis name:
131
+
132
+ ``` bpl
133
+ axes←["city":["NY" "LA"] "month":["Jan" "Feb" "Mar"]]
134
+ sales←axes:[10 20 30 ⋄ 40 50 60]
135
+ "LA" "Feb"⌷sales
136
+ +/⍠"month" sales
137
+ ```
138
+
139
+ 50
140
+
141
+ ["city":2]⍴["NY":60 "LA":150]
142
+
143
+ Keys and names travel with axes through operations such as transpose. Arithmetic aligns matching names and keys. See [Axis keys](https://answerdotai.github.io/basedpl/keyed.html).
144
+
145
+ ### Function operators
146
+
147
+ A vector of counts keeps the history: one state for each count, where count 0 is the initial value. Here, double up to four times:
148
+
149
+ ``` bpl
150
+ 2×⍣(⍳5) 1
151
+ ```
152
+
153
+ 1 2 4 8 16
154
+
155
+ Under (`⌾`) transforms the argument, applies a function, then reverses the transformation. Scale by ten, floor, and scale back to round down to tenths:
156
+
157
+ ``` bpl
158
+ ⌊⌾ 10× 1.25 2.78
159
+ ```
160
+
161
+ 1.2 2.7
162
+
163
+ Explore [iteration and inverses](https://answerdotai.github.io/basedpl/glyphs/power.html), [Under](https://answerdotai.github.io/basedpl/glyphs/under.html), [windows](https://answerdotai.github.io/basedpl/glyphs/windows.html) and [function selection](https://answerdotai.github.io/basedpl/glyphs/agenda.html).
164
+
165
+ ### Mathematical tools
166
+
167
+ [Primes](https://answerdotai.github.io/basedpl/glyphs/prime.html) and [factorisation](https://answerdotai.github.io/basedpl/glyphs/factor.html) are built in:
168
+
169
+ ``` bpl
170
+ ⨸360ₓ
171
+ ```
172
+
173
+ [2 2 2 3 3 5]ₓ
174
+
175
+ [Polynomials](https://answerdotai.github.io/basedpl/glyphs/polynomial.html) support coefficients, roots and evaluation. Polynomial functions can be [differentiated](https://answerdotai.github.io/basedpl/glyphs/derivative.html): for f(x) = 1 + 2x + 3x², f′(2) = 14.
176
+
177
+ ``` bpl
178
+ f←[1 2 3]ₓ⌻ ⋄ f∂2ₓ
179
+ ```
180
+
181
+ 14ₓ
182
+
183
+ [Probability distributions](https://answerdotai.github.io/basedpl/distributions.html) provide sampling, density, CDF and quantiles. Two fair coin tosses give these probabilities for 0, 1 and 2 heads:
184
+
185
+ ``` bpl
186
+ coin←2 0.5 •distribution "binomial"
187
+ coin.density 0 1 2
188
+ ```
189
+
190
+ 0.25 0.5 0.25
191
+
192
+ [Matrix division](https://answerdotai.github.io/basedpl/glyphs/domino.html) handles linear systems and least squares.
193
+
194
+ ### Data and text
195
+
196
+ JSON objects become keyed arrays, with dot access to their fields:
197
+
198
+ ``` bpl
199
+ order←•json "{""price"":10.5,""qty"":2}"
200
+ order.price×order.qty
201
+ ```
202
+
203
+ 21
204
+
205
+ CSV headers likewise name column vectors. [Files, CSV and JSON](https://answerdotai.github.io/basedpl/data.html) covers reading, transforming and writing data. [Regex](https://answerdotai.github.io/basedpl/regex.html) supplies matching, captures and replacement through Rust’s regex engine.
206
+
207
+ ### Drawing
208
+
209
+ `•plot` draws charts from arrays. Keys label the axes and name the lines. See [Plots](https://answerdotai.github.io/basedpl/plot.html).
210
+
211
+ ``` bpl
212
+ ["legend":"end"]•plot sales
213
+ ```
214
+
215
+ ![](index_files/figure-commonmark/cell-17-output-1.svg)
216
+
217
+ Build SVG from element functions and keyed attributes. Notebooks display the picture directly. The same element trees serialize to XML. See [XML and SVG](https://answerdotai.github.io/basedpl/xml.html).
218
+
219
+ ``` bpl
220
+ circle←•element "circle"
221
+ text←•element "text"
222
+ c←["cx":50 "cy":40 "r":25 "fill":"orange"]circle ""
223
+ t←["x":50 "y":85 "text-anchor":"middle"]text "Hello, SVG"
224
+ ["width":240 "height":240]•svg [c t]
225
+ ```
226
+
227
+ ![](index_files/figure-commonmark/cell-18-output-1.svg)
228
+
229
+ ## Python
230
+
231
+ BPL functions are Python callables:
232
+
233
+ ``` python
234
+ from basedpl import fn
235
+
236
+ mean = fn('+/÷≢')
237
+ mean([1, 2, 3])
238
+ ```
239
+
240
+ Arrays have `.py`, `.np` and `.df` conversions for Python values, NumPy and pandas. Functions also have Python names and composition operators. See the [Python tutorial](https://answerdotai.github.io/basedpl/python.html).
241
+
242
+ For other frontends, the [process interfaces](https://answerdotai.github.io/basedpl/processes.html) provide JSON messages and interruptible workers. The [BPL library](https://github.com/AnswerDotAI/basedpl/tree/main/lib) contains more algorithms, codecs, interpreters and puzzles.
@@ -0,0 +1,626 @@
1
+ export class Session {
2
+ __destroy_into_raw() {
3
+ const ptr = this.__wbg_ptr;
4
+ this.__wbg_ptr = 0;
5
+ SessionFinalization.unregister(this);
6
+ return ptr;
7
+ }
8
+ free() {
9
+ const ptr = this.__destroy_into_raw();
10
+ wasm.__wbg_session_free(ptr, 0);
11
+ }
12
+ constructor() {
13
+ const ret = wasm.session_new();
14
+ this.__wbg_ptr = ret;
15
+ SessionFinalization.register(this, this.__wbg_ptr, this);
16
+ return this;
17
+ }
18
+ /**
19
+ * The JSON reply to a JSON request: `{"error": …}`, with `null` when the request succeeds. Each output goes to `output`, as JSON,
20
+ * while the program runs. The reply has no value: a page shows the output, and a value that holds functions has no JSON form.
21
+ * @param {string} request
22
+ * @param {Function} output
23
+ * @returns {string}
24
+ */
25
+ request(request, output) {
26
+ let deferred2_0;
27
+ let deferred2_1;
28
+ try {
29
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
30
+ const ptr0 = passStringToWasm0(request, wasm.__wbindgen_export, wasm.__wbindgen_export2);
31
+ const len0 = WASM_VECTOR_LEN;
32
+ wasm.session_request(retptr, this.__wbg_ptr, ptr0, len0, addHeapObject(output));
33
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
34
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
35
+ deferred2_0 = r0;
36
+ deferred2_1 = r1;
37
+ return getStringFromWasm0(r0, r1);
38
+ } finally {
39
+ wasm.__wbindgen_add_to_stack_pointer(16);
40
+ wasm.__wbindgen_export4(deferred2_0, deferred2_1, 1);
41
+ }
42
+ }
43
+ }
44
+ if (Symbol.dispose) Session.prototype[Symbol.dispose] = Session.prototype.free;
45
+
46
+ /**
47
+ * Sets the URL that relative paths resolve against, and the function that receives a panic's message.
48
+ * @param {string} base
49
+ * @param {Function} panic
50
+ */
51
+ export function configure(base, panic) {
52
+ const ptr0 = passStringToWasm0(base, wasm.__wbindgen_export, wasm.__wbindgen_export2);
53
+ const len0 = WASM_VECTOR_LEN;
54
+ wasm.configure(ptr0, len0, addHeapObject(panic));
55
+ }
56
+
57
+ /**
58
+ * Every glyph's row, as JSON, for the language bar.
59
+ * @returns {string}
60
+ */
61
+ export function symbols() {
62
+ let deferred1_0;
63
+ let deferred1_1;
64
+ try {
65
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
66
+ wasm.symbols(retptr);
67
+ var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
68
+ var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
69
+ deferred1_0 = r0;
70
+ deferred1_1 = r1;
71
+ return getStringFromWasm0(r0, r1);
72
+ } finally {
73
+ wasm.__wbindgen_add_to_stack_pointer(16);
74
+ wasm.__wbindgen_export4(deferred1_0, deferred1_1, 1);
75
+ }
76
+ }
77
+ function __wbg_get_imports() {
78
+ const import0 = {
79
+ __proto__: null,
80
+ __wbg___wbindgen_is_function_1f9d30630b8b1d3d: function(arg0) {
81
+ const ret = typeof(getObject(arg0)) === 'function';
82
+ return ret;
83
+ },
84
+ __wbg___wbindgen_is_undefined_8865fb403f8fe9d8: function(arg0) {
85
+ const ret = getObject(arg0) === undefined;
86
+ return ret;
87
+ },
88
+ __wbg___wbindgen_number_get_2e0e7dee9f701a71: function(arg0, arg1) {
89
+ const obj = getObject(arg1);
90
+ const ret = typeof(obj) === 'number' ? obj : undefined;
91
+ getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true);
92
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);
93
+ },
94
+ __wbg___wbindgen_string_get_0380ccaa2f57f0d9: function(arg0, arg1) {
95
+ const obj = getObject(arg1);
96
+ const ret = typeof(obj) === 'string' ? obj : undefined;
97
+ var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_export, wasm.__wbindgen_export2);
98
+ var len1 = WASM_VECTOR_LEN;
99
+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
100
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
101
+ },
102
+ __wbg___wbindgen_throw_41e9ee4f547fc59a: function(arg0, arg1) {
103
+ throw new Error(getStringFromWasm0(arg0, arg1));
104
+ },
105
+ __wbg_call_187d372bd5fdd4aa: function() { return handleError(function (arg0, arg1, arg2) {
106
+ const ret = getObject(arg0).call(getObject(arg1), getObject(arg2));
107
+ return addHeapObject(ret);
108
+ }, arguments); },
109
+ __wbg_construct_2cc135b78387ed16: function() { return handleError(function (arg0, arg1) {
110
+ const ret = Reflect.construct(getObject(arg0), getObject(arg1));
111
+ return addHeapObject(ret);
112
+ }, arguments); },
113
+ __wbg_createElement_74049073a11f9c31: function() { return handleError(function (arg0, arg1, arg2) {
114
+ const ret = getObject(arg0).createElement(getStringFromWasm0(arg1, arg2));
115
+ return addHeapObject(ret);
116
+ }, arguments); },
117
+ __wbg_document_9854e03c05fc8834: function(arg0) {
118
+ const ret = getObject(arg0).document;
119
+ return isLikeNone(ret) ? 0 : addHeapObject(ret);
120
+ },
121
+ __wbg_done_b41a1d26cdb37fb6: function(arg0) {
122
+ const ret = getObject(arg0).done;
123
+ return ret;
124
+ },
125
+ __wbg_exec_a5f4ba02713fbebe: function(arg0, arg1, arg2) {
126
+ const ret = getObject(arg0).exec(getStringFromWasm0(arg1, arg2));
127
+ return isLikeNone(ret) ? 0 : addHeapObject(ret);
128
+ },
129
+ __wbg_fontBoundingBoxAscent_694ba20be295b1c3: function(arg0) {
130
+ const ret = getObject(arg0).fontBoundingBoxAscent;
131
+ return ret;
132
+ },
133
+ __wbg_fontBoundingBoxDescent_e0d660bcc3049b29: function(arg0) {
134
+ const ret = getObject(arg0).fontBoundingBoxDescent;
135
+ return ret;
136
+ },
137
+ __wbg_getAllResponseHeaders_537d007c37d53dba: function() { return handleError(function (arg0, arg1) {
138
+ const ret = getObject(arg1).getAllResponseHeaders();
139
+ const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export, wasm.__wbindgen_export2);
140
+ const len1 = WASM_VECTOR_LEN;
141
+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
142
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
143
+ }, arguments); },
144
+ __wbg_getContext_635e36719cad2623: function() { return handleError(function (arg0, arg1, arg2) {
145
+ const ret = getObject(arg0).getContext(getStringFromWasm0(arg1, arg2));
146
+ return isLikeNone(ret) ? 0 : addHeapObject(ret);
147
+ }, arguments); },
148
+ __wbg_getContext_e567868594d2e0c6: function() { return handleError(function (arg0, arg1, arg2) {
149
+ const ret = getObject(arg0).getContext(getStringFromWasm0(arg1, arg2));
150
+ return isLikeNone(ret) ? 0 : addHeapObject(ret);
151
+ }, arguments); },
152
+ __wbg_getRandomValues_436a51d0629d84e1: function() { return handleError(function (arg0, arg1) {
153
+ globalThis.crypto.getRandomValues(getArrayU8FromWasm0(arg0, arg1));
154
+ }, arguments); },
155
+ __wbg_getRandomValues_fc33165644b9e145: function() { return handleError(function (arg0, arg1) {
156
+ globalThis.crypto.getRandomValues(getArrayU8FromWasm0(arg0, arg1));
157
+ }, arguments); },
158
+ __wbg_getTime_f5a55efff2585d5d: function(arg0) {
159
+ const ret = getObject(arg0).getTime();
160
+ return ret;
161
+ },
162
+ __wbg_getTimezoneOffset_2e851fdaecc2dc92: function(arg0) {
163
+ const ret = getObject(arg0).getTimezoneOffset();
164
+ return ret;
165
+ },
166
+ __wbg_get_31af05bd4842a84f: function() { return handleError(function (arg0, arg1) {
167
+ const ret = Reflect.get(getObject(arg0), getObject(arg1));
168
+ return addHeapObject(ret);
169
+ }, arguments); },
170
+ __wbg_get_6c896e0571ddae51: function(arg0, arg1) {
171
+ const ret = getObject(arg0)[arg1 >>> 0];
172
+ return addHeapObject(ret);
173
+ },
174
+ __wbg_get_unchecked_288889d017702237: function(arg0, arg1) {
175
+ const ret = getObject(arg0)[arg1 >>> 0];
176
+ return addHeapObject(ret);
177
+ },
178
+ __wbg_href_221703ee1ed727fc: function(arg0, arg1) {
179
+ const ret = getObject(arg1).href;
180
+ const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export, wasm.__wbindgen_export2);
181
+ const len1 = WASM_VECTOR_LEN;
182
+ getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true);
183
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true);
184
+ },
185
+ __wbg_instanceof_CanvasRenderingContext2d_769208c72dcbf5e6: function(arg0) {
186
+ let result;
187
+ try {
188
+ result = getObject(arg0) instanceof CanvasRenderingContext2D;
189
+ } catch (_) {
190
+ result = false;
191
+ }
192
+ const ret = result;
193
+ return ret;
194
+ },
195
+ __wbg_instanceof_Error_80a725f81f2e102d: function(arg0) {
196
+ let result;
197
+ try {
198
+ result = getObject(arg0) instanceof Error;
199
+ } catch (_) {
200
+ result = false;
201
+ }
202
+ const ret = result;
203
+ return ret;
204
+ },
205
+ __wbg_instanceof_HtmlCanvasElement_0a30c11fbbf41841: function(arg0) {
206
+ let result;
207
+ try {
208
+ result = getObject(arg0) instanceof HTMLCanvasElement;
209
+ } catch (_) {
210
+ result = false;
211
+ }
212
+ const ret = result;
213
+ return ret;
214
+ },
215
+ __wbg_instanceof_OffscreenCanvasRenderingContext2d_957f1a991324c9dc: function(arg0) {
216
+ let result;
217
+ try {
218
+ result = getObject(arg0) instanceof OffscreenCanvasRenderingContext2D;
219
+ } catch (_) {
220
+ result = false;
221
+ }
222
+ const ret = result;
223
+ return ret;
224
+ },
225
+ __wbg_instanceof_Window_82d71df4eddf88bc: function(arg0) {
226
+ let result;
227
+ try {
228
+ result = getObject(arg0) instanceof Window;
229
+ } catch (_) {
230
+ result = false;
231
+ }
232
+ const ret = result;
233
+ return ret;
234
+ },
235
+ __wbg_length_7f3c00c40364105e: function(arg0) {
236
+ const ret = getObject(arg0).length;
237
+ return ret;
238
+ },
239
+ __wbg_length_d4bdea10311bd9cf: function(arg0) {
240
+ const ret = getObject(arg0).length;
241
+ return ret;
242
+ },
243
+ __wbg_matchAll_049fec9c830bd9e3: function(arg0, arg1) {
244
+ const ret = getObject(arg0).matchAll(getObject(arg1));
245
+ return addHeapObject(ret);
246
+ },
247
+ __wbg_measureText_1035b288be51876c: function() { return handleError(function (arg0, arg1, arg2) {
248
+ const ret = getObject(arg0).measureText(getStringFromWasm0(arg1, arg2));
249
+ return addHeapObject(ret);
250
+ }, arguments); },
251
+ __wbg_measureText_57347b02ada3a4ad: function() { return handleError(function (arg0, arg1, arg2) {
252
+ const ret = getObject(arg0).measureText(getStringFromWasm0(arg1, arg2));
253
+ return addHeapObject(ret);
254
+ }, arguments); },
255
+ __wbg_message_5f8387f0c32b90a7: function(arg0) {
256
+ const ret = getObject(arg0).message;
257
+ return addHeapObject(ret);
258
+ },
259
+ __wbg_new_0_72d020f0c63443d4: function() {
260
+ const ret = new Date();
261
+ return addHeapObject(ret);
262
+ },
263
+ __wbg_new_1dbf7428bba60a42: function(arg0) {
264
+ const ret = new Uint8Array(getObject(arg0));
265
+ return addHeapObject(ret);
266
+ },
267
+ __wbg_new_34e56228080aa9f8: function(arg0) {
268
+ const ret = new Date(getObject(arg0));
269
+ return addHeapObject(ret);
270
+ },
271
+ __wbg_new_a217df4351db4b9b: function() { return handleError(function (arg0, arg1) {
272
+ const ret = new OffscreenCanvas(arg0 >>> 0, arg1 >>> 0);
273
+ return addHeapObject(ret);
274
+ }, arguments); },
275
+ __wbg_new_d1d1f48568532d74: function() { return handleError(function () {
276
+ const ret = new XMLHttpRequest();
277
+ return addHeapObject(ret);
278
+ }, arguments); },
279
+ __wbg_new_with_base_29cdb449ce79d2d5: function() { return handleError(function (arg0, arg1, arg2, arg3) {
280
+ const ret = new URL(getStringFromWasm0(arg0, arg1), getStringFromWasm0(arg2, arg3));
281
+ return addHeapObject(ret);
282
+ }, arguments); },
283
+ __wbg_new_with_year_month_day_hr_min_sec_53f4266b8db312e3: function(arg0, arg1, arg2, arg3, arg4, arg5) {
284
+ const ret = new Date(arg0 >>> 0, arg1, arg2, arg3, arg4, arg5);
285
+ return addHeapObject(ret);
286
+ },
287
+ __wbg_next_f4aac29c42af995c: function() { return handleError(function (arg0) {
288
+ const ret = getObject(arg0).next();
289
+ return addHeapObject(ret);
290
+ }, arguments); },
291
+ __wbg_normalize_5be7b1fd0a79da76: function(arg0, arg1, arg2) {
292
+ const ret = getObject(arg0).normalize(getStringFromWasm0(arg1, arg2));
293
+ return addHeapObject(ret);
294
+ },
295
+ __wbg_now_7c246bb37a807593: function() { return handleError(function () {
296
+ const ret = Date.now();
297
+ return ret;
298
+ }, arguments); },
299
+ __wbg_now_e7c6795a7f81e10f: function(arg0) {
300
+ const ret = getObject(arg0).now();
301
+ return ret;
302
+ },
303
+ __wbg_of_20798cb14708764f: function(arg0, arg1) {
304
+ const ret = Array.of(getObject(arg0), getObject(arg1));
305
+ return addHeapObject(ret);
306
+ },
307
+ __wbg_open_f0c8628338345808: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4, arg5) {
308
+ getObject(arg0).open(getStringFromWasm0(arg1, arg2), getStringFromWasm0(arg3, arg4), arg5 !== 0);
309
+ }, arguments); },
310
+ __wbg_performance_3fcf6e32a7e1ed0a: function(arg0) {
311
+ const ret = getObject(arg0).performance;
312
+ return addHeapObject(ret);
313
+ },
314
+ __wbg_prototypesetcall_bc27214492979395: function(arg0, arg1, arg2) {
315
+ Uint8Array.prototype.set.call(getArrayU8FromWasm0(arg0, arg1), getObject(arg2));
316
+ },
317
+ __wbg_replace_89a2bb260816315a: function(arg0, arg1, arg2, arg3) {
318
+ const ret = getObject(arg0).replace(getObject(arg1), getStringFromWasm0(arg2, arg3));
319
+ return addHeapObject(ret);
320
+ },
321
+ __wbg_response_ce3feafb4716c448: function() { return handleError(function (arg0) {
322
+ const ret = getObject(arg0).response;
323
+ return addHeapObject(ret);
324
+ }, arguments); },
325
+ __wbg_send_3b3b20df5e2e7616: function() { return handleError(function (arg0, arg1, arg2) {
326
+ getObject(arg0).send(arg1 === 0 ? undefined : getArrayU8FromWasm0(arg1, arg2));
327
+ }, arguments); },
328
+ __wbg_send_9d00bd9d7a2c90b5: function() { return handleError(function (arg0) {
329
+ getObject(arg0).send();
330
+ }, arguments); },
331
+ __wbg_setRequestHeader_733b74e99bf9b791: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) {
332
+ getObject(arg0).setRequestHeader(getStringFromWasm0(arg1, arg2), getStringFromWasm0(arg3, arg4));
333
+ }, arguments); },
334
+ __wbg_set_font_1f60a05a2544a2ff: function(arg0, arg1, arg2) {
335
+ getObject(arg0).font = getStringFromWasm0(arg1, arg2);
336
+ },
337
+ __wbg_set_font_7ef69121e02464cd: function(arg0, arg1, arg2) {
338
+ getObject(arg0).font = getStringFromWasm0(arg1, arg2);
339
+ },
340
+ __wbg_set_responseType_1f631c1316f4c16e: function(arg0, arg1) {
341
+ getObject(arg0).responseType = __wbindgen_enum_XmlHttpRequestResponseType[arg1];
342
+ },
343
+ __wbg_static_accessor_GLOBAL_266715b9d96ba635: function() {
344
+ const ret = typeof global === 'undefined' ? null : global;
345
+ return isLikeNone(ret) ? 0 : addHeapObject(ret);
346
+ },
347
+ __wbg_static_accessor_GLOBAL_THIS_10fb7dc1ae063179: function() {
348
+ const ret = typeof globalThis === 'undefined' ? null : globalThis;
349
+ return isLikeNone(ret) ? 0 : addHeapObject(ret);
350
+ },
351
+ __wbg_static_accessor_SELF_0b583911f537483a: function() {
352
+ const ret = typeof self === 'undefined' ? null : self;
353
+ return isLikeNone(ret) ? 0 : addHeapObject(ret);
354
+ },
355
+ __wbg_static_accessor_WINDOW_d7f903d1508cbdc4: function() {
356
+ const ret = typeof window === 'undefined' ? null : window;
357
+ return isLikeNone(ret) ? 0 : addHeapObject(ret);
358
+ },
359
+ __wbg_status_734f92f48f0f8b78: function() { return handleError(function (arg0) {
360
+ const ret = getObject(arg0).status;
361
+ return ret;
362
+ }, arguments); },
363
+ __wbg_value_f3c585ee8f5ba40c: function(arg0) {
364
+ const ret = getObject(arg0).value;
365
+ return addHeapObject(ret);
366
+ },
367
+ __wbg_width_e95ad291d52fe17e: function(arg0) {
368
+ const ret = getObject(arg0).width;
369
+ return ret;
370
+ },
371
+ __wbindgen_generic_0000000000000001: function(arg0) {
372
+ // Cast intrinsic for `F64 -> Externref`.
373
+ const ret = arg0;
374
+ return addHeapObject(ret);
375
+ },
376
+ __wbindgen_generic_0000000000000002: function(arg0, arg1) {
377
+ // Cast intrinsic for `Ref(String) -> Externref`.
378
+ const ret = getStringFromWasm0(arg0, arg1);
379
+ return addHeapObject(ret);
380
+ },
381
+ __wbindgen_object_clone_ref: function(arg0) {
382
+ const ret = getObject(arg0);
383
+ return addHeapObject(ret);
384
+ },
385
+ __wbindgen_object_drop_ref: function(arg0) {
386
+ takeObject(arg0);
387
+ },
388
+ };
389
+ return {
390
+ __proto__: null,
391
+ "./basedpl_wasm_bg.js": import0,
392
+ };
393
+ }
394
+
395
+ const __wbindgen_enum_XmlHttpRequestResponseType = ["", "arraybuffer", "blob", "document", "json", "text"];
396
+ const SessionFinalization = (typeof FinalizationRegistry === 'undefined')
397
+ ? { register: () => {}, unregister: () => {} }
398
+ : new FinalizationRegistry(ptr => wasm.__wbg_session_free(ptr, 1));
399
+
400
+ function addHeapObject(obj) {
401
+ if (heap_next === heap.length) heap.push(heap.length + 1);
402
+ const idx = heap_next;
403
+ heap_next = heap[idx];
404
+
405
+ heap[idx] = obj;
406
+ return idx;
407
+ }
408
+
409
+ function dropObject(idx) {
410
+ if (idx < 1028) return;
411
+ heap[idx] = heap_next;
412
+ heap_next = idx;
413
+ }
414
+
415
+ function getArrayU8FromWasm0(ptr, len) {
416
+ ptr = ptr >>> 0;
417
+ return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
418
+ }
419
+
420
+ let cachedDataViewMemory0 = null;
421
+ function getDataViewMemory0() {
422
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
423
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
424
+ }
425
+ return cachedDataViewMemory0;
426
+ }
427
+
428
+ function getStringFromWasm0(ptr, len) {
429
+ return decodeText(ptr >>> 0, len);
430
+ }
431
+
432
+ let cachedUint8ArrayMemory0 = null;
433
+ function getUint8ArrayMemory0() {
434
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
435
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
436
+ }
437
+ return cachedUint8ArrayMemory0;
438
+ }
439
+
440
+ function getObject(idx) { return heap[idx]; }
441
+
442
+ function handleError(f, args) {
443
+ try {
444
+ return f.apply(this, args);
445
+ } catch (e) {
446
+ wasm.__wbindgen_export3(addHeapObject(e));
447
+ }
448
+ }
449
+
450
+ let heap = new Array(1024).fill(undefined);
451
+ heap.push(undefined, null, true, false);
452
+
453
+ let heap_next = heap.length;
454
+
455
+ function isLikeNone(x) {
456
+ return x === undefined || x === null;
457
+ }
458
+
459
+ function passStringToWasm0(arg, malloc, realloc) {
460
+ if (realloc === undefined) {
461
+ const buf = cachedTextEncoder.encode(arg);
462
+ const ptr = malloc(buf.length, 1) >>> 0;
463
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
464
+ WASM_VECTOR_LEN = buf.length;
465
+ return ptr;
466
+ }
467
+
468
+ let len = arg.length;
469
+ let ptr = malloc(len, 1) >>> 0;
470
+
471
+ const mem = getUint8ArrayMemory0();
472
+
473
+ let offset = 0;
474
+
475
+ for (; offset < len; offset++) {
476
+ const code = arg.charCodeAt(offset);
477
+ if (code > 0x7F) break;
478
+ mem[ptr + offset] = code;
479
+ }
480
+ if (offset !== len) {
481
+ if (offset !== 0) {
482
+ arg = arg.slice(offset);
483
+ }
484
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
485
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
486
+ const ret = cachedTextEncoder.encodeInto(arg, view);
487
+
488
+ offset += ret.written;
489
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
490
+ }
491
+
492
+ WASM_VECTOR_LEN = offset;
493
+ return ptr;
494
+ }
495
+
496
+ function takeObject(idx) {
497
+ const ret = getObject(idx);
498
+ dropObject(idx);
499
+ return ret;
500
+ }
501
+
502
+ let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
503
+ cachedTextDecoder.decode();
504
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
505
+ let numBytesDecoded = 0;
506
+ function decodeText(ptr, len) {
507
+ numBytesDecoded += len;
508
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
509
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
510
+ cachedTextDecoder.decode();
511
+ numBytesDecoded = len;
512
+ }
513
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
514
+ }
515
+
516
+ const cachedTextEncoder = new TextEncoder();
517
+
518
+ if (!('encodeInto' in cachedTextEncoder)) {
519
+ cachedTextEncoder.encodeInto = function (arg, view) {
520
+ const buf = cachedTextEncoder.encode(arg);
521
+ view.set(buf);
522
+ return {
523
+ read: arg.length,
524
+ written: buf.length
525
+ };
526
+ };
527
+ }
528
+
529
+ let WASM_VECTOR_LEN = 0;
530
+
531
+ let wasmModule, wasmInstance, wasm;
532
+ function __wbg_finalize_init(instance, module) {
533
+ wasmInstance = instance;
534
+ wasm = instance.exports;
535
+ wasmModule = module;
536
+ cachedDataViewMemory0 = null;
537
+ cachedUint8ArrayMemory0 = null;
538
+ return wasm;
539
+ }
540
+
541
+ async function __wbg_load(module, imports) {
542
+ if (typeof Response === 'function' && module instanceof Response) {
543
+ if (!module.ok) {
544
+ throw new Error(`failed to fetch Wasm: ${module.status} ${module.statusText} fetching '${module.url}'`);
545
+ }
546
+
547
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
548
+ try {
549
+ return await WebAssembly.instantiateStreaming(module, imports);
550
+ } catch (e) {
551
+ const validResponse = expectedResponseType(module.type);
552
+
553
+ if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
554
+ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
555
+
556
+ } else { throw e; }
557
+ }
558
+ }
559
+
560
+ const bytes = await module.arrayBuffer();
561
+ return await WebAssembly.instantiate(bytes, imports);
562
+ } else {
563
+ const instance = await WebAssembly.instantiate(module, imports);
564
+
565
+ if (instance instanceof WebAssembly.Instance) {
566
+ return { instance, module };
567
+ } else {
568
+ return instance;
569
+ }
570
+ }
571
+
572
+ function expectedResponseType(type) {
573
+ switch (type) {
574
+ case 'basic': case 'cors': case 'default': return true;
575
+ }
576
+ return false;
577
+ }
578
+ }
579
+
580
+ function initSync(module) {
581
+ if (wasm !== undefined) return wasm;
582
+
583
+
584
+ if (module !== undefined) {
585
+ if (Object.getPrototypeOf(module) === Object.prototype) {
586
+ ({module} = module)
587
+ } else {
588
+ console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
589
+ }
590
+ }
591
+
592
+ const imports = __wbg_get_imports();
593
+ if (!(module instanceof WebAssembly.Module)) {
594
+ module = new WebAssembly.Module(module);
595
+ }
596
+ const instance = new WebAssembly.Instance(module, imports);
597
+ return __wbg_finalize_init(instance, module);
598
+ }
599
+
600
+ async function __wbg_init(module_or_path) {
601
+ if (wasm !== undefined) return wasm;
602
+
603
+
604
+ if (module_or_path !== undefined) {
605
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
606
+ ({module_or_path} = module_or_path)
607
+ } else {
608
+ console.warn('using deprecated parameters for the initialization function; pass a single object instead')
609
+ }
610
+ }
611
+
612
+ if (module_or_path === undefined) {
613
+ module_or_path = new URL('basedpl_wasm_bg.wasm', import.meta.url);
614
+ }
615
+ const imports = __wbg_get_imports();
616
+
617
+ if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
618
+ module_or_path = fetch(module_or_path);
619
+ }
620
+
621
+ const { instance, module } = await __wbg_load(await module_or_path, imports);
622
+
623
+ return __wbg_finalize_init(instance, module);
624
+ }
625
+
626
+ export { initSync, __wbg_init as default };
Binary file
package/input.js ADDED
@@ -0,0 +1,103 @@
1
+ ((symbols, layout) => {
2
+ // US physical keys, before macOS Option or another layout transforms event.key.
3
+ const punctuation = {Backquote: '`~', Minus: '-_', Equal: '=+', BracketLeft: '[{', BracketRight: ']}',
4
+ Backslash: '\\|', Semicolon: ';:', Quote: "'\"", Comma: ',<', Period: '.>', Slash: '/?'};
5
+ function usKey({code, shiftKey}) {
6
+ if (/^Key[A-Z]$/.test(code)) return shiftKey ? code.slice(3) : code.slice(3).toLowerCase();
7
+ if (/^Digit[0-9]$/.test(code)) return shiftKey ? ')!@#$%^&*('[Number(code[5])] : code[5];
8
+ return punctuation[code]?.[Number(shiftKey)];
9
+ }
10
+
11
+ // Composed input from `layout.json`, with the same rules as the REPL and the macOS layout. `pending` is the dead-key state
12
+ // that the next key completes.
13
+ let pending = null;
14
+ const act = action => typeof action === 'string' ? (pending = null, action) : (pending = action.state, '');
15
+ // What a key types: `{text, stop}`, where `stop` means the key itself does nothing more, or nothing for an ordinary key.
16
+ // `option` is whether an Option chord counts here.
17
+ function press(ev, option) {
18
+ const key = usKey(ev), plain = !ev.altKey && !ev.ctrlKey && !ev.metaKey;
19
+ // Native Option can hide the alias character; accept its US physical chord too.
20
+ const action = option && ev.altKey && !ev.ctrlKey && !ev.metaKey
21
+ ? layout.alt_aliases[ev.key] ?? layout.option[key] ?? (Object.values(layout.alt_aliases).includes(key) ? key : null) : null;
22
+ if (pending) {
23
+ const state = layout.states[pending], repeated = action?.state === pending;
24
+ pending = null;
25
+ if (repeated) return {text: state.terminator, stop: true};
26
+ if (plain && ev.key === ' ') return {text: state.terminator, stop: true};
27
+ if (ev.key === 'Backspace' || ev.key === 'Escape') return {text: '', stop: true};
28
+ if (plain && key in state.keys) return {text: act(state.keys[key]), stop: true};
29
+ // Any other key types the terminator, then acts as if nothing were pending.
30
+ const rest = press(ev, option);
31
+ return {text: state.terminator + (rest?.text ?? ''), stop: rest?.stop ?? false};
32
+ }
33
+ if (action) return {text: act(action), stop: true};
34
+ }
35
+ const reset = () => { pending = null; };
36
+
37
+ // At each level (exact, prefix, prefixes of hyphen-separated parts) a name outranks a search word, as in `matches` in `symbols.rs`.
38
+ function matches(query) {
39
+ query = query.toLowerCase();
40
+ const letters = word => word.replaceAll('-', '');
41
+ let best = Infinity, found = [];
42
+ for (const {glyph, name, monad, dyad, aliases} of symbols) {
43
+ let rank = Infinity;
44
+ [name, monad, dyad, ...aliases.split(' ')].filter(Boolean).forEach((word, i) => {
45
+ const level = letters(word) === query ? 0 : letters(word).startsWith(query) ? 1 : 2;
46
+ if (level === 2) {
47
+ let rest = query;
48
+ for (const part of word.split('-')) {
49
+ let n = 0;
50
+ while (n < part.length && part[n] === rest[n]) n++;
51
+ if (!n) break;
52
+ rest = rest.slice(n);
53
+ if (!rest) break;
54
+ }
55
+ if (rest) return;
56
+ }
57
+ rank = Math.min(rank, 2 * level + (i > 0));
58
+ });
59
+ if (rank < best) { best = rank; found = []; }
60
+ if (rank < Infinity && rank === best) found.push([glyph, name]);
61
+ }
62
+ // A name that is a prefix of every other match wins: `om gives omega, `omu gives omega-underbar.
63
+ const shortest = found.find(([, a]) => found.every(([, b]) => letters(b).startsWith(letters(a))));
64
+ return shortest && found.length > 1 ? [shortest] : found;
65
+ }
66
+
67
+ function inCode(text, python = false) {
68
+ let quote = '', comment = false;
69
+ for (let i = 0; i < text.length; i++) {
70
+ const c = text[i];
71
+ if (comment) { if (c === '\n') comment = false; }
72
+ else if (quote) {
73
+ if (python && c === '\\') i++;
74
+ else if (text.startsWith(quote, i)) { i += quote.length - 1; quote = ''; }
75
+ } else if (c === "'" && !python) {
76
+ if (i + 2 >= text.length) return false;
77
+ i += 2;
78
+ } else if (c === "'" || c === '"') {
79
+ quote = python && text.startsWith(c.repeat(3), i) ? c.repeat(3) : c;
80
+ i += quote.length - 1;
81
+ } else if (c === (python ? '#' : '⍝')) comment = true;
82
+ }
83
+ return !quote && !comment;
84
+ }
85
+
86
+ function bplStart(e) {
87
+ if (e.bpl) return 0;
88
+ const header = /^%%(?:bpl|apl)[^\S\n]*(?:\r?\n|$)/.exec(e.text);
89
+ if (header) return e.pos >= header[0].length ? header[0].length : -1;
90
+ const start = e.text.lastIndexOf('\n', e.pos - 1) + 1;
91
+ const line = /^[ \t]*(?:[\p{ID_Start}_][\p{ID_Continue}]*[ \t]*=[ \t]*)?%bpl[ \t]+/u.exec(e.text.slice(start, e.pos));
92
+ return line && inCode(e.text.slice(0, start), true) ? start + line[0].length : -1;
93
+ }
94
+
95
+ function entry(e) {
96
+ const body = bplStart(e), start = e.text.lastIndexOf('`', e.pos - 1);
97
+ if (body < 0 || start < body || !e.empty || !inCode(e.text.slice(body, start))) return;
98
+ const query = e.text.slice(start + 1, e.pos);
99
+ if (/^[a-z]*$/i.test(query)) return {start, query, found: matches(query)};
100
+ }
101
+
102
+ return {matches, inCode, bplStart, entry, press, reset};
103
+ })
package/layout.json ADDED
@@ -0,0 +1,80 @@
1
+ {
2
+ "alt_aliases": {"£": "#"},
3
+ "option": {
4
+ "`": {"state": "diamond"},
5
+ "1": {"state": "diaeresis"},
6
+ "3": "√",
7
+ "4": "⇄",
8
+ "5": {"state": "subscript"},
9
+ "6": {"state": "superscript"},
10
+ "7": {"state": "delta"},
11
+ "8": "∞",
12
+ "9": {"state": "or"},
13
+ "0": {"state": "and"},
14
+ ")": "⍬",
15
+ "-": {"state": "bar"},
16
+ "=": {"state": "match"},
17
+ "q": {"state": "quad"},
18
+ "w": {"state": "omega"},
19
+ "e": {"state": "epsilon"},
20
+ "r": "⍴",
21
+ "t": "∘",
22
+ "y": "•",
23
+ "u": "÷",
24
+ "i": {"state": "iota"},
25
+ "o": {"state": "circle"},
26
+ "p": "π",
27
+ "+": "≠",
28
+ "\\": {"state": "stile"},
29
+ "a": {"state": "alpha"},
30
+ "s": "⌈",
31
+ "d": "⌊",
32
+ "f": "∂",
33
+ "g": {"state": "del"},
34
+ "h": "←",
35
+ "j": "↓",
36
+ "k": {"state": "take"},
37
+ "l": "→",
38
+ ";": "⊣",
39
+ "'": "⊢",
40
+ "z": {"state": "enclose"},
41
+ "x": "⊃",
42
+ "c": {"state": "cap"},
43
+ "v": "∪",
44
+ "b": {"state": "decode"},
45
+ "n": {"state": "encode"},
46
+ "m": "×",
47
+ ",": "↢",
48
+ ".": "↣",
49
+ "<": "≤",
50
+ ">": "≥",
51
+ "|": "⌽",
52
+ "/": "¿"
53
+ },
54
+ "states": {
55
+ "diaeresis": {"terminator": "¨", "keys": {"t": "⍤", "o": "⍥", "*": "⍣", "~": "⍨", "g": "⍢", "8": "⍣", "`": "⍨"}},
56
+ "superscript": {"terminator": "^", "keys": {"0": "⁰", "1": "¹", "2": "²", "3": "³", "4": "⁴", "5": "⁵", "6": "⁶", "7": "⁷", "8": "⁸", "9": "⁹", "-": {"state": "superscript-minus"}, "t": "ᵀ", "u": "ᵘ"}},
57
+ "superscript-minus": {"terminator": "⁻", "keys": {"0": "⁻⁰", "1": "⁻¹", "2": "⁻²", "3": "⁻³", "4": "⁻⁴", "5": "⁻⁵", "6": "⁻⁶", "7": "⁻⁷", "8": "⁻⁸", "9": "⁻⁹"}},
58
+ "subscript": {"terminator": "_", "keys": {"0": "₀", "1": "₁", "2": "₂", "3": "₃", "4": "₄", "5": "₅", "6": "₆", "7": "₇", "8": "₈", "9": "₉", "x": "ₓ", "j": "ⱼ", "e": "ₑ", "r": "ᵣ", "-": {"state": "subscript-minus"}}},
59
+ "subscript-minus": {"terminator": "₋", "keys": {"0": "₋₀", "1": "₋₁", "2": "₋₂", "3": "₋₃", "4": "₋₄", "5": "₋₅", "6": "₋₆", "7": "₋₇", "8": "₋₈", "9": "₋₉"}},
60
+ "diamond": {"terminator": "⋄", "keys": {"_": "⍚", "-": "⍚"}},
61
+ "delta": {"terminator": "∆", "keys": {"|": "⍋", "_": "⍙", "\\": "⍋", "-": "⍙"}},
62
+ "or": {"terminator": "∨", "keys": {"~": "⍱", "`": "⍱"}},
63
+ "and": {"terminator": "∧", "keys": {"~": "⍲", "`": "⍲"}},
64
+ "bar": {"terminator": "¯", "keys": {",": "⍪", "\\": "⍀", "/": "⌿"}},
65
+ "match": {"terminator": "≡", "keys": {"/": "≢"}},
66
+ "quad": {"terminator": "⎕", "keys": {"t": "⌻", ":": "⍠", "=": "⌸", "u": "⌹", "|": "⌷", "`": "⌺", ";": "⍠", "\\": "⌷"}},
67
+ "omega": {"terminator": "⍵", "keys": {"_": "⍹", "-": "⍹"}},
68
+ "epsilon": {"terminator": "∊", "keys": {"_": "⍷", "-": "⍷"}},
69
+ "iota": {"terminator": "⍳", "keys": {"_": "⍸", "-": "⍸"}},
70
+ "circle": {"terminator": "○", "keys": {"-": "⊖", "\\": "⍉", "/": "⊘", "*": "⍟", "m": "⊗", "u": "⨸", "t": "⌾", "8": "⍟"}},
71
+ "stile": {"terminator": "|", "keys": {"~": "⍭", "`": "⍭"}},
72
+ "alpha": {"terminator": "⍺", "keys": {"_": "⍶", "-": "⍶"}},
73
+ "del": {"terminator": "∇", "keys": {"|": "⍒", "\\": "⍒"}},
74
+ "take": {"terminator": "↑", "keys": {"j": "↕"}},
75
+ "enclose": {"terminator": "⊂", "keys": {"_": "⊆", "-": "⊆"}},
76
+ "cap": {"terminator": "∩", "keys": {"t": "⍝"}},
77
+ "decode": {"terminator": "⊥", "keys": {"t": "⍎"}},
78
+ "encode": {"terminator": "⊤", "keys": {"t": "⍕"}}
79
+ }
80
+ }
package/lb.js ADDED
@@ -0,0 +1,196 @@
1
+ // Based on Adám Brudzewsky's APL language bar: https://abrudz.github.io/lb
2
+ // MIT License, Copyright (c) 2011-2020 Nikolay G. Nikolov and Adam Brudzevski.
3
+ // BPL name completion, editor adapters, dark mode and overlay layout by Jeremy Howard.
4
+ ((symbols, input, layout) => {
5
+ const d = document;
6
+ // Docs pages have no bar, except a page with a `data-bpl` editor, such as the playground.
7
+ if (d.querySelector('.ngn_lb') || d.querySelector('meta[name=generator][content^=quarto]') && !d.querySelector('[data-bpl]')) return;
8
+
9
+ const {inCode, bplStart, entry, press, reset} = input(symbols, layout);
10
+ const shortcuts = new Map(symbols.map(({glyph, shortcut}) => [glyph, shortcut]));
11
+ let leftAlt = false, rightAlt = false;
12
+
13
+ function textareaRect(t) {
14
+ const mirror = d.createElement('div'), caret = d.createElement('span'), css = getComputedStyle(t), rect = t.getBoundingClientRect();
15
+ for (const p of ['font', 'lineHeight', 'letterSpacing', 'padding', 'border', 'boxSizing', 'width', 'tabSize']) mirror.style[p] = css[p];
16
+ Object.assign(mirror.style, {position: 'fixed', visibility: 'hidden', whiteSpace: 'pre-wrap', overflowWrap: 'break-word',
17
+ left: `${rect.left - t.scrollLeft}px`, top: `${rect.top - t.scrollTop}px`});
18
+ mirror.textContent = t.value.slice(0, t.selectionStart);
19
+ caret.textContent = '\u200b';
20
+ mirror.append(caret);
21
+ d.body.append(mirror);
22
+ const result = caret.getBoundingClientRect();
23
+ mirror.remove();
24
+ return result;
25
+ }
26
+
27
+ function editor(target) {
28
+ if (target.closest?.('.text_cell, .jp-MarkdownCell')) return;
29
+ const m = window.monaco?.editor?.getEditors?.().find(e => e.hasTextFocus());
30
+ if (m) {
31
+ const model = m.getModel(), p = m.getPosition(), selection = m.getSelection();
32
+ if (model.getLanguageId() === 'markdown' || m.getOption(window.monaco.editor.EditorOption.readOnly)) return;
33
+ return {id: m, text: model.getValue(), pos: model.getOffsetAt(p), empty: selection.isEmpty(), bpl: model.getLanguageId() === 'bpl',
34
+ rect: () => {
35
+ const r = m.getDomNode().getBoundingClientRect(), c = m.getScrolledVisiblePosition(p);
36
+ return {left: r.left + c.left, bottom: r.top + c.top + c.height};
37
+ },
38
+ insert: (text, from = model.getOffsetAt(selection.getStartPosition())) => {
39
+ const a = model.getPositionAt(from), b = selection.getEndPosition();
40
+ m.pushUndoStop();
41
+ m.executeEdits('aplnb', [{range: {startLineNumber: a.lineNumber, startColumn: a.column,
42
+ endLineNumber: b.lineNumber, endColumn: b.column}, text}], () => {
43
+ const end = model.getPositionAt(from + text.length);
44
+ return [new window.monaco.Selection(end.lineNumber, end.column, end.lineNumber, end.column)];
45
+ });
46
+ m.pushUndoStop();
47
+ m.focus();
48
+ }};
49
+ }
50
+ const view = target.closest?.('.cm-editor')?.querySelector('.cm-content')?.cmTile?.view;
51
+ if (view) {
52
+ if (view.state.readOnly) return;
53
+ const sel = view.state.selection.main;
54
+ return {id: view, text: view.state.doc.toString(), pos: sel.head, empty: sel.empty,
55
+ rect: () => view.coordsAtPos(sel.head),
56
+ insert: (text, from = sel.from) => {
57
+ view.dispatch({changes: {from, to: sel.to, insert: text}, selection: {anchor: from + text.length}, userEvent: 'input.complete'});
58
+ view.focus();
59
+ }};
60
+ }
61
+ if (target.tagName !== 'TEXTAREA' || target.readOnly || target.disabled) return;
62
+ return {id: target, text: target.value, pos: target.selectionStart, empty: target.selectionStart === target.selectionEnd, bpl: target.hasAttribute('data-bpl'),
63
+ rect: () => textareaRect(target),
64
+ insert: (text, from = target.selectionStart) => {
65
+ target.focus();
66
+ target.selectionStart = from;
67
+ d.execCommand('insertText', false, text);
68
+ }};
69
+ }
70
+
71
+ const host = d.createElement('div');
72
+ host.innerHTML = `<div class="ngn_lb" aria-label="BPL symbols"><button class="ngn_x" title="Close symbol bar">×</button><button class="ngn_o" title="Toggle overlay/push-down"></button></div>
73
+ <div class="bpl_choices" role="group" aria-label="BPL symbol completions" hidden></div>
74
+ <style>
75
+ .ngn_lb,.bpl_choices{background:#eee;color:#111;font:15px var(--bpl-font),monospace;z-index:2147483647}
76
+ .ngn_lb{position:fixed;top:0;left:0;right:0;border-bottom:1px solid #999;padding:2px}
77
+ .ngn_lb button,.bpl_choices button{font:inherit;color:inherit;background:none;border:0;cursor:pointer;padding:2px 4px}
78
+ .ngn_lb button:hover,.bpl_choices button:hover{background:#777;color:white}
79
+ .ngn_x,.ngn_o{float:right}
80
+ .bpl_choices{position:fixed;max-height:240px;max-width:calc(100vw - 16px);overflow:auto;border:1px solid #888;border-radius:4px;box-shadow:0 3px 12px #0003;padding:4px}
81
+ .bpl_choices button{display:block;width:100%;text-align:left;white-space:nowrap}
82
+ .bpl_choices small{display:block;padding:4px}
83
+ @media(prefers-color-scheme:dark){.ngn_lb,.bpl_choices{background:#222;color:#ddd}.ngn_lb button:hover,.bpl_choices button:hover{background:#bbb;color:#111}}
84
+ </style>`;
85
+ d.body.append(host);
86
+ const bar = host.querySelector('.ngn_lb'), tip = host.querySelector('.bpl_choices'), toggle = bar.querySelector('.ngn_o');
87
+ let overlay = false, active, lastEditor, choice, keyInput = false;
88
+ const originalPadding = d.body.style.paddingTop;
89
+ try { overlay = localStorage.getItem('ngn_lb_overlay') === '1'; } catch {}
90
+ function reflow() {
91
+ toggle.textContent = overlay ? '▼' : '▲';
92
+ d.body.style.paddingTop = overlay || bar.hidden ? originalPadding : `${bar.offsetHeight}px`;
93
+ }
94
+ function button(glyph, name) {
95
+ const b = d.createElement('button');
96
+ b.type = 'button'; b.textContent = glyph; b.title = name + shortcuts.get(glyph); b.dataset.glyph = glyph;
97
+ return b;
98
+ }
99
+ for (const {glyph, name, monad, dyad, aliases} of symbols)
100
+ bar.append(button(glyph, [...new Set([name, monad, dyad, aliases].join(' ').split(' ').filter(Boolean))].join(' ')));
101
+ new ResizeObserver(reflow).observe(bar);
102
+ reflow();
103
+
104
+ function cancel() { active = undefined; choice = undefined; tip.hidden = true; }
105
+ function show(e, item) {
106
+ if (choice?.item.query !== item.query) {
107
+ tip.replaceChildren();
108
+ for (const [glyph, name] of item.found) {
109
+ const b = button(glyph, name);
110
+ b.textContent = `${glyph} ${b.title}`;
111
+ tip.append(b);
112
+ }
113
+ if (!item.found.length) {
114
+ const note = d.createElement('small'); note.textContent = 'Unknown symbol'; tip.append(note);
115
+ }
116
+ }
117
+ choice = {e, item};
118
+ tip.hidden = false;
119
+ const r = e.rect();
120
+ tip.style.left = `${Math.max(4, Math.min(r.left, innerWidth - tip.offsetWidth - 8))}px`;
121
+ tip.style.top = `${Math.max(bar.hidden || overlay ? 4 : bar.offsetHeight, Math.min(r.bottom + 4, innerHeight - tip.offsetHeight - 8))}px`;
122
+ }
123
+ function refresh(target) {
124
+ const e = editor(target), item = e && entry(e);
125
+ if (item && active?.id === e.id && active.start === item.start) show(e, item);
126
+ else cancel();
127
+ }
128
+ bar.addEventListener('mousedown', ev => {
129
+ ev.preventDefault();
130
+ const b = ev.target.closest('button');
131
+ if (b?.classList.contains('ngn_x')) { bar.hidden = true; reflow(); }
132
+ else if (b === toggle) {
133
+ overlay = !overlay;
134
+ try { localStorage.setItem('ngn_lb_overlay', overlay ? '1' : '0'); } catch {}
135
+ reflow();
136
+ } else if (b?.dataset.glyph && lastEditor) lastEditor.insert(b.dataset.glyph);
137
+ cancel();
138
+ });
139
+ tip.addEventListener('mousedown', ev => {
140
+ ev.preventDefault();
141
+ const b = ev.target.closest('button');
142
+ if (b && choice) choice.e.insert(b.dataset.glyph, choice.item.start);
143
+ cancel();
144
+ });
145
+ d.addEventListener('focusin', ev => { lastEditor = editor(ev.target); cancel(); });
146
+ d.addEventListener('pointerdown', ev => { if (!host.contains(ev.target)) cancel(); }, true);
147
+ d.addEventListener('pointerup', ev => { if (!host.contains(ev.target)) lastEditor = editor(ev.target); });
148
+ for (const event of ['paste', 'cut', 'compositionstart', 'focusout']) d.addEventListener(event, cancel, true);
149
+ d.addEventListener('input', ev => {
150
+ if (!keyInput || ev.inputType !== 'insertText' && ev.inputType !== 'deleteContentBackward') cancel();
151
+ keyInput = false;
152
+ requestAnimationFrame(() => { lastEditor = editor(ev.target); refresh(ev.target); });
153
+ });
154
+ window.addEventListener('blur', () => { leftAlt = rightAlt = false; cancel(); reset(); });
155
+ window.addEventListener('focusin', reset, true);
156
+ window.addEventListener('keyup', ev => {
157
+ if (ev.code === 'AltLeft') leftAlt = false;
158
+ if (ev.code === 'AltRight') rightAlt = false;
159
+ keyInput = false; lastEditor = editor(ev.target); if (active) refresh(ev.target);
160
+ }, true);
161
+ window.addEventListener('keydown', ev => {
162
+ keyInput = false;
163
+ if (ev.code === 'AltLeft') leftAlt = true;
164
+ if (ev.code === 'AltRight') rightAlt = true;
165
+ if (['Shift', 'Control', 'Alt', 'Meta'].includes(ev.key)) return;
166
+ const e = editor(ev.target);
167
+ if (!e || ev.isComposing || ev.defaultPrevented) { cancel(); return; }
168
+ lastEditor = e;
169
+ const body = bplStart(e);
170
+ const pressed = press(ev, leftAlt && !rightAlt && !ev.getModifierState('AltGraph') && body >= 0);
171
+ if (pressed) {
172
+ if (pressed.text) e.insert(pressed.text);
173
+ if (pressed.stop) { cancel(); ev.preventDefault(); ev.stopImmediatePropagation(); return; }
174
+ }
175
+ const item = entry(e), plain = !ev.ctrlKey && !ev.altKey && !ev.metaKey;
176
+ const tab = ev.key === 'Tab' && plain && !ev.shiftKey, enter = ev.key === 'Enter';
177
+ const typed = active?.id === e.id && active.start === item?.start;
178
+ const delimiter = plain && ev.key.length === 1 && !/[a-z]/i.test(ev.key);
179
+ if (item && (tab || typed && (enter || delimiter))) {
180
+ if (item.found.length === 1) {
181
+ e.insert(item.found[0][0], item.start);
182
+ cancel();
183
+ } else if (tab) {
184
+ active = {id: e.id, start: item.start};
185
+ show(e, item);
186
+ }
187
+ if (tab) { ev.preventDefault(); ev.stopImmediatePropagation(); return; }
188
+ }
189
+ if (ev.key === '`' && plain) {
190
+ const updated = editor(ev.target), body = bplStart(updated);
191
+ if (body >= 0 && updated.empty && inCode(updated.text.slice(body, updated.pos))) active = {id: updated.id, start: updated.pos};
192
+ else cancel();
193
+ } else if (!(typed && plain && (/^[a-z]$/i.test(ev.key) || ev.key === 'Backspace'))) cancel();
194
+ keyInput = plain && (ev.key.length === 1 || ev.key === 'Backspace');
195
+ }, true);
196
+ })
package/package.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "basedpl",
3
+ "version": "0.1.24",
4
+ "description": "BasedPL, the Based-array Programming Language, is an APL-derived array language, borrowing ideas from J and BQN, with an emphasis on simple, consistent notation.",
5
+ "license": "Apache-2.0",
6
+ "repository": "https://github.com/AnswerDotAI/basedpl",
7
+ "type": "module",
8
+ "main": "basedpl_wasm.js"
9
+ }