@sdkurjnk/blackshell 0.1.0 → 0.2.1

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.
@@ -1,84 +0,0 @@
1
- """Toy interpreter — executes an IR module on value inputs.
2
-
3
- This is the PoC's only execution backend (no native/LLVM yet) and the primitive
4
- the equivalence harness is built on: `verify` just runs two modules here and
5
- compares outputs (docs/interfaces/05). PoC/dev-only; production execution is
6
- native.
7
- """
8
-
9
- from .ir import BIN_OPS
10
- from .messages import EngineError
11
-
12
- _STEP_LIMIT = 1_000_000
13
-
14
-
15
- def run(module, inputs):
16
- """inputs: {param_name: int} -> {return_name: int}."""
17
- regs = {}
18
- for p in module["params"]:
19
- if p not in inputs:
20
- raise EngineError("interp.missing_input", param=p)
21
- regs[p] = int(inputs[p])
22
-
23
- mem = {} # isolated local store, index -> value
24
- blocks = {b["label"]: b for b in module["blocks"]}
25
- cur = module["blocks"][0]["label"]
26
-
27
- steps = 0
28
- while True:
29
- steps += 1
30
- if steps > _STEP_LIMIT:
31
- raise EngineError("interp.step_limit")
32
-
33
- next_label = None
34
- for inst in blocks[cur]["insts"]:
35
- op = inst["op"]
36
- if op == "const":
37
- regs[inst["dst"]] = int(inst["imm"])
38
- elif op == "mov":
39
- regs[inst["dst"]] = regs[inst["src"]]
40
- elif op in BIN_OPS:
41
- regs[inst["dst"]] = _binop(op, regs[inst["lhs"]], regs[inst["rhs"]])
42
- elif op == "load":
43
- regs[inst["dst"]] = mem.get(_addr(regs, inst["addr"]), 0)
44
- elif op == "store":
45
- mem[_addr(regs, inst["addr"])] = regs[inst["src"]]
46
- elif op == "br":
47
- next_label = inst["then"] if regs[inst["cond"]] != 0 else inst["else"]
48
- break
49
- elif op == "jmp":
50
- next_label = inst["target"]
51
- break
52
- elif op == "ret":
53
- return {r: regs[r] for r in module["returns"]}
54
- else:
55
- raise EngineError("interp.unknown_op", op=op)
56
-
57
- if next_label is None:
58
- # Fell off the end of a block with no branch/ret: implicit return.
59
- return {r: regs.get(r, 0) for r in module["returns"]}
60
- cur = next_label
61
-
62
-
63
- def _addr(regs, a):
64
- return a if isinstance(a, int) else regs[a]
65
-
66
-
67
- def _binop(op, a, b):
68
- if op == "add":
69
- return a + b
70
- if op == "sub":
71
- return a - b
72
- if op == "mul":
73
- return a * b
74
- if op == "and":
75
- return a & b
76
- if op == "or":
77
- return a | b
78
- if op == "xor":
79
- return a ^ b
80
- if op == "shl":
81
- return a << b
82
- if op == "shr":
83
- return a >> b
84
- raise EngineError("interp.unknown_op", op=op)
@@ -1,50 +0,0 @@
1
- """Toy IR model — load + validate (docs/interfaces/03-ir-model.md).
2
-
3
- The IR is JSON. A module is one sealed unit: a function with value inputs
4
- (`params`), value outputs (`returns`), virtual registers (`locals`), and basic
5
- blocks. No pointers / globals / I/O are representable — that is the §5
6
- condition-1 isolation enforced structurally.
7
-
8
- This layer never prints: malformed IR raises EngineError (rendered by the
9
- driver, docs/interfaces/02 error handling).
10
- """
11
-
12
- import json
13
-
14
- from .messages import EngineError
15
-
16
- BIN_OPS = {"add", "sub", "mul", "and", "or", "xor", "shl", "shr"}
17
-
18
-
19
- def load_ir(path):
20
- try:
21
- with open(path, "r", encoding="utf-8") as f:
22
- module = json.load(f)
23
- except FileNotFoundError:
24
- raise EngineError("file.not_found", path=path)
25
- except json.JSONDecodeError as e:
26
- raise EngineError("ir.bad_json", path=path, detail=str(e))
27
- validate(module)
28
- return module
29
-
30
-
31
- def validate(m):
32
- for key in ("name", "params", "returns", "locals", "blocks"):
33
- if key not in m:
34
- raise EngineError("ir.missing_field", field=key)
35
- if not m["blocks"]:
36
- raise EngineError("ir.no_blocks")
37
-
38
- labels = {b["label"] for b in m["blocks"]}
39
- for b in m["blocks"]:
40
- if "insts" not in b:
41
- raise EngineError("ir.block_no_insts", label=b.get("label"))
42
- for inst in b["insts"]:
43
- op = inst.get("op")
44
- if op is None:
45
- raise EngineError("ir.inst_no_op", label=b["label"])
46
- if op == "br" and (inst["then"] not in labels or inst["else"] not in labels):
47
- raise EngineError("ir.bad_branch", label=b["label"])
48
- if op == "jmp" and inst["target"] not in labels:
49
- raise EngineError("ir.bad_branch", label=b["label"])
50
- return m
@@ -1,61 +0,0 @@
1
- """Single source of truth for user-facing messages and the exit-code protocol
2
- (docs/interfaces/02-driver.md).
3
-
4
- Pipeline code (ir / interp / passes) never prints — it raises
5
- ``EngineError(key, **params)``. The driver is the only place that renders a
6
- message (``driver._emit``), looking everything up here. Keeping the whole
7
- catalog in one module is what lets a future JS-side CLI take over rendering by
8
- consuming this table, instead of the driver.
9
- """
10
-
11
- EXIT_OK = 0
12
- EXIT_ERR = 1
13
- EXIT_REJECT = 2 # gate rejected a unit (§5 condition 1)
14
- EXIT_ENGINE_MISSING = 127 # set by the JS launcher; listed here for completeness
15
-
16
- OUT, ERR = "out", "err"
17
-
18
- # key -> (template, stream, exit_code)
19
- CATALOG = {
20
- # --- errors (stderr, exit 1) ---
21
- "ir.missing_field": ("error: IR missing field: {field}", ERR, EXIT_ERR),
22
- "ir.no_blocks": ("error: module has no blocks", ERR, EXIT_ERR),
23
- "ir.block_no_insts": ("error: block {label!r} has no insts", ERR, EXIT_ERR),
24
- "ir.inst_no_op": ("error: instruction without op in block {label!r}", ERR, EXIT_ERR),
25
- "ir.bad_branch": ("error: branch to unknown label in block {label!r}", ERR, EXIT_ERR),
26
- "ir.bad_json": ("error: invalid JSON in {path}: {detail}", ERR, EXIT_ERR),
27
- "file.not_found": ("error: file not found: {path}", ERR, EXIT_ERR),
28
- "arg.one_positional": ("error: expected exactly one <ir-file> argument", ERR, EXIT_ERR),
29
- "interp.missing_input": ("error: missing input: {param}", ERR, EXIT_ERR),
30
- "interp.step_limit": ("error: interpreter step limit exceeded (infinite loop?)", ERR, EXIT_ERR),
31
- "interp.unknown_op": ("error: unknown op: {op}", ERR, EXIT_ERR),
32
- "cmd.unknown": ("error: unknown command: {cmd}", ERR, EXIT_ERR),
33
- "stage.not_staged": ("error: not staged: {path}", ERR, EXIT_ERR),
34
- "verify.broken": ("error: {pass_name} broke equivalence on {path}: {mismatch}", ERR, EXIT_ERR),
35
- # --- reject (stderr, exit 2) ---
36
- "gate.reject": ("reject: {path} — {reason}", ERR, EXIT_REJECT),
37
- # --- info (stdout, exit 0) ---
38
- "check.pass": ("pass: {path} is eligible (gate: {gate})", OUT, EXIT_OK),
39
- "stage.added": ("staged: {path} [{levels}]", OUT, EXIT_OK),
40
- "stage.dropped": ("dropped: {path}", OUT, EXIT_OK),
41
- "stage.nothing": ("nothing staged", OUT, EXIT_OK),
42
- "stage.list_item": (" {path} [{levels}]", OUT, EXIT_OK),
43
- "enshell.sealed": ("sealed: {path} -> {out}", OUT, EXIT_OK),
44
- "enshell.done": ("enshell complete: {count} unit(s); staging cleared", OUT, EXIT_OK),
45
- }
46
-
47
-
48
- class EngineError(Exception):
49
- """Raised by pipeline code; carries a catalog key + params so the driver
50
- can render it. Pipeline code must never print directly."""
51
-
52
- def __init__(self, key, **params):
53
- self.key = key
54
- self.params = params
55
- super().__init__(key)
56
-
57
-
58
- def render(key, **params):
59
- """Return (line, stream, exit_code) for a catalog key."""
60
- template, stream, code = CATALOG[key]
61
- return template.format(**params), stream, code
@@ -1,39 +0,0 @@
1
- """Pass registry + dummy passes (docs/interfaces/04-pass-contract.md).
2
-
3
- Two pass kinds, two signatures:
4
- - noising : IR -> IR (semantics-preserving; here: identity)
5
- - gate : IR -> Verdict (read-only; here: accept-all)
6
-
7
- The working-skeleton point: dummy and real passes share these signatures, so
8
- replacing a dummy with a real pass never touches the driver (just swap the
9
- registry entry). Identity noising is SAFE ("correct but unprotected");
10
- accept-all gate is NOT — it gives a false "sealed" confidence and must be
11
- replaced before shipping.
12
- """
13
-
14
- import copy
15
-
16
-
17
- def dummy_gate(module):
18
- """IR -> Verdict. DUMMY accept-all. Replace with the real §5 condition-1
19
- static check before shipping."""
20
- return {"ok": True, "dummy": True}
21
-
22
-
23
- def _identity(module):
24
- """IR -> IR, unchanged. Returns a copy so callers can treat passes as pure."""
25
- return copy.deepcopy(module)
26
-
27
-
28
- # Gate always runs ahead of noising (verdict carries the pass name).
29
- GATE = ("dummy-accept-all", dummy_gate)
30
-
31
- # Noising passes keyed by level; all identity in the skeleton.
32
- NOISING = {
33
- "L1": ("identity-L1", _identity),
34
- "L2": ("identity-L2", _identity),
35
- "L3": ("identity-L3", _identity),
36
- }
37
-
38
- # Fixed application order regardless of selection order.
39
- LEVEL_ORDER = ("L1", "L2", "L3")
@@ -1,50 +0,0 @@
1
- """Staging index (docs/interfaces/02-driver.md).
2
-
3
- The git-style index shared by add / drop / list. Lives in the working
4
- directory at .blackshell/stage.json (cf. .git/index). Records each staged
5
- unit's path and its per-unit noising levels.
6
- """
7
-
8
- import json
9
- import os
10
-
11
- INDEX_DIR = ".blackshell"
12
- INDEX_PATH = os.path.join(INDEX_DIR, "stage.json")
13
-
14
-
15
- def _read():
16
- if not os.path.exists(INDEX_PATH):
17
- return {"units": []}
18
- with open(INDEX_PATH, "r", encoding="utf-8") as f:
19
- return json.load(f)
20
-
21
-
22
- def _write(index):
23
- os.makedirs(INDEX_DIR, exist_ok=True)
24
- with open(INDEX_PATH, "w", encoding="utf-8") as f:
25
- json.dump(index, f, indent=2)
26
- f.write("\n")
27
-
28
-
29
- def add(path, levels):
30
- index = _read()
31
- units = [u for u in index["units"] if u["path"] != path]
32
- units.append({"path": path, "levels": levels})
33
- index["units"] = units
34
- _write(index)
35
-
36
-
37
- def drop(path):
38
- index = _read()
39
- before = len(index["units"])
40
- index["units"] = [u for u in index["units"] if u["path"] != path]
41
- _write(index)
42
- return before != len(index["units"])
43
-
44
-
45
- def staged():
46
- return _read()["units"]
47
-
48
-
49
- def clear():
50
- _write({"units": []})
@@ -1,13 +0,0 @@
1
- {
2
- "name": "add2",
3
- "params": ["a"],
4
- "returns": ["r"],
5
- "locals": ["t0"],
6
- "blocks": [
7
- { "label": "entry", "insts": [
8
- { "op": "const", "dst": "t0", "imm": 2 },
9
- { "op": "add", "dst": "r", "lhs": "a", "rhs": "t0" },
10
- { "op": "ret" }
11
- ]}
12
- ]
13
- }
@@ -1,19 +0,0 @@
1
- {
2
- "name": "select",
3
- "params": ["a", "b"],
4
- "returns": ["r"],
5
- "locals": [],
6
- "blocks": [
7
- { "label": "entry", "insts": [
8
- { "op": "br", "cond": "a", "then": "use_a", "else": "use_b" }
9
- ]},
10
- { "label": "use_a", "insts": [
11
- { "op": "mov", "dst": "r", "src": "a" },
12
- { "op": "ret" }
13
- ]},
14
- { "label": "use_b", "insts": [
15
- { "op": "mov", "dst": "r", "src": "b" },
16
- { "op": "ret" }
17
- ]}
18
- ]
19
- }