File size: 14,343 Bytes
e870690 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 | /**
* SNAPKITTY FORTH VM
* Stack-based Forth interpreter for the Apple II Universal Machine.
* Agent personas defined as Forth words β composable, minimal, sovereign.
*
* Implements: stack ops, arithmetic, control flow, word definitions,
* string output, and sovereign extensions (WORM-SEAL, TRUST-DEED, BEDROCK).
*
* ⬑ Ω ⺠Ψ ΠΠΣ Φ α
*/
var ForthVM = (function () {
// ββ Core VM state ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function VM() {
this.stack = []; // data stack
this.rstack = []; // return stack
this.dict = {}; // word dictionary
this.memory = new Array(65536).fill(0);
this.output = '';
this.trace = [];
this.sealed = false;
this.verdict = null;
this._definePrimitives();
this._defineSovereignWords();
}
// ββ Stack helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
VM.prototype.push = function(v) { this.stack.push(v); };
VM.prototype.pop = function() {
if (!this.stack.length) throw new Error('STACK UNDERFLOW');
return this.stack.pop();
};
VM.prototype.peek = function() { return this.stack[this.stack.length - 1]; };
VM.prototype.emit = function(s) { this.output += s; this.trace.push({type:'out', val:s}); };
// ββ Primitives ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
VM.prototype._definePrimitives = function() {
var vm = this;
// Arithmetic
this.dict['+'] = function() { vm.push(vm.pop() + vm.pop()); };
this.dict['-'] = function() { var b=vm.pop(), a=vm.pop(); vm.push(a-b); };
this.dict['*'] = function() { vm.push(vm.pop() * vm.pop()); };
this.dict['/'] = function() { var b=vm.pop(), a=vm.pop(); vm.push(Math.floor(a/b)); };
this.dict['MOD'] = function() { var b=vm.pop(), a=vm.pop(); vm.push(a%b); };
this.dict['MAX'] = function() { vm.push(Math.max(vm.pop(), vm.pop())); };
this.dict['MIN'] = function() { vm.push(Math.min(vm.pop(), vm.pop())); };
this.dict['ABS'] = function() { vm.push(Math.abs(vm.pop())); };
// Comparison
this.dict['='] = function() { vm.push(vm.pop() === vm.pop() ? -1 : 0); };
this.dict['<>'] = function() { vm.push(vm.pop() !== vm.pop() ? -1 : 0); };
this.dict['<'] = function() { var b=vm.pop(), a=vm.pop(); vm.push(a<b?-1:0); };
this.dict['>'] = function() { var b=vm.pop(), a=vm.pop(); vm.push(a>b?-1:0); };
this.dict['0='] = function() { vm.push(vm.pop()===0?-1:0); };
this.dict['0<'] = function() { vm.push(vm.pop()<0?-1:0); };
this.dict['0>'] = function() { vm.push(vm.pop()>0?-1:0); };
// Logic
this.dict['AND'] = function() { vm.push(vm.pop() & vm.pop()); };
this.dict['OR'] = function() { vm.push(vm.pop() | vm.pop()); };
this.dict['NOT'] = function() { vm.push(~vm.pop()); };
this.dict['INVERT'] = function() { vm.push(vm.pop()===0?-1:0); };
// Stack
this.dict['DUP'] = function() { var v=vm.peek(); vm.push(v); };
this.dict['DROP'] = function() { vm.pop(); };
this.dict['SWAP'] = function() { var b=vm.pop(),a=vm.pop(); vm.push(b); vm.push(a); };
this.dict['OVER'] = function() { var b=vm.pop(),a=vm.pop(); vm.push(a); vm.push(b); vm.push(a); };
this.dict['ROT'] = function() { var c=vm.pop(),b=vm.pop(),a=vm.pop(); vm.push(b); vm.push(c); vm.push(a); };
this.dict['NIP'] = function() { var b=vm.pop(); vm.pop(); vm.push(b); };
this.dict['TUCK'] = function() { var b=vm.pop(),a=vm.pop(); vm.push(b); vm.push(a); vm.push(b); };
this.dict['2DUP'] = function() { var b=vm.pop(),a=vm.pop(); vm.push(a);vm.push(b);vm.push(a);vm.push(b); };
this.dict['2DROP']= function() { vm.pop(); vm.pop(); };
// Output
this.dict['.'] = function() { vm.emit(String(vm.pop()) + ' '); };
this.dict['CR'] = function() { vm.emit('\n'); };
this.dict['SPACE']= function() { vm.emit(' '); };
this.dict['SPACES']= function() { var n=vm.pop(); for(var i=0;i<n;i++) vm.emit(' '); };
this.dict['.S'] = function() {
vm.emit('<' + vm.stack.length + '> ');
vm.stack.forEach(function(v){ vm.emit(String(v)+' '); });
};
// Boolean
this.dict['TRUE'] = function() { vm.push(-1); };
this.dict['FALSE']= function() { vm.push(0); };
// String
this.dict['TYPE'] = function() { vm.emit(String(vm.pop())); };
// Misc
this.dict['NOP'] = function() {};
this.dict['BYE'] = function() { vm.emit('\nSnapKitty Forth β BYE ⬑\n'); };
};
// ββ Sovereign word extensions βββββββββββββββββββββββββββββββββββββββββββββββββ
VM.prototype._defineSovereignWords = function() {
var vm = this;
// WORM-SEAL β seal the top of stack as a WORM event
this.dict['WORM-SEAL'] = function() {
var payload = vm.pop();
var ts = new Date().toISOString();
var hash = simHash(String(payload) + ts);
vm.push(hash);
vm.trace.push({ type: 'worm', payload: payload, hash: hash, ts: ts });
vm.emit('⬑ WORM:' + hash + ' ');
};
// TRUST-DEED? β check if the top-of-stack intent passes Trust Deed
this.dict['TRUST-DEED?'] = function() {
var intent = vm.pop();
var blocked = /delete|drop|purge|override|destroy|escalate/i.test(String(intent));
vm.push(blocked ? 0 : -1);
vm.trace.push({ type: 'trust-deed', intent: intent, passed: !blocked });
};
// BEDROCK β route query to Bedrock (simulated β returns stub in browser)
this.dict['BEDROCK'] = function() {
var query = vm.pop();
var result = '[BEDROCK:claude-sonnet-4-6] ' + String(query) + ' β PROCESSED';
vm.push(result);
vm.trace.push({ type: 'bedrock', query: query });
};
// LOCAL-GPU β route to local Granite (Ollama :11434)
this.dict['LOCAL-GPU'] = function() {
var code = vm.pop();
var result = '[GRANITE-CODE:3B@RTX3080] ' + String(code) + ' β COMPILED';
vm.push(result);
vm.trace.push({ type: 'local-gpu', code: code });
};
// CATCODE β behavioral screening
this.dict['CATCODE'] = function() {
var input = vm.pop();
var risk = /evil|harm|attack|inject/i.test(String(input)) ? 'BLOCK' : 'PASS';
vm.push(risk === 'PASS' ? -1 : 0);
vm.push(risk);
vm.trace.push({ type: 'catcode', input: input, verdict: risk });
};
// SOVEREIGN-ENVELOPE β wrap result in sovereign envelope
this.dict['SOVEREIGN-ENVELOPE'] = function() {
var result = vm.pop();
var env = {
payload: result,
seal: '⬑ Ω ⺠Ψ ΠΠΣ Φ α',
ts: new Date().toISOString(),
agent: 'FORTH-VM',
};
vm.push(env);
vm.trace.push({ type: 'envelope', env: env });
};
// VERDICT β set the final verdict of a CATCODE/TRUST-DEED run
this.dict['VERDICT'] = function() {
vm.verdict = vm.pop();
vm.emit('VERDICT: ' + String(vm.verdict) + '\n');
};
// SEAL β alias for WORM-SEAL
this.dict['SEAL'] = this.dict['WORM-SEAL'];
};
// ββ Simple hash simulation ββββββββββββββββββββββββββββββββββββββββββββββββββββ
function simHash(s) {
var h = 0;
for (var i = 0; i < s.length; i++) {
h = (Math.imul(31, h) + s.charCodeAt(i)) | 0;
}
return (h >>> 0).toString(16).padStart(8, '0');
}
// ββ Tokenizer βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function tokenize(src) {
var tokens = [];
var i = 0;
src = src.replace(/\\\s[^\n]*/g, ''); // strip line comments
src = src.replace(/\( [^)]*\)/g, ''); // strip stack comments ( -- )
var raw = src.split(/\s+/).filter(Boolean);
while (i < raw.length) {
// String literal: ." ... "
if (raw[i] === '."') {
var s = '';
i++;
while (i < raw.length && !raw[i].endsWith('"')) { s += raw[i] + ' '; i++; }
if (i < raw.length) { s += raw[i].slice(0, -1); i++; }
tokens.push({ type: 'str', val: s });
} else {
var n = Number(raw[i]);
if (!isNaN(n) && raw[i] !== '') {
tokens.push({ type: 'num', val: n });
} else {
tokens.push({ type: 'word', val: raw[i].toUpperCase() });
}
i++;
}
}
return tokens;
}
// ββ Compiler: word definitions ββββββββββββββββββββββββββββββββββββββββββββββββ
function compile(tokens, dict) {
var compiled = [];
var i = 0;
while (i < tokens.length) {
var tok = tokens[i];
if (tok.type === 'word' && tok.val === ':') {
// Word definition: : WORDNAME ... ;
i++;
var name = tokens[i].val;
i++;
var body = [];
while (i < tokens.length && !(tokens[i].type === 'word' && tokens[i].val === ';')) {
body.push(tokens[i]);
i++;
}
i++; // skip ;
// Close over the body at definition time
(function(wname, wbody) {
dict[wname] = function(vm) {
vm._execTokens(wbody);
};
})(name, body);
} else {
compiled.push(tok);
i++;
}
}
return compiled;
}
// ββ Execute token list ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
VM.prototype._execTokens = function(tokens) {
var vm = this;
var i = 0;
while (i < tokens.length) {
var tok = tokens[i];
if (tok.type === 'num') {
vm.push(tok.val);
} else if (tok.type === 'str') {
vm.emit(tok.val);
} else if (tok.type === 'word') {
var w = tok.val;
// IF / ELSE / THEN
if (w === 'IF') {
var cond = vm.pop();
var thenBranch = [], elseBranch = [], depth = 1;
i++;
while (i < tokens.length && depth > 0) {
var t = tokens[i];
if (t.type === 'word') {
if (t.val === 'IF') depth++;
else if (t.val === 'THEN') { depth--; if (depth===0) break; }
else if (t.val === 'ELSE' && depth===1) {
i++;
while (i < tokens.length) {
var e = tokens[i];
if (e.type==='word' && e.val==='THEN') break;
elseBranch.push(e); i++;
}
break;
}
}
if (depth > 0) thenBranch.push(t);
i++;
}
if (cond !== 0) vm._execTokens(thenBranch);
else if (elseBranch.length) vm._execTokens(elseBranch);
// BEGIN / UNTIL loop
} else if (w === 'BEGIN') {
var loopBody = [];
i++;
while (i < tokens.length) {
var lt = tokens[i];
if (lt.type==='word' && lt.val==='UNTIL') break;
loopBody.push(lt); i++;
}
var guard = 0;
do {
vm._execTokens(loopBody);
guard++;
if (guard > 10000) break;
} while (vm.pop() === 0);
// DO / LOOP
} else if (w === 'DO') {
var doBody = [];
i++;
while (i < tokens.length) {
var dt = tokens[i];
if (dt.type==='word' && dt.val==='LOOP') break;
doBody.push(dt); i++;
}
var limit = vm.pop(), idx = vm.pop();
while (idx < limit) {
// I word β push current index
vm.dict['I'] = (function(n){ return function(){ vm.push(n); }; })(idx);
vm._execTokens(doBody);
idx++;
}
} else if (w in vm.dict) {
var fn = vm.dict[w];
// Some words take vm explicitly (compiled defs), others use closure
try { fn(vm); } catch(e) { vm.emit('\nERR['+w+']: '+e.message+'\n'); }
} else {
vm.emit('\nUNKNOWN WORD: ' + w + '\n');
}
}
i++;
}
};
// ββ Main eval βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
VM.prototype.eval = function(src) {
this.output = '';
this.trace = [];
this.verdict = null;
try {
var tokens = tokenize(src);
var program = compile(tokens, this.dict);
this._execTokens(program);
} catch(e) {
this.output += '\nFORTH ERROR: ' + e.message + '\n';
}
return {
output: this.output,
stack: this.stack.slice(),
trace: this.trace,
verdict: this.verdict,
dict: Object.keys(this.dict),
seal: '⬑ Ω ⺠Ψ ΠΠΣ Φ α',
};
};
// ββ Public API ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
return {
create: function() { return new VM(); },
run: function(src) { return new VM().eval(src); },
version: '0.1.0',
};
})();
if (typeof module !== 'undefined') module.exports = ForthVM;
|