rei-lang 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nobuki Fujimoto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,246 @@
1
+ # Rei (0₀式) — D-FUMT Computational Language
2
+
3
+ [![npm version](https://img.shields.io/npm/v/rei-lang)](https://www.npmjs.com/package/rei-lang)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-gold.svg)](./LICENSE)
5
+ [![Tests](https://img.shields.io/badge/tests-85%2F85-brightgreen)]()
6
+
7
+ **Rei** (0₀式 / れいしき) is a mathematical computation language based on **D-FUMT** (Dimensional Fujimoto Universal Mathematical Theory). Its center-periphery patterns as language primitives achieve an **average 74% code reduction** over equivalent implementations in general-purpose languages.
8
+
9
+ **Author:** Nobuki Fujimoto
10
+
11
+ ---
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm install rei-lang
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ### As a Library
22
+
23
+ ```typescript
24
+ import { rei } from 'rei-lang';
25
+
26
+ // Multi-dimensional number computation
27
+ rei('let field = 𝕄{5; 1, 2, 3, 4}');
28
+ const result = rei('field |> compute :weighted');
29
+ console.log(result); // 7.5
30
+
31
+ // Define functions with compress
32
+ rei('compress energy(m) = m |> compute :weighted');
33
+ rei('let e = energy(𝕄{0; 10, 20, 30})');
34
+ console.log(rei('e')); // 20
35
+
36
+ // Genesis axiom system
37
+ rei('let g = genesis()');
38
+ rei('g |> forward');
39
+ rei('g |> forward');
40
+ console.log(rei('g.state')); // "line"
41
+
42
+ // Reset state between sessions
43
+ rei.reset();
44
+ ```
45
+
46
+ ### Interactive REPL
47
+
48
+ ```bash
49
+ npx rei
50
+ ```
51
+
52
+ ```
53
+ ╔══════════════════════════════════════════╗
54
+ ║ Rei (0₀式) REPL v0.2.0 ║
55
+ ║ D-FUMT Computational Language ║
56
+ ╚══════════════════════════════════════════╝
57
+
58
+ 零 > 𝕄{5; 1, 2, 3, 4} |> compute :weighted
59
+ 7.5
60
+
61
+ 零 > compress karma(i, e, r) = i * e * r
62
+ compress karma(i, e, r)
63
+
64
+ 零 > karma(0.8, 0.9, 0.7)
65
+ 0.504
66
+ ```
67
+
68
+ ### Execute a File
69
+
70
+ ```bash
71
+ npx rei program.rei
72
+ ```
73
+
74
+ ### Inline Evaluation
75
+
76
+ ```bash
77
+ npx rei -e "2 + 3 * 4"
78
+ # → 14
79
+ ```
80
+
81
+ ---
82
+
83
+ ## Language Features
84
+
85
+ ### Multi-Dimensional Numbers (𝕄)
86
+
87
+ The core data structure. A center value with peripheral neighbors, computed in 4 modes:
88
+
89
+ ```rei
90
+ let m = 𝕄{5; 1, 2, 3, 4}
91
+
92
+ m |> compute :weighted // center + weighted avg of neighbors
93
+ m |> compute :multiplicative // center × Π(1 + nᵢ)
94
+ m |> compute :harmonic // center + n / Σ(1/|nᵢ|)
95
+ m |> compute :exponential // center × avg(e^nᵢ)
96
+ ```
97
+
98
+ ### Extended Numbers (拡張数)
99
+
100
+ Numbers with subscript-based dimensional extension:
101
+
102
+ ```rei
103
+ let a = 0ooo // 3rd-order extension of zero
104
+ a >> :x >> :x // extend: order 3 → 5
105
+ a << // reduce: order 3 → 2
106
+ a |> valStar // numeric projection: 0.001
107
+
108
+ πooo // π extended to 3rd order
109
+ 0₀ // D-FUMT zero symbol
110
+ ```
111
+
112
+ ### Compress (関数定義)
113
+
114
+ Functions are defined with `compress` — reflecting D-FUMT's compression philosophy:
115
+
116
+ ```rei
117
+ compress distance(x, y) = sqrt(x * x + y * y)
118
+ compress field(c, r) = 𝕄{c; r, r, r, r}
119
+
120
+ distance(3, 4) // 5
121
+ field(10, 2) |> compute :weighted // 12
122
+ ```
123
+
124
+ ### Pipe Operator (|>)
125
+
126
+ Center-to-periphery data flow:
127
+
128
+ ```rei
129
+ -25 |> abs |> sqrt // 5
130
+ [3, 1, 2] |> sort |> reverse // [3, 2, 1]
131
+ "hello" |> upper // "HELLO"
132
+ 𝕄{0; 1, 2, 3} |> normalize // normalized neighbors
133
+ ```
134
+
135
+ ### Genesis Axiom System (生成公理系)
136
+
137
+ Models computational emergence from void:
138
+
139
+ ```rei
140
+ let g = genesis() // void
141
+ g |> forward // void → dot
142
+ g |> forward // dot → line
143
+ g |> forward // line → surface
144
+ g |> forward // surface → solid
145
+ g |> forward // solid → omega (Ω)
146
+ g.omega // 1
147
+ ```
148
+
149
+ Or from the primordial dot (・):
150
+
151
+ ```rei
152
+ let g = ・
153
+ g |> forward // dot
154
+ g |> forward // line
155
+ ```
156
+
157
+ ### Four-Valued Logic (四価0π)
158
+
159
+ Beyond true/false — Theory #21:
160
+
161
+ ```rei
162
+ ⊤ // true
163
+ ⊥ // false
164
+ ⊤π // true-pi (π-rotated truth)
165
+ ⊥π // false-pi
166
+
167
+ ¬⊤ // ⊥
168
+ ⊤ ∧ ⊥ // ⊥
169
+ ⊥ ∨ ⊤ // ⊤
170
+ ```
171
+
172
+ ### Variable Binding
173
+
174
+ ```rei
175
+ let x = 42 // immutable
176
+ let mut y = 10 // mutable
177
+ ```
178
+
179
+ ---
180
+
181
+ ## Benchmarks
182
+
183
+ | Task | Conventional | Rei | Reduction |
184
+ |------|-------------|-----|-----------|
185
+ | Image kernel calculations | 32 lines | 8 lines | **4×** |
186
+ | Multi-dimensional data aggregation | 45 lines | 12 lines | **3.7×** |
187
+ | Graph structure transformation | 52 lines | 14 lines | **3.7×** |
188
+ | **Average** | | | **74%** |
189
+
190
+ ---
191
+
192
+ ## API Reference
193
+
194
+ ### `rei(code: string): ReiValue`
195
+
196
+ Evaluate a string of Rei code. State persists across calls.
197
+
198
+ ### `rei.reset(): void`
199
+
200
+ Clear all variable and function bindings.
201
+
202
+ ### `rei.parse(code: string): ASTNode`
203
+
204
+ Parse code and return the AST without evaluating.
205
+
206
+ ### `rei.tokenize(code: string): Token[]`
207
+
208
+ Tokenize code and return the token stream.
209
+
210
+ ### Classes
211
+
212
+ - `Lexer` — Tokenizer
213
+ - `Parser` — Recursive descent parser
214
+ - `Evaluator` — AST evaluator with environment/scope chain
215
+ - `Environment` — Scope management
216
+
217
+ ### Types
218
+
219
+ - `MultiDimNumber` — `{ center, neighbors, mode, weights? }`
220
+ - `ReiExtended` — `{ base, order, subscripts, valStar() }`
221
+ - `GenesisState` — `{ state, omega, history }`
222
+ - `ReiFunction` — `{ name, params, body, closure }`
223
+ - `Quad` — `{ value: 'top' | 'bottom' | 'topPi' | 'bottomPi' }`
224
+
225
+ ---
226
+
227
+ ## BNF Specification
228
+
229
+ The complete BNF v0.2 specification is in [`spec/REI_BNF_v0.2.md`](./spec/REI_BNF_v0.2.md).
230
+
231
+ Key features integrated from 21 D-FUMT theories:
232
+ - 45 keywords, 10 operators, 9 types
233
+ - Full backward compatibility with v0.1
234
+ - Complete operator precedence table
235
+
236
+ ---
237
+
238
+ ## Theoretical Foundation
239
+
240
+ Rei is grounded in **D-FUMT** (Dimensional Fujimoto Universal Mathematical Theory), a framework of 66 interconnected theories spanning pure mathematics to philosophy and AI consciousness. The language's core innovation — **center-periphery patterns as language primitives** — derives from D-FUMT's multi-dimensional number system theory.
241
+
242
+ ---
243
+
244
+ ## License
245
+
246
+ MIT © Nobuki Fujimoto
package/bin/rei.js ADDED
@@ -0,0 +1,212 @@
1
+ #!/usr/bin/env node
2
+
3
+ // ============================================================
4
+ // Rei (0₀式) CLI — REPL & File Execution
5
+ // Author: Nobuki Fujimoto
6
+ // ============================================================
7
+
8
+ const { Lexer } = require('../dist/index.js');
9
+ const { Parser } = require('../dist/index.js');
10
+ const { Evaluator } = require('../dist/index.js');
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+ const readline = require('readline');
14
+
15
+ const VERSION = '0.2.0';
16
+
17
+ // --- Result formatting ---
18
+ function formatResult(val) {
19
+ if (val === null || val === undefined) return 'null';
20
+ if (typeof val === 'number') return String(val);
21
+ if (typeof val === 'string') return `"${val}"`;
22
+ if (typeof val === 'boolean') return String(val);
23
+ if (Array.isArray(val)) return `[${val.map(formatResult).join(', ')}]`;
24
+
25
+ if (val && typeof val === 'object') {
26
+ switch (val.reiType) {
27
+ case 'Ext':
28
+ return `Ext(base=${val.base}, order=${val.order}, subs="${val.subscripts}", val*=${val.valStar()})`;
29
+ case 'MDim':
30
+ return `𝕄{${val.center}; ${val.neighbors.join(', ')}} :${val.mode}`;
31
+ case 'State':
32
+ return `Genesis(${val.state}, ω=${val.omega})`;
33
+ case 'Function':
34
+ return `compress ${val.name}(${val.params.join(', ')})`;
35
+ case 'Quad':
36
+ const sym = { top: '⊤', bottom: '⊥', topPi: '⊤π', bottomPi: '⊥π' };
37
+ return sym[val.value] || val.value;
38
+ default:
39
+ return JSON.stringify(val);
40
+ }
41
+ }
42
+ return String(val);
43
+ }
44
+
45
+ // --- Evaluate code string ---
46
+ function evaluate(code, evaluator) {
47
+ const lexer = new Lexer(code);
48
+ const tokens = lexer.tokenize();
49
+ const parser = new Parser(tokens);
50
+ const ast = parser.parseProgram();
51
+ return evaluator.eval(ast);
52
+ }
53
+
54
+ // --- CLI argument parsing ---
55
+ const args = process.argv.slice(2);
56
+
57
+ if (args.includes('--version') || args.includes('-v')) {
58
+ console.log(`rei-lang v${VERSION}`);
59
+ process.exit(0);
60
+ }
61
+
62
+ if (args.includes('--help') || args.includes('-h')) {
63
+ console.log(`
64
+ Rei (0₀式) — D-FUMT Computational Language v${VERSION}
65
+
66
+ Usage:
67
+ rei Start interactive REPL
68
+ rei <file.rei> Execute a Rei source file
69
+ rei -e "<code>" Evaluate inline code
70
+ rei --version Show version
71
+ rei --help Show this help
72
+
73
+ REPL commands:
74
+ :env Show all bindings
75
+ :ast <code> Show AST for code
76
+ :tokens <code> Show token stream
77
+ :reset Clear all state
78
+ :quit Exit REPL
79
+
80
+ Author: Nobuki Fujimoto
81
+ `);
82
+ process.exit(0);
83
+ }
84
+
85
+ // --- Inline eval: -e ---
86
+ const eIdx = args.indexOf('-e');
87
+ if (eIdx >= 0 && args[eIdx + 1]) {
88
+ try {
89
+ const evaluator = new Evaluator();
90
+ const result = evaluate(args[eIdx + 1], evaluator);
91
+ console.log(formatResult(result));
92
+ } catch (e) {
93
+ console.error(`Error: ${e.message}`);
94
+ process.exit(1);
95
+ }
96
+ process.exit(0);
97
+ }
98
+
99
+ // --- File execution ---
100
+ if (args.length > 0 && !args[0].startsWith('-')) {
101
+ const filePath = path.resolve(args[0]);
102
+ try {
103
+ const code = fs.readFileSync(filePath, 'utf-8');
104
+ const evaluator = new Evaluator();
105
+ const result = evaluate(code, evaluator);
106
+ if (result !== null && result !== undefined) {
107
+ console.log(formatResult(result));
108
+ }
109
+ } catch (e) {
110
+ if (e.code === 'ENOENT') {
111
+ console.error(`File not found: ${filePath}`);
112
+ } else {
113
+ console.error(`Error: ${e.message}`);
114
+ }
115
+ process.exit(1);
116
+ }
117
+ process.exit(0);
118
+ }
119
+
120
+ // --- Interactive REPL ---
121
+ console.log(`
122
+ ╔══════════════════════════════════════════╗
123
+ ║ Rei (0₀式) REPL v${VERSION} ║
124
+ ║ D-FUMT Computational Language ║
125
+ ║ Author: Nobuki Fujimoto ║
126
+ ╚══════════════════════════════════════════╝
127
+
128
+ Type :help for commands, :quit to exit
129
+ `);
130
+
131
+ const evaluator = new Evaluator();
132
+ const rl = readline.createInterface({
133
+ input: process.stdin,
134
+ output: process.stdout,
135
+ prompt: '\x1b[33m零 >\x1b[0m ',
136
+ });
137
+
138
+ rl.prompt();
139
+
140
+ rl.on('line', (input) => {
141
+ const trimmed = input.trim();
142
+ if (!trimmed) { rl.prompt(); return; }
143
+
144
+ // Meta commands
145
+ if (trimmed === ':quit' || trimmed === ':q') {
146
+ console.log('\nさようなら');
147
+ process.exit(0);
148
+ }
149
+ if (trimmed === ':help' || trimmed === ':h') {
150
+ console.log(' :env Show all bindings');
151
+ console.log(' :ast Show AST for last input');
152
+ console.log(' :tokens Show token stream');
153
+ console.log(' :reset Clear state');
154
+ console.log(' :quit Exit');
155
+ rl.prompt();
156
+ return;
157
+ }
158
+ if (trimmed === ':reset') {
159
+ Object.assign(evaluator, new Evaluator());
160
+ console.log(' State reset.');
161
+ rl.prompt();
162
+ return;
163
+ }
164
+ if (trimmed === ':env') {
165
+ const bindings = evaluator.env.allBindings();
166
+ for (const [k, v] of bindings) {
167
+ if (v.value && typeof v.value === 'object' && v.value.reiType === 'Function' && !v.value.body) continue;
168
+ console.log(` ${v.mutable ? 'mut ' : ''}${k} = ${formatResult(v.value)}`);
169
+ }
170
+ rl.prompt();
171
+ return;
172
+ }
173
+ if (trimmed.startsWith(':ast ')) {
174
+ try {
175
+ const code = trimmed.slice(5);
176
+ const lexer = new Lexer(code);
177
+ const tokens = lexer.tokenize();
178
+ const parser = new Parser(tokens);
179
+ const ast = parser.parseProgram();
180
+ console.log(JSON.stringify(ast, null, 2));
181
+ } catch (e) { console.log(`\x1b[31m${e.message}\x1b[0m`); }
182
+ rl.prompt();
183
+ return;
184
+ }
185
+ if (trimmed.startsWith(':tokens ')) {
186
+ try {
187
+ const code = trimmed.slice(8);
188
+ const lexer = new Lexer(code);
189
+ const tokens = lexer.tokenize();
190
+ tokens.forEach(t => console.log(` ${t.type.padEnd(15)} ${JSON.stringify(t.value)}`));
191
+ } catch (e) { console.log(`\x1b[31m${e.message}\x1b[0m`); }
192
+ rl.prompt();
193
+ return;
194
+ }
195
+
196
+ // Evaluate
197
+ try {
198
+ const result = evaluate(trimmed, evaluator);
199
+ const out = formatResult(result);
200
+ if (out !== 'null' && out !== 'undefined') {
201
+ console.log(`\x1b[33m${out}\x1b[0m`);
202
+ }
203
+ } catch (e) {
204
+ console.log(`\x1b[31m${e.message}\x1b[0m`);
205
+ }
206
+ rl.prompt();
207
+ });
208
+
209
+ rl.on('close', () => {
210
+ console.log('\nさようなら');
211
+ process.exit(0);
212
+ });