@hviana/sema 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.
- package/dist/example/demo.d.ts +1 -0
- package/dist/example/demo.js +39 -0
- package/dist/example/train_base.d.ts +87 -0
- package/dist/example/train_base.js +2216 -0
- package/dist/src/alphabet.d.ts +7 -0
- package/dist/src/alphabet.js +33 -0
- package/dist/src/alu/src/alu.d.ts +185 -0
- package/dist/src/alu/src/alu.js +440 -0
- package/dist/src/alu/src/expr.d.ts +61 -0
- package/dist/src/alu/src/expr.js +318 -0
- package/dist/src/alu/src/index.d.ts +11 -0
- package/dist/src/alu/src/index.js +19 -0
- package/dist/src/alu/src/kernel-arith.d.ts +16 -0
- package/dist/src/alu/src/kernel-arith.js +264 -0
- package/dist/src/alu/src/kernel-bits.d.ts +19 -0
- package/dist/src/alu/src/kernel-bits.js +152 -0
- package/dist/src/alu/src/kernel-logic.d.ts +4 -0
- package/dist/src/alu/src/kernel-logic.js +60 -0
- package/dist/src/alu/src/kernel-nd.d.ts +3 -0
- package/dist/src/alu/src/kernel-nd.js +208 -0
- package/dist/src/alu/src/kernel-numeric.d.ts +54 -0
- package/dist/src/alu/src/kernel-numeric.js +366 -0
- package/dist/src/alu/src/operation.d.ts +168 -0
- package/dist/src/alu/src/operation.js +189 -0
- package/dist/src/alu/src/parser.d.ts +212 -0
- package/dist/src/alu/src/parser.js +469 -0
- package/dist/src/alu/src/resonance.d.ts +55 -0
- package/dist/src/alu/src/resonance.js +126 -0
- package/dist/src/alu/src/text.d.ts +31 -0
- package/dist/src/alu/src/text.js +73 -0
- package/dist/src/alu/src/value.d.ts +109 -0
- package/dist/src/alu/src/value.js +300 -0
- package/dist/src/alu/test/alu.test.d.ts +1 -0
- package/dist/src/alu/test/alu.test.js +764 -0
- package/dist/src/bytes.d.ts +14 -0
- package/dist/src/bytes.js +59 -0
- package/dist/src/config.d.ts +114 -0
- package/dist/src/config.js +96 -0
- package/dist/src/derive/src/deduction.d.ts +125 -0
- package/dist/src/derive/src/deduction.js +155 -0
- package/dist/src/derive/src/index.d.ts +7 -0
- package/dist/src/derive/src/index.js +11 -0
- package/dist/src/derive/src/priority-queue.d.ts +20 -0
- package/dist/src/derive/src/priority-queue.js +73 -0
- package/dist/src/derive/src/rewrite.d.ts +56 -0
- package/dist/src/derive/src/rewrite.js +100 -0
- package/dist/src/derive/src/trie.d.ts +90 -0
- package/dist/src/derive/src/trie.js +217 -0
- package/dist/src/derive/test/derive.test.d.ts +1 -0
- package/dist/src/derive/test/derive.test.js +122 -0
- package/dist/src/extension.d.ts +37 -0
- package/dist/src/extension.js +7 -0
- package/dist/src/geometry.d.ts +137 -0
- package/dist/src/geometry.js +430 -0
- package/dist/src/index.d.ts +15 -0
- package/dist/src/index.js +21 -0
- package/dist/src/ingest-cache.d.ts +41 -0
- package/dist/src/ingest-cache.js +161 -0
- package/dist/src/mind/articulation.d.ts +6 -0
- package/dist/src/mind/articulation.js +99 -0
- package/dist/src/mind/attention.d.ts +72 -0
- package/dist/src/mind/attention.js +894 -0
- package/dist/src/mind/canonical.d.ts +29 -0
- package/dist/src/mind/canonical.js +88 -0
- package/dist/src/mind/graph-search.d.ts +270 -0
- package/dist/src/mind/graph-search.js +847 -0
- package/dist/src/mind/index.d.ts +5 -0
- package/dist/src/mind/index.js +5 -0
- package/dist/src/mind/junction.d.ts +95 -0
- package/dist/src/mind/junction.js +262 -0
- package/dist/src/mind/learning.d.ts +47 -0
- package/dist/src/mind/learning.js +201 -0
- package/dist/src/mind/match.d.ts +111 -0
- package/dist/src/mind/match.js +422 -0
- package/dist/src/mind/mechanisms/alu.d.ts +4 -0
- package/dist/src/mind/mechanisms/alu.js +29 -0
- package/dist/src/mind/mechanisms/cast.d.ts +35 -0
- package/dist/src/mind/mechanisms/cast.js +447 -0
- package/dist/src/mind/mechanisms/confluence.d.ts +24 -0
- package/dist/src/mind/mechanisms/confluence.js +213 -0
- package/dist/src/mind/mechanisms/cover.d.ts +6 -0
- package/dist/src/mind/mechanisms/cover.js +179 -0
- package/dist/src/mind/mechanisms/extraction.d.ts +67 -0
- package/dist/src/mind/mechanisms/extraction.js +342 -0
- package/dist/src/mind/mechanisms/recall.d.ts +13 -0
- package/dist/src/mind/mechanisms/recall.js +151 -0
- package/dist/src/mind/mind.d.ts +147 -0
- package/dist/src/mind/mind.js +300 -0
- package/dist/src/mind/pipeline-mechanism.d.ts +142 -0
- package/dist/src/mind/pipeline-mechanism.js +213 -0
- package/dist/src/mind/pipeline.d.ts +20 -0
- package/dist/src/mind/pipeline.js +185 -0
- package/dist/src/mind/primitives.d.ts +43 -0
- package/dist/src/mind/primitives.js +162 -0
- package/dist/src/mind/rationale.d.ts +134 -0
- package/dist/src/mind/rationale.js +162 -0
- package/dist/src/mind/reasoning.d.ts +15 -0
- package/dist/src/mind/reasoning.js +162 -0
- package/dist/src/mind/recognition.d.ts +20 -0
- package/dist/src/mind/recognition.js +223 -0
- package/dist/src/mind/resonance.d.ts +23 -0
- package/dist/src/mind/resonance.js +0 -0
- package/dist/src/mind/trace.d.ts +15 -0
- package/dist/src/mind/trace.js +73 -0
- package/dist/src/mind/traverse.d.ts +100 -0
- package/dist/src/mind/traverse.js +447 -0
- package/dist/src/mind/types.d.ts +174 -0
- package/dist/src/mind/types.js +84 -0
- package/dist/src/rabitq-hnsw/src/database.d.ts +200 -0
- package/dist/src/rabitq-hnsw/src/database.js +388 -0
- package/dist/src/rabitq-hnsw/src/heap.d.ts +22 -0
- package/dist/src/rabitq-hnsw/src/heap.js +89 -0
- package/dist/src/rabitq-hnsw/src/hnsw.d.ts +125 -0
- package/dist/src/rabitq-hnsw/src/hnsw.js +474 -0
- package/dist/src/rabitq-hnsw/src/index.d.ts +10 -0
- package/dist/src/rabitq-hnsw/src/index.js +6 -0
- package/dist/src/rabitq-hnsw/src/prng.d.ts +19 -0
- package/dist/src/rabitq-hnsw/src/prng.js +36 -0
- package/dist/src/rabitq-hnsw/src/rabitq.d.ts +95 -0
- package/dist/src/rabitq-hnsw/src/rabitq.js +283 -0
- package/dist/src/rabitq-hnsw/src/store.d.ts +162 -0
- package/dist/src/rabitq-hnsw/src/store.js +825 -0
- package/dist/src/rabitq-hnsw/test/hnsw.test.d.ts +1 -0
- package/dist/src/rabitq-hnsw/test/hnsw.test.js +948 -0
- package/dist/src/store-sqlite.d.ts +149 -0
- package/dist/src/store-sqlite.js +702 -0
- package/dist/src/store.d.ts +638 -0
- package/dist/src/store.js +1618 -0
- package/dist/src/vec.d.ts +31 -0
- package/dist/src/vec.js +109 -0
- package/package.json +1 -1
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// alphabet.ts — the byte→vector mapping.
|
|
2
|
+
//
|
|
3
|
+
// 256 unit vectors, one per byte value, built by recursive refinement:
|
|
4
|
+
// 16 coarse directions → 64 mids → 256 fines. Same-fine neighbours
|
|
5
|
+
// resonate; far-apart values are quasi-orthogonal.
|
|
6
|
+
import { addInto, copy, normalize, randomUnit, rng } from "./vec.js";
|
|
7
|
+
export class Alphabet {
|
|
8
|
+
vecs = [];
|
|
9
|
+
config;
|
|
10
|
+
constructor(seed, D, config) {
|
|
11
|
+
this.config = {
|
|
12
|
+
roughness: config?.roughness ?? 0.65,
|
|
13
|
+
seedMask: config?.seedMask ?? 0xa1fa17,
|
|
14
|
+
};
|
|
15
|
+
const rand = rng((seed ^ this.config.seedMask) >>> 0);
|
|
16
|
+
const refine = (parent) => {
|
|
17
|
+
const v = copy(parent);
|
|
18
|
+
for (let i = 0; i < v.length; i++) {
|
|
19
|
+
v[i] *= Math.sqrt(1 - this.config.roughness);
|
|
20
|
+
}
|
|
21
|
+
addInto(v, randomUnit(D, rand), Math.sqrt(this.config.roughness));
|
|
22
|
+
return normalize(v);
|
|
23
|
+
};
|
|
24
|
+
const coarse = [];
|
|
25
|
+
for (let i = 0; i < 16; i++)
|
|
26
|
+
coarse.push(randomUnit(D, rand));
|
|
27
|
+
const mid = [];
|
|
28
|
+
for (let i = 0; i < 64; i++)
|
|
29
|
+
mid.push(refine(coarse[i >> 2]));
|
|
30
|
+
for (let b = 0; b < 256; b++)
|
|
31
|
+
this.vecs.push(refine(mid[b >> 2]));
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { type Value, type ValueCodec } from "./value.js";
|
|
2
|
+
import { OperationRegistry, type ResonanceSync } from "./operation.js";
|
|
3
|
+
import { ExprGrammar } from "./expr.js";
|
|
4
|
+
import type { ConceptAnchor } from "./resonance.js";
|
|
5
|
+
import { type AluHost, type ComputedSpan } from "./parser.js";
|
|
6
|
+
/** A numeric literal found in the byte stream, with its parsed value. */
|
|
7
|
+
export interface OperandSpan {
|
|
8
|
+
i: number;
|
|
9
|
+
j: number;
|
|
10
|
+
value: Value;
|
|
11
|
+
}
|
|
12
|
+
/** A recognised operator span: the byte range and the canonical op it names. */
|
|
13
|
+
export interface OperatorSpan {
|
|
14
|
+
i: number;
|
|
15
|
+
j: number;
|
|
16
|
+
name: string;
|
|
17
|
+
/** Operand count for INFIX use — a fixed arity as registered, or 2 for a
|
|
18
|
+
* variadic op used as a binary infix operator. */
|
|
19
|
+
arity: number;
|
|
20
|
+
}
|
|
21
|
+
/** Options for assembling an {@link Alu}. */
|
|
22
|
+
export interface AluOptions {
|
|
23
|
+
/** Decimal places a real result is rounded to before encoding (determinism). */
|
|
24
|
+
precision?: number;
|
|
25
|
+
/** Numerical convergence tolerance and iteration ceiling. */
|
|
26
|
+
tol?: number;
|
|
27
|
+
maxIter?: number;
|
|
28
|
+
}
|
|
29
|
+
export declare class Alu {
|
|
30
|
+
readonly registry: OperationRegistry;
|
|
31
|
+
readonly codec: ValueCodec;
|
|
32
|
+
private readonly rt;
|
|
33
|
+
/** Symbolic operator forms (no ASCII letter/digit), as byte patterns, sorted
|
|
34
|
+
* longest-first so the scanner matches "<=" before "<". */
|
|
35
|
+
private readonly symbolicForms;
|
|
36
|
+
private _grammar?;
|
|
37
|
+
private _anchors?;
|
|
38
|
+
/** How many {@link apply} calls ended in a caught throw this session, and
|
|
39
|
+
* the most recent caught error. A caught throw is USUALLY a routine
|
|
40
|
+
* decline (a symbol fed to arithmetic — the "rule does not fire"
|
|
41
|
+
* contract), but the same catch would also swallow a genuine kernel bug;
|
|
42
|
+
* these two fields make that observable instead of silent. Zero cost when
|
|
43
|
+
* nothing throws. */
|
|
44
|
+
applyCaught: number;
|
|
45
|
+
lastApplyError: unknown;
|
|
46
|
+
private readonly decoder;
|
|
47
|
+
/** The query parser, wired to the host port — internal; hosts reach it only
|
|
48
|
+
* through {@link parse} and {@link compute}. */
|
|
49
|
+
private readonly parser;
|
|
50
|
+
constructor(opts?: AluOptions, host?: AluHost);
|
|
51
|
+
/** Recognise and evaluate every computation `query` invokes — infix
|
|
52
|
+
* arithmetic runs, and operations named literally or by meaning (through the
|
|
53
|
+
* host port). All async resonance is resolved inside, so the caller
|
|
54
|
+
* receives finished spans it can fold synchronously into its search. See
|
|
55
|
+
* {@link "./parser.js".QueryParser.parse}. */
|
|
56
|
+
parse(query: Uint8Array): Promise<ComputedSpan[]>;
|
|
57
|
+
/** Apply an operation to operand byte spans — operand STRUCTURE recognised
|
|
58
|
+
* into Values, every reachable symbol's resonance pre-resolved through the
|
|
59
|
+
* host port — and encode the result canonically; null when the computation
|
|
60
|
+
* declines. See {@link "./parser.js".QueryParser.compute}. */
|
|
61
|
+
compute(name: string, operandBytes: Uint8Array[], asSymbol?: (idx: number) => boolean): Promise<Uint8Array | null>;
|
|
62
|
+
/** Infix arity of an op: its fixed arity, or 2 for a variadic op (an infix
|
|
63
|
+
* operator binds two operands; the registry's variadic fold still accepts
|
|
64
|
+
* the pair). */
|
|
65
|
+
private infixArity;
|
|
66
|
+
/** Collect the symbolic surface forms (punctuation, no letters/digits) as
|
|
67
|
+
* UTF-8 byte patterns. Each maps to the binary claimant when one exists, so
|
|
68
|
+
* an infix scan resolves a shared symbol to its two-operand reading. */
|
|
69
|
+
private buildSymbolicForms;
|
|
70
|
+
/** The canonical op name(s) a literal surface form names (exact lookup). */
|
|
71
|
+
lookupOperator(form: string): readonly string[];
|
|
72
|
+
/** The operation CONCEPT anchors: the (canonical name, form bytes) pairs a
|
|
73
|
+
* span's MEANING is resonated against, so an operation the bytes do not
|
|
74
|
+
* literally spell (an integral, a derivative, a limit, …, in any modality)
|
|
75
|
+
* is recognised by gist nearness to one of these forms. This is what makes
|
|
76
|
+
* operation recognition generic and modality-agnostic rather than a fixed
|
|
77
|
+
* symbol table — and the ALU, not the host, decides which of its surface
|
|
78
|
+
* forms are anchors, using its own machinery:
|
|
79
|
+
*
|
|
80
|
+
* • a form the SCANNER already reads in full (a pure operator symbol like
|
|
81
|
+
* "<=", a numeral like "0") is excluded — the literal path owns it, and
|
|
82
|
+
* its meaning-space image would only add noise;
|
|
83
|
+
* • a form must be COMPOUND (≥ 2 runes): a single atom's gist is a
|
|
84
|
+
* coordinate of the alphabet, not a distributional meaning, so there is
|
|
85
|
+
* nothing for resonance to read.
|
|
86
|
+
*
|
|
87
|
+
* Cached once; the stable array identity lets the host memoise whatever
|
|
88
|
+
* representation (gists, indices) it derives from it. */
|
|
89
|
+
conceptAnchors(): ReadonlyArray<ConceptAnchor>;
|
|
90
|
+
/** The registry-derived expression grammar, built once: infix binding and
|
|
91
|
+
* prefix/function/constant resolution all read off the registered ops, and
|
|
92
|
+
* every evaluation step routes back through this registry's own arithmetic —
|
|
93
|
+
* recursion all the way down (see expr.ts). */
|
|
94
|
+
get grammar(): ExprGrammar;
|
|
95
|
+
/** Evaluate an expression's bytes at a variable binding, through this
|
|
96
|
+
* registry's own arithmetic (see {@link grammar}). */
|
|
97
|
+
evalExpression(bytes: Uint8Array, variable: string, at: number): number | null;
|
|
98
|
+
/** Whether a name is a registered operation. */
|
|
99
|
+
has(name: string): boolean;
|
|
100
|
+
/** The infix arity of a registered op (for the host to size a rule), or 0. */
|
|
101
|
+
arityOf(name: string): number;
|
|
102
|
+
/** Whether an op acts on an EXPRESSION (a function) rather than plain numbers
|
|
103
|
+
* — declared by the op itself at registration (the `expression` trait), so
|
|
104
|
+
* there is no side table of names here. */
|
|
105
|
+
isExpressionOp(name: string): boolean;
|
|
106
|
+
/** Scan a byte span for operand (numeric) and operator (symbolic) spans. A
|
|
107
|
+
* pure, deterministic left-to-right lexer: at each position take a numeral if
|
|
108
|
+
* one starts there, else the longest symbolic operator form, else skip one
|
|
109
|
+
* byte. Numerals and operator symbols are disjoint character classes, so the
|
|
110
|
+
* two never overlap. */
|
|
111
|
+
scan(bytes: Uint8Array): {
|
|
112
|
+
operands: OperandSpan[];
|
|
113
|
+
operators: OperatorSpan[];
|
|
114
|
+
};
|
|
115
|
+
private matchSymbolic;
|
|
116
|
+
/** Read a byte span into a {@link Value} by recognising its STRUCTURE — the
|
|
117
|
+
* byte⇄Value boundary the host computes across. The kernel itself only knows
|
|
118
|
+
* the irreducible scalar floor (a numeral's digits → a quantity, via {@link
|
|
119
|
+
* parseValue}); recognising whether a span is one quantity or a LIST of them is
|
|
120
|
+
* layered here, over {@link scan}, so no caller re-implements it.
|
|
121
|
+
*
|
|
122
|
+
* A LIST is a run of element values joined by a CONSISTENT separator. No
|
|
123
|
+
* spelling is privileged: two complementary readings cover the forms a list
|
|
124
|
+
* takes —
|
|
125
|
+
*
|
|
126
|
+
* • CONTAINER — an explicit `[ … ]` group delimits a list whose elements may
|
|
127
|
+
* be anything (symbols, nested groups, mixed): split its interior at the TOP
|
|
128
|
+
* level (bracket-depth aware) on separator runs, each element recognised in
|
|
129
|
+
* turn (so nesting and heterogeneity recurse for free). This is also the
|
|
130
|
+
* codec's canonical OUTPUT spelling, so a computed list feeds straight back
|
|
131
|
+
* in as an operand.
|
|
132
|
+
* • SEQUENCE — a bare run of ≥2 numeric operands with a consistent connective
|
|
133
|
+
* between them (`1 2 3`, `1, 2, 3`, `1 and 2 and 3`): the operands {@link
|
|
134
|
+
* scan} finds are the elements, and whatever sits between them — a space, a
|
|
135
|
+
* comma, " and " — is the separator, accepted as long as it is the same
|
|
136
|
+
* throughout and the run has no leftover edges.
|
|
137
|
+
*
|
|
138
|
+
* Anything else is a SCALAR ({@link parseValue}): a numeral, or an opaque
|
|
139
|
+
* symbol of any modality (a learnt form, an operator name a higher-order op
|
|
140
|
+
* will resolve, a single word). */
|
|
141
|
+
recogniseValue(bytes: Uint8Array): Value;
|
|
142
|
+
/** Split a CONTAINER's interior into its element values — top-level (bracket-
|
|
143
|
+
* depth aware) spans divided by separator RUNS (maximal runs of {@link
|
|
144
|
+
* isSepByte}). The brackets are the explicit delimiter, so the divider's
|
|
145
|
+
* spelling is not privileged (`[1,2,3]`, `[1, 2, 3]`, `[1 2 3]` are the same
|
|
146
|
+
* list). Each element is recognised in turn, so a nested `[ … ]` element
|
|
147
|
+
* recurses and a symbol element stays opaque. An empty interior is `[]`. */
|
|
148
|
+
private recogniseContainer;
|
|
149
|
+
/** Recognise a bare SEQUENCE — ≥2 numeric operands separated by a consistent
|
|
150
|
+
* connective, with no leftover material at the edges — or null when the span
|
|
151
|
+
* is not such a sequence. The operands are exactly the ones {@link scan}
|
|
152
|
+
* finds; the bytes between consecutive operands are the separator, which need
|
|
153
|
+
* only be the SAME throughout (a space, a comma, " and ", …) — its spelling is
|
|
154
|
+
* not constrained, so no separator is privileged. */
|
|
155
|
+
private recogniseSequence;
|
|
156
|
+
/** Apply an op to operand values, with the given pre-resolved resonance.
|
|
157
|
+
* Returns the result value, or null if the op is unknown or the computation
|
|
158
|
+
* throws (e.g. a symbol fed to arithmetic) — the caller treats null as "this
|
|
159
|
+
* rule does not fire", never as a wrong answer. */
|
|
160
|
+
apply(name: string, operands: Value[], resonance?: ResonanceSync): Value | null;
|
|
161
|
+
/** The expression evaluator handed to op contexts, bound to the cached {@link
|
|
162
|
+
* grammar}: the numerical layer's integrand is evaluated by a recursive
|
|
163
|
+
* application of the same derived-from-nand arithmetic. */
|
|
164
|
+
private makeEvalExpr;
|
|
165
|
+
/** Decode operand byte spans, apply `name`, and encode the result — the pure
|
|
166
|
+
* computation the graph rule materialises into an output span. Returns null
|
|
167
|
+
* on any failure (unknown op, undecodable operand, thrown computation), so a
|
|
168
|
+
* rule that cannot compute simply does not fire. The result bytes are
|
|
169
|
+
* canonical (see {@link decimalCodec}), so two derivations of the same value
|
|
170
|
+
* agree byte-for-byte — required for the search's chart memoization. */
|
|
171
|
+
applyBytes(name: string, operandBytes: Uint8Array[], resonance?: ResonanceSync): Uint8Array | null;
|
|
172
|
+
/** Apply `name` to operand VALUES (a scalar, or an `nd` recognised by {@link
|
|
173
|
+
* recogniseValue}), and encode the result canonically. This is the entry
|
|
174
|
+
* point for computation over STRUCTURE: the scalar kernel and the nd kernel
|
|
175
|
+
* both consume Values, so once a span is recognised the computation is the
|
|
176
|
+
* same whether the operand came in as a number or a list. Returns null on any
|
|
177
|
+
* failure (unknown op, thrown computation), the same "this rule does not fire"
|
|
178
|
+
* contract as {@link applyBytes}. */
|
|
179
|
+
applyValues(name: string, operands: Value[], resonance?: ResonanceSync): Uint8Array | null;
|
|
180
|
+
/** Like {@link applyBytes}, but `asSymbol(idx)` marks operand positions that
|
|
181
|
+
* must be kept as an opaque SYMBOL (not parsed as a number) — the convention
|
|
182
|
+
* the numerical layer needs, where operand 0 is an EXPRESSION (a function's
|
|
183
|
+
* bytes) the kernel samples via the expression evaluator, not a numeral. */
|
|
184
|
+
applyBytesTyped(name: string, operandBytes: Uint8Array[], asSymbol: (idx: number) => boolean, resonance?: ResonanceSync): Uint8Array | null;
|
|
185
|
+
}
|
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
// alu.ts — the assembled ALU: registry + the synchronous recogniser the search
|
|
2
|
+
// consults.
|
|
3
|
+
//
|
|
4
|
+
// `Alu` wires the kernels into one OperationRegistry and exposes exactly what a
|
|
5
|
+
// host needs to fold computation into its lightest-derivation search:
|
|
6
|
+
//
|
|
7
|
+
// • scan(bytes) — find OPERAND spans (numeric literals) and OPERATOR
|
|
8
|
+
// spans (literal symbolic forms) directly in the raw
|
|
9
|
+
// bytes, independent of any host chunking.
|
|
10
|
+
// • recogniseValue — read a byte span into a Value: a scalar, or a LIST (a
|
|
11
|
+
// run of element values joined by a consistent separator
|
|
12
|
+
// — `[1,2,3]`, `1 2 3`, `1, 2, 3`, none privileged).
|
|
13
|
+
// • lookupOperator — the canonical op(s) a literal surface form names.
|
|
14
|
+
// • applyValues — apply an op to operand VALUES, encode the result.
|
|
15
|
+
// • applyBytes — decode operand spans, apply an op, encode the result;
|
|
16
|
+
// the pure computation a graph rule materialises.
|
|
17
|
+
// • grammar — the registry-derived expression grammar (expr.ts),
|
|
18
|
+
// through which infix runs and integrands evaluate by
|
|
19
|
+
// a recursive application of the same kernel.
|
|
20
|
+
//
|
|
21
|
+
// The facade is also the sub-library's ONE doorway for a host: it is built
|
|
22
|
+
// over an {@link "./parser.js".AluHost} port (resonance + geometry — by default
|
|
23
|
+
// a structural stub, so the ALU runs fully decoupled) and exposes
|
|
24
|
+
//
|
|
25
|
+
// • parse(query) — recognise and evaluate every computation a raw byte
|
|
26
|
+
// query invokes (the query parser, parser.ts);
|
|
27
|
+
// • compute(name, …) — apply an operation to operand byte spans, structure
|
|
28
|
+
// recognised and resonance pre-resolved (the
|
|
29
|
+
// n-dimensional entry point).
|
|
30
|
+
//
|
|
31
|
+
// Operations recognised by MEANING — a synonym form ("plus", "increased by"), a
|
|
32
|
+
// glyph, or an operation the bytes do not spell at all (an integral, a limit) —
|
|
33
|
+
// are resolved only through the host port; the kernel itself stays a pure,
|
|
34
|
+
// deterministic machine over literal numerals and registered surface forms.
|
|
35
|
+
import { asReal, decimalCodec, nd, parseValue, real, } from "./value.js";
|
|
36
|
+
import { NO_RESONANCE, OperationRegistry, } from "./operation.js";
|
|
37
|
+
import { registerLogic } from "./kernel-logic.js";
|
|
38
|
+
import { registerBits } from "./kernel-bits.js";
|
|
39
|
+
import { registerArith } from "./kernel-arith.js";
|
|
40
|
+
import { registerNumeric } from "./kernel-numeric.js";
|
|
41
|
+
import { registerNd } from "./kernel-nd.js";
|
|
42
|
+
import { ExprGrammar } from "./expr.js";
|
|
43
|
+
import { QueryParser, STRUCTURAL_HOST, } from "./parser.js";
|
|
44
|
+
import { CLOSE, DOT, isDigitByte, isSepByte, matchBracket, OPEN, trimEnd, trimStart, } from "./text.js";
|
|
45
|
+
import { latin1 } from "../../bytes.js";
|
|
46
|
+
export class Alu {
|
|
47
|
+
registry = new OperationRegistry();
|
|
48
|
+
codec;
|
|
49
|
+
rt;
|
|
50
|
+
/** Symbolic operator forms (no ASCII letter/digit), as byte patterns, sorted
|
|
51
|
+
* longest-first so the scanner matches "<=" before "<". */
|
|
52
|
+
symbolicForms;
|
|
53
|
+
_grammar;
|
|
54
|
+
_anchors;
|
|
55
|
+
/** How many {@link apply} calls ended in a caught throw this session, and
|
|
56
|
+
* the most recent caught error. A caught throw is USUALLY a routine
|
|
57
|
+
* decline (a symbol fed to arithmetic — the "rule does not fire"
|
|
58
|
+
* contract), but the same catch would also swallow a genuine kernel bug;
|
|
59
|
+
* these two fields make that observable instead of silent. Zero cost when
|
|
60
|
+
* nothing throws. */
|
|
61
|
+
applyCaught = 0;
|
|
62
|
+
lastApplyError = null;
|
|
63
|
+
decoder = new TextDecoder();
|
|
64
|
+
/** The query parser, wired to the host port — internal; hosts reach it only
|
|
65
|
+
* through {@link parse} and {@link compute}. */
|
|
66
|
+
parser;
|
|
67
|
+
constructor(opts = {}, host = STRUCTURAL_HOST) {
|
|
68
|
+
const precision = opts.precision ?? 6;
|
|
69
|
+
this.codec = decimalCodec(precision);
|
|
70
|
+
this.rt = { tol: opts.tol ?? 1e-10, maxIter: opts.maxIter ?? 1000 };
|
|
71
|
+
registerLogic(this.registry);
|
|
72
|
+
registerBits(this.registry);
|
|
73
|
+
registerArith(this.registry);
|
|
74
|
+
registerNumeric(this.registry);
|
|
75
|
+
registerNd(this.registry);
|
|
76
|
+
this.symbolicForms = this.buildSymbolicForms();
|
|
77
|
+
this.parser = new QueryParser(this, host);
|
|
78
|
+
}
|
|
79
|
+
/** Recognise and evaluate every computation `query` invokes — infix
|
|
80
|
+
* arithmetic runs, and operations named literally or by meaning (through the
|
|
81
|
+
* host port). All async resonance is resolved inside, so the caller
|
|
82
|
+
* receives finished spans it can fold synchronously into its search. See
|
|
83
|
+
* {@link "./parser.js".QueryParser.parse}. */
|
|
84
|
+
parse(query) {
|
|
85
|
+
return this.parser.parse(query);
|
|
86
|
+
}
|
|
87
|
+
/** Apply an operation to operand byte spans — operand STRUCTURE recognised
|
|
88
|
+
* into Values, every reachable symbol's resonance pre-resolved through the
|
|
89
|
+
* host port — and encode the result canonically; null when the computation
|
|
90
|
+
* declines. See {@link "./parser.js".QueryParser.compute}. */
|
|
91
|
+
compute(name, operandBytes, asSymbol = () => false) {
|
|
92
|
+
return this.parser.compute(name, operandBytes, asSymbol);
|
|
93
|
+
}
|
|
94
|
+
/** Infix arity of an op: its fixed arity, or 2 for a variadic op (an infix
|
|
95
|
+
* operator binds two operands; the registry's variadic fold still accepts
|
|
96
|
+
* the pair). */
|
|
97
|
+
infixArity(op) {
|
|
98
|
+
return op.arity === "variadic" ? 2 : op.arity;
|
|
99
|
+
}
|
|
100
|
+
/** Collect the symbolic surface forms (punctuation, no letters/digits) as
|
|
101
|
+
* UTF-8 byte patterns. Each maps to the binary claimant when one exists, so
|
|
102
|
+
* an infix scan resolves a shared symbol to its two-operand reading. */
|
|
103
|
+
buildSymbolicForms() {
|
|
104
|
+
const enc = new TextEncoder();
|
|
105
|
+
const isSymbolic = (s) => s.length > 0 && !/[A-Za-z0-9]/.test(s);
|
|
106
|
+
const byForm = new Map();
|
|
107
|
+
for (const { form, name } of this.registry.formEntries()) {
|
|
108
|
+
if (!isSymbolic(form))
|
|
109
|
+
continue;
|
|
110
|
+
const a = byForm.get(form);
|
|
111
|
+
if (a)
|
|
112
|
+
a.push(name);
|
|
113
|
+
else
|
|
114
|
+
byForm.set(form, [name]);
|
|
115
|
+
}
|
|
116
|
+
const out = [];
|
|
117
|
+
for (const [form, names] of byForm) {
|
|
118
|
+
// Prefer a binary/variadic claimant for infix matching.
|
|
119
|
+
let chosen = names[0];
|
|
120
|
+
let chosenArity = this.infixArity(this.registry.get(chosen));
|
|
121
|
+
for (const n of names) {
|
|
122
|
+
const a = this.infixArity(this.registry.get(n));
|
|
123
|
+
if (a === 2) {
|
|
124
|
+
chosen = n;
|
|
125
|
+
chosenArity = a;
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
out.push({ bytes: enc.encode(form), name: chosen, arity: chosenArity });
|
|
130
|
+
}
|
|
131
|
+
// Longest first so a longer form wins over a prefix of it ("<=" before "<").
|
|
132
|
+
out.sort((a, b) => b.bytes.length - a.bytes.length);
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
/** The canonical op name(s) a literal surface form names (exact lookup). */
|
|
136
|
+
lookupOperator(form) {
|
|
137
|
+
return this.registry.lookupForm(form);
|
|
138
|
+
}
|
|
139
|
+
/** The operation CONCEPT anchors: the (canonical name, form bytes) pairs a
|
|
140
|
+
* span's MEANING is resonated against, so an operation the bytes do not
|
|
141
|
+
* literally spell (an integral, a derivative, a limit, …, in any modality)
|
|
142
|
+
* is recognised by gist nearness to one of these forms. This is what makes
|
|
143
|
+
* operation recognition generic and modality-agnostic rather than a fixed
|
|
144
|
+
* symbol table — and the ALU, not the host, decides which of its surface
|
|
145
|
+
* forms are anchors, using its own machinery:
|
|
146
|
+
*
|
|
147
|
+
* • a form the SCANNER already reads in full (a pure operator symbol like
|
|
148
|
+
* "<=", a numeral like "0") is excluded — the literal path owns it, and
|
|
149
|
+
* its meaning-space image would only add noise;
|
|
150
|
+
* • a form must be COMPOUND (≥ 2 runes): a single atom's gist is a
|
|
151
|
+
* coordinate of the alphabet, not a distributional meaning, so there is
|
|
152
|
+
* nothing for resonance to read.
|
|
153
|
+
*
|
|
154
|
+
* Cached once; the stable array identity lets the host memoise whatever
|
|
155
|
+
* representation (gists, indices) it derives from it. */
|
|
156
|
+
conceptAnchors() {
|
|
157
|
+
if (this._anchors)
|
|
158
|
+
return this._anchors;
|
|
159
|
+
const enc = new TextEncoder();
|
|
160
|
+
const out = [];
|
|
161
|
+
for (const { form, name } of this.registry.formEntries()) {
|
|
162
|
+
if ([...form].length < 2)
|
|
163
|
+
continue; // a lone atom carries no gist
|
|
164
|
+
const bytes = enc.encode(form);
|
|
165
|
+
// Fully claimed by the literal scanner → the literal path owns it.
|
|
166
|
+
const { operands, operators } = this.scan(bytes);
|
|
167
|
+
let claimed = 0;
|
|
168
|
+
for (const t of [...operands, ...operators])
|
|
169
|
+
claimed += t.j - t.i;
|
|
170
|
+
if (claimed === bytes.length)
|
|
171
|
+
continue;
|
|
172
|
+
out.push({ name, form: bytes });
|
|
173
|
+
}
|
|
174
|
+
return (this._anchors = out);
|
|
175
|
+
}
|
|
176
|
+
/** The registry-derived expression grammar, built once: infix binding and
|
|
177
|
+
* prefix/function/constant resolution all read off the registered ops, and
|
|
178
|
+
* every evaluation step routes back through this registry's own arithmetic —
|
|
179
|
+
* recursion all the way down (see expr.ts). */
|
|
180
|
+
get grammar() {
|
|
181
|
+
if (!this._grammar) {
|
|
182
|
+
const scalarCtx = this.registry.context(NO_RESONANCE, this.rt);
|
|
183
|
+
this._grammar = new ExprGrammar(this.registry, (name, args) => asReal(scalarCtx.apply(name, args.map(real))));
|
|
184
|
+
}
|
|
185
|
+
return this._grammar;
|
|
186
|
+
}
|
|
187
|
+
/** Evaluate an expression's bytes at a variable binding, through this
|
|
188
|
+
* registry's own arithmetic (see {@link grammar}). */
|
|
189
|
+
evalExpression(bytes, variable, at) {
|
|
190
|
+
return this.grammar.eval(this.decoder.decode(bytes), variable, at);
|
|
191
|
+
}
|
|
192
|
+
/** Whether a name is a registered operation. */
|
|
193
|
+
has(name) {
|
|
194
|
+
return this.registry.has(name);
|
|
195
|
+
}
|
|
196
|
+
/** The infix arity of a registered op (for the host to size a rule), or 0. */
|
|
197
|
+
arityOf(name) {
|
|
198
|
+
const op = this.registry.get(name);
|
|
199
|
+
return op ? this.infixArity(op) : 0;
|
|
200
|
+
}
|
|
201
|
+
/** Whether an op acts on an EXPRESSION (a function) rather than plain numbers
|
|
202
|
+
* — declared by the op itself at registration (the `expression` trait), so
|
|
203
|
+
* there is no side table of names here. */
|
|
204
|
+
isExpressionOp(name) {
|
|
205
|
+
return this.registry.get(name)?.expression === true;
|
|
206
|
+
}
|
|
207
|
+
/** Scan a byte span for operand (numeric) and operator (symbolic) spans. A
|
|
208
|
+
* pure, deterministic left-to-right lexer: at each position take a numeral if
|
|
209
|
+
* one starts there, else the longest symbolic operator form, else skip one
|
|
210
|
+
* byte. Numerals and operator symbols are disjoint character classes, so the
|
|
211
|
+
* two never overlap. */
|
|
212
|
+
scan(bytes) {
|
|
213
|
+
const operands = [];
|
|
214
|
+
const operators = [];
|
|
215
|
+
const n = bytes.length;
|
|
216
|
+
let i = 0;
|
|
217
|
+
while (i < n) {
|
|
218
|
+
const c = bytes[i];
|
|
219
|
+
// A numeral: a run of digits, with at most one interior decimal point that
|
|
220
|
+
// is itself flanked by digits (so a trailing "." is left to the operators
|
|
221
|
+
// / skip path, not swallowed).
|
|
222
|
+
if (isDigitByte(c) || (c === DOT && i + 1 < n && isDigitByte(bytes[i + 1]))) {
|
|
223
|
+
let j = i;
|
|
224
|
+
let seenDot = false;
|
|
225
|
+
while (j < n) {
|
|
226
|
+
if (isDigitByte(bytes[j])) {
|
|
227
|
+
j++;
|
|
228
|
+
}
|
|
229
|
+
else if (bytes[j] === DOT && !seenDot && j + 1 < n &&
|
|
230
|
+
isDigitByte(bytes[j + 1])) {
|
|
231
|
+
seenDot = true;
|
|
232
|
+
j++;
|
|
233
|
+
}
|
|
234
|
+
else
|
|
235
|
+
break;
|
|
236
|
+
}
|
|
237
|
+
operands.push({ i, j, value: parseValue(bytes.subarray(i, j)) });
|
|
238
|
+
i = j;
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
// The longest symbolic operator form starting here.
|
|
242
|
+
const op = this.matchSymbolic(bytes, i);
|
|
243
|
+
if (op) {
|
|
244
|
+
operators.push({
|
|
245
|
+
i,
|
|
246
|
+
j: i + op.bytes.length,
|
|
247
|
+
name: op.name,
|
|
248
|
+
arity: op.arity,
|
|
249
|
+
});
|
|
250
|
+
i += op.bytes.length;
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
i++;
|
|
254
|
+
}
|
|
255
|
+
return { operands, operators };
|
|
256
|
+
}
|
|
257
|
+
matchSymbolic(bytes, at) {
|
|
258
|
+
for (const f of this.symbolicForms) {
|
|
259
|
+
const len = f.bytes.length;
|
|
260
|
+
if (at + len > bytes.length)
|
|
261
|
+
continue;
|
|
262
|
+
let ok = true;
|
|
263
|
+
for (let k = 0; k < len; k++) {
|
|
264
|
+
if (bytes[at + k] !== f.bytes[k]) {
|
|
265
|
+
ok = false;
|
|
266
|
+
break;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
if (ok)
|
|
270
|
+
return f;
|
|
271
|
+
}
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
/** Read a byte span into a {@link Value} by recognising its STRUCTURE — the
|
|
275
|
+
* byte⇄Value boundary the host computes across. The kernel itself only knows
|
|
276
|
+
* the irreducible scalar floor (a numeral's digits → a quantity, via {@link
|
|
277
|
+
* parseValue}); recognising whether a span is one quantity or a LIST of them is
|
|
278
|
+
* layered here, over {@link scan}, so no caller re-implements it.
|
|
279
|
+
*
|
|
280
|
+
* A LIST is a run of element values joined by a CONSISTENT separator. No
|
|
281
|
+
* spelling is privileged: two complementary readings cover the forms a list
|
|
282
|
+
* takes —
|
|
283
|
+
*
|
|
284
|
+
* • CONTAINER — an explicit `[ … ]` group delimits a list whose elements may
|
|
285
|
+
* be anything (symbols, nested groups, mixed): split its interior at the TOP
|
|
286
|
+
* level (bracket-depth aware) on separator runs, each element recognised in
|
|
287
|
+
* turn (so nesting and heterogeneity recurse for free). This is also the
|
|
288
|
+
* codec's canonical OUTPUT spelling, so a computed list feeds straight back
|
|
289
|
+
* in as an operand.
|
|
290
|
+
* • SEQUENCE — a bare run of ≥2 numeric operands with a consistent connective
|
|
291
|
+
* between them (`1 2 3`, `1, 2, 3`, `1 and 2 and 3`): the operands {@link
|
|
292
|
+
* scan} finds are the elements, and whatever sits between them — a space, a
|
|
293
|
+
* comma, " and " — is the separator, accepted as long as it is the same
|
|
294
|
+
* throughout and the run has no leftover edges.
|
|
295
|
+
*
|
|
296
|
+
* Anything else is a SCALAR ({@link parseValue}): a numeral, or an opaque
|
|
297
|
+
* symbol of any modality (a learnt form, an operator name a higher-order op
|
|
298
|
+
* will resolve, a single word). */
|
|
299
|
+
recogniseValue(bytes) {
|
|
300
|
+
const s = bytes.subarray(trimStart(bytes), trimEnd(bytes));
|
|
301
|
+
// CONTAINER: a balanced [ … ] group spanning the whole (trimmed) span.
|
|
302
|
+
if (s.length >= 2 && s[0] === OPEN && matchBracket(s, 0) === s.length - 1) {
|
|
303
|
+
return nd(this.recogniseContainer(s.subarray(1, s.length - 1)));
|
|
304
|
+
}
|
|
305
|
+
// SEQUENCE: ≥2 numeric operands with a consistent connective between them.
|
|
306
|
+
const seq = this.recogniseSequence(s);
|
|
307
|
+
if (seq !== null)
|
|
308
|
+
return nd(seq);
|
|
309
|
+
// SCALAR floor.
|
|
310
|
+
return parseValue(s);
|
|
311
|
+
}
|
|
312
|
+
/** Split a CONTAINER's interior into its element values — top-level (bracket-
|
|
313
|
+
* depth aware) spans divided by separator RUNS (maximal runs of {@link
|
|
314
|
+
* isSepByte}). The brackets are the explicit delimiter, so the divider's
|
|
315
|
+
* spelling is not privileged (`[1,2,3]`, `[1, 2, 3]`, `[1 2 3]` are the same
|
|
316
|
+
* list). Each element is recognised in turn, so a nested `[ … ]` element
|
|
317
|
+
* recurses and a symbol element stays opaque. An empty interior is `[]`. */
|
|
318
|
+
recogniseContainer(inner) {
|
|
319
|
+
if (trimEnd(inner) <= trimStart(inner))
|
|
320
|
+
return []; // empty / all space → []
|
|
321
|
+
const elements = [];
|
|
322
|
+
let depth = 0;
|
|
323
|
+
let start = 0;
|
|
324
|
+
let p = 0;
|
|
325
|
+
while (p < inner.length) {
|
|
326
|
+
const c = inner[p];
|
|
327
|
+
if (c === OPEN)
|
|
328
|
+
depth++;
|
|
329
|
+
else if (c === CLOSE)
|
|
330
|
+
depth--;
|
|
331
|
+
if (depth === 0 && isSepByte(c)) {
|
|
332
|
+
let q = p;
|
|
333
|
+
while (q < inner.length && isSepByte(inner[q]))
|
|
334
|
+
q++;
|
|
335
|
+
elements.push(inner.subarray(start, p));
|
|
336
|
+
start = q;
|
|
337
|
+
p = q;
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
p++;
|
|
341
|
+
}
|
|
342
|
+
elements.push(inner.subarray(start));
|
|
343
|
+
return elements.map((e) => this.recogniseValue(e));
|
|
344
|
+
}
|
|
345
|
+
/** Recognise a bare SEQUENCE — ≥2 numeric operands separated by a consistent
|
|
346
|
+
* connective, with no leftover material at the edges — or null when the span
|
|
347
|
+
* is not such a sequence. The operands are exactly the ones {@link scan}
|
|
348
|
+
* finds; the bytes between consecutive operands are the separator, which need
|
|
349
|
+
* only be the SAME throughout (a space, a comma, " and ", …) — its spelling is
|
|
350
|
+
* not constrained, so no separator is privileged. */
|
|
351
|
+
recogniseSequence(s) {
|
|
352
|
+
const { operands } = this.scan(s);
|
|
353
|
+
if (operands.length < 2)
|
|
354
|
+
return null;
|
|
355
|
+
// No leftover before the first operand or after the last (a clean sequence).
|
|
356
|
+
if (trimStart(s) !== operands[0].i)
|
|
357
|
+
return null;
|
|
358
|
+
if (trimEnd(s) !== operands[operands.length - 1].j)
|
|
359
|
+
return null;
|
|
360
|
+
let sep = null;
|
|
361
|
+
for (let k = 0; k + 1 < operands.length; k++) {
|
|
362
|
+
const gap = latin1(s.subarray(operands[k].j, operands[k + 1].i));
|
|
363
|
+
if (gap.length === 0)
|
|
364
|
+
return null; // operands must be separated
|
|
365
|
+
if (sep === null)
|
|
366
|
+
sep = gap;
|
|
367
|
+
else if (gap !== sep)
|
|
368
|
+
return null; // inconsistent → not one sequence
|
|
369
|
+
}
|
|
370
|
+
return operands.map((o) => this.recogniseValue(s.subarray(o.i, o.j)));
|
|
371
|
+
}
|
|
372
|
+
/** Apply an op to operand values, with the given pre-resolved resonance.
|
|
373
|
+
* Returns the result value, or null if the op is unknown or the computation
|
|
374
|
+
* throws (e.g. a symbol fed to arithmetic) — the caller treats null as "this
|
|
375
|
+
* rule does not fire", never as a wrong answer. */
|
|
376
|
+
apply(name, operands, resonance = NO_RESONANCE) {
|
|
377
|
+
if (!this.registry.has(name))
|
|
378
|
+
return null;
|
|
379
|
+
try {
|
|
380
|
+
const ctx = this.registry.context(resonance, this.rt, this.makeEvalExpr());
|
|
381
|
+
return ctx.apply(name, operands);
|
|
382
|
+
}
|
|
383
|
+
catch (err) {
|
|
384
|
+
// The "rule does not fire" contract — but never invisibly: the counter
|
|
385
|
+
// and lastApplyError let a debugger distinguish a routine decline from
|
|
386
|
+
// a kernel bug that would otherwise read as "computation unknown".
|
|
387
|
+
this.applyCaught++;
|
|
388
|
+
this.lastApplyError = err;
|
|
389
|
+
return null;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
/** The expression evaluator handed to op contexts, bound to the cached {@link
|
|
393
|
+
* grammar}: the numerical layer's integrand is evaluated by a recursive
|
|
394
|
+
* application of the same derived-from-nand arithmetic. */
|
|
395
|
+
makeEvalExpr() {
|
|
396
|
+
return (bytes, variable, at) => this.grammar.eval(this.decoder.decode(bytes), variable, at);
|
|
397
|
+
}
|
|
398
|
+
/** Decode operand byte spans, apply `name`, and encode the result — the pure
|
|
399
|
+
* computation the graph rule materialises into an output span. Returns null
|
|
400
|
+
* on any failure (unknown op, undecodable operand, thrown computation), so a
|
|
401
|
+
* rule that cannot compute simply does not fire. The result bytes are
|
|
402
|
+
* canonical (see {@link decimalCodec}), so two derivations of the same value
|
|
403
|
+
* agree byte-for-byte — required for the search's chart memoization. */
|
|
404
|
+
applyBytes(name, operandBytes, resonance = NO_RESONANCE) {
|
|
405
|
+
return this.applyBytesTyped(name, operandBytes, () => false, resonance);
|
|
406
|
+
}
|
|
407
|
+
/** Apply `name` to operand VALUES (a scalar, or an `nd` recognised by {@link
|
|
408
|
+
* recogniseValue}), and encode the result canonically. This is the entry
|
|
409
|
+
* point for computation over STRUCTURE: the scalar kernel and the nd kernel
|
|
410
|
+
* both consume Values, so once a span is recognised the computation is the
|
|
411
|
+
* same whether the operand came in as a number or a list. Returns null on any
|
|
412
|
+
* failure (unknown op, thrown computation), the same "this rule does not fire"
|
|
413
|
+
* contract as {@link applyBytes}. */
|
|
414
|
+
applyValues(name, operands, resonance = NO_RESONANCE) {
|
|
415
|
+
const result = this.apply(name, operands, resonance);
|
|
416
|
+
if (result === null)
|
|
417
|
+
return null;
|
|
418
|
+
return this.codec.encode(result);
|
|
419
|
+
}
|
|
420
|
+
/** Like {@link applyBytes}, but `asSymbol(idx)` marks operand positions that
|
|
421
|
+
* must be kept as an opaque SYMBOL (not parsed as a number) — the convention
|
|
422
|
+
* the numerical layer needs, where operand 0 is an EXPRESSION (a function's
|
|
423
|
+
* bytes) the kernel samples via the expression evaluator, not a numeral. */
|
|
424
|
+
applyBytesTyped(name, operandBytes, asSymbol, resonance = NO_RESONANCE) {
|
|
425
|
+
const operands = [];
|
|
426
|
+
for (let i = 0; i < operandBytes.length; i++) {
|
|
427
|
+
const b = operandBytes[i];
|
|
428
|
+
const v = asSymbol(i)
|
|
429
|
+
? { domain: "symbol", bytes: b }
|
|
430
|
+
: this.codec.decode(b);
|
|
431
|
+
if (v === null)
|
|
432
|
+
return null;
|
|
433
|
+
operands.push(v);
|
|
434
|
+
}
|
|
435
|
+
const result = this.apply(name, operands, resonance);
|
|
436
|
+
if (result === null)
|
|
437
|
+
return null;
|
|
438
|
+
return this.codec.encode(result);
|
|
439
|
+
}
|
|
440
|
+
}
|