rei-lang 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE +230 -191
  2. package/PEACE_USE_CLAUSE.md +95 -0
  3. package/README.md +257 -186
  4. package/bin/rei.js +259 -144
  5. package/dist/index.d.mts +257 -0
  6. package/dist/index.d.ts +181 -93
  7. package/dist/index.js +5710 -239
  8. package/dist/index.js.map +1 -1
  9. package/dist/index.mjs +8741 -0
  10. package/dist/index.mjs.map +1 -0
  11. package/package.json +73 -62
  12. package/spec/REI_BNF_v0.2.md +398 -0
  13. package/spec/REI_BNF_v0.3.md +358 -0
  14. package/spec/REI_SPEC_v0.1.md +587 -0
  15. package/theory/LICENSE-THEORY.md +57 -0
  16. package/theory/README.md +85 -0
  17. package/theory/category-c-design.md +502 -0
  18. package/theory/core-theories-11-14.md +799 -0
  19. package/theory/core-theories-15-21.md +675 -0
  20. package/theory/core-theories-8-10.md +582 -0
  21. package/theory/d-fumt-overview.md +99 -0
  22. package/theory/genesis-axiom-system.md +124 -0
  23. package/theory/gft-theory.md +160 -0
  24. package/theory/index.ts +9 -0
  25. package/theory/notation-equivalence.md +134 -0
  26. package/theory/semantic-compressor.ts +903 -0
  27. package/theory/stdlib-tier1-design.md +477 -0
  28. package/theory/theories-11-14.ts +466 -0
  29. package/theory/theories-15-21.ts +762 -0
  30. package/theory/theories-22-28.ts +794 -0
  31. package/theory/theories-29-35.ts +607 -0
  32. package/theory/theories-36-42.ts +937 -0
  33. package/theory/theories-43-49.ts +1298 -0
  34. package/theory/theories-50-56.ts +1449 -0
  35. package/theory/theories-57-66.ts +1724 -0
  36. package/theory/theories-67.ts +1696 -0
  37. package/theory/theories-8-10.ts +284 -0
  38. package/dist/index.cjs +0 -3282
  39. package/dist/index.cjs.map +0 -1
  40. package/dist/index.d.cts +0 -169
