nv-ctx-cpu
v1.0.0
Published
Downloads
6
Readme
@nv-ctx-cpu (JS Version AI generated)
Chinese
这是一个从原始 C 语言版本转写的纯 JavaScript 轻量级指令执行器模拟。
它将逻辑解构为一系列有序指令,通过程序计数器(pc)控制流转,
目的是为了测试状态机、自动化脚本和协议解析器的开发。
English
This is a lightweight JavaScript instruction executor transpiled from the original C version. It deconstructs logic into a series of ordered instructions and controls flow via a program counter (pc). Its purpose is to facilitate the development and testing of state machines, automation scripts, and protocol parsers.
Spanish
Este es un ejecutor de instrucciones ligero en JavaScript, transcrito de la versión original en C. Descompone la lógica en una serie de instrucciones ordenadas y controla el flujo mediante un contador de programa (pc). Su propósito es facilitar el desarrollo y las pruebas de máquinas de estado, scripts de automatización y analizadores de protocolos.
🚀 快速开始与 API 综合演示
const createCpu = require('./cpu');
// 1. 定义指令集 (支持 Function, Array<Function>, 或 Object)
const instructions = {
"init": (self) => {
self.state = { count: 0 };
console.log("PC 1 [init]: 系统初始化...");
},
"step": async (self) => {
await new Promise(r => setTimeout(r, 100)); // 模拟异步IO
self.state.count++;
console.log(`PC 2 [step]: 计数增加到 ${self.state.count}`);
},
"check": (self) => {
// 这里的返回值将作为后续 cpu.j 跳转的判断依据
return self.state.count < 3;
}
};
// 2. 初始化 CPU
const cpu = createCpu(instructions);
// 3. 核心 API 执行流程
async function main() {
/**
* [API] .n() - Next
* 执行当前指令,随后 PC + 1。返回指令执行结果。
*/
await cpu.n();
/**
* [API] .j(target_pc, cond_func) - Jump
* 条件跳转逻辑:
* 1. 它是原子操作:先执行跳转判定,再决定是否 goto,最后执行 n()。
* 2. 如果 cond_func 返回真,则跳到 target_pc 并执行该位置指令。
*/
while(await cpu.j(2, (self) => self.ir(self) === true)) {
// 逻辑流会在 PC 2 (step) 和 PC 3 (check) 之间循环
}
/**
* [API] .show_arch()
* 返回当前的运行快照 [pc, {name: func}]
*/
console.log("最终架构状态:", cpu.show_arch());
}
main();
### 🛠️ API 详解
#### 1. 状态属性 (Stateful Properties)
| 属性 | 类型 | 说明 |
| :--- | :--- | :--- |
| `pc` | `number` | 程序计数器(从 1 开始)。 |
| `ir` | `Function` | 指令寄存器。获取当前 `pc` 指向的函数。 |
#### 2. 指令流控制 (Flow Control)
| 方法 | 参数 | 说明 |
| :--- | :--- | :--- |
| `exec()` | 无 | **Execute**: 仅执行当前指令。内部自动识别 `async` 并处理 `await`。 |
| `n()` | 无 | **Next**: 执行 `ir(self)` -> 随后 `pc++`。返回执行结果。 |
| **`b()`** | 无 | **Back**: `pc--` -> 执行新指向的 `ir(self)` -> 随后 `pc++`。用于逻辑重试。 |
| **`goto(i)`** | `i: number` | **Goto**: 强制修改 `pc` 到序号 `i`。内置边界保护(1 至 length-1)。|
| **`j(i, cond_f)`** | `i: number`, `cond_f: Function` | **Jump**: 如果 `cond_f(self)` 返回真,则 `goto(i)`,最后执行 `n()`。|