package/dist/index.cjs DELETED
@@ -1,3282 +0,0 @@
1
- 'use strict';
2
-
3
- // src/lang/lexer.ts
4
- var TokenType = {
5
- // Literals
6
- NUMBER: "NUMBER",
7
- STRING: "STRING",
8
- EXT_LIT: "EXT_LIT",
9
- SYMBOL_0_0: "SYMBOL_0_0",
10
- SYMBOL_DOT_PRIM: "SYMBOL_DOT_PRIM",
11
- BOOL_TRUE: "BOOL_TRUE",
12
- BOOL_FALSE: "BOOL_FALSE",
13
- // Math constants
14
- CONST_PI: "CONST_PI",
15
- CONST_E: "CONST_E",
16
- CONST_PHI: "CONST_PHI",
17
- CONST_I: "CONST_I",
18
- CONST_PHI_UP: "CONST_PHI_UP",
19
- CONST_PSI_UP: "CONST_PSI_UP",
20
- CONST_OMEGA_UP: "CONST_OMEGA_UP",
21
- CONST_EMPTY: "CONST_EMPTY",
22
- // Quad literals (v0.2)
23
- QUAD_TOP: "QUAD_TOP",
24
- QUAD_BOT: "QUAD_BOT",
25
- QUAD_TOP_PI: "QUAD_TOP_PI",
26
- QUAD_BOT_PI: "QUAD_BOT_PI",
27
- // Keywords
28
- LET: "LET",
29
- MUT: "MUT",
30
- COMPRESS: "COMPRESS",
31
- WEIGHT: "WEIGHT",
32
- GENESIS: "GENESIS",
33
- IF: "IF",
34
- THEN: "THEN",
35
- ELSE: "ELSE",
36
- MATCH: "MATCH",
37
- CASE: "CASE",
38
- WITNESSED: "WITNESSED",
39
- BY: "BY",
40
- TRUE: "TRUE",
41
- FALSE: "FALSE",
42
- NULL: "NULL",
43
- TEMPORAL: "TEMPORAL",
44
- TIMELESS: "TIMELESS",
45
- // ── v0.3 Space-Layer-Diffusion keywords ──
46
- SPACE: "SPACE",
47
- // 空 or "space"
48
- LAYER: "LAYER",
49
- // 層 or "layer"
50
- // Identifiers
51
- IDENT: "IDENT",
52
- // Operators
53
- PLUS: "PLUS",
54
- MINUS: "MINUS",
55
- STAR: "STAR",
56
- SLASH: "SLASH",
57
- OPLUS: "OPLUS",
58
- OTIMES: "OTIMES",
59
- CDOT: "CDOT",
60
- PIPE_OP: "PIPE_OP",
61
- EXTEND: "EXTEND",
62
- REDUCE: "REDUCE",
63
- ASSIGN: "ASSIGN",
64
- DOT: "DOT",
65
- ARROW: "ARROW",
66
- SEMICOLON: "SEMICOLON",
67
- COMMA: "COMMA",
68
- COLON: "COLON",
69
- LPAREN: "LPAREN",
70
- RPAREN: "RPAREN",
71
- LBRACE: "LBRACE",
72
- RBRACE: "RBRACE",
73
- LBRACKET: "LBRACKET",
74
- RBRACKET: "RBRACKET",
75
- CONVERGE: "CONVERGE",
76
- DIVERGE: "DIVERGE",
77
- REFLECT: "REFLECT",
78
- AND: "AND",
79
- OR: "OR",
80
- NOT: "NOT",
81
- GT_K: "GT_K",
82
- LT_K: "LT_K",
83
- EQ_K: "EQ_K",
84
- GT: "GT",
85
- LT: "LT",
86
- EQ: "EQ",
87
- NEQ: "NEQ",
88
- GTE: "GTE",
89
- LTE: "LTE",
90
- MDIM_OPEN: "MDIM_OPEN",
91
- // Special
92
- NEWLINE: "NEWLINE",
93
- EOF: "EOF"
94
- };
95
- var KEYWORDS = {
96
- "let": TokenType.LET,
97
- "mut": TokenType.MUT,
98
- "compress": TokenType.COMPRESS,
99
- "weight": TokenType.WEIGHT,
100
- "genesis": TokenType.GENESIS,
101
- "if": TokenType.IF,
102
- "then": TokenType.THEN,
103
- "else": TokenType.ELSE,
104
- "match": TokenType.MATCH,
105
- "case": TokenType.CASE,
106
- "witnessed": TokenType.WITNESSED,
107
- "by": TokenType.BY,
108
- "true": TokenType.TRUE,
109
- "false": TokenType.FALSE,
110
- "null": TokenType.NULL,
111
- "Temporal": TokenType.TEMPORAL,
112
- "Timeless": TokenType.TIMELESS,
113
- // ── v0.3 ──
114
- "space": TokenType.SPACE,
115
- "layer": TokenType.LAYER
116
- };
117
- var SUBSCRIPT_CHARS = new Set("oxzwensbua".split(""));
118
- var Lexer = class {
119
- constructor(source) {
120
- this.source = source;
121
- this.pos = 0;
122
- this.line = 1;
123
- this.col = 1;
124
- this.tokens = [];
125
- this.chars = Array.from(source);
126
- }
127
- tokenize() {
128
- this.tokens = [];
129
- while (this.pos < this.chars.length) {
130
- this.skipWhitespaceAndComments();
131
- if (this.pos >= this.chars.length) break;
132
- const ch = this.chars[this.pos];
133
- if (ch === "\n") {
134
- this.emit(TokenType.NEWLINE, "\n");
135
- this.advance();
136
- this.line++;
137
- this.col = 1;
138
- continue;
139
- }
140
- if (ch === '"') {
141
- this.readString();
142
- continue;
143
- }
144
- if (ch === "0" && this.peek(1) === "\u2080") {
145
- this.emit(TokenType.SYMBOL_0_0, "0\u2080");
146
- this.advance();
147
- this.advance();
148
- continue;
149
- }
150
- if (ch === "\u{1D544}" && this.peek(1) === "{") {
151
- this.emit(TokenType.MDIM_OPEN, "\u{1D544}{");
152
- this.advance();
153
- this.advance();
154
- continue;
155
- }
156
- if (ch === "\u7A7A") {
157
- this.emit(TokenType.SPACE, "\u7A7A");
158
- this.advance();
159
- continue;
160
- }
161
- if (ch === "\u5C64") {
162
- this.emit(TokenType.LAYER, "\u5C64");
163
- this.advance();
164
- continue;
165
- }
166
- if (this.isExtStart(ch)) {
167
- const ext = this.readExtLit();
168
- if (ext) continue;
169
- }
170
- if (this.isDigit(ch) || ch === "-" && this.isDigit(this.peek(1) ?? "") && this.shouldNegateBePrefix()) {
171
- this.readNumber();
172
- continue;
173
- }
174
- if (this.readUnicodeToken(ch)) continue;
175
- if (this.readMultiCharOp(ch)) continue;
176
- if (this.readSingleCharOp(ch)) continue;
177
- if (this.isIdentStart(ch)) {
178
- this.readIdentOrKeyword();
179
- continue;
180
- }
181
- this.advance();
182
- }
183
- this.emit(TokenType.EOF, "");
184
- return this.tokens.filter((t) => t.type !== TokenType.NEWLINE);
185
- }
186
- skipWhitespaceAndComments() {
187
- while (this.pos < this.chars.length) {
188
- const ch = this.chars[this.pos];
189
- if (ch === " " || ch === " " || ch === "\r") {
190
- this.advance();
191
- continue;
192
- }
193
- if (ch === "/" && this.peek(1) === "/") {
194
- while (this.pos < this.chars.length && this.chars[this.pos] !== "\n") this.advance();
195
- continue;
196
- }
197
- if (ch === "/" && this.peek(1) === "*") {
198
- this.advance();
199
- this.advance();
200
- while (this.pos < this.chars.length) {
201
- if (this.chars[this.pos] === "*" && this.peek(1) === "/") {
202
- this.advance();
203
- this.advance();
204
- break;
205
- }
206
- if (this.chars[this.pos] === "\n") {
207
- this.line++;
208
- this.col = 0;
209
- }
210
- this.advance();
211
- }
212
- continue;
213
- }
214
- break;
215
- }
216
- }
217
- readString() {
218
- const startCol = this.col;
219
- this.advance();
220
- let str = "";
221
- while (this.pos < this.chars.length && this.chars[this.pos] !== '"') {
222
- if (this.chars[this.pos] === "\\" && this.pos + 1 < this.chars.length) {
223
- this.advance();
224
- const esc = this.chars[this.pos];
225
- if (esc === "n") str += "\n";
226
- else if (esc === "t") str += " ";
227
- else if (esc === "\\") str += "\\";
228
- else if (esc === '"') str += '"';
229
- else str += esc;
230
- } else {
231
- str += this.chars[this.pos];
232
- }
233
- this.advance();
234
- }
235
- if (this.pos < this.chars.length) this.advance();
236
- this.tokens.push({ type: TokenType.STRING, value: str, line: this.line, col: startCol });
237
- }
238
- isExtStart(ch) {
239
- if (ch === "0" && SUBSCRIPT_CHARS.has(this.peek(1) ?? "")) return true;
240
- if (ch === "\u03C0" || ch === "\u03C6") {
241
- const next = this.peek(1);
242
- if (next && SUBSCRIPT_CHARS.has(next)) return true;
243
- }
244
- if (ch === "e" || ch === "i") {
245
- const next = this.peek(1);
246
- if (!next || !SUBSCRIPT_CHARS.has(next)) return false;
247
- let offset = 1;
248
- while (this.peek(offset) && SUBSCRIPT_CHARS.has(this.peek(offset))) offset++;
249
- const afterSubs = this.peek(offset);
250
- if (afterSubs && /[a-zA-Z0-9_]/.test(afterSubs)) return false;
251
- return true;
252
- }
253
- return false;
254
- }
255
- readExtLit() {
256
- const startCol = this.col;
257
- const base = this.chars[this.pos];
258
- this.advance();
259
- let subs = "";
260
- while (this.pos < this.chars.length && SUBSCRIPT_CHARS.has(this.chars[this.pos])) {
261
- subs += this.chars[this.pos];
262
- this.advance();
263
- }
264
- if (subs.length > 0) {
265
- this.tokens.push({ type: TokenType.EXT_LIT, value: base + subs, line: this.line, col: startCol });
266
- return true;
267
- }
268
- this.pos--;
269
- this.col--;
270
- return false;
271
- }
272
- readNumber() {
273
- const startCol = this.col;
274
- let num = "";
275
- if (this.chars[this.pos] === "-") {
276
- num += "-";
277
- this.advance();
278
- }
279
- while (this.pos < this.chars.length && this.isDigit(this.chars[this.pos])) {
280
- num += this.chars[this.pos];
281
- this.advance();
282
- }
283
- if (this.pos < this.chars.length && this.chars[this.pos] === "." && this.isDigit(this.peek(1) ?? "")) {
284
- num += ".";
285
- this.advance();
286
- while (this.pos < this.chars.length && this.isDigit(this.chars[this.pos])) {
287
- num += this.chars[this.pos];
288
- this.advance();
289
- }
290
- }
291
- this.tokens.push({ type: TokenType.NUMBER, value: num, line: this.line, col: startCol });
292
- }
293
- readUnicodeToken(ch) {
294
- const map = [
295
- ["\u2295", TokenType.OPLUS],
296
- ["\u2297", TokenType.OTIMES],
297
- ["\xB7", TokenType.CDOT],
298
- ["\u03C0", TokenType.CONST_PI],
299
- ["\u03C6", TokenType.CONST_PHI],
300
- ["\u03A6", TokenType.CONST_PHI_UP],
301
- ["\u03A8", TokenType.CONST_PSI_UP],
302
- ["\u03A9", TokenType.CONST_OMEGA_UP],
303
- ["\u2205", TokenType.CONST_EMPTY],
304
- ["\u22A4", TokenType.QUAD_TOP],
305
- ["\u22A5", TokenType.QUAD_BOT],
306
- ["\u290A", TokenType.CONVERGE],
307
- ["\u290B", TokenType.DIVERGE],
308
- ["\u25C1", TokenType.REFLECT],
309
- ["\u2227", TokenType.AND],
310
- ["\u2228", TokenType.OR],
311
- ["\xAC", TokenType.NOT],
312
- ["\u30FB", TokenType.SYMBOL_DOT_PRIM]
313
- ];
314
- if (ch === "\u22A4" && this.peek(1) === "\u03C0") {
315
- this.emit(TokenType.QUAD_TOP_PI, "\u22A4\u03C0");
316
- this.advance();
317
- this.advance();
318
- return true;
319
- }
320
- if (ch === "\u22A5" && this.peek(1) === "\u03C0") {
321
- this.emit(TokenType.QUAD_BOT_PI, "\u22A5\u03C0");
322
- this.advance();
323
- this.advance();
324
- return true;
325
- }
326
- for (const [sym, type] of map) {
327
- if (ch === sym) {
328
- this.emit(type, sym);
329
- this.advance();
330
- return true;
331
- }
332
- }
333
- return false;
334
- }
335
- readMultiCharOp(ch) {
336
- const next = this.peek(1);
337
- if (ch === "|" && next === ">") {
338
- this.emit(TokenType.PIPE_OP, "|>");
339
- this.advance();
340
- this.advance();
341
- return true;
342
- }
343
- if (ch === ">" && next === ">") {
344
- this.emit(TokenType.EXTEND, ">>");
345
- this.advance();
346
- this.advance();
347
- return true;
348
- }
349
- if (ch === "<" && next === "<") {
350
- this.emit(TokenType.REDUCE, "<<");
351
- this.advance();
352
- this.advance();
353
- return true;
354
- }
355
- if (ch === "-" && next === ">") {
356
- this.emit(TokenType.ARROW, "->");
357
- this.advance();
358
- this.advance();
359
- return true;
360
- }
361
- if (ch === "=" && next === "=") {
362
- this.emit(TokenType.EQ, "==");
363
- this.advance();
364
- this.advance();
365
- return true;
366
- }
367
- if (ch === "!" && next === "=") {
368
- this.emit(TokenType.NEQ, "!=");
369
- this.advance();
370
- this.advance();
371
- return true;
372
- }
373
- if (ch === ">" && next === "=") {
374
- this.emit(TokenType.GTE, ">=");
375
- this.advance();
376
- this.advance();
377
- return true;
378
- }
379
- if (ch === "<" && next === "=") {
380
- this.emit(TokenType.LTE, "<=");
381
- this.advance();
382
- this.advance();
383
- return true;
384
- }
385
- if (ch === ">" && next === "\u03BA") {
386
- this.emit(TokenType.GT_K, ">\u03BA");
387
- this.advance();
388
- this.advance();
389
- return true;
390
- }
391
- if (ch === "<" && next === "\u03BA") {
392
- this.emit(TokenType.LT_K, "<\u03BA");
393
- this.advance();
394
- this.advance();
395
- return true;
396
- }
397
- if (ch === "=" && next === "\u03BA") {
398
- this.emit(TokenType.EQ_K, "=\u03BA");
399
- this.advance();
400
- this.advance();
401
- return true;
402
- }
403
- return false;
404
- }
405
- readSingleCharOp(ch) {
406
- const map = {
407
- "+": TokenType.PLUS,
408
- "-": TokenType.MINUS,
409
- "*": TokenType.STAR,
410
- "/": TokenType.SLASH,
411
- "=": TokenType.ASSIGN,
412
- ".": TokenType.DOT,
413
- ",": TokenType.COMMA,
414
- ":": TokenType.COLON,
415
- ";": TokenType.SEMICOLON,
416
- "(": TokenType.LPAREN,
417
- ")": TokenType.RPAREN,
418
- "{": TokenType.LBRACE,
419
- "}": TokenType.RBRACE,
420
- "[": TokenType.LBRACKET,
421
- "]": TokenType.RBRACKET,
422
- "|": TokenType.PIPE_OP,
423
- ">": TokenType.GT,
424
- "<": TokenType.LT
425
- };
426
- const type = map[ch];
427
- if (type) {
428
- this.emit(type, ch);
429
- this.advance();
430
- return true;
431
- }
432
- return false;
433
- }
434
- readIdentOrKeyword() {
435
- const startCol = this.col;
436
- let name = "";
437
- while (this.pos < this.chars.length && this.isIdentPart(this.chars[this.pos])) {
438
- name += this.chars[this.pos];
439
- this.advance();
440
- }
441
- if (name.startsWith("compress") && name.length > 8) {
442
- const suffix = name.slice(8);
443
- if (["\u2070", "\xB9", "\xB2", "\xB3", "\u221E"].includes(suffix)) {
444
- this.tokens.push({ type: TokenType.COMPRESS, value: name, line: this.line, col: startCol });
445
- return;
446
- }
447
- }
448
- const kw = KEYWORDS[name];
449
- if (kw) {
450
- this.tokens.push({ type: kw, value: name, line: this.line, col: startCol });
451
- } else {
452
- this.tokens.push({ type: TokenType.IDENT, value: name, line: this.line, col: startCol });
453
- }
454
- }
455
- advance() {
456
- this.pos++;
457
- this.col++;
458
- }
459
- peek(offset) {
460
- return this.chars[this.pos + offset];
461
- }
462
- emit(type, value) {
463
- this.tokens.push({ type, value, line: this.line, col: this.col });
464
- }
465
- isDigit(ch) {
466
- return ch >= "0" && ch <= "9";
467
- }
468
- isIdentStart(ch) {
469
- return /[a-zA-Z_α-ωΑ-Ω𝕄𝕌]/.test(ch);
470
- }
471
- isIdentPart(ch) {
472
- return /[a-zA-Z0-9_α-ωΑ-Ω⁰¹²³∞𝕄𝕌]/.test(ch);
473
- }
474
- shouldNegateBePrefix() {
475
- if (this.tokens.length === 0) return true;
476
- const last = this.tokens[this.tokens.length - 1];
477
- return [
478
- TokenType.LPAREN,
479
- TokenType.COMMA,
480
- TokenType.ASSIGN,
481
- TokenType.PLUS,
482
- TokenType.MINUS,
483
- TokenType.STAR,
484
- TokenType.SLASH,
485
- TokenType.OPLUS,
486
- TokenType.OTIMES,
487
- TokenType.PIPE_OP,
488
- TokenType.SEMICOLON,
489
- TokenType.LBRACKET,
490
- TokenType.COLON,
491
- TokenType.MDIM_OPEN,
492
- TokenType.LBRACE
493
- ].includes(last.type);
494
- }
495
- };
496
-
497
- // src/lang/parser.ts
498
- function node(type, props = {}) {
499
- return { type, ...props };
500
- }
501
- var Parser = class {
502
- constructor(tokens) {
503
- this.pos = 0;
504
- this.tokens = tokens.filter((t) => t.type !== TokenType.NEWLINE);
505
- }
506
- parseProgram() {
507
- const stmts = [];
508
- while (!this.isAtEnd()) {
509
- while (this.check(TokenType.SEMICOLON)) this.advance();
510
- if (this.isAtEnd()) break;
511
- stmts.push(this.parseStatement());
512
- while (this.check(TokenType.SEMICOLON)) this.advance();
513
- }
514
- return node("Program", { body: stmts });
515
- }
516
- parseStatement() {
517
- if (this.check(TokenType.LET)) return this.parseLetStmt();
518
- if (this.check(TokenType.COMPRESS)) return this.parseCompressDef();
519
- return this.parseExpression();
520
- }
521
- // --- let [mut] name [: type] = expr [witnessed by "..."] ---
522
- parseLetStmt() {
523
- this.expect(TokenType.LET);
524
- const mutable = this.match(TokenType.MUT);
525
- const name = this.expect(TokenType.IDENT).value;
526
- let typeAnnotation = null;
527
- let phaseGuard = null;
528
- if (this.match(TokenType.COLON)) {
529
- typeAnnotation = this.expect(TokenType.IDENT).value;
530
- if (this.check(TokenType.IDENT) && this.peek().value.startsWith("@")) {
531
- phaseGuard = this.advance().value.slice(1);
532
- }
533
- }
534
- this.expect(TokenType.ASSIGN);
535
- const init = this.parseExpression();
536
- let witness = null;
537
- if (this.match(TokenType.WITNESSED)) {
538
- this.expect(TokenType.BY);
539
- witness = this.expect(TokenType.STRING).value;
540
- }
541
- return node(mutable ? "MutStmt" : "LetStmt", {
542
- name,
543
- init,
544
- typeAnnotation,
545
- phaseGuard,
546
- witness
547
- });
548
- }
549
- // --- compress [level] name(params) [-> type] = body ---
550
- parseCompressDef() {
551
- const compressToken = this.expect(TokenType.COMPRESS);
552
- const level = this.parseCompressLevel(compressToken.value);
553
- const name = this.expect(TokenType.IDENT).value;
554
- this.expect(TokenType.LPAREN);
555
- const params = [];
556
- if (!this.check(TokenType.RPAREN)) {
557
- params.push(this.parseParamDecl());
558
- while (this.match(TokenType.COMMA)) {
559
- params.push(this.parseParamDecl());
560
- }
561
- }
562
- this.expect(TokenType.RPAREN);
563
- let returnType = null;
564
- if (this.match(TokenType.ARROW)) {
565
- returnType = this.expect(TokenType.IDENT).value;
566
- }
567
- this.expect(TokenType.ASSIGN);
568
- const body = this.parseExpression();
569
- return node("CompressDef", { name, params, body, level, returnType });
570
- }
571
- parseCompressLevel(value) {
572
- if (value === "compress") return -1;
573
- const suffixMap = {
574
- "compress\u2070": 0,
575
- // ⁰
576
- "compress\xB9": 1,
577
- // ¹
578
- "compress\xB2": 2,
579
- // ²
580
- "compress\xB3": 3,
581
- // ³
582
- "compress\u221E": Infinity
583
- // ∞
584
- };
585
- return suffixMap[value] ?? -1;
586
- }
587
- parseParamDecl() {
588
- let name;
589
- if (this.check(TokenType.IDENT)) {
590
- name = this.advance().value;
591
- } else if (this.check(TokenType.CONST_E)) {
592
- name = this.advance().value;
593
- } else if (this.check(TokenType.CONST_I)) {
594
- name = this.advance().value;
595
- } else {
596
- name = this.expect(TokenType.IDENT).value;
597
- }
598
- if (this.match(TokenType.COLON)) {
599
- this.expect(TokenType.IDENT);
600
- }
601
- return name;
602
- }
603
- // --- Expression hierarchy (low → high precedence) ---
604
- parseExpression() {
605
- return this.parsePipe();
606
- }
607
- // Level 1: |> pipe, ◁ reflect
608
- parsePipe() {
609
- let left = this.parseLogicOr();
610
- while (this.check(TokenType.PIPE_OP) || this.check(TokenType.REFLECT)) {
611
- if (this.match(TokenType.PIPE_OP)) {
612
- const cmd = this.parsePipeCommand();
613
- left = node("Pipe", { input: left, command: cmd });
614
- } else if (this.match(TokenType.REFLECT)) {
615
- const right = this.parseLogicOr();
616
- left = node("ReflectOp", { left, right });
617
- }
618
- }
619
- return left;
620
- }
621
- parsePipeCommand() {
622
- if (this.check(TokenType.IDENT) || this.check(TokenType.GENESIS) || this.check(TokenType.SPACE) || this.check(TokenType.LAYER)) {
623
- const cmd = this.advance().value;
624
- let mode = null;
625
- let args = [];
626
- if (this.match(TokenType.COLON)) {
627
- mode = this.expect(TokenType.IDENT).value;
628
- }
629
- if (this.match(TokenType.LPAREN)) {
630
- if (!this.check(TokenType.RPAREN)) {
631
- args.push(this.parseExpression());
632
- while (this.match(TokenType.COMMA)) args.push(this.parseExpression());
633
- }
634
- this.expect(TokenType.RPAREN);
635
- }
636
- return node("PipeCmd", { cmd, mode, args });
637
- }
638
- if (this.match(TokenType.CONVERGE)) return node("PipeCmd", { cmd: "\u290A", mode: null, args: [] });
639
- if (this.match(TokenType.DIVERGE)) return node("PipeCmd", { cmd: "\u290B", mode: null, args: [] });
640
- throw this.error("\u30D1\u30A4\u30D7\u30B3\u30DE\u30F3\u30C9\u304C\u5FC5\u8981");
641
- }
642
- // Level 2: ∧ ∨ (logic)
643
- parseLogicOr() {
644
- let left = this.parseLogicAnd();
645
- while (this.match(TokenType.OR)) {
646
- const right = this.parseLogicAnd();
647
- left = node("BinOp", { op: "\u2228", left, right });
648
- }
649
- return left;
650
- }
651
- parseLogicAnd() {
652
- let left = this.parseComparison();
653
- while (this.match(TokenType.AND)) {
654
- const right = this.parseComparison();
655
- left = node("BinOp", { op: "\u2227", left, right });
656
- }
657
- return left;
658
- }
659
- // Level 3: comparison operators
660
- parseComparison() {
661
- let left = this.parseAddition();
662
- const compOps = [
663
- TokenType.GT_K,
664
- TokenType.LT_K,
665
- TokenType.EQ_K,
666
- TokenType.EQ,
667
- TokenType.NEQ,
668
- TokenType.GT,
669
- TokenType.LT,
670
- TokenType.GTE,
671
- TokenType.LTE
672
- ];
673
- while (compOps.some((op) => this.check(op))) {
674
- const opToken = this.advance();
675
- const right = this.parseAddition();
676
- left = node("BinOp", { op: opToken.value, left, right });
677
- }
678
- return left;
679
- }
680
- // Level 4: + - ⊕
681
- parseAddition() {
682
- let left = this.parseMultiplication();
683
- while (this.check(TokenType.PLUS) || this.check(TokenType.MINUS) || this.check(TokenType.OPLUS)) {
684
- const op = this.advance().value;
685
- const right = this.parseMultiplication();
686
- left = node("BinOp", { op, left, right });
687
- }
688
- return left;
689
- }
690
- // Level 5: * / ⊗ ·
691
- parseMultiplication() {
692
- let left = this.parseExtendReduce();
693
- while (this.check(TokenType.STAR) || this.check(TokenType.SLASH) || this.check(TokenType.OTIMES) || this.check(TokenType.CDOT)) {
694
- const op = this.advance().value;
695
- const right = this.parseExtendReduce();
696
- left = node("BinOp", { op, left, right });
697
- }
698
- return left;
699
- }
700
- // Level 6: >> << ⤊ ⤋
701
- parseExtendReduce() {
702
- let left = this.parseUnary();
703
- while (true) {
704
- if (this.match(TokenType.EXTEND)) {
705
- if (this.match(TokenType.COLON)) {
706
- const sub = this.expect(TokenType.IDENT).value;
707
- left = node("Extend", { target: left, subscript: sub });
708
- } else {
709
- const right = this.parseUnary();
710
- left = node("Extend", { target: left, expr: right });
711
- }
712
- } else if (this.match(TokenType.REDUCE)) {
713
- left = node("Reduce", { target: left });
714
- } else if (this.match(TokenType.CONVERGE)) {
715
- const right = this.parseUnary();
716
- left = node("ConvergeOp", { left, right });
717
- } else if (this.match(TokenType.DIVERGE)) {
718
- const right = this.parseUnary();
719
- left = node("DivergeOp", { left, right });
720
- } else {
721
- break;
722
- }
723
- }
724
- return left;
725
- }
726
- // Level 7: unary ¬ -
727
- parseUnary() {
728
- if (this.match(TokenType.NOT)) {
729
- const operand = this.parseUnary();
730
- return node("UnaryOp", { op: "\xAC", operand });
731
- }
732
- if (this.check(TokenType.MINUS) && this.shouldNegateBePrefix()) {
733
- this.advance();
734
- const operand = this.parseUnary();
735
- return node("UnaryOp", { op: "-", operand });
736
- }
737
- return this.parsePostfix();
738
- }
739
- // Level 8: . member access, [index], (call)
740
- parsePostfix() {
741
- let left = this.parsePrimary();
742
- while (true) {
743
- if (this.match(TokenType.DOT)) {
744
- if (this.check(TokenType.IDENT)) {
745
- const member = this.advance().value;
746
- if (this.check(TokenType.DOT) && this.checkAhead(TokenType.IDENT, 1) && this.tokens[this.pos + 1]?.value === "\u03BA") {
747
- this.advance();
748
- this.advance();
749
- left = node("MemberAccess", { object: left, member, kappa: true });
750
- } else {
751
- left = node("MemberAccess", { object: left, member, kappa: false });
752
- }
753
- }
754
- } else if (this.match(TokenType.LPAREN)) {
755
- const args = [];
756
- if (!this.check(TokenType.RPAREN)) {
757
- args.push(this.parseExpression());
758
- while (this.match(TokenType.COMMA)) args.push(this.parseExpression());
759
- }
760
- this.expect(TokenType.RPAREN);
761
- left = node("FnCall", { callee: left, args });
762
- } else if (this.match(TokenType.LBRACKET)) {
763
- const index = this.parseExpression();
764
- this.expect(TokenType.RBRACKET);
765
- left = node("IndexAccess", { object: left, index });
766
- } else {
767
- break;
768
- }
769
- }
770
- return left;
771
- }
772
- // --- Primary expressions ---
773
- parsePrimary() {
774
- if (this.check(TokenType.NUMBER)) {
775
- const val = this.advance().value;
776
- return node("NumLit", { value: parseFloat(val) });
777
- }
778
- if (this.check(TokenType.STRING)) {
779
- return node("StrLit", { value: this.advance().value });
780
- }
781
- if (this.match(TokenType.TRUE)) return node("BoolLit", { value: true });
782
- if (this.match(TokenType.FALSE)) return node("BoolLit", { value: false });
783
- if (this.match(TokenType.NULL)) return node("NullLit", {});
784
- if (this.check(TokenType.EXT_LIT)) {
785
- const val = this.advance().value;
786
- return node("ExtLit", { raw: val });
787
- }
788
- if (this.match(TokenType.SYMBOL_0_0)) {
789
- return node("ExtLit", { raw: "0\u2080" });
790
- }
791
- if (this.match(TokenType.SYMBOL_DOT_PRIM)) {
792
- return node("ConstLit", { value: "\u30FB" });
793
- }
794
- if (this.match(TokenType.CONST_PI)) return node("NumLit", { value: Math.PI });
795
- if (this.match(TokenType.CONST_E)) return node("NumLit", { value: Math.E });
796
- if (this.match(TokenType.CONST_PHI)) return node("NumLit", { value: (1 + Math.sqrt(5)) / 2 });
797
- if (this.match(TokenType.CONST_I)) return node("ConstLit", { value: "i" });
798
- if (this.match(TokenType.CONST_EMPTY)) return node("ConstLit", { value: "\u2205" });
799
- if (this.match(TokenType.CONST_PHI_UP)) return node("ConstLit", { value: "\u03A6" });
800
- if (this.match(TokenType.CONST_PSI_UP)) return node("ConstLit", { value: "\u03A8" });
801
- if (this.match(TokenType.CONST_OMEGA_UP)) return node("ConstLit", { value: "\u03A9" });
802
- if (this.match(TokenType.QUAD_TOP)) return node("QuadLit", { value: "top" });
803
- if (this.match(TokenType.QUAD_BOT)) return node("QuadLit", { value: "bottom" });
804
- if (this.match(TokenType.QUAD_TOP_PI)) return node("QuadLit", { value: "topPi" });
805
- if (this.match(TokenType.QUAD_BOT_PI)) return node("QuadLit", { value: "bottomPi" });
806
- if (this.match(TokenType.MDIM_OPEN)) {
807
- return this.parseMDimLit();
808
- }
809
- if (this.match(TokenType.LBRACKET)) {
810
- const elems = [];
811
- if (!this.check(TokenType.RBRACKET)) {
812
- elems.push(this.parseExpression());
813
- while (this.match(TokenType.COMMA)) elems.push(this.parseExpression());
814
- }
815
- this.expect(TokenType.RBRACKET);
816
- return node("ArrayLit", { elements: elems });
817
- }
818
- if (this.match(TokenType.LPAREN)) {
819
- const expr = this.parseExpression();
820
- this.expect(TokenType.RPAREN);
821
- return expr;
822
- }
823
- if (this.check(TokenType.IF)) return this.parseIfExpr();
824
- if (this.check(TokenType.MATCH)) return this.parseMatchExpr();
825
- if (this.check(TokenType.GENESIS)) {
826
- this.advance();
827
- if (this.match(TokenType.LPAREN)) {
828
- this.expect(TokenType.RPAREN);
829
- }
830
- return node("FnCall", { callee: node("Ident", { name: "genesis" }), args: [] });
831
- }
832
- if (this.check(TokenType.SPACE)) {
833
- return this.parseSpaceLit();
834
- }
835
- if (this.check(TokenType.IDENT)) {
836
- const name = this.advance().value;
837
- return node("Ident", { name });
838
- }
839
- throw this.error(`\u4E88\u671F\u3057\u306A\u3044\u30C8\u30FC\u30AF\u30F3: ${this.peek().value} (${this.peek().type})`);
840
- }
841
- // --- MDim literal: 𝕄{center; n1, n2, ... [weight w] [mode]} ---
842
- parseMDimLit() {
843
- const center = this.parseExpression();
844
- this.expect(TokenType.SEMICOLON);
845
- const neighbors = [];
846
- neighbors.push(this.parseExpression());
847
- while (this.match(TokenType.COMMA)) {
848
- if (this.check(TokenType.RBRACE)) break;
849
- if (this.check(TokenType.WEIGHT)) break;
850
- neighbors.push(this.parseExpression());
851
- }
852
- let weight = null;
853
- if (this.match(TokenType.WEIGHT)) {
854
- weight = this.parseExpression();
855
- }
856
- let mode = "weighted";
857
- if (this.match(TokenType.COLON)) {
858
- if (this.check(TokenType.IDENT)) {
859
- mode = this.advance().value;
860
- }
861
- }
862
- this.expect(TokenType.RBRACE);
863
- return node("MDimLit", { center, neighbors, weight, mode });
864
- }
865
- // ── v0.3: Space literal: 空{ 層 0: expr, expr 層 1: expr } ──
866
- parseSpaceLit() {
867
- this.expect(TokenType.SPACE);
868
- this.expect(TokenType.LBRACE);
869
- const layers = [];
870
- let topology = "flat";
871
- if (this.check(TokenType.IDENT) && this.peek().value === "topology") {
872
- this.advance();
873
- this.expect(TokenType.COLON);
874
- if (this.check(TokenType.IDENT)) {
875
- topology = this.advance().value;
876
- }
877
- this.match(TokenType.COMMA);
878
- }
879
- while (!this.check(TokenType.RBRACE) && !this.isAtEnd()) {
880
- if (!this.check(TokenType.LAYER)) {
881
- throw this.error(`\u5C64\u306E\u5B9A\u7FA9\u304C\u5FC5\u8981\u3067\u3059\u3002\u5B9F\u969B: ${this.peek().type} ("${this.peek().value}")`);
882
- }
883
- this.expect(TokenType.LAYER);
884
- const layerIndex = this.parseExpression();
885
- this.expect(TokenType.COLON);
886
- const nodes = [];
887
- nodes.push(this.parseExpression());
888
- while (this.match(TokenType.COMMA)) {
889
- if (this.check(TokenType.LAYER) || this.check(TokenType.RBRACE)) break;
890
- nodes.push(this.parseExpression());
891
- }
892
- layers.push({ index: layerIndex, nodes });
893
- }
894
- this.expect(TokenType.RBRACE);
895
- return node("SpaceLit", { layers, topology });
896
- }
897
- // --- if expr then expr else expr ---
898
- parseIfExpr() {
899
- this.expect(TokenType.IF);
900
- const cond = this.parseExpression();
901
- this.expect(TokenType.THEN);
902
- const then = this.parseExpression();
903
- this.expect(TokenType.ELSE);
904
- const elseExpr = this.parseExpression();
905
- return node("IfExpr", { cond, then, else: elseExpr });
906
- }
907
- // --- match expr { case pat -> expr, ... } ---
908
- parseMatchExpr() {
909
- this.expect(TokenType.MATCH);
910
- const target = this.parseExpression();
911
- this.expect(TokenType.LBRACE);
912
- const cases = [];
913
- while (!this.check(TokenType.RBRACE) && !this.isAtEnd()) {
914
- this.expect(TokenType.CASE);
915
- const pattern = this.parsePrimary();
916
- this.expect(TokenType.ARROW);
917
- const body = this.parseExpression();
918
- cases.push({ pattern, body });
919
- this.match(TokenType.COMMA);
920
- }
921
- this.expect(TokenType.RBRACE);
922
- return node("MatchExpr", { target, cases });
923
- }
924
- // --- Helpers ---
925
- peek() {
926
- return this.tokens[this.pos] || { type: TokenType.EOF, value: "", line: 0, col: 0 };
927
- }
928
- isAtEnd() {
929
- return this.peek().type === TokenType.EOF;
930
- }
931
- check(type) {
932
- return this.peek().type === type;
933
- }
934
- checkAhead(type, offset) {
935
- const idx = this.pos + offset;
936
- return idx < this.tokens.length && this.tokens[idx].type === type;
937
- }
938
- advance() {
939
- const t = this.tokens[this.pos];
940
- this.pos++;
941
- return t;
942
- }
943
- match(type) {
944
- if (this.check(type)) {
945
- this.advance();
946
- return true;
947
- }
948
- return false;
949
- }
950
- expect(type) {
951
- if (this.check(type)) return this.advance();
952
- const t = this.peek();
953
- throw this.error(`\u671F\u5F85: ${type}, \u5B9F\u969B: ${t.type} ("${t.value}")`);
954
- }
955
- error(msg) {
956
- const t = this.peek();
957
- return new Error(`[\u884C ${t.line}:${t.col}] \u69CB\u6587\u30A8\u30E9\u30FC: ${msg}`);
958
- }
959
- shouldNegateBePrefix() {
960
- if (this.pos === 0) return true;
961
- const prev = this.tokens[this.pos - 1];
962
- return [
963
- TokenType.LPAREN,
964
- TokenType.COMMA,
965
- TokenType.ASSIGN,
966
- TokenType.PLUS,
967
- TokenType.MINUS,
968
- TokenType.STAR,
969
- TokenType.SLASH,
970
- TokenType.OPLUS,
971
- TokenType.OTIMES,
972
- TokenType.PIPE_OP,
973
- TokenType.SEMICOLON,
974
- TokenType.LBRACKET,
975
- TokenType.COLON,
976
- TokenType.MDIM_OPEN,
977
- TokenType.LBRACE
978
- ].includes(prev.type);
979
- }
980
- };
981
-
982
- // src/lang/space.ts
983
- function createSpace(topology = "flat") {
984
- return {
985
- reiType: "Space",
986
- topology,
987
- layers: /* @__PURE__ */ new Map(),
988
- globalStage: 0
989
- };
990
- }
991
- function addNodeToLayer(space, layerIndex, center, neighbors, mode, weights) {
992
- if (!space.layers.has(layerIndex)) {
993
- space.layers.set(layerIndex, { index: layerIndex, nodes: [], frozen: false });
994
- }
995
- const layer = space.layers.get(layerIndex);
996
- const node2 = {
997
- reiType: "DNode",
998
- center,
999
- neighbors: [...neighbors],
1000
- mode: mode || "weighted",
1001
- weights,
1002
- layerIndex,
1003
- nodeIndex: layer.nodes.length,
1004
- stage: 0,
1005
- momentum: 0,
1006
- history: [center],
1007
- frozen: false
1008
- };
1009
- layer.nodes.push(node2);
1010
- return node2;
1011
- }
1012
- function computeNodeValue(node2) {
1013
- const { center, neighbors, mode } = node2;
1014
- if (neighbors.length === 0) return center;
1015
- switch (mode) {
1016
- case "weighted":
1017
- default: {
1018
- const avg = neighbors.reduce((a, b) => a + b, 0) / neighbors.length;
1019
- return center + avg;
1020
- }
1021
- case "geometric": {
1022
- const prod = neighbors.reduce((a, b) => a * Math.abs(b), 1);
1023
- return center * Math.pow(prod, 1 / neighbors.length);
1024
- }
1025
- case "harmonic": {
1026
- const hm = neighbors.length / neighbors.reduce((a, b) => a + 1 / (Math.abs(b) || 1), 0);
1027
- return center + hm;
1028
- }
1029
- }
1030
- }
1031
- function stepNode(node2) {
1032
- if (node2.frozen) return;
1033
- const val = computeNodeValue(node2);
1034
- node2.history.push(val);
1035
- const newCenter = val;
1036
- const diff = newCenter - node2.center;
1037
- node2.momentum = diff;
1038
- node2.center = newCenter;
1039
- node2.stage++;
1040
- }
1041
- function stepSpace(space, targetLayer) {
1042
- for (const [lIdx, layer] of space.layers) {
1043
- if (targetLayer !== void 0 && lIdx !== targetLayer) continue;
1044
- if (layer.frozen) continue;
1045
- for (const node2 of layer.nodes) {
1046
- stepNode(node2);
1047
- }
1048
- }
1049
- space.globalStage++;
1050
- }
1051
- function diffuseSpace(space, criteria, targetLayer, contractionMethod = "weighted") {
1052
- const maxSteps = criteria.type === "steps" ? criteria.max : 100;
1053
- const epsilon = criteria.type === "epsilon" ? criteria.threshold : 1e-6;
1054
- for (let i = 0; i < maxSteps; i++) {
1055
- const prevCenters = [];
1056
- for (const [, layer] of space.layers) {
1057
- for (const node2 of layer.nodes) prevCenters.push(node2.center);
1058
- }
1059
- stepSpace(space, targetLayer);
1060
- if (criteria.type === "converged" || criteria.type === "epsilon") {
1061
- let idx = 0;
1062
- let maxDiff = 0;
1063
- for (const [, layer] of space.layers) {
1064
- for (const node2 of layer.nodes) {
1065
- maxDiff = Math.max(maxDiff, Math.abs(node2.center - prevCenters[idx++]));
1066
- }
1067
- }
1068
- if (maxDiff < epsilon) break;
1069
- }
1070
- if (criteria.type === "fixed") break;
1071
- }
1072
- return space;
1073
- }
1074
- function getSigmaFlow(node2) {
1075
- const direction = node2.momentum > 0 ? "expand" : node2.momentum < 0 ? "contract" : "rest";
1076
- return {
1077
- direction,
1078
- momentum: node2.momentum,
1079
- stage: node2.stage
1080
- };
1081
- }
1082
- function getSigmaMemory(node2) {
1083
- return [...node2.history];
1084
- }
1085
- function getSigmaWill(node2) {
1086
- const tendency = node2.momentum > 0 ? "expand" : node2.momentum < 0 ? "contract" : "rest";
1087
- return {
1088
- tendency,
1089
- strength: Math.abs(node2.momentum)
1090
- };
1091
- }
1092
- function getSpaceSigma(space) {
1093
- let totalNodes = 0;
1094
- let activeNodes = 0;
1095
- let convergedNodes = 0;
1096
- let expandingNodes = 0;
1097
- for (const [, layer] of space.layers) {
1098
- for (const node2 of layer.nodes) {
1099
- totalNodes++;
1100
- if (!node2.frozen) activeNodes++;
1101
- if (Math.abs(node2.momentum) < 1e-6) convergedNodes++;
1102
- if (node2.momentum > 0) expandingNodes++;
1103
- }
1104
- }
1105
- return {
1106
- reiType: "SigmaResult",
1107
- field: {
1108
- layers: space.layers.size,
1109
- total_nodes: totalNodes,
1110
- active_nodes: activeNodes,
1111
- topology: space.topology
1112
- },
1113
- flow: {
1114
- global_stage: space.globalStage,
1115
- converged_nodes: convergedNodes,
1116
- expanding_nodes: expandingNodes
1117
- },
1118
- memory: [],
1119
- layer: 0,
1120
- will: { tendency: "rest", strength: 0 },
1121
- relation: []
1122
- };
1123
- }
1124
- function findResonances(space, threshold = 0.5) {
1125
- const resonances = [];
1126
- const allNodes = [];
1127
- for (const [, layer] of space.layers) {
1128
- for (const node2 of layer.nodes) allNodes.push(node2);
1129
- }
1130
- for (let i = 0; i < allNodes.length; i++) {
1131
- for (let j = i + 1; j < allNodes.length; j++) {
1132
- const a = allNodes[i], b = allNodes[j];
1133
- const diff = Math.abs(a.center - b.center);
1134
- const maxAbs = Math.max(Math.abs(a.center), Math.abs(b.center), 1);
1135
- const similarity = 1 - diff / maxAbs;
1136
- if (similarity >= threshold) {
1137
- resonances.push({
1138
- nodeA: { layer: a.layerIndex, index: a.nodeIndex },
1139
- nodeB: { layer: b.layerIndex, index: b.nodeIndex },
1140
- strength: similarity
1141
- });
1142
- }
1143
- }
1144
- }
1145
- return resonances;
1146
- }
1147
-
1148
- // src/lang/evaluator.ts
1149
- function createSigmaMeta() {
1150
- return { memory: [], tendency: "rest", pipeCount: 0 };
1151
- }
1152
- function wrapWithSigma(value, prevValue, prevMeta) {
1153
- const rawValue = unwrapReiVal(value);
1154
- const rawPrev = unwrapReiVal(prevValue);
1155
- const meta = prevMeta ? { ...prevMeta, memory: [...prevMeta.memory, rawPrev], pipeCount: prevMeta.pipeCount + 1 } : { memory: [rawPrev], tendency: "rest", pipeCount: 1 };
1156
- meta.tendency = computeTendency(meta.memory, rawValue);
1157
- if (rawValue === null || typeof rawValue !== "object") {
1158
- return { reiType: "ReiVal", value: rawValue, __sigma__: meta };
1159
- }
1160
- rawValue.__sigma__ = meta;
1161
- return rawValue;
1162
- }
1163
- function computeTendency(memory, currentValue) {
1164
- if (memory.length < 2) return "rest";
1165
- const recent = memory.slice(-5).map(toNumSafe);
1166
- const current = toNumSafe(currentValue);
1167
- let expandCount = 0, contractCount = 0, alternating = 0;
1168
- for (let i = 0; i < recent.length; i++) {
1169
- const prev = i === 0 ? recent[0] : recent[i - 1];
1170
- const cur = i === recent.length - 1 ? current : recent[i + 1];
1171
- if (cur > prev) expandCount++;
1172
- else if (cur < prev) contractCount++;
1173
- if (i > 0 && cur > prev !== recent[i] > recent[i - 1]) alternating++;
1174
- }
1175
- if (alternating >= recent.length - 1) return "spiral";
1176
- if (expandCount > contractCount) return "expand";
1177
- if (contractCount > expandCount) return "contract";
1178
- return "rest";
1179
- }
1180
- function toNumSafe(v) {
1181
- if (typeof v === "number") return v;
1182
- if (v === null || v === void 0) return 0;
1183
- if (typeof v === "boolean") return v ? 1 : 0;
1184
- if (typeof v === "object" && v.reiType === "ReiVal") return toNumSafe(v.value);
1185
- if (typeof v === "object" && v.reiType === "Ext") return v.valStar();
1186
- if (typeof v === "object" && v.reiType === "MDim") {
1187
- const { center, neighbors, mode } = v;
1188
- const weights = v.weights ?? neighbors.map(() => 1);
1189
- const n = neighbors.length;
1190
- if (n === 0) return center;
1191
- const wSum = weights.reduce((a, b) => a + b, 0);
1192
- const wAvg = neighbors.reduce((sum, vi, i) => sum + (weights[i] ?? 1) * vi, 0) / (wSum || 1);
1193
- return center + wAvg;
1194
- }
1195
- return 0;
1196
- }
1197
- function unwrapReiVal(v) {
1198
- if (v !== null && typeof v === "object" && v.reiType === "ReiVal") return v.value;
1199
- return v;
1200
- }
1201
- function getSigmaOf(v) {
1202
- if (v !== null && typeof v === "object") {
1203
- if (v.reiType === "ReiVal") return v.__sigma__;
1204
- if (v.__sigma__) return v.__sigma__;
1205
- }
1206
- return createSigmaMeta();
1207
- }
1208
- function buildSigmaResult(rawVal, meta) {
1209
- const val = unwrapReiVal(rawVal);
1210
- let field;
1211
- let layer = 0;
1212
- let flow = { direction: meta.tendency === "rest" ? "rest" : meta.tendency, momentum: meta.pipeCount, velocity: 0 };
1213
- if (val !== null && typeof val === "object") {
1214
- if (val.reiType === "MDim") {
1215
- field = { center: val.center, neighbors: [...val.neighbors], mode: val.mode, dim: val.neighbors.length };
1216
- } else if (val.reiType === "Ext") {
1217
- field = { base: val.base, order: val.order, subscripts: val.subscripts };
1218
- layer = val.order;
1219
- } else if (val.reiType === "State") {
1220
- field = { state: val.state, omega: val.omega };
1221
- flow = { direction: "forward", momentum: val.history.length - 1, velocity: 1 };
1222
- } else if (val.reiType === "Quad") {
1223
- field = { value: val.value };
1224
- } else if (val.reiType === "DNode") {
1225
- field = { center: val.center, neighbors: [...val.neighbors], layer: val.layerIndex, index: val.nodeIndex };
1226
- layer = val.layerIndex;
1227
- flow = { stage: val.stage, directions: val.neighbors.length, momentum: val.momentum, velocity: 0 };
1228
- if (val.diffusionHistory.length >= 2) {
1229
- flow.velocity = Math.abs(
1230
- val.diffusionHistory[val.diffusionHistory.length - 1].result - val.diffusionHistory[val.diffusionHistory.length - 2].result
1231
- );
1232
- }
1233
- } else if (val.reiType === "Space") {
1234
- field = { type: "space" };
1235
- } else if (Array.isArray(val)) {
1236
- field = { length: val.length, first: val[0] ?? null, last: val[val.length - 1] ?? null };
1237
- } else {
1238
- field = { type: typeof val };
1239
- }
1240
- } else if (typeof val === "number") {
1241
- field = { center: val, neighbors: [] };
1242
- } else if (typeof val === "string") {
1243
- field = { value: val, length: val.length };
1244
- } else if (typeof val === "boolean") {
1245
- field = { value: val };
1246
- } else {
1247
- field = { value: null };
1248
- }
1249
- const memory = [...meta.memory];
1250
- if (val !== null && typeof val === "object" && val.reiType === "State" && val.history) {
1251
- if (memory.length === 0 && val.history.length > 1) {
1252
- for (let i = 0; i < val.history.length - 1; i++) {
1253
- memory.push(val.history[i]);
1254
- }
1255
- }
1256
- }
1257
- const will = {
1258
- tendency: meta.tendency,
1259
- strength: meta.pipeCount > 0 ? Math.min(meta.pipeCount / 5, 1) : 0,
1260
- history: meta.memory.map((_, i) => {
1261
- if (i === 0) return "rest";
1262
- const prev = toNumSafe(meta.memory[i - 1]);
1263
- const cur = toNumSafe(meta.memory[i]);
1264
- return cur > prev ? "expand" : cur < prev ? "contract" : "rest";
1265
- })
1266
- };
1267
- return {
1268
- reiType: "SigmaResult",
1269
- field,
1270
- flow,
1271
- memory,
1272
- layer,
1273
- will,
1274
- relation: []
1275
- };
1276
- }
1277
- var Environment = class {
1278
- constructor(parent = null) {
1279
- this.bindings = /* @__PURE__ */ new Map();
1280
- this.parent = parent;
1281
- }
1282
- define(name, value, mutable = false) {
1283
- this.bindings.set(name, { value, mutable });
1284
- }
1285
- get(name) {
1286
- const b = this.bindings.get(name);
1287
- if (b) return b.value;
1288
- if (this.parent) return this.parent.get(name);
1289
- throw new Error(`\u672A\u5B9A\u7FA9\u306E\u5909\u6570: ${name}`);
1290
- }
1291
- set(name, value) {
1292
- const b = this.bindings.get(name);
1293
- if (b) {
1294
- if (!b.mutable) throw new Error(`\u4E0D\u5909\u306E\u5909\u6570\u306B\u4EE3\u5165: ${name}`);
1295
- b.value = value;
1296
- return;
1297
- }
1298
- if (this.parent) {
1299
- this.parent.set(name, value);
1300
- return;
1301
- }
1302
- throw new Error(`\u672A\u5B9A\u7FA9\u306E\u5909\u6570: ${name}`);
1303
- }
1304
- has(name) {
1305
- if (this.bindings.has(name)) return true;
1306
- if (this.parent) return this.parent.has(name);
1307
- return false;
1308
- }
1309
- getBinding(name) {
1310
- const b = this.bindings.get(name);
1311
- if (b) return b;
1312
- if (this.parent) return this.parent.getBinding(name);
1313
- return null;
1314
- }
1315
- allBindings() {
1316
- const all = /* @__PURE__ */ new Map();
1317
- if (this.parent) {
1318
- for (const [k, v] of this.parent.allBindings()) all.set(k, v);
1319
- }
1320
- for (const [k, v] of this.bindings) all.set(k, v);
1321
- return all;
1322
- }
1323
- };
1324
- function createExtended(base, subscripts) {
1325
- const order = subscripts.length;
1326
- return {
1327
- reiType: "Ext",
1328
- base,
1329
- order,
1330
- subscripts,
1331
- valStar() {
1332
- if (base === 0) return Math.pow(0.1, order);
1333
- return base * Math.pow(0.1, order);
1334
- }
1335
- };
1336
- }
1337
- function parseExtLit(raw) {
1338
- if (raw === "0\u2080") return createExtended(0, "o");
1339
- const baseChar = raw[0];
1340
- const subs = raw.slice(1);
1341
- const baseMap = {
1342
- "0": 0,
1343
- "\u03C0": Math.PI,
1344
- "e": Math.E,
1345
- "\u03C6": (1 + Math.sqrt(5)) / 2,
1346
- "i": NaN
1347
- };
1348
- return createExtended(baseMap[baseChar] ?? 0, subs);
1349
- }
1350
- var ALL_COMPUTE_MODES = [
1351
- "weighted",
1352
- "multiplicative",
1353
- "harmonic",
1354
- "exponential",
1355
- "geometric",
1356
- "median",
1357
- "minkowski",
1358
- "entropy"
1359
- ];
1360
- function computeMDim(md) {
1361
- const { center, neighbors, mode } = md;
1362
- const weights = md.weights ?? neighbors.map(() => 1);
1363
- const n = neighbors.length;
1364
- if (n === 0) return center;
1365
- if (typeof mode === "string" && mode.startsWith("blend(")) {
1366
- return computeBlend(md, mode);
1367
- }
1368
- switch (mode) {
1369
- case "weighted": {
1370
- const wSum = weights.reduce((a, b) => a + b, 0);
1371
- const wAvg = neighbors.reduce((sum, v, i) => sum + (weights[i] ?? 1) * v, 0) / (wSum || 1);
1372
- return center + wAvg;
1373
- }
1374
- case "multiplicative": {
1375
- const prod = neighbors.reduce((p, v) => p * (1 + v), 1);
1376
- return center * prod;
1377
- }
1378
- case "harmonic": {
1379
- const harmSum = neighbors.reduce((s, v) => s + 1 / (Math.abs(v) || 1), 0);
1380
- return center + n / harmSum;
1381
- }
1382
- case "exponential": {
1383
- const expSum = neighbors.reduce((s, v) => s + Math.exp(v), 0);
1384
- return center * (expSum / n);
1385
- }
1386
- // ── Tier 2 M1: 新計算モード ──
1387
- case "geometric": {
1388
- const prod = neighbors.reduce((p, v) => p * Math.abs(v || 1), 1);
1389
- return center * Math.pow(prod, 1 / n);
1390
- }
1391
- case "median": {
1392
- const sorted = [...neighbors].sort((a, b) => a - b);
1393
- const mid = Math.floor(n / 2);
1394
- const med = n % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
1395
- return center + med;
1396
- }
1397
- case "minkowski": {
1398
- const p = md.minkowskiP ?? 2;
1399
- const sumP = neighbors.reduce((s, v) => s + Math.pow(Math.abs(v), p), 0);
1400
- return center + Math.pow(sumP / n, 1 / p);
1401
- }
1402
- case "entropy": {
1403
- const total = neighbors.reduce((s, v) => s + Math.abs(v), 0) || 1;
1404
- const probs = neighbors.map((v) => Math.abs(v) / total);
1405
- const H = -probs.reduce((s, p) => s + (p > 0 ? p * Math.log2(p) : 0), 0);
1406
- return center * (1 + H);
1407
- }
1408
- default:
1409
- return center;
1410
- }
1411
- }
1412
- function computeBlend(md, blendSpec) {
1413
- const inner = blendSpec.slice(6, -1);
1414
- const parts = inner.split(",").map((s) => s.trim());
1415
- let totalWeight = 0;
1416
- let blendedResult = 0;
1417
- for (const part of parts) {
1418
- const [modeName, weightStr] = part.split(":").map((s) => s.trim());
1419
- const w = parseFloat(weightStr) || 0;
1420
- const result = computeMDim({ ...md, mode: modeName });
1421
- blendedResult += w * result;
1422
- totalWeight += w;
1423
- }
1424
- return totalWeight > 0 ? blendedResult / totalWeight : md.center;
1425
- }
1426
- function projectToMDim(input, centerSpec, args) {
1427
- let elements;
1428
- if (Array.isArray(input)) {
1429
- elements = [...input];
1430
- } else if (typeof input === "string") {
1431
- elements = Array.from(input).map((c) => c.charCodeAt(0));
1432
- } else if (typeof input === "number") {
1433
- const digits = Math.abs(input).toString().split("").map(Number);
1434
- elements = digits;
1435
- } else if (input !== null && typeof input === "object" && input.reiType === "MDim") {
1436
- elements = [input.center, ...input.neighbors];
1437
- } else {
1438
- return { reiType: "MDim", center: input ?? 0, neighbors: [], mode: "weighted" };
1439
- }
1440
- if (elements.length === 0) {
1441
- return { reiType: "MDim", center: 0, neighbors: [], mode: "weighted" };
1442
- }
1443
- let centerIndex = 0;
1444
- if (centerSpec === ":max" || centerSpec === "max") {
1445
- centerIndex = elements.indexOf(Math.max(...elements.map(Number)));
1446
- } else if (centerSpec === ":min" || centerSpec === "min") {
1447
- centerIndex = elements.indexOf(Math.min(...elements.map(Number)));
1448
- } else if (centerSpec === ":first" || centerSpec === "first") {
1449
- centerIndex = 0;
1450
- } else if (centerSpec === ":last" || centerSpec === "last") {
1451
- centerIndex = elements.length - 1;
1452
- } else if (centerSpec === ":middle" || centerSpec === "middle") {
1453
- centerIndex = Math.floor(elements.length / 2);
1454
- } else if (typeof centerSpec === "number") {
1455
- const idx = elements.indexOf(centerSpec);
1456
- centerIndex = idx >= 0 ? idx : 0;
1457
- }
1458
- const center = elements[centerIndex];
1459
- const neighbors = elements.filter((_, i) => i !== centerIndex);
1460
- return { reiType: "MDim", center, neighbors, mode: "weighted" };
1461
- }
1462
- function projectAll(input) {
1463
- let elements;
1464
- if (Array.isArray(input)) {
1465
- elements = [...input];
1466
- } else if (typeof input === "string") {
1467
- elements = Array.from(input).map((c) => c.charCodeAt(0));
1468
- } else if (typeof input === "number") {
1469
- elements = Math.abs(input).toString().split("").map(Number);
1470
- } else if (input !== null && typeof input === "object" && input.reiType === "MDim") {
1471
- elements = [input.center, ...input.neighbors];
1472
- } else {
1473
- return [{ reiType: "MDim", center: input ?? 0, neighbors: [], mode: "weighted" }];
1474
- }
1475
- if (elements.length === 0) return [];
1476
- return elements.map((_, centerIdx) => {
1477
- const center = elements[centerIdx];
1478
- const neighbors = elements.filter((_2, i) => i !== centerIdx);
1479
- return { reiType: "MDim", center, neighbors, mode: "weighted" };
1480
- });
1481
- }
1482
- function computeAll(md) {
1483
- if (!md || md.reiType !== "MDim") return [];
1484
- return ALL_COMPUTE_MODES.map((mode) => ({
1485
- mode,
1486
- value: computeMDim({ ...md, mode })
1487
- }));
1488
- }
1489
- function compareModes(md, mode1, mode2) {
1490
- if (!md || md.reiType !== "MDim") return null;
1491
- const v1 = computeMDim({ ...md, mode: mode1 });
1492
- const v2 = computeMDim({ ...md, mode: mode2 });
1493
- return {
1494
- reiType: "CompareResult",
1495
- mode1: { mode: mode1, value: v1 },
1496
- mode2: { mode: mode2, value: v2 },
1497
- diff: Math.abs(v1 - v2),
1498
- ratio: v2 !== 0 ? v1 / v2 : Infinity
1499
- };
1500
- }
1501
- function perspectives(input) {
1502
- const allProjections = projectAll(input);
1503
- return allProjections.map((proj, idx) => {
1504
- const results = ALL_COMPUTE_MODES.map((mode) => ({
1505
- mode,
1506
- value: computeMDim({ ...proj, mode })
1507
- }));
1508
- return {
1509
- projectionIndex: idx,
1510
- center: proj.center,
1511
- neighbors: proj.neighbors,
1512
- results
1513
- };
1514
- });
1515
- }
1516
- function computeNestedMDim(md) {
1517
- const center = md.reiType === "MDim" ? md.center !== null && typeof md.center === "object" && md.center.reiType === "MDim" ? computeNestedMDim(md.center) : typeof md.center === "number" ? md.center : 0 : typeof md === "number" ? md : 0;
1518
- const neighbors = (md.neighbors ?? []).map(
1519
- (n) => n !== null && typeof n === "object" && n.reiType === "MDim" ? computeNestedMDim(n) : typeof n === "number" ? n : 0
1520
- );
1521
- return computeMDim({ ...md, center, neighbors });
1522
- }
1523
- function respondToStimulus(input, stimulus, method = "absorb") {
1524
- if (input !== null && typeof input === "object" && input.reiType === "MDim") {
1525
- const md = input;
1526
- switch (method) {
1527
- case "absorb": {
1528
- const factor = stimulus / (Math.abs(md.center) + Math.abs(stimulus) || 1);
1529
- const newCenter = md.center + stimulus * factor;
1530
- return { ...md, center: newCenter };
1531
- }
1532
- case "distribute": {
1533
- const share = stimulus / (md.neighbors.length || 1);
1534
- const newNeighbors = md.neighbors.map((n) => n + share);
1535
- return { ...md, neighbors: newNeighbors };
1536
- }
1537
- case "reflect": {
1538
- const newNeighbors = md.neighbors.map((n) => n - stimulus / (md.neighbors.length || 1));
1539
- return { ...md, neighbors: newNeighbors };
1540
- }
1541
- case "resonate": {
1542
- const newCenter = md.center * (1 + Math.sin(stimulus));
1543
- const newNeighbors = md.neighbors.map(
1544
- (n, i) => n * (1 + Math.sin(stimulus + (i + 1) * Math.PI / md.neighbors.length))
1545
- );
1546
- return { ...md, center: newCenter, neighbors: newNeighbors };
1547
- }
1548
- default:
1549
- return respondToStimulus(input, stimulus, "absorb");
1550
- }
1551
- }
1552
- if (typeof input === "number") return input + stimulus;
1553
- return input;
1554
- }
1555
- function computeSensitivity(input) {
1556
- if (input !== null && typeof input === "object" && input.reiType === "MDim") {
1557
- const original = computeMDim(input);
1558
- const epsilon = 1e-3;
1559
- const perturbed = respondToStimulus(input, epsilon, "absorb");
1560
- const perturbedVal = computeMDim(perturbed);
1561
- return Math.abs(perturbedVal - original) / epsilon;
1562
- }
1563
- if (typeof input === "number") return 1;
1564
- return 0;
1565
- }
1566
- function computeAwareness(input, meta) {
1567
- let score = 0;
1568
- const maxScore = 5;
1569
- score += Math.min(meta.memory.length / 5, 1);
1570
- if (meta.tendency !== "rest") score += 1;
1571
- score += Math.min(meta.pipeCount / 5, 1);
1572
- const raw = unwrapReiVal(input);
1573
- if (raw !== null && typeof raw === "object") {
1574
- if (raw.reiType === "MDim" && raw.neighbors) {
1575
- score += Math.min(raw.neighbors.length / 8, 1);
1576
- } else if (raw.reiType === "Space") {
1577
- score += 1;
1578
- } else if (raw.reiType === "State" && raw.history) {
1579
- score += Math.min(raw.history.length / 5, 1);
1580
- }
1581
- }
1582
- if (meta.memory.length >= 2) {
1583
- const unique = new Set(meta.memory.map((v) => JSON.stringify(v)));
1584
- score += Math.min(unique.size / meta.memory.length, 1);
1585
- }
1586
- return Math.min(score / maxScore, 1);
1587
- }
1588
- var AWAKENING_THRESHOLD = 0.6;
1589
- function applyTransform(input, transformName, param) {
1590
- const raw = unwrapReiVal(input);
1591
- if (raw !== null && typeof raw === "object" && raw.reiType === "MDim") {
1592
- const md = raw;
1593
- switch (transformName) {
1594
- case "scale": {
1595
- return { ...md, center: md.center * param, neighbors: md.neighbors.map((n) => n * param) };
1596
- }
1597
- case "shift": {
1598
- return { ...md, center: md.center + param, neighbors: md.neighbors.map((n) => n + param) };
1599
- }
1600
- case "rotate": {
1601
- const n = md.neighbors.length;
1602
- if (n === 0) return md;
1603
- const shift = (param % n + n) % n;
1604
- const rotated = [...md.neighbors.slice(shift), ...md.neighbors.slice(0, shift)];
1605
- return { ...md, neighbors: rotated };
1606
- }
1607
- case "invert": {
1608
- return { ...md, neighbors: md.neighbors.map((n) => 2 * md.center - n) };
1609
- }
1610
- case "normalize_to": {
1611
- const total = Math.abs(md.center) + md.neighbors.reduce((s, v) => s + Math.abs(v), 0) || 1;
1612
- const factor = param / total;
1613
- return { ...md, center: md.center * factor, neighbors: md.neighbors.map((n) => n * factor) };
1614
- }
1615
- default:
1616
- throw new Error(`\u672A\u77E5\u306E\u5909\u63DB: ${transformName}`);
1617
- }
1618
- }
1619
- if (typeof raw === "number") {
1620
- switch (transformName) {
1621
- case "scale":
1622
- return raw * param;
1623
- case "shift":
1624
- return raw + param;
1625
- case "invert":
1626
- return -raw;
1627
- default:
1628
- return raw;
1629
- }
1630
- }
1631
- return raw;
1632
- }
1633
- function checkModeEquivalence(md, mode1, mode2) {
1634
- if (!md || md.reiType !== "MDim") return { equivalent: false, reason: "non-MDim input" };
1635
- const v1 = computeMDim({ ...md, mode: mode1 });
1636
- const v2 = computeMDim({ ...md, mode: mode2 });
1637
- return {
1638
- reiType: "ModeEquivResult",
1639
- mode1,
1640
- mode2,
1641
- type_equivalent: typeof v1 === typeof v2,
1642
- // M2: 出力型が等価
1643
- value1: v1,
1644
- value2: v2,
1645
- relative_diff: Math.abs(v2) > 0 ? Math.abs(v1 - v2) / Math.abs(v2) : v1 === v2 ? 0 : Infinity
1646
- };
1647
- }
1648
- function computeResonance(a, b) {
1649
- const aRaw = unwrapReiVal(a);
1650
- const bRaw = unwrapReiVal(b);
1651
- const aNum = typeof aRaw === "number" ? aRaw : aRaw?.center ?? 0;
1652
- const bNum = typeof bRaw === "number" ? bRaw : bRaw?.center ?? 0;
1653
- const aDim = aRaw?.neighbors?.length ?? 0;
1654
- const bDim = bRaw?.neighbors?.length ?? 0;
1655
- const dimMatch = aDim === 0 && bDim === 0 ? 1 : 1 - Math.abs(aDim - bDim) / Math.max(aDim, bDim, 1);
1656
- const maxAbs = Math.max(Math.abs(aNum), Math.abs(bNum), 1);
1657
- const valueProximity = 1 - Math.abs(aNum - bNum) / maxAbs;
1658
- let patternSimilarity = 0;
1659
- if (aDim > 0 && bDim > 0) {
1660
- const minLen = Math.min(aDim, bDim);
1661
- const aN = aRaw.neighbors.slice(0, minLen);
1662
- const bN = bRaw.neighbors.slice(0, minLen);
1663
- const dotProduct = aN.reduce((s, v, i) => s + v * bN[i], 0);
1664
- const normA = Math.sqrt(aN.reduce((s, v) => s + v * v, 0)) || 1;
1665
- const normB = Math.sqrt(bN.reduce((s, v) => s + v * v, 0)) || 1;
1666
- patternSimilarity = dotProduct / (normA * normB);
1667
- }
1668
- const strength = dimMatch * 0.3 + Math.max(valueProximity, 0) * 0.3 + (patternSimilarity + 1) / 2 * 0.4;
1669
- return {
1670
- reiType: "ResonanceResult",
1671
- strength: Math.max(0, Math.min(1, strength)),
1672
- dimMatch,
1673
- valueProximity: Math.max(0, valueProximity),
1674
- patternSimilarity,
1675
- resonates: strength >= 0.5
1676
- };
1677
- }
1678
- function getResonanceField(input, meta) {
1679
- const raw = unwrapReiVal(input);
1680
- const isAwakened = computeAwareness(input, meta) >= AWAKENING_THRESHOLD;
1681
- return {
1682
- reiType: "ResonanceField",
1683
- awakened: isAwakened,
1684
- // 覚醒値はより広い共鳴場を持つ
1685
- range: isAwakened ? "non-local" : "local",
1686
- capacity: isAwakened ? 1 : 0.3,
1687
- signature: raw?.neighbors?.length ?? 0
1688
- };
1689
- }
1690
- function resonanceMap(input) {
1691
- const raw = unwrapReiVal(input);
1692
- if (!Array.isArray(raw)) {
1693
- if (raw?.reiType === "MDim") {
1694
- return raw.neighbors.map((n, i) => ({
1695
- pair: [raw.center, n],
1696
- index: i,
1697
- strength: 1 - Math.abs(raw.center - n) / Math.max(Math.abs(raw.center), Math.abs(n), 1)
1698
- }));
1699
- }
1700
- return [];
1701
- }
1702
- const results = [];
1703
- for (let i = 0; i < raw.length; i++) {
1704
- for (let j = i + 1; j < raw.length; j++) {
1705
- const res = computeResonance(raw[i], raw[j]);
1706
- results.push({ pair: [i, j], ...res });
1707
- }
1708
- }
1709
- return results;
1710
- }
1711
- function resonanceChain(input) {
1712
- const raw = unwrapReiVal(input);
1713
- if (!raw || raw.reiType !== "MDim") {
1714
- return { reiType: "ResonanceChain", chain: [], depth: 0 };
1715
- }
1716
- const chain = [];
1717
- const visited = /* @__PURE__ */ new Set();
1718
- function trace(value, depth) {
1719
- if (visited.has(value) || depth > 5) return;
1720
- visited.add(value);
1721
- chain.push({ value, depth });
1722
- for (const n of raw.neighbors) {
1723
- if (!visited.has(n)) {
1724
- const proximity = 1 - Math.abs(value - n) / Math.max(Math.abs(value), Math.abs(n), 1);
1725
- if (proximity > 0.3) trace(n, depth + 1);
1726
- }
1727
- }
1728
- }
1729
- trace(raw.center, 0);
1730
- return { reiType: "ResonanceChain", chain, depth: chain.length };
1731
- }
1732
- function projectAs(input, targetType) {
1733
- const raw = unwrapReiVal(input);
1734
- let md;
1735
- if (raw?.reiType === "MDim") {
1736
- md = raw;
1737
- } else if (Array.isArray(raw)) {
1738
- md = projectToMDim(raw, "first");
1739
- } else if (typeof raw === "number") {
1740
- const digits = String(Math.abs(Math.floor(raw))).split("").map(Number);
1741
- md = { reiType: "MDim", center: digits[0], neighbors: digits.slice(1), mode: "weighted" };
1742
- } else {
1743
- md = { reiType: "MDim", center: 0, neighbors: [], mode: "weighted" };
1744
- }
1745
- switch (targetType) {
1746
- case "graph": {
1747
- const edges = md.neighbors.map((n, i) => ({
1748
- from: md.center,
1749
- to: n,
1750
- weight: Math.abs(md.center - n)
1751
- }));
1752
- return {
1753
- reiType: "GraphProjection",
1754
- hub: md.center,
1755
- nodes: [md.center, ...md.neighbors],
1756
- edges,
1757
- degree: md.neighbors.length
1758
- };
1759
- }
1760
- case "series": {
1761
- const series = [md.center, ...md.neighbors];
1762
- const deltas = [];
1763
- for (let i = 1; i < series.length; i++) deltas.push(series[i] - series[i - 1]);
1764
- return {
1765
- reiType: "SeriesProjection",
1766
- values: series,
1767
- deltas,
1768
- trend: deltas.length > 0 ? deltas.reduce((a, b) => a + b, 0) / deltas.length > 0 ? "up" : "down" : "flat",
1769
- length: series.length
1770
- };
1771
- }
1772
- case "matrix": {
1773
- const size = md.neighbors.length + 1;
1774
- const row = [md.center, ...md.neighbors];
1775
- return {
1776
- reiType: "MatrixProjection",
1777
- row,
1778
- size,
1779
- diagonal: md.center,
1780
- trace: md.center
1781
- // 1行分のtrace
1782
- };
1783
- }
1784
- case "tree": {
1785
- const children = md.neighbors.map((n, i) => ({
1786
- value: n,
1787
- depth: 1,
1788
- index: i,
1789
- leaf: true
1790
- }));
1791
- return {
1792
- reiType: "TreeProjection",
1793
- root: md.center,
1794
- children,
1795
- height: md.neighbors.length > 0 ? 1 : 0,
1796
- leaves: md.neighbors.length
1797
- };
1798
- }
1799
- default:
1800
- throw new Error(`\u672A\u77E5\u306E\u5C04\u5F71\u578B: ${targetType}`);
1801
- }
1802
- }
1803
- function composeProjections(input) {
1804
- const raw = unwrapReiVal(input);
1805
- if (!Array.isArray(raw)) {
1806
- if (raw?.reiType === "MDim") {
1807
- const allProj = projectAll(raw);
1808
- const values = allProj.map((p) => computeMDim(p));
1809
- const center = values.reduce((a, b) => a + b, 0) / values.length;
1810
- return { reiType: "MDim", center, neighbors: values, mode: "weighted" };
1811
- }
1812
- return raw;
1813
- }
1814
- const projected = raw.map((item) => {
1815
- if (item?.reiType === "MDim") return item;
1816
- return projectToMDim(typeof item === "number" ? [item] : item, "first");
1817
- });
1818
- const centers = projected.map((p) => p.center);
1819
- const avgCenter = centers.reduce((a, b) => a + b, 0) / centers.length;
1820
- return { reiType: "MDim", center: avgCenter, neighbors: centers, mode: "weighted" };
1821
- }
1822
- function checkRepresentable(input) {
1823
- const raw = unwrapReiVal(input);
1824
- const result = { reiType: "RepresentableResult", representable: true, reason: "", lossless: true };
1825
- if (raw === null || raw === void 0) {
1826
- result.representable = true;
1827
- result.reason = "null \u2192 \u{1D544}{0;}";
1828
- result.lossless = true;
1829
- } else if (typeof raw === "number") {
1830
- result.representable = true;
1831
- result.reason = "number \u2192 \u{1D544}{n;}";
1832
- result.lossless = true;
1833
- } else if (typeof raw === "string") {
1834
- result.representable = true;
1835
- result.reason = "string \u2192 \u{1D544}{charCode(center); charCodes(rest)}";
1836
- result.lossless = true;
1837
- } else if (typeof raw === "boolean") {
1838
- result.representable = true;
1839
- result.reason = "boolean \u2192 \u{1D544}{0|1;}";
1840
- result.lossless = true;
1841
- } else if (Array.isArray(raw)) {
1842
- result.representable = true;
1843
- result.reason = `array[${raw.length}] \u2192 \u{1D544}{first; rest}`;
1844
- result.lossless = true;
1845
- } else if (raw?.reiType === "MDim") {
1846
- result.representable = true;
1847
- result.reason = "already \u{1D544}";
1848
- result.lossless = true;
1849
- } else if (raw?.reiType === "Space") {
1850
- result.representable = true;
1851
- result.reason = "Space \u2192 nested \u{1D544} (U3 hierarchical)";
1852
- result.lossless = true;
1853
- } else if (raw?.reiType) {
1854
- result.representable = true;
1855
- result.reason = `${raw.reiType} \u2192 \u{1D544} via structural projection`;
1856
- result.lossless = false;
1857
- } else if (typeof raw === "object") {
1858
- result.representable = true;
1859
- result.reason = "object \u2192 \u{1D544}{keys; values}";
1860
- result.lossless = false;
1861
- } else {
1862
- result.representable = false;
1863
- result.reason = `unknown type: ${typeof raw}`;
1864
- result.lossless = false;
1865
- }
1866
- return result;
1867
- }
1868
- function deriveMode(md, baseModes, weights) {
1869
- if (!md || md.reiType !== "MDim") throw new Error("derive_mode: \u{1D544}\u578B\u304C\u5FC5\u8981\u3067\u3059");
1870
- const results = baseModes.map((m) => computeMDim({ ...md, mode: m }));
1871
- let derived = 0;
1872
- let totalWeight = 0;
1873
- for (let i = 0; i < results.length; i++) {
1874
- const w = weights[i] ?? 1;
1875
- derived += results[i] * w;
1876
- totalWeight += w;
1877
- }
1878
- derived = totalWeight > 0 ? derived / totalWeight : 0;
1879
- return {
1880
- reiType: "DerivedModeResult",
1881
- value: derived,
1882
- baseModes,
1883
- weights,
1884
- formula: baseModes.map((m, i) => `${weights[i] ?? 1}\xD7${m}`).join(" + ")
1885
- };
1886
- }
1887
- function getModeSpace(md) {
1888
- if (!md || md.reiType !== "MDim") {
1889
- return { reiType: "ModeSpace", modes: ALL_COMPUTE_MODES.length, values: [], coverage: 0 };
1890
- }
1891
- const values = ALL_COMPUTE_MODES.map((mode) => ({
1892
- mode,
1893
- value: computeMDim({ ...md, mode })
1894
- }));
1895
- const distances = [];
1896
- for (let i = 0; i < values.length; i++) {
1897
- distances[i] = [];
1898
- for (let j = 0; j < values.length; j++) {
1899
- distances[i][j] = Math.abs(values[i].value - values[j].value);
1900
- }
1901
- }
1902
- const allVals = values.map((v) => v.value);
1903
- const mean = allVals.reduce((a, b) => a + b, 0) / allVals.length;
1904
- const variance = allVals.reduce((a, v) => a + (v - mean) ** 2, 0) / allVals.length;
1905
- return {
1906
- reiType: "ModeSpace",
1907
- modes: ALL_COMPUTE_MODES.length,
1908
- values,
1909
- variance,
1910
- diversity: Math.sqrt(variance),
1911
- coverage: 1
1912
- // 全モード利用可能
1913
- };
1914
- }
1915
- function measureDepth(input) {
1916
- const raw = unwrapReiVal(input);
1917
- if (!raw || raw.reiType !== "MDim") return 0;
1918
- let maxDepth = 0;
1919
- if (raw.center !== null && typeof raw.center === "object" && raw.center.reiType === "MDim") {
1920
- maxDepth = Math.max(maxDepth, 1 + measureDepth(raw.center));
1921
- }
1922
- if (raw.neighbors) {
1923
- for (const n of raw.neighbors) {
1924
- if (n !== null && typeof n === "object" && n.reiType === "MDim") {
1925
- maxDepth = Math.max(maxDepth, 1 + measureDepth(n));
1926
- }
1927
- }
1928
- }
1929
- return maxDepth;
1930
- }
1931
- function nestMDim(input, levels = 1) {
1932
- const raw = unwrapReiVal(input);
1933
- if (!raw || raw.reiType !== "MDim") {
1934
- const md = { reiType: "MDim", center: typeof raw === "number" ? raw : 0, neighbors: [], mode: "weighted" };
1935
- return levels <= 1 ? md : nestMDim(md, levels - 1);
1936
- }
1937
- if (levels <= 0) return raw;
1938
- const wrapped = {
1939
- reiType: "MDim",
1940
- center: raw,
1941
- neighbors: [],
1942
- mode: "weighted"
1943
- };
1944
- return levels <= 1 ? wrapped : nestMDim(wrapped, levels - 1);
1945
- }
1946
- function recursiveCompute(input) {
1947
- const raw = unwrapReiVal(input);
1948
- if (typeof raw === "number") return raw;
1949
- if (!raw || raw.reiType !== "MDim") return 0;
1950
- const centerVal = raw.center?.reiType === "MDim" ? recursiveCompute(raw.center) : typeof raw.center === "number" ? raw.center : 0;
1951
- const neighborVals = (raw.neighbors || []).map(
1952
- (n) => n?.reiType === "MDim" ? recursiveCompute(n) : typeof n === "number" ? n : 0
1953
- );
1954
- return computeMDim({
1955
- reiType: "MDim",
1956
- center: centerVal,
1957
- neighbors: neighborVals,
1958
- mode: raw.mode || "weighted"
1959
- });
1960
- }
1961
- function structuralSimilarity(a, b) {
1962
- const aRaw = unwrapReiVal(a);
1963
- const bRaw = unwrapReiVal(b);
1964
- const aDim = aRaw?.neighbors?.length ?? 0;
1965
- const bDim = bRaw?.neighbors?.length ?? 0;
1966
- const dimSim = aDim === 0 && bDim === 0 ? 1 : 1 - Math.abs(aDim - bDim) / Math.max(aDim, bDim, 1);
1967
- const aCenter = typeof aRaw === "number" ? aRaw : aRaw?.center ?? 0;
1968
- const bCenter = typeof bRaw === "number" ? bRaw : bRaw?.center ?? 0;
1969
- const aRatios = (aRaw?.neighbors ?? []).map((n) => aCenter !== 0 ? n / aCenter : n);
1970
- const bRatios = (bRaw?.neighbors ?? []).map((n) => bCenter !== 0 ? n / bCenter : n);
1971
- let ratioSim = 0;
1972
- if (aRatios.length > 0 && bRatios.length > 0) {
1973
- const minLen = Math.min(aRatios.length, bRatios.length);
1974
- let sumDiff = 0;
1975
- for (let i = 0; i < minLen; i++) {
1976
- sumDiff += Math.abs(aRatios[i] - bRatios[i]);
1977
- }
1978
- ratioSim = 1 / (1 + sumDiff / minLen);
1979
- } else if (aRatios.length === 0 && bRatios.length === 0) {
1980
- ratioSim = 1;
1981
- }
1982
- const modeSim = (aRaw?.mode ?? "weighted") === (bRaw?.mode ?? "weighted") ? 1 : 0.5;
1983
- const similarity = dimSim * 0.4 + ratioSim * 0.4 + modeSim * 0.2;
1984
- return {
1985
- reiType: "SimilarityResult",
1986
- similarity,
1987
- dimSimilarity: dimSim,
1988
- ratioSimilarity: ratioSim,
1989
- modeSimilarity: modeSim,
1990
- isomorphic: similarity > 0.9
1991
- };
1992
- }
1993
- function bridgeMDim(a, b) {
1994
- const sim = structuralSimilarity(a, b);
1995
- const aRaw = unwrapReiVal(a);
1996
- const bRaw = unwrapReiVal(b);
1997
- const aCenter = typeof aRaw === "number" ? aRaw : aRaw?.center ?? 0;
1998
- const bCenter = typeof bRaw === "number" ? bRaw : bRaw?.center ?? 0;
1999
- const scaleFactor = aCenter !== 0 ? bCenter / aCenter : 1;
2000
- return {
2001
- reiType: "BridgeResult",
2002
- similarity: sim.similarity,
2003
- scaleFactor,
2004
- mapping: {
2005
- centerA: aCenter,
2006
- centerB: bCenter,
2007
- dimA: aRaw?.neighbors?.length ?? 0,
2008
- dimB: bRaw?.neighbors?.length ?? 0
2009
- },
2010
- transferable: sim.similarity > 0.5
2011
- };
2012
- }
2013
- function encodeMDim(input) {
2014
- const raw = unwrapReiVal(input);
2015
- if (raw?.reiType === "MDim") return raw;
2016
- if (typeof raw === "number") {
2017
- return { reiType: "MDim", center: raw, neighbors: [], mode: "weighted" };
2018
- }
2019
- if (typeof raw === "string") {
2020
- const codes = Array.from(raw).map((c) => c.charCodeAt(0));
2021
- if (codes.length === 0) return { reiType: "MDim", center: 0, neighbors: [], mode: "weighted" };
2022
- return { reiType: "MDim", center: codes[0], neighbors: codes.slice(1), mode: "weighted" };
2023
- }
2024
- if (typeof raw === "boolean") {
2025
- return { reiType: "MDim", center: raw ? 1 : 0, neighbors: [], mode: "weighted" };
2026
- }
2027
- if (raw === null || raw === void 0) {
2028
- return { reiType: "MDim", center: 0, neighbors: [], mode: "weighted" };
2029
- }
2030
- if (Array.isArray(raw)) {
2031
- const nums = raw.map((v) => typeof v === "number" ? v : 0);
2032
- return { reiType: "MDim", center: nums[0] ?? 0, neighbors: nums.slice(1), mode: "weighted" };
2033
- }
2034
- if (typeof raw === "object") {
2035
- const values = Object.values(raw).filter((v) => typeof v === "number");
2036
- return { reiType: "MDim", center: values[0] ?? 0, neighbors: values.slice(1), mode: "weighted" };
2037
- }
2038
- return { reiType: "MDim", center: 0, neighbors: [], mode: "weighted" };
2039
- }
2040
- function decodeMDim(input, targetType) {
2041
- const raw = unwrapReiVal(input);
2042
- const md = raw?.reiType === "MDim" ? raw : encodeMDim(raw);
2043
- switch (targetType) {
2044
- case "number":
2045
- return computeMDim(md);
2046
- case "array":
2047
- return [md.center, ...md.neighbors];
2048
- case "string":
2049
- return String.fromCharCode(md.center, ...md.neighbors);
2050
- case "object":
2051
- const obj = { center: md.center };
2052
- md.neighbors.forEach((n, i) => {
2053
- obj[`n${i}`] = n;
2054
- });
2055
- return obj;
2056
- default:
2057
- return [md.center, ...md.neighbors];
2058
- }
2059
- }
2060
- function mapSolutions(md, transformName, param = 1) {
2061
- const solutions = computeAll(md);
2062
- return solutions.map((sol) => {
2063
- let transformed;
2064
- switch (transformName) {
2065
- case "scale":
2066
- transformed = sol.value * param;
2067
- break;
2068
- case "shift":
2069
- transformed = sol.value + param;
2070
- break;
2071
- case "normalize": {
2072
- const maxVal = Math.max(...solutions.map((s) => Math.abs(s.value)), 1);
2073
- transformed = sol.value / maxVal;
2074
- break;
2075
- }
2076
- case "rank_normalize": {
2077
- const sorted = [...solutions].sort((a, b) => a.value - b.value);
2078
- const rank = sorted.findIndex((s) => s.mode === sol.mode);
2079
- transformed = (rank + 1) / solutions.length;
2080
- break;
2081
- }
2082
- default:
2083
- transformed = sol.value;
2084
- }
2085
- return { ...sol, original: sol.value, value: transformed, transform: transformName };
2086
- });
2087
- }
2088
- function computeConsensus(md) {
2089
- const solutions = computeAll(md);
2090
- const values = solutions.map((s) => s.value);
2091
- const sorted = [...values].sort((a, b) => a - b);
2092
- const median = sorted.length % 2 === 0 ? (sorted[sorted.length / 2 - 1] + sorted[sorted.length / 2]) / 2 : sorted[Math.floor(sorted.length / 2)];
2093
- const mean = values.reduce((a, b) => a + b, 0) / values.length;
2094
- const variance = values.reduce((a, v) => a + (v - mean) ** 2, 0) / values.length;
2095
- const stddev = Math.sqrt(variance);
2096
- const agreement = 1 / (1 + stddev / (Math.abs(mean) || 1));
2097
- return {
2098
- reiType: "ConsensusResult",
2099
- median,
2100
- mean,
2101
- stddev,
2102
- agreement,
2103
- solutions: solutions.length,
2104
- range: { min: sorted[0], max: sorted[sorted.length - 1] }
2105
- };
2106
- }
2107
- function selectBest(md, criteria = "median_closest") {
2108
- const solutions = computeAll(md);
2109
- const values = solutions.map((s) => s.value);
2110
- switch (criteria) {
2111
- case "max":
2112
- return solutions.reduce((best, s) => s.value > best.value ? s : best);
2113
- case "min":
2114
- return solutions.reduce((best, s) => s.value < best.value ? s : best);
2115
- case "median_closest":
2116
- default: {
2117
- const sorted = [...values].sort((a, b) => a - b);
2118
- const median = sorted.length % 2 === 0 ? (sorted[sorted.length / 2 - 1] + sorted[sorted.length / 2]) / 2 : sorted[Math.floor(sorted.length / 2)];
2119
- return solutions.reduce(
2120
- (best, s) => Math.abs(s.value - median) < Math.abs(best.value - median) ? s : best
2121
- );
2122
- }
2123
- }
2124
- }
2125
- function rankSolutions(md, criteria = "value") {
2126
- const solutions = computeAll(md);
2127
- const sorted = [...solutions].sort((a, b) => {
2128
- switch (criteria) {
2129
- case "value":
2130
- return b.value - a.value;
2131
- // 降順
2132
- case "abs":
2133
- return Math.abs(b.value) - Math.abs(a.value);
2134
- default:
2135
- return b.value - a.value;
2136
- }
2137
- });
2138
- return sorted.map((s, i) => ({ ...s, rank: i + 1 }));
2139
- }
2140
- function solutionCompleteness(md) {
2141
- const solutions = computeAll(md);
2142
- const values = solutions.map((s) => s.value);
2143
- const uniqueValues = new Set(values.map((v) => Math.round(v * 1e6) / 1e6));
2144
- const uniqueRatio = uniqueValues.size / values.length;
2145
- const sorted = [...values].sort((a, b) => a - b);
2146
- const range = sorted[sorted.length - 1] - sorted[0];
2147
- const bins = 4;
2148
- const binWidth = range / bins || 1;
2149
- const histogram = new Array(bins).fill(0);
2150
- for (const v of values) {
2151
- const bin = Math.min(Math.floor((v - sorted[0]) / binWidth), bins - 1);
2152
- histogram[bin]++;
2153
- }
2154
- const total = values.length;
2155
- let entropy = 0;
2156
- for (const count of histogram) {
2157
- if (count > 0) {
2158
- const p = count / total;
2159
- entropy -= p * Math.log2(p);
2160
- }
2161
- }
2162
- const maxEntropy = Math.log2(bins);
2163
- const uniformity = maxEntropy > 0 ? entropy / maxEntropy : 1;
2164
- return {
2165
- reiType: "CompletenessResult",
2166
- totalModes: solutions.length,
2167
- uniqueSolutions: uniqueValues.size,
2168
- uniqueRatio,
2169
- range,
2170
- uniformity,
2171
- completeness: uniqueRatio * 0.5 + uniformity * 0.5,
2172
- isComplete: uniqueRatio > 0.5 && uniformity > 0.3
2173
- };
2174
- }
2175
- function quadNot(v) {
2176
- switch (v) {
2177
- case "top":
2178
- return "bottom";
2179
- case "bottom":
2180
- return "top";
2181
- case "topPi":
2182
- return "bottomPi";
2183
- case "bottomPi":
2184
- return "topPi";
2185
- default:
2186
- return v;
2187
- }
2188
- }
2189
- function quadAnd(a, b) {
2190
- if (a === "bottom" || b === "bottom") return "bottom";
2191
- if (a === "top" && b === "top") return "top";
2192
- return "bottomPi";
2193
- }
2194
- function quadOr(a, b) {
2195
- if (a === "top" || b === "top") return "top";
2196
- if (a === "bottom" && b === "bottom") return "bottom";
2197
- return "topPi";
2198
- }
2199
- var PHASE_ORDER = ["void", "dot", "line", "surface", "solid", "omega"];
2200
- function createGenesis() {
2201
- return { reiType: "State", state: "void", omega: 0, history: ["void"] };
2202
- }
2203
- function genesisForward(g) {
2204
- const idx = PHASE_ORDER.indexOf(g.state);
2205
- if (idx < PHASE_ORDER.length - 1) {
2206
- g.state = PHASE_ORDER[idx + 1];
2207
- g.history.push(g.state);
2208
- if (g.state === "omega") g.omega = 1;
2209
- }
2210
- }
2211
- var Evaluator = class {
2212
- constructor(parent) {
2213
- this.env = new Environment(parent ?? null);
2214
- this.registerBuiltins();
2215
- }
2216
- registerBuiltins() {
2217
- this.env.define("e", Math.E);
2218
- this.env.define("PI", Math.PI);
2219
- this.env.define("genesis", {
2220
- reiType: "Function",
2221
- name: "genesis",
2222
- params: [],
2223
- body: null,
2224
- closure: this.env
2225
- });
2226
- const mathFns = ["abs", "sqrt", "sin", "cos", "log", "exp", "floor", "ceil", "round", "min", "max", "len", "print"];
2227
- for (const name of mathFns) {
2228
- this.env.define(name, {
2229
- reiType: "Function",
2230
- name,
2231
- params: ["x"],
2232
- body: null,
2233
- closure: this.env
2234
- });
2235
- }
2236
- }
2237
- eval(ast) {
2238
- switch (ast.type) {
2239
- case "Program":
2240
- return this.evalProgram(ast);
2241
- case "NumLit":
2242
- return ast.value;
2243
- case "StrLit":
2244
- return ast.value;
2245
- case "BoolLit":
2246
- return ast.value;
2247
- case "NullLit":
2248
- return null;
2249
- case "ExtLit":
2250
- return parseExtLit(ast.raw);
2251
- case "ConstLit":
2252
- return this.evalConstLit(ast);
2253
- case "QuadLit":
2254
- return { reiType: "Quad", value: ast.value };
2255
- case "MDimLit":
2256
- return this.evalMDimLit(ast);
2257
- case "ArrayLit":
2258
- return ast.elements.map((e) => this.eval(e));
2259
- case "Ident":
2260
- return this.env.get(ast.name);
2261
- case "LetStmt":
2262
- return this.evalLetStmt(ast);
2263
- case "MutStmt":
2264
- return this.evalMutStmt(ast);
2265
- case "CompressDef":
2266
- return this.evalCompressDef(ast);
2267
- case "BinOp":
2268
- return this.evalBinOp(ast);
2269
- case "UnaryOp":
2270
- return this.evalUnaryOp(ast);
2271
- case "Pipe":
2272
- return this.evalPipe(ast);
2273
- case "FnCall":
2274
- return this.evalFnCall(ast);
2275
- case "MemberAccess":
2276
- return this.evalMemberAccess(ast);
2277
- case "IndexAccess":
2278
- return this.evalIndexAccess(ast);
2279
- case "Extend":
2280
- return this.evalExtend(ast);
2281
- case "Reduce":
2282
- return this.evalReduce(ast);
2283
- case "ConvergeOp":
2284
- return this.evalConverge(ast);
2285
- case "DivergeOp":
2286
- return this.evalDiverge(ast);
2287
- case "ReflectOp":
2288
- return this.evalReflect(ast);
2289
- case "IfExpr":
2290
- return this.evalIfExpr(ast);
2291
- case "MatchExpr":
2292
- return this.evalMatchExpr(ast);
2293
- // ── v0.3 ──
2294
- case "SpaceLit":
2295
- return this.evalSpaceLit(ast);
2296
- default:
2297
- throw new Error(`\u672A\u5B9F\u88C5\u306E\u30CE\u30FC\u30C9\u578B: ${ast.type}`);
2298
- }
2299
- }
2300
- evalProgram(ast) {
2301
- let result = null;
2302
- for (const stmt of ast.body) {
2303
- result = this.eval(stmt);
2304
- }
2305
- return result;
2306
- }
2307
- evalConstLit(ast) {
2308
- switch (ast.value) {
2309
- case "\u30FB":
2310
- return createGenesis();
2311
- case "\u2205":
2312
- return null;
2313
- case "i":
2314
- return { reiType: "Ext", base: NaN, order: 0, subscripts: "", valStar: () => NaN };
2315
- case "\u03A6":
2316
- return "\u03A6";
2317
- case "\u03A8":
2318
- return "\u03A8";
2319
- case "\u03A9":
2320
- return "\u03A9";
2321
- default:
2322
- return null;
2323
- }
2324
- }
2325
- evalMDimLit(ast) {
2326
- const center = this.toNumber(this.eval(ast.center));
2327
- const neighbors = ast.neighbors.map((n) => this.toNumber(this.eval(n)));
2328
- const weights = ast.weight ? [this.toNumber(this.eval(ast.weight))] : void 0;
2329
- const mode = ast.mode || "weighted";
2330
- return { reiType: "MDim", center, neighbors, mode, weights };
2331
- }
2332
- // ── v0.3: Space literal evaluation ──
2333
- evalSpaceLit(ast) {
2334
- const space = createSpace(ast.topology || "flat");
2335
- for (const layerDef of ast.layers) {
2336
- const layerIndex = typeof layerDef.index === "object" ? this.toNumber(this.eval(layerDef.index)) : layerDef.index;
2337
- for (const nodeExpr of layerDef.nodes) {
2338
- const val = this.eval(nodeExpr);
2339
- if (this.isMDim(val)) {
2340
- addNodeToLayer(space, layerIndex, val.center, val.neighbors, val.mode, val.weights);
2341
- } else if (typeof val === "number") {
2342
- addNodeToLayer(space, layerIndex, val, []);
2343
- }
2344
- }
2345
- }
2346
- return space;
2347
- }
2348
- evalLetStmt(ast) {
2349
- const val = this.eval(ast.init);
2350
- this.env.define(ast.name, val, false);
2351
- return val;
2352
- }
2353
- evalMutStmt(ast) {
2354
- const val = this.eval(ast.init);
2355
- this.env.define(ast.name, val, true);
2356
- return val;
2357
- }
2358
- evalCompressDef(ast) {
2359
- const fn = {
2360
- reiType: "Function",
2361
- name: ast.name,
2362
- params: ast.params,
2363
- body: ast.body,
2364
- closure: this.env
2365
- };
2366
- this.env.define(ast.name, fn);
2367
- return fn;
2368
- }
2369
- evalBinOp(ast) {
2370
- const left = this.eval(ast.left);
2371
- const right = this.eval(ast.right);
2372
- if (this.isQuad(left) && this.isQuad(right)) {
2373
- switch (ast.op) {
2374
- case "\u2227":
2375
- return { reiType: "Quad", value: quadAnd(left.value, right.value) };
2376
- case "\u2228":
2377
- return { reiType: "Quad", value: quadOr(left.value, right.value) };
2378
- }
2379
- }
2380
- const l = this.toNumber(left);
2381
- const r = this.toNumber(right);
2382
- switch (ast.op) {
2383
- case "+":
2384
- return l + r;
2385
- case "-":
2386
- return l - r;
2387
- case "*":
2388
- return l * r;
2389
- case "/":
2390
- return r !== 0 ? l / r : NaN;
2391
- case "\u2295":
2392
- return l + r;
2393
- // ⊕
2394
- case "\u2297":
2395
- return l * r;
2396
- // ⊗
2397
- case "\xB7":
2398
- return l * r;
2399
- // ·
2400
- case "==":
2401
- return l === r;
2402
- case "!=":
2403
- return l !== r;
2404
- case ">":
2405
- return l > r;
2406
- case "<":
2407
- return l < r;
2408
- case ">=":
2409
- return l >= r;
2410
- case "<=":
2411
- return l <= r;
2412
- case ">\u03BA":
2413
- return l > r;
2414
- // >κ
2415
- case "<\u03BA":
2416
- return l < r;
2417
- // <κ
2418
- case "=\u03BA":
2419
- return l === r;
2420
- // =κ
2421
- case "\u2227":
2422
- return l !== 0 && r !== 0;
2423
- // ∧
2424
- case "\u2228":
2425
- return l !== 0 || r !== 0;
2426
- // ∨
2427
- default:
2428
- throw new Error(`\u672A\u77E5\u306E\u6F14\u7B97\u5B50: ${ast.op}`);
2429
- }
2430
- }
2431
- evalUnaryOp(ast) {
2432
- const operand = this.eval(ast.operand);
2433
- switch (ast.op) {
2434
- case "-":
2435
- return -this.toNumber(operand);
2436
- case "\xAC":
2437
- if (this.isQuad(operand)) return { reiType: "Quad", value: quadNot(operand.value) };
2438
- return !operand;
2439
- default:
2440
- throw new Error(`\u672A\u77E5\u306E\u5358\u9805\u6F14\u7B97\u5B50: ${ast.op}`);
2441
- }
2442
- }
2443
- evalPipe(ast) {
2444
- const rawInput = this.eval(ast.input);
2445
- const cmd = ast.command;
2446
- if (cmd.type === "PipeCmd") {
2447
- if (cmd.cmd === "sigma") {
2448
- return this.execPipeCmd(rawInput, cmd);
2449
- }
2450
- const result = this.execPipeCmd(rawInput, cmd);
2451
- const prevMeta = getSigmaOf(rawInput);
2452
- return wrapWithSigma(result, rawInput, prevMeta.pipeCount > 0 ? prevMeta : void 0);
2453
- }
2454
- throw new Error("\u7121\u52B9\u306A\u30D1\u30A4\u30D7\u30B3\u30DE\u30F3\u30C9");
2455
- }
2456
- execPipeCmd(input, cmd) {
2457
- const { cmd: cmdName, mode, args: argNodes } = cmd;
2458
- const args = argNodes.map((a) => this.eval(a));
2459
- const sigmaMetadata = getSigmaOf(input);
2460
- const rawInput = unwrapReiVal(input);
2461
- if (cmdName === "sigma") {
2462
- if (this.isSpace(rawInput)) return getSpaceSigma(rawInput);
2463
- if (this.isDNode(rawInput)) {
2464
- const dn = rawInput;
2465
- return {
2466
- reiType: "SigmaResult",
2467
- flow: getSigmaFlow(dn),
2468
- memory: [...getSigmaMemory(dn), ...sigmaMetadata.memory],
2469
- layer: dn.layerIndex,
2470
- will: getSigmaWill(dn),
2471
- field: { center: dn.center, neighbors: [...dn.neighbors], layer: dn.layerIndex, index: dn.nodeIndex },
2472
- relation: []
2473
- };
2474
- }
2475
- return buildSigmaResult(rawInput, sigmaMetadata);
2476
- }
2477
- if (this.isSpace(rawInput)) {
2478
- const sp = rawInput;
2479
- switch (cmdName) {
2480
- case "step": {
2481
- const targetLayer = args.length > 0 ? this.toNumber(args[0]) : void 0;
2482
- stepSpace(sp, targetLayer);
2483
- return sp;
2484
- }
2485
- case "diffuse": {
2486
- let criteria = { type: "converged" };
2487
- let targetLayer;
2488
- let contractionMethod = "weighted";
2489
- if (args.length >= 1) {
2490
- const arg0 = args[0];
2491
- if (typeof arg0 === "number") {
2492
- criteria = { type: "steps", max: arg0 };
2493
- } else if (typeof arg0 === "string") {
2494
- switch (arg0) {
2495
- case "converged":
2496
- criteria = { type: "converged" };
2497
- break;
2498
- case "fixed":
2499
- criteria = { type: "fixed" };
2500
- break;
2501
- default:
2502
- const eps = parseFloat(arg0);
2503
- if (!isNaN(eps)) criteria = { type: "epsilon", threshold: eps };
2504
- }
2505
- }
2506
- }
2507
- if (args.length >= 2 && typeof args[1] === "number") targetLayer = args[1];
2508
- if (args.length >= 3 && typeof args[2] === "string") contractionMethod = args[2];
2509
- return diffuseSpace(sp, criteria, targetLayer, contractionMethod);
2510
- }
2511
- case "node": {
2512
- const layerIdx = args.length >= 1 ? this.toNumber(args[0]) : 0;
2513
- const nodeIdx = args.length >= 2 ? this.toNumber(args[1]) : 0;
2514
- const layer = sp.layers.get(layerIdx);
2515
- if (layer && layer.nodes[nodeIdx]) return layer.nodes[nodeIdx];
2516
- throw new Error(`\u30CE\u30FC\u30C9\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: \u5C64${layerIdx}, index ${nodeIdx}`);
2517
- }
2518
- case "sigma":
2519
- return getSpaceSigma(sp);
2520
- case "resonances": {
2521
- const threshold = args.length >= 1 ? this.toNumber(args[0]) : 0.5;
2522
- return findResonances(sp, threshold);
2523
- }
2524
- case "freeze": {
2525
- const layerIdx = this.toNumber(args[0] ?? 0);
2526
- const layer = sp.layers.get(layerIdx);
2527
- if (layer) layer.frozen = true;
2528
- return sp;
2529
- }
2530
- case "thaw": {
2531
- const layerIdx = this.toNumber(args[0] ?? 0);
2532
- const layer = sp.layers.get(layerIdx);
2533
- if (layer) layer.frozen = false;
2534
- return sp;
2535
- }
2536
- case "spawn": {
2537
- const val = args[0];
2538
- const layerIdx = args.length >= 2 ? this.toNumber(args[1]) : 0;
2539
- if (this.isMDim(val)) {
2540
- addNodeToLayer(sp, layerIdx, val.center, val.neighbors, val.mode, val.weights);
2541
- }
2542
- return sp;
2543
- }
2544
- case "result": {
2545
- const layerIdx = args.length >= 1 ? this.toNumber(args[0]) : void 0;
2546
- const results = [];
2547
- for (const [lIdx, layer] of sp.layers) {
2548
- if (layerIdx !== void 0 && lIdx !== layerIdx) continue;
2549
- for (const n of layer.nodes) results.push(computeNodeValue(n));
2550
- }
2551
- return results.length === 1 ? results[0] : results;
2552
- }
2553
- }
2554
- }
2555
- if (this.isDNode(rawInput)) {
2556
- const dn = rawInput;
2557
- switch (cmdName) {
2558
- case "sigma": {
2559
- return buildSigmaResult(dn, sigmaMetadata);
2560
- }
2561
- case "compute":
2562
- return computeNodeValue(dn);
2563
- case "center":
2564
- return dn.center;
2565
- case "neighbors":
2566
- return dn.neighbors;
2567
- case "dim":
2568
- return dn.neighbors.length;
2569
- case "stage":
2570
- return dn.stage;
2571
- case "step": {
2572
- stepNode(dn);
2573
- return dn;
2574
- }
2575
- case "extract": {
2576
- return { reiType: "MDim", center: dn.center, neighbors: dn.neighbors, mode: dn.mode, weights: dn.weights };
2577
- }
2578
- }
2579
- }
2580
- if (this.isObj(rawInput) && rawInput.reiType === "SigmaResult") {
2581
- switch (cmdName) {
2582
- case "flow":
2583
- return rawInput.flow;
2584
- case "memory":
2585
- return rawInput.memory;
2586
- case "layer":
2587
- case "\u5C64":
2588
- return rawInput.layer;
2589
- case "will":
2590
- return rawInput.will;
2591
- case "field":
2592
- return rawInput.field;
2593
- case "relation":
2594
- return rawInput.relation ?? [];
2595
- }
2596
- }
2597
- if (cmdName === "project") {
2598
- const centerSpec = args.length > 0 ? args[0] : ":first";
2599
- return projectToMDim(rawInput, centerSpec);
2600
- }
2601
- if (cmdName === "reproject") {
2602
- if (this.isMDim(rawInput) && args.length > 0) {
2603
- const newCenter = args[0];
2604
- const allElements = [rawInput.center, ...rawInput.neighbors];
2605
- const idx = typeof newCenter === "number" ? allElements.indexOf(newCenter) : 0;
2606
- if (idx < 0) throw new Error(`reproject: \u4E2D\u5FC3\u5024 ${newCenter} \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`);
2607
- const center = allElements[idx];
2608
- const neighbors = allElements.filter((_, i) => i !== idx);
2609
- return { reiType: "MDim", center, neighbors, mode: rawInput.mode };
2610
- }
2611
- return projectToMDim(rawInput, args[0] ?? ":first");
2612
- }
2613
- if (cmdName === "modes") {
2614
- return [...ALL_COMPUTE_MODES];
2615
- }
2616
- if (cmdName === "blend") {
2617
- if (!this.isMDim(rawInput)) throw new Error("blend: \u{1D544}\u578B\u306E\u5024\u304C\u5FC5\u8981\u3067\u3059");
2618
- let blendedResult = 0;
2619
- let totalWeight = 0;
2620
- for (let i = 0; i < args.length - 1; i += 2) {
2621
- const modeName = String(args[i]);
2622
- const w = typeof args[i + 1] === "number" ? args[i + 1] : 0;
2623
- const result = computeMDim({ ...rawInput, mode: modeName });
2624
- blendedResult += w * result;
2625
- totalWeight += w;
2626
- }
2627
- return totalWeight > 0 ? blendedResult / totalWeight : computeMDim(rawInput);
2628
- }
2629
- if (cmdName === "project_all") {
2630
- return projectAll(rawInput);
2631
- }
2632
- if (cmdName === "compute_all") {
2633
- if (this.isMDim(rawInput)) return computeAll(rawInput);
2634
- if (Array.isArray(rawInput)) {
2635
- const projected = projectToMDim(rawInput, "first");
2636
- return computeAll(projected);
2637
- }
2638
- return [];
2639
- }
2640
- if (cmdName === "compare") {
2641
- if (!this.isMDim(rawInput)) throw new Error("compare: \u{1D544}\u578B\u306E\u5024\u304C\u5FC5\u8981\u3067\u3059");
2642
- const mode1 = args.length >= 1 ? String(args[0]) : "weighted";
2643
- const mode2 = args.length >= 2 ? String(args[1]) : "geometric";
2644
- return compareModes(rawInput, mode1, mode2);
2645
- }
2646
- if (cmdName === "perspectives") {
2647
- return perspectives(rawInput);
2648
- }
2649
- if (cmdName === "flatten_nested") {
2650
- if (this.isMDim(rawInput)) return computeNestedMDim(rawInput);
2651
- return rawInput;
2652
- }
2653
- if (cmdName === "respond") {
2654
- const stimulus = args.length >= 1 ? this.toNumber(args[0]) : 0;
2655
- const method = args.length >= 2 ? String(args[1]) : "absorb";
2656
- return respondToStimulus(rawInput, stimulus, method);
2657
- }
2658
- if (cmdName === "sensitivity") {
2659
- return computeSensitivity(rawInput);
2660
- }
2661
- if (cmdName === "awareness") {
2662
- return computeAwareness(rawInput, sigmaMetadata);
2663
- }
2664
- if (cmdName === "awakened") {
2665
- return computeAwareness(rawInput, sigmaMetadata) >= AWAKENING_THRESHOLD;
2666
- }
2667
- if (cmdName === "transform") {
2668
- const transformName = args.length >= 1 ? String(args[0]) : "scale";
2669
- const param = args.length >= 2 ? this.toNumber(args[1]) : 1;
2670
- return applyTransform(rawInput, transformName, param);
2671
- }
2672
- if (cmdName === "mode_equiv") {
2673
- if (!this.isMDim(rawInput)) throw new Error("mode_equiv: \u{1D544}\u578B\u306E\u5024\u304C\u5FC5\u8981\u3067\u3059");
2674
- const m1 = args.length >= 1 ? String(args[0]) : "weighted";
2675
- const m2 = args.length >= 2 ? String(args[1]) : "geometric";
2676
- return checkModeEquivalence(rawInput, m1, m2);
2677
- }
2678
- if (cmdName === "resonate") {
2679
- if (args.length < 1) throw new Error("resonate: \u6BD4\u8F03\u5BFE\u8C61\u304C\u5FC5\u8981\u3067\u3059");
2680
- return computeResonance(rawInput, args[0]);
2681
- }
2682
- if (cmdName === "resonance_field") {
2683
- return getResonanceField(rawInput, sigmaMetadata);
2684
- }
2685
- if (cmdName === "resonance_map") {
2686
- return resonanceMap(rawInput);
2687
- }
2688
- if (cmdName === "resonance_chain") {
2689
- return resonanceChain(rawInput);
2690
- }
2691
- if (cmdName === "project_as") {
2692
- const targetType = args.length >= 1 ? String(args[0]) : "graph";
2693
- return projectAs(rawInput, targetType);
2694
- }
2695
- if (cmdName === "compose_projections") {
2696
- return composeProjections(rawInput);
2697
- }
2698
- if (cmdName === "representable") {
2699
- return checkRepresentable(rawInput);
2700
- }
2701
- if (cmdName === "derive_mode") {
2702
- if (!this.isMDim(rawInput)) throw new Error("derive_mode: \u{1D544}\u578B\u304C\u5FC5\u8981\u3067\u3059");
2703
- const modes = args.filter((a) => typeof a === "string");
2704
- const weights = args.filter((a) => typeof a === "number");
2705
- if (modes.length === 0) modes.push("weighted", "geometric");
2706
- if (weights.length === 0) weights.push(0.5, 0.5);
2707
- return deriveMode(rawInput, modes, weights);
2708
- }
2709
- if (cmdName === "mode_space") {
2710
- return getModeSpace(rawInput);
2711
- }
2712
- if (cmdName === "depth") {
2713
- return measureDepth(rawInput);
2714
- }
2715
- if (cmdName === "nest") {
2716
- const levels = args.length >= 1 ? this.toNumber(args[0]) : 1;
2717
- return nestMDim(rawInput, levels);
2718
- }
2719
- if (cmdName === "recursive_compute") {
2720
- return recursiveCompute(rawInput);
2721
- }
2722
- if (cmdName === "bridge") {
2723
- if (args.length < 1) throw new Error("bridge: \u6BD4\u8F03\u5BFE\u8C61\u304C\u5FC5\u8981\u3067\u3059");
2724
- return bridgeMDim(rawInput, args[0]);
2725
- }
2726
- if (cmdName === "structural_similarity") {
2727
- if (args.length < 1) throw new Error("structural_similarity: \u6BD4\u8F03\u5BFE\u8C61\u304C\u5FC5\u8981\u3067\u3059");
2728
- return structuralSimilarity(rawInput, args[0]);
2729
- }
2730
- if (cmdName === "encode") {
2731
- return encodeMDim(rawInput);
2732
- }
2733
- if (cmdName === "decode") {
2734
- const targetType = args.length >= 1 ? String(args[0]) : "array";
2735
- return decodeMDim(rawInput, targetType);
2736
- }
2737
- if (cmdName === "map_solutions") {
2738
- if (!this.isMDim(rawInput)) {
2739
- if (Array.isArray(rawInput)) {
2740
- const projected = projectToMDim(rawInput, "first");
2741
- return mapSolutions(projected, args.length >= 1 ? String(args[0]) : "scale", args.length >= 2 ? this.toNumber(args[1]) : 1);
2742
- }
2743
- throw new Error("map_solutions: \u{1D544}\u578B\u307E\u305F\u306F\u914D\u5217\u304C\u5FC5\u8981\u3067\u3059");
2744
- }
2745
- return mapSolutions(rawInput, args.length >= 1 ? String(args[0]) : "scale", args.length >= 2 ? this.toNumber(args[1]) : 1);
2746
- }
2747
- if (cmdName === "consensus") {
2748
- if (!this.isMDim(rawInput)) {
2749
- if (Array.isArray(rawInput)) {
2750
- return computeConsensus(projectToMDim(rawInput, "first"));
2751
- }
2752
- throw new Error("consensus: \u{1D544}\u578B\u307E\u305F\u306F\u914D\u5217\u304C\u5FC5\u8981\u3067\u3059");
2753
- }
2754
- return computeConsensus(rawInput);
2755
- }
2756
- if (cmdName === "best") {
2757
- if (!this.isMDim(rawInput)) {
2758
- if (Array.isArray(rawInput)) {
2759
- return selectBest(projectToMDim(rawInput, "first"), args.length >= 1 ? String(args[0]) : "median_closest");
2760
- }
2761
- throw new Error("best: \u{1D544}\u578B\u307E\u305F\u306F\u914D\u5217\u304C\u5FC5\u8981\u3067\u3059");
2762
- }
2763
- return selectBest(rawInput, args.length >= 1 ? String(args[0]) : "median_closest");
2764
- }
2765
- if (cmdName === "rank") {
2766
- if (!this.isMDim(rawInput)) {
2767
- if (Array.isArray(rawInput)) {
2768
- return rankSolutions(projectToMDim(rawInput, "first"), args.length >= 1 ? String(args[0]) : "value");
2769
- }
2770
- throw new Error("rank: \u{1D544}\u578B\u307E\u305F\u306F\u914D\u5217\u304C\u5FC5\u8981\u3067\u3059");
2771
- }
2772
- return rankSolutions(rawInput, args.length >= 1 ? String(args[0]) : "value");
2773
- }
2774
- if (cmdName === "solution_completeness") {
2775
- if (!this.isMDim(rawInput)) {
2776
- if (Array.isArray(rawInput)) {
2777
- return solutionCompleteness(projectToMDim(rawInput, "first"));
2778
- }
2779
- throw new Error("solution_completeness: \u{1D544}\u578B\u307E\u305F\u306F\u914D\u5217\u304C\u5FC5\u8981\u3067\u3059");
2780
- }
2781
- return solutionCompleteness(rawInput);
2782
- }
2783
- if (this.isMDim(rawInput)) {
2784
- const md = rawInput;
2785
- switch (cmdName) {
2786
- case "compute": {
2787
- const m = mode || md.mode;
2788
- return computeMDim({ ...md, mode: m });
2789
- }
2790
- case "center":
2791
- return md.center;
2792
- case "neighbors":
2793
- return md.neighbors;
2794
- case "dim":
2795
- return md.neighbors.length;
2796
- case "normalize": {
2797
- const sum = md.neighbors.reduce((a, b) => a + Math.abs(b), 0) || 1;
2798
- return { reiType: "MDim", center: md.center, neighbors: md.neighbors.map((n) => n / sum), mode: md.mode };
2799
- }
2800
- case "flatten":
2801
- return computeMDim(md);
2802
- case "map": {
2803
- if (args.length > 0 && this.isFunction(args[0])) {
2804
- const fn = args[0];
2805
- const newNeighbors = md.neighbors.map((n) => this.toNumber(this.callFunction(fn, [n])));
2806
- return { ...md, neighbors: newNeighbors };
2807
- }
2808
- return md;
2809
- }
2810
- }
2811
- }
2812
- if (this.isExt(rawInput)) {
2813
- const ext = rawInput;
2814
- switch (cmdName) {
2815
- case "order":
2816
- return ext.order;
2817
- case "base":
2818
- return ext.base;
2819
- case "valStar":
2820
- case "val":
2821
- return ext.valStar();
2822
- case "subscripts":
2823
- return ext.subscripts;
2824
- }
2825
- }
2826
- if (this.isGenesis(rawInput)) {
2827
- const g = rawInput;
2828
- switch (cmdName) {
2829
- case "forward":
2830
- genesisForward(g);
2831
- return g;
2832
- case "phase":
2833
- return g.state;
2834
- case "history":
2835
- return g.history;
2836
- case "omega":
2837
- return g.omega;
2838
- }
2839
- }
2840
- if (Array.isArray(rawInput)) {
2841
- switch (cmdName) {
2842
- case "len":
2843
- return rawInput.length;
2844
- case "sum":
2845
- return rawInput.reduce((a, b) => a + this.toNumber(b), 0);
2846
- case "avg":
2847
- return rawInput.length === 0 ? 0 : rawInput.reduce((a, b) => a + this.toNumber(b), 0) / rawInput.length;
2848
- case "first":
2849
- return rawInput[0] ?? null;
2850
- case "last":
2851
- return rawInput[rawInput.length - 1] ?? null;
2852
- case "reverse":
2853
- return [...rawInput].reverse();
2854
- case "sort":
2855
- return [...rawInput].sort((a, b) => this.toNumber(a) - this.toNumber(b));
2856
- case "map": {
2857
- if (args.length > 0 && this.isFunction(args[0])) {
2858
- return rawInput.map((v) => this.callFunction(args[0], [v]));
2859
- }
2860
- return rawInput;
2861
- }
2862
- case "filter": {
2863
- if (args.length > 0 && this.isFunction(args[0])) {
2864
- return rawInput.filter((v) => !!this.callFunction(args[0], [v]));
2865
- }
2866
- return rawInput;
2867
- }
2868
- case "reduce": {
2869
- if (args.length >= 2 && this.isFunction(args[0])) {
2870
- return rawInput.reduce((acc, v) => this.callFunction(args[0], [acc, v]), args[1]);
2871
- }
2872
- return rawInput;
2873
- }
2874
- }
2875
- }
2876
- if (typeof rawInput === "number") {
2877
- switch (cmdName) {
2878
- case "abs":
2879
- return Math.abs(rawInput);
2880
- case "sqrt":
2881
- return Math.sqrt(rawInput);
2882
- case "round":
2883
- return Math.round(rawInput);
2884
- case "floor":
2885
- return Math.floor(rawInput);
2886
- case "ceil":
2887
- return Math.ceil(rawInput);
2888
- case "negate":
2889
- return -rawInput;
2890
- }
2891
- }
2892
- if (typeof rawInput === "string") {
2893
- switch (cmdName) {
2894
- case "len":
2895
- return rawInput.length;
2896
- case "upper":
2897
- return rawInput.toUpperCase();
2898
- case "lower":
2899
- return rawInput.toLowerCase();
2900
- case "trim":
2901
- return rawInput.trim();
2902
- case "split":
2903
- return rawInput.split(args[0] ?? "");
2904
- case "reverse":
2905
- return Array.from(rawInput).reverse().join("");
2906
- }
2907
- }
2908
- if (cmdName === "\u290A" || cmdName === "converge") {
2909
- if (this.isMDim(rawInput)) return computeMDim(rawInput);
2910
- return rawInput;
2911
- }
2912
- if (cmdName === "\u290B" || cmdName === "diverge") {
2913
- if (typeof rawInput === "number") {
2914
- return { reiType: "MDim", center: rawInput, neighbors: [rawInput, rawInput, rawInput, rawInput], mode: "weighted" };
2915
- }
2916
- return rawInput;
2917
- }
2918
- if (this.env.has(cmdName)) {
2919
- const fn = this.env.get(cmdName);
2920
- if (this.isFunction(fn)) return this.callFunction(fn, [rawInput, ...args]);
2921
- }
2922
- throw new Error(`\u672A\u77E5\u306E\u30D1\u30A4\u30D7\u30B3\u30DE\u30F3\u30C9: ${cmdName}`);
2923
- }
2924
- evalFnCall(ast) {
2925
- const callee = this.eval(ast.callee);
2926
- const args = ast.args.map((a) => this.eval(a));
2927
- if (ast.callee.type === "Ident" && ast.callee.name === "genesis") return createGenesis();
2928
- if (this.isFunction(callee)) return this.callFunction(callee, args);
2929
- throw new Error(`\u547C\u3073\u51FA\u3057\u4E0D\u53EF\u80FD: ${JSON.stringify(callee)}`);
2930
- }
2931
- callFunction(fn, args) {
2932
- if (fn.body === null || fn.body === void 0) return this.callBuiltin(fn.name, args);
2933
- const callEnv = new Environment(fn.closure);
2934
- for (let i = 0; i < fn.params.length; i++) {
2935
- callEnv.define(fn.params[i], args[i] ?? null);
2936
- }
2937
- const savedEnv = this.env;
2938
- this.env = callEnv;
2939
- const result = this.eval(fn.body);
2940
- this.env = savedEnv;
2941
- return result;
2942
- }
2943
- callBuiltin(name, args) {
2944
- if (name === "genesis") return createGenesis();
2945
- const a = args[0] !== void 0 ? this.toNumber(args[0]) : 0;
2946
- const b = args[1] !== void 0 ? this.toNumber(args[1]) : 0;
2947
- switch (name) {
2948
- case "abs":
2949
- return Math.abs(a);
2950
- case "sqrt":
2951
- return Math.sqrt(a);
2952
- case "sin":
2953
- return Math.sin(a);
2954
- case "cos":
2955
- return Math.cos(a);
2956
- case "log":
2957
- return Math.log(a);
2958
- case "exp":
2959
- return Math.exp(a);
2960
- case "floor":
2961
- return Math.floor(a);
2962
- case "ceil":
2963
- return Math.ceil(a);
2964
- case "round":
2965
- return Math.round(a);
2966
- case "min":
2967
- return Math.min(a, b);
2968
- case "max":
2969
- return Math.max(a, b);
2970
- case "len":
2971
- if (Array.isArray(args[0])) return args[0].length;
2972
- if (typeof args[0] === "string") return args[0].length;
2973
- return 0;
2974
- case "print":
2975
- return args[0] ?? null;
2976
- default:
2977
- throw new Error(`\u672A\u77E5\u306E\u7D44\u8FBC\u307F\u95A2\u6570: ${name}`);
2978
- }
2979
- }
2980
- evalMemberAccess(ast) {
2981
- const rawObj = this.eval(ast.object);
2982
- const obj = unwrapReiVal(rawObj);
2983
- if (ast.member === "__sigma__") {
2984
- return getSigmaOf(rawObj);
2985
- }
2986
- if (this.isObj(obj) && obj.reiType === "SigmaResult") {
2987
- switch (ast.member) {
2988
- case "flow":
2989
- return obj.flow;
2990
- case "memory":
2991
- return obj.memory;
2992
- case "layer":
2993
- return obj.layer;
2994
- case "will":
2995
- return obj.will;
2996
- case "field":
2997
- return obj.field;
2998
- case "relation":
2999
- return obj.relation ?? [];
3000
- }
3001
- }
3002
- if (this.isObj(obj) && obj.stage !== void 0 && obj.momentum !== void 0 && obj.directions !== void 0) {
3003
- switch (ast.member) {
3004
- case "stage":
3005
- return obj.stage;
3006
- case "directions":
3007
- return obj.directions;
3008
- case "momentum":
3009
- return obj.momentum;
3010
- case "velocity":
3011
- return obj.velocity;
3012
- }
3013
- }
3014
- if (this.isObj(obj) && obj.tendency !== void 0 && obj.strength !== void 0) {
3015
- switch (ast.member) {
3016
- case "tendency":
3017
- return obj.tendency;
3018
- case "strength":
3019
- return obj.strength;
3020
- case "history":
3021
- return obj.history;
3022
- }
3023
- }
3024
- if (this.isObj(obj) && obj.layers !== void 0 && obj.total_nodes !== void 0) {
3025
- switch (ast.member) {
3026
- case "layers":
3027
- return obj.layers;
3028
- case "total_nodes":
3029
- return obj.total_nodes;
3030
- case "active_nodes":
3031
- return obj.active_nodes;
3032
- case "topology":
3033
- return obj.topology;
3034
- }
3035
- }
3036
- if (this.isObj(obj) && obj.global_stage !== void 0 && obj.converged_nodes !== void 0) {
3037
- switch (ast.member) {
3038
- case "global_stage":
3039
- return obj.global_stage;
3040
- case "converged_nodes":
3041
- return obj.converged_nodes;
3042
- case "expanding_nodes":
3043
- return obj.expanding_nodes;
3044
- }
3045
- }
3046
- if (this.isDNode(obj)) {
3047
- const dn = obj;
3048
- switch (ast.member) {
3049
- case "center":
3050
- return dn.center;
3051
- case "neighbors":
3052
- return dn.neighbors;
3053
- case "stage":
3054
- return dn.stage;
3055
- case "momentum":
3056
- return dn.momentum;
3057
- case "mode":
3058
- return dn.mode;
3059
- case "dim":
3060
- return dn.neighbors.length;
3061
- }
3062
- }
3063
- if (this.isMDim(obj)) {
3064
- switch (ast.member) {
3065
- case "center":
3066
- return obj.center;
3067
- case "neighbors":
3068
- return obj.neighbors;
3069
- case "mode":
3070
- return obj.mode;
3071
- case "dim":
3072
- return obj.neighbors.length;
3073
- }
3074
- }
3075
- if (this.isExt(obj)) {
3076
- switch (ast.member) {
3077
- case "order":
3078
- return obj.order;
3079
- case "base":
3080
- return obj.base;
3081
- case "subscripts":
3082
- return obj.subscripts;
3083
- case "valStar":
3084
- return obj.valStar();
3085
- }
3086
- }
3087
- if (this.isGenesis(obj)) {
3088
- switch (ast.member) {
3089
- case "state":
3090
- case "phase":
3091
- return obj.state;
3092
- case "omega":
3093
- return obj.omega;
3094
- case "history":
3095
- return obj.history;
3096
- }
3097
- }
3098
- if (Array.isArray(obj)) {
3099
- switch (ast.member) {
3100
- case "length":
3101
- return obj.length;
3102
- case "first":
3103
- return obj[0] ?? null;
3104
- case "last":
3105
- return obj[obj.length - 1] ?? null;
3106
- }
3107
- }
3108
- throw new Error(`\u30E1\u30F3\u30D0\u30FC ${ast.member} \u306B\u30A2\u30AF\u30BB\u30B9\u3067\u304D\u307E\u305B\u3093`);
3109
- }
3110
- evalIndexAccess(ast) {
3111
- const obj = this.eval(ast.object);
3112
- const idx = this.toNumber(this.eval(ast.index));
3113
- if (Array.isArray(obj)) return obj[idx] ?? null;
3114
- if (typeof obj === "string") return obj[idx] ?? null;
3115
- if (this.isMDim(obj)) return obj.neighbors[idx] ?? null;
3116
- throw new Error("\u30A4\u30F3\u30C7\u30C3\u30AF\u30B9\u30A2\u30AF\u30BB\u30B9\u4E0D\u53EF");
3117
- }
3118
- evalExtend(ast) {
3119
- const target = this.eval(ast.target);
3120
- if (this.isExt(target)) {
3121
- if (ast.subscript) return createExtended(target.base, target.subscripts + ast.subscript);
3122
- return createExtended(target.base, target.subscripts + "o");
3123
- }
3124
- throw new Error("\u62E1\u5F35\u306F\u62E1\u5F35\u6570\u306B\u306E\u307F\u9069\u7528\u53EF\u80FD");
3125
- }
3126
- evalReduce(ast) {
3127
- const target = this.eval(ast.target);
3128
- if (this.isExt(target)) {
3129
- if (target.order <= 1) return target.base;
3130
- return createExtended(target.base, target.subscripts.slice(0, -1));
3131
- }
3132
- throw new Error("\u7E2E\u7D04\u306F\u62E1\u5F35\u6570\u306B\u306E\u307F\u9069\u7528\u53EF\u80FD");
3133
- }
3134
- evalConverge(ast) {
3135
- const left = this.eval(ast.left);
3136
- const right = this.eval(ast.right);
3137
- if (this.isMDim(left) && this.isMDim(right)) {
3138
- return {
3139
- reiType: "MDim",
3140
- center: (left.center + right.center) / 2,
3141
- neighbors: [...left.neighbors, ...right.neighbors],
3142
- mode: left.mode
3143
- };
3144
- }
3145
- return this.toNumber(left) + this.toNumber(right);
3146
- }
3147
- evalDiverge(ast) {
3148
- const left = this.eval(ast.left);
3149
- const right = this.eval(ast.right);
3150
- if (this.isMDim(left)) {
3151
- this.toNumber(right);
3152
- const half = Math.floor(left.neighbors.length / 2);
3153
- return [
3154
- { reiType: "MDim", center: left.center, neighbors: left.neighbors.slice(0, half), mode: left.mode },
3155
- { reiType: "MDim", center: left.center, neighbors: left.neighbors.slice(half), mode: left.mode }
3156
- ];
3157
- }
3158
- return this.toNumber(left) - this.toNumber(right);
3159
- }
3160
- evalReflect(ast) {
3161
- const left = this.eval(ast.left);
3162
- this.eval(ast.right);
3163
- if (this.isMDim(left)) {
3164
- return { reiType: "MDim", center: left.center, neighbors: [...left.neighbors].reverse(), mode: left.mode };
3165
- }
3166
- return this.toNumber(left);
3167
- }
3168
- evalIfExpr(ast) {
3169
- const cond = this.eval(ast.cond);
3170
- return this.isTruthy(cond) ? this.eval(ast.then) : this.eval(ast.else);
3171
- }
3172
- evalMatchExpr(ast) {
3173
- const target = this.eval(ast.target);
3174
- for (const { pattern, body } of ast.cases) {
3175
- const patVal = this.eval(pattern);
3176
- if (this.matches(target, patVal)) return this.eval(body);
3177
- }
3178
- throw new Error("\u30DE\u30C3\u30C1\u3059\u308B\u5206\u5C90\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093");
3179
- }
3180
- // --- Helpers ---
3181
- toNumber(val) {
3182
- if (val !== null && typeof val === "object" && val.reiType === "ReiVal") return this.toNumber(val.value);
3183
- if (typeof val === "number") return val;
3184
- if (typeof val === "boolean") return val ? 1 : 0;
3185
- if (val === null) return 0;
3186
- if (this.isExt(val)) return val.valStar();
3187
- if (this.isMDim(val)) return computeMDim(val);
3188
- if (typeof val === "string") return parseFloat(val) || 0;
3189
- return 0;
3190
- }
3191
- isTruthy(val) {
3192
- const v = unwrapReiVal(val);
3193
- if (v === null || v === false || v === 0) return false;
3194
- if (this.isQuad(v)) return v.value === "top" || v.value === "topPi";
3195
- return true;
3196
- }
3197
- matches(target, pattern) {
3198
- if (typeof target === typeof pattern && target === pattern) return true;
3199
- if (this.isQuad(target) && this.isQuad(pattern)) return target.value === pattern.value;
3200
- return false;
3201
- }
3202
- isObj(v) {
3203
- const u = unwrapReiVal(v);
3204
- return u !== null && typeof u === "object" && !Array.isArray(u);
3205
- }
3206
- isMDim(v) {
3207
- const u = unwrapReiVal(v);
3208
- return u !== null && typeof u === "object" && u.reiType === "MDim";
3209
- }
3210
- isExt(v) {
3211
- const u = unwrapReiVal(v);
3212
- return u !== null && typeof u === "object" && u.reiType === "Ext";
3213
- }
3214
- isGenesis(v) {
3215
- const u = unwrapReiVal(v);
3216
- return u !== null && typeof u === "object" && u.reiType === "State";
3217
- }
3218
- isFunction(v) {
3219
- const u = unwrapReiVal(v);
3220
- return u !== null && typeof u === "object" && u.reiType === "Function";
3221
- }
3222
- isQuad(v) {
3223
- const u = unwrapReiVal(v);
3224
- return u !== null && typeof u === "object" && u.reiType === "Quad";
3225
- }
3226
- // ── v0.3 ──
3227
- isSpace(v) {
3228
- const u = unwrapReiVal(v);
3229
- return u !== null && typeof u === "object" && u.reiType === "Space";
3230
- }
3231
- isDNode(v) {
3232
- const u = unwrapReiVal(v);
3233
- return u !== null && typeof u === "object" && u.reiType === "DNode";
3234
- }
3235
- // ── Tier 1 ──
3236
- isReiVal(v) {
3237
- return v !== null && typeof v === "object" && v.reiType === "ReiVal";
3238
- }
3239
- /** 値からσメタデータを取得(Tier 1) */
3240
- getSigmaMetadata(v) {
3241
- return getSigmaOf(v);
3242
- }
3243
- /** ReiValを透過的にアンラップ */
3244
- unwrap(v) {
3245
- return unwrapReiVal(v);
3246
- }
3247
- };
3248
-
3249
- // src/index.ts
3250
- var _evaluator = new Evaluator();
3251
- function rei(code) {
3252
- const lexer = new Lexer(code);
3253
- const tokens = lexer.tokenize();
3254
- const parser = new Parser(tokens);
3255
- const ast = parser.parseProgram();
3256
- return _evaluator.eval(ast);
3257
- }
3258
- rei.reset = function reset() {
3259
- _evaluator = new Evaluator();
3260
- };
3261
- rei.evaluator = function evaluator() {
3262
- return _evaluator;
3263
- };
3264
- rei.parse = function parse(code) {
3265
- const lexer = new Lexer(code);
3266
- const tokens = lexer.tokenize();
3267
- const parser = new Parser(tokens);
3268
- return parser.parseProgram();
3269
- };
3270
- rei.tokenize = function tokenize(code) {
3271
- const lexer = new Lexer(code);
3272
- return lexer.tokenize();
3273
- };
3274
-
3275
- exports.Environment = Environment;
3276
- exports.Evaluator = Evaluator;
3277
- exports.Lexer = Lexer;
3278
- exports.Parser = Parser;
3279
- exports.TokenType = TokenType;
3280
- exports.rei = rei;
3281
- //# sourceMappingURL=index.cjs.map
3282
- //# sourceMappingURL=index.cjs.map