+++ /dev/null
-
-**RT Code Format Enforcement:**
-1. **Format:** Pre-space commas `(a ,b)`. 2-space indent.
-2. **Enclosures:** Space padding ONLY for nested/multi-level enclosures (e.g., `if( (a) )` or `if( func() )`, but `if( a )`).
-3. **Naming:** `PascalCase` for Types/Modules. `snake_case` for Functions/Vars.
-4. **Acronyms:** MUST be capitalized in `snake_case` (e.g., `TM_module`, `JSON_parser`, `CLI_func`).
-5. **Plurals:** Forbidden in identifiers. Use container suffixes (e.g., `item_list`, `arg_tuple`, `peer_set`).
-
+++ /dev/null
-#!/usr/bin/env python3
-import sys
-from enum import Enum, auto
-
-try:
- import TM_module
-except ImportError:
- print("Error: Import failed. Run 'python3 setup.py build_ext --inplace'")
- sys.exit(1)
-
-# ==========================================
-# 1. Enums & Features
-# ==========================================
-
-class Features:
- APPEND_RIGHT = "aR"
-
-class Status(Enum):
- ABANDONED = auto()
- ACTIVE = auto()
- EMPTY = auto()
- PARKED = auto()
-
-class Topology(Enum):
- CIRCLE = auto()
- LINEAR_RIGHT = auto()
- LINEAR_OPEN = auto()
- NULL = auto()
- SEGMENT = auto()
-
-# The Factory
-TM = TM_module.FastTM
-
-# ==========================================
-# 2. TM Workspace Functions
-# ==========================================
-class TM_workspace:
- @staticmethod
- def head_on_same_cell(tm1, tm2):
- """
- Predicate: Returns true if entangled machines are on the same cell.
- Requires: tm1 and tm2 share the same tape.
- """
- if tm1.empty() or tm2.empty(): return False
- # TODO: Verify entanglement identity via C-extension property if needed.
- return tm1.address() == tm2.address()
-
- @staticmethod
- def step_tandem(tm1, tm2):
- if tm1.empty() or tm2.empty(): return
- tm1.s()
- tm2.s()
-
-# ==========================================
-# 3. Status Wrapper (TMS)
-# ==========================================
-
-class TMS:
- def __init__(self, data_obj, features=None):
- """
- TMS Constructor.
- Args:
- data_obj: MANDATORY. List or existing TM.
- """
- # 1. Wrap Existing (Entangled) TM
- if hasattr(data_obj, '__class__') and data_obj.__class__.__module__ == 'TM_module':
- self.tm = data_obj
- self._stat = Status.ACTIVE
-
- # 2. Handle Empty List (Demotion to Empty Status)
- # The C-TM rejects empty lists, so we handle it here.
- elif isinstance(data_obj, list) and len(data_obj) == 0:
- self.tm = None
- self._stat = Status.EMPTY
-
- # 3. Create New Active TM via Factory
- else:
- self.tm = TM(data_obj, features)
- self._stat = Status.ACTIVE
-
- # --- Base Methods ---
- def r(self):
- if self.empty(): raise RuntimeError("Attempted to read from EMPTY machine.")
- return self.tm.r()
-
- def rn(self, n): return self.tm.rn(n)
- def w(self, v): return self.tm.w(v)
- def wn(self, v): return self.tm.wn(v)
-
- def s(self):
- if self.empty(): raise RuntimeError("Attempted to step EMPTY machine.")
- return self.tm.s()
-
- def sn(self, n): return self.tm.sn(n)
-
- def address(self): return 0 if self.empty() else self.tm.address()
- def len(self): return 0 if self.empty() else self.tm.len()
-
- # --- Features ---
- def aR(self, v):
- if self.empty():
- # Promotion: Empty -> Active
- # We must assume implicit list container for now
- self.tm = TM([v])
- self._stat = Status.ACTIVE
- else:
- self.tm.aR(v)
-
- # --- Meta ---
- def e(self):
- return TMS(self.tm.e()) if not self.empty() else TMS([])
-
- def empty(self): return self._stat == Status.EMPTY
- def rightmost(self): return True if self.empty() else self.tm.rightmost()
-
-# ==========================================
-# 4. Region Machine
-# ==========================================
-
-class RegionMachine:
- def __init__(self, t_active):
- """
- Constructs a Region Machine from a single Active TM.
- Initializes Left/Right boundaries to the current Active position.
- """
- self.t_active = t_active
- self.t_left = t_active.e() # Left Boundary
- self.t_right = t_active.e() # Right Boundary
-
- # --- Bounds Management ---
- def qL(self):
- return TM_workspace.head_on_same_cell(self.t_active, self.t_left)
-
- def qR(self):
- return TM_workspace.head_on_same_cell(self.t_active, self.t_right)
-
- def sR(self):
- # Cue to Right Boundary (Simulated via address copying or step loop)
- # Since we lack random access 'cue' in SR_ND, we might need 's' loop
- # or direct address manipulation if supported.
- # For now, we rely on the implementation matching the head.
- pass # Todo: Implement cue via delta steps
-
- # --- Navigation (Guarded) ---
- def s(self):
- if self.qR():
- raise RuntimeError("Region Boundary Violation: Cannot step past Right Bound.")
- self.t_active.s()
-
- def r(self):
- return self.t_active.r()
+++ /dev/null
-#!/usr/bin/env python3
-# -*- mode: python; coding: utf-8; python-indent-offset: 2 -*-
-
-"""
-ObjectRegistry
-
-Maps Python runtime objects to ProcessLocalId.
-
-Strategies:
- 1. Weak Identity (Preferred): For objects that support weakrefs (instances ,classes).
- - ID lifetime is bound to object lifetime.
- - Auto-cleaned on GC.
-
- 2. Value Identity (Fallback): For immutable primitives (int ,str ,tuple).
- - ID is bound to the *value* (hash/equality).
- - Stored strongly (since values like 42 or "red" are conceptually eternal).
-"""
-
-from __future__ import annotations
-
-import weakref
-from typing import Any ,Callable ,Dict ,Optional
-
-from .ProcessLocalId import ProcessLocalIdGenerator ,ProcessLocalId
-
-
-class ObjectRegistry:
- def __init__(self ,id_gen: ProcessLocalIdGenerator):
- self._id_gen = id_gen
-
- # Strategy 1: Entities (Weakref-able)
- self._obj_to_id_wkd: "weakref.WeakKeyDictionary[Any ,ProcessLocalId]" = weakref.WeakKeyDictionary()
- self._id_to_obj_ref: Dict[ProcessLocalId ,weakref.ref] = {}
-
- # Strategy 2: Values (Hashable ,not weakref-able)
- self._value_to_id: Dict[Any ,ProcessLocalId] = {}
-
- self._finalizers: Dict[ProcessLocalId ,Callable[[ProcessLocalId] ,None]] = {}
- self._global_finalizer: Optional[Callable[[ProcessLocalId] ,None]] = None
-
- def register_finalizer(self ,fn: Callable[[ProcessLocalId] ,None]):
- """
- Registers a finalizer callback invoked when any registered *weak-refable* object is GC'd.
- """
- self._global_finalizer = fn
-
- def _on_collect(self ,obj_id: ProcessLocalId):
- # Only called for Strategy 1 objects
- ref = self._id_to_obj_ref.pop(obj_id ,None)
- if(ref is not None):
- # The WeakKeyDictionary auto-cleans the forward mapping ,
- # but we double check or clean any edge cases if needed.
- pass
-
- fn = self._global_finalizer
- if(fn is not None):
- fn(obj_id)
-
- def get_id(self ,obj: Any) -> ProcessLocalId:
- """
- Returns the ProcessLocalId for `obj` ,registering it if needed.
- """
- # 1. Try WeakRef Strategy (Entities)
- try:
- existing = self._obj_to_id_wkd.get(obj)
- if(existing is not None):
- return existing
- except TypeError:
- # obj is not weakref-able (e.g. int ,str ,tuple ,or list).
- # Fall through to Strategy 2.
- pass
- else:
- # It IS weakref-able ,but wasn't in the dictionary. Register it.
- obj_id = self._id_gen.next_id()
- self._obj_to_id_wkd[obj] = obj_id
- # Create reverse lookup with callback
- self._id_to_obj_ref[obj_id] = weakref.ref(obj ,lambda _ref ,oid=obj_id: self._on_collect(oid))
- return obj_id
-
- # 2. Try Value Strategy (Primitives)
- # Note: Mutable non-weakrefables (like standard lists) will fail here because they are unhashable.
- try:
- existing = self._value_to_id.get(obj)
- if(existing is not None):
- return existing
-
- # Register new value
- obj_id = self._id_gen.next_id()
- self._value_to_id[obj] = obj_id
- return obj_id
- except TypeError:
- # It is neither weakref-able NOR hashable (e.g. standard list ,dict).
- raise TypeError(
- f"ObjectRegistry: cannot track object of type {type(obj)!r}. "
- "It is neither weakref-able (Entity) nor hashable (Value)."
- )
-
- def try_get_object(self ,obj_id: ProcessLocalId) -> Optional[Any]:
- """
- Best-effort: returns the live object/value.
- """
- # Check Entities
- ref = self._id_to_obj_ref.get(obj_id)
- if(ref is not None):
- return ref()
-
- # Check Values
- # For now ,we assume values identify themselves.
- for val ,pid in self._value_to_id.items():
- if(pid == obj_id):
- return val
-
- return None
+++ /dev/null
-#!/usr/bin/env python3
-# -*- mode: python; coding: utf-8; python-indent-offset: 2 -*-
-
-
-"""
-ProcessLocalId
-
-A process-local identifier used as an internal key.
-
-Design constraint:
- - NOT intended to be serialized or persisted.
- - `repr()` intentionally does not reveal the numeric token, to discourage logging/persistence.
-"""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-
-
-@dataclass(frozen=True ,slots=True)
-class ProcessLocalId:
- _n: int
-
- def __repr__(self) -> str:
- return "<ProcessLocalId>"
-
- def __str__(self) -> str:
- return "<ProcessLocalId>"
-
- def as_int_UNSAFE(self) -> int:
- """
- Returns the raw integer token.
-
- UNSAFE because:
- - tokens are process-local
- - do not write these into files/databases/logs as stable identifiers
- """
- return self._n
-
-
-class ProcessLocalIdGenerator:
- """
- Monotonic generator; ids are never recycled.
- """
- def __init__(self ,start: int = 1):
- if start < 1: raise ValueError("start must be >= 1")
- self._next_n: int = start
-
- def next_id(self) -> ProcessLocalId:
- n = self._next_n
- self._next_n += 1
- return ProcessLocalId(n)
+++ /dev/null
-#!/usr/bin/env python3
-# -*- mode: python; coding: utf-8; python-indent-offset: 2 -*-
-
-
-"""
-Property
-
-A Property is itself an entity (it has an Identity id) so that:
- - properties can have properties
- - properties can be members of semantic sets
-"""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-from typing import Optional ,Tuple
-
-from .ProcessLocalId import ProcessLocalId
-
-
-@dataclass(frozen=True ,slots=True)
-class Property:
- id: ProcessLocalId
- name_path: Tuple[str ,...]
- doc: str = ""
-
- def __repr__(self) -> str:
- # name_path is safe to reveal; id token is not.
- return f"<Property {'.'.join(self.name_path)!r}>"
+++ /dev/null
-#!/usr/bin/env python3
-# -*- mode: python; coding: utf-8; python-indent-offset: 2 -*-
-
-
-"""
-PropertyManager
-
-Core RT property system.
-
-Key decisions vs the earlier `property_manager.py`:
- - do NOT key by `object_path()` strings (avoids collisions) fileciteturn3file4
- - runtime objects are keyed by weak identity (ProcessLocalId assigned by ObjectRegistry)
- - properties are first-class entities (Property has an id), so properties can have properties
-
-This remains process-local and in-memory.
-"""
-
-from __future__ import annotations
-
-from typing import Any ,Dict ,Iterable ,List ,Optional ,Tuple ,Union
-
-from .ProcessLocalId import ProcessLocalIdGenerator ,ProcessLocalId
-from .ObjectRegistry import ObjectRegistry
-from .PropertyStore import PropertyStore
-from .Property import Property
-from .SemanticSets import SemanticSet ,SemanticSetStore
-from .Syntax import SyntaxInstance
-
-
-NamePathLike = Union[str ,List[str] ,Tuple[str ,...]]
-
-
-class PropertyManager:
- def __init__(self):
- self._id_gen = ProcessLocalIdGenerator()
- self._obj_reg = ObjectRegistry(self._id_gen)
- self._store = PropertyStore()
- self._sets = SemanticSetStore()
-
- # Declare-by-name registry
- self._name_path_to_property: Dict[Tuple[str ,...],Property] = {}
- self._property_id_to_property: Dict[ProcessLocalId ,Property] = {}
-
- self._name_path_to_set: Dict[Tuple[str ,...],SemanticSet] = {}
- self._set_id_to_set: Dict[ProcessLocalId ,SemanticSet] = {}
-
- # Optional syntax instances (if user chooses to model them)
- self._syntax_id_to_instance: Dict[ProcessLocalId ,SyntaxInstance] = {}
-
- # Finalization cleanup
- self._obj_reg.register_finalizer(self._on_subject_finalized)
-
- def _on_subject_finalized(self ,subject_id: ProcessLocalId):
- self._store.remove_subject(subject_id)
- self._sets.remove_subject(subject_id)
-
- def _normalize_name_path(self ,name_path: NamePathLike) -> Tuple[str ,...]:
- if isinstance(name_path ,tuple): return name_path
- if isinstance(name_path ,list): return tuple(name_path)
- if isinstance(name_path ,str): return tuple(name_path.split("."))
- raise TypeError("name_path must be str ,list[str] ,or tuple[str ,...]")
-
- # -------------------------
- # Identity acquisition
- # -------------------------
- def id_of_py_object(self ,obj: Any) -> ProcessLocalId:
- return self._obj_reg.get_id(obj)
-
- def create_syntax_identity(self ,syntax: SyntaxInstance) -> ProcessLocalId:
- sid = self._id_gen.next_id()
- self._syntax_id_to_instance[sid] = syntax
- return sid
-
- def try_get_syntax(self ,syntax_id: ProcessLocalId) -> Optional[SyntaxInstance]:
- return self._syntax_id_to_instance.get(syntax_id)
-
- # -------------------------
- # Property declaration
- # -------------------------
- def declare_property(self ,name_path: NamePathLike ,doc: str = "") -> ProcessLocalId:
- np = self._normalize_name_path(name_path)
- existing = self._name_path_to_property.get(np)
- if existing is not None: return existing.id
- pid = self._id_gen.next_id()
- p = Property(pid ,np ,doc)
- self._name_path_to_property[np] = p
- self._property_id_to_property[pid] = p
- return pid
-
- def property_id(self ,name_path: NamePathLike) -> ProcessLocalId:
- np = self._normalize_name_path(name_path)
- p = self._name_path_to_property.get(np)
- if p is None: raise KeyError(f"Property not declared: {np!r}")
- return p.id
-
- def try_get_property(self ,prop_id: ProcessLocalId) -> Optional[Property]:
- return self._property_id_to_property.get(prop_id)
-
- # -------------------------
- # Semantic sets
- # -------------------------
- def declare_set(self ,name_path: NamePathLike ,doc: str = "") -> ProcessLocalId:
- np = self._normalize_name_path(name_path)
- existing = self._name_path_to_set.get(np)
- if existing is not None: return existing.id
- sid = self._id_gen.next_id()
- s = SemanticSet(sid ,np ,doc)
- self._name_path_to_set[np] = s
- self._set_id_to_set[sid] = s
- return sid
-
- def add_to_set(self ,subject: Any ,set_id: ProcessLocalId):
- subject_id = self._coerce_subject_id(subject)
- self._sets.add_member(set_id ,subject_id)
-
- def is_in_set(self ,subject: Any ,set_id: ProcessLocalId) -> bool:
- subject_id = self._coerce_subject_id(subject)
- return self._sets.has_member(set_id ,subject_id)
-
- def members(self ,set_id: ProcessLocalId) -> List[ProcessLocalId]:
- return list(self._sets.members(set_id))
-
- # -------------------------
- # Set/get properties
- # -------------------------
- def set(self ,subject: Any ,prop: Union[ProcessLocalId ,NamePathLike] ,value: Any):
- subject_id = self._coerce_subject_id(subject)
- prop_id = self._coerce_property_id(prop)
- self._store.set(subject_id ,prop_id ,value)
-
- def get(self ,subject: Any ,prop: Union[ProcessLocalId ,NamePathLike] ,default: Any = None) -> Any:
- subject_id = self._coerce_subject_id(subject)
- prop_id = self._coerce_property_id(prop)
- return self._store.get(subject_id ,prop_id ,default)
-
- def has(self ,subject: Any ,prop: Union[ProcessLocalId ,NamePathLike]) -> bool:
- subject_id = self._coerce_subject_id(subject)
- prop_id = self._coerce_property_id(prop)
- return self._store.has(subject_id ,prop_id)
-
- def subjects_with(self ,prop: Union[ProcessLocalId ,NamePathLike]) -> List[ProcessLocalId]:
- prop_id = self._coerce_property_id(prop)
- return list(self._store.subjects_with(prop_id))
-
- # -------------------------
- # Coercions
- # -------------------------
- def _coerce_subject_id(self ,subject: Any) -> ProcessLocalId:
- if isinstance(subject ,ProcessLocalId): return subject
- # For Python runtime objects, we require weakref-able instances.
- return self._obj_reg.get_id(subject)
-
- def _coerce_property_id(self ,prop: Union[ProcessLocalId ,NamePathLike]) -> ProcessLocalId:
- if isinstance(prop ,ProcessLocalId): return prop
- return self.property_id(prop)
+++ /dev/null
-#!/usr/bin/env python3
-# -*- mode: python; coding: utf-8; python-indent-offset: 2 -*-
-
-
-"""
-PropertyStore
-
-Stores property values and maintains reverse lookups.
-
-This is intentionally process-local and in-memory.
-"""
-
-from __future__ import annotations
-
-from typing import Any ,Dict ,Optional ,Set ,Tuple
-
-from .ProcessLocalId import ProcessLocalId
-
-
-class PropertyStore:
- def __init__(self):
- # (subject_id ,property_id) -> value
- self._values: Dict[Tuple[ProcessLocalId ,ProcessLocalId] ,Any] = {}
-
- # subject_id -> set(property_id)
- self._subject_to_props: Dict[ProcessLocalId ,Set[ProcessLocalId]] = {}
-
- # property_id -> set(subject_id)
- self._prop_to_subjects: Dict[ProcessLocalId ,Set[ProcessLocalId]] = {}
-
- def set(self ,subject_id: ProcessLocalId ,prop_id: ProcessLocalId ,value: Any):
- key = (subject_id ,prop_id)
- self._values[key] = value
- self._subject_to_props.setdefault(subject_id ,set()).add(prop_id)
- self._prop_to_subjects.setdefault(prop_id ,set()).add(subject_id)
-
- def get(self ,subject_id: ProcessLocalId ,prop_id: ProcessLocalId ,default: Any = None) -> Any:
- return self._values.get((subject_id ,prop_id) ,default)
-
- def has(self ,subject_id: ProcessLocalId ,prop_id: ProcessLocalId) -> bool:
- return (subject_id ,prop_id) in self._values
-
- def subjects_with(self ,prop_id: ProcessLocalId) -> Set[ProcessLocalId]:
- return set(self._prop_to_subjects.get(prop_id ,set()))
-
- def props_of(self ,subject_id: ProcessLocalId) -> Set[ProcessLocalId]:
- return set(self._subject_to_props.get(subject_id ,set()))
-
- def remove_subject(self ,subject_id: ProcessLocalId):
- """
- Remove all stored properties for a subject (used on finalization).
- """
- prop_ids = self._subject_to_props.pop(subject_id ,set())
- for prop_id in prop_ids:
- self._values.pop((subject_id ,prop_id) ,None)
- s = self._prop_to_subjects.get(prop_id)
- if s is not None:
- s.discard(subject_id)
- if not s: self._prop_to_subjects.pop(prop_id ,None)
+++ /dev/null
-#!/usr/bin/env python3
-# -*- mode: python; coding: utf-8; python-indent-offset: 2 -*-
-
-
-"""
-SemanticSets
-
-Membership sets over identities. Used for semantic typing.
-
-Design:
- - set_id identifies the set
- - members are subject ids
- - reverse index for cleanup
-"""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-from typing import Dict ,Optional ,Set
-
-from .ProcessLocalId import ProcessLocalId
-
-
-@dataclass(frozen=True ,slots=True)
-class SemanticSet:
- id: ProcessLocalId
- name_path: tuple[str ,...]
- doc: str = ""
-
- def __repr__(self) -> str:
- return f"<SemanticSet {'.'.join(self.name_path)!r}>"
-
-
-class SemanticSetStore:
- def __init__(self):
- self._members: Dict[ProcessLocalId ,Set[ProcessLocalId]] = {}
- self._subject_to_sets: Dict[ProcessLocalId ,Set[ProcessLocalId]] = {}
-
- def add_member(self ,set_id: ProcessLocalId ,subject_id: ProcessLocalId):
- self._members.setdefault(set_id ,set()).add(subject_id)
- self._subject_to_sets.setdefault(subject_id ,set()).add(set_id)
-
- def has_member(self ,set_id: ProcessLocalId ,subject_id: ProcessLocalId) -> bool:
- return subject_id in self._members.get(set_id ,set())
-
- def members(self ,set_id: ProcessLocalId) -> Set[ProcessLocalId]:
- return set(self._members.get(set_id ,set()))
-
- def remove_subject(self ,subject_id: ProcessLocalId):
- set_ids = self._subject_to_sets.pop(subject_id ,set())
- for set_id in set_ids:
- m = self._members.get(set_id)
- if m is not None:
- m.discard(subject_id)
- if not m: self._members.pop(set_id ,None)
+++ /dev/null
-#!/usr/bin/env python3
-# -*- mode: python; coding: utf-8; python-indent-offset: 2 -*-
-
-
-"""
-Syntax
-
-RT syntax identity instances.
-
-We treat "syntax" as AST-level objects:
- - kind: official-ish AST node kind name (e.g., "ast.FunctionDef")
- - location: file + span
- - scope: enclosing syntax identity id (optional)
- - parts: mapping of part-name to literal or referenced syntax identity id(s)
-
-This module does NOT traverse Python programs. It only defines the data model.
-"""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-from typing import Any ,Dict ,Optional ,Tuple ,Union ,List
-
-from .ProcessLocalId import ProcessLocalId
-
-
-@dataclass(frozen=True ,slots=True)
-class SourceSpan:
- file_path: str
- lineno: int
- col: int
- end_lineno: int
- end_col: int
-
-
-SyntaxPartValue = Union[
- None
- ,bool
- ,int
- ,float
- ,str
- ,ProcessLocalId
- ,List["SyntaxPartValue"]
- ,Dict[str ,"SyntaxPartValue"]
-]
-
-
-@dataclass(frozen=True ,slots=True)
-class SyntaxInstance:
- """
- A single syntax node instance.
-
- NOTE: many syntax nodes have no identifier-name. Name-like things (identifiers)
- appear as child nodes or literals inside `parts`.
- """
- kind: str
- span: SourceSpan
- scope_id: Optional[ProcessLocalId] = None
- parts: Dict[str ,SyntaxPartValue] = None
+++ /dev/null
-/*
- TM First Order Machine - C Implementation
- RT Code Format Compliant
-*/
-
-/* ========================================================= */
-/* INTERFACE */
-/* ========================================================= */
-#ifdef FACE
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-
-/* Opaque Handle */
-typedef struct TM TM;
-
-/* Constructor / Destructor */
-TM* TM_new(int size ,int* initial_data);
-void TM_free(TM* tm);
-
-/* Core Operations */
-int TM_r(TM* tm);
-void TM_rn(TM* tm ,int n ,int* buffer);
-
-void TM_w(TM* tm ,int v);
-void TM_wn(TM* tm ,int n ,int* v);
-
-void TM_s(TM* tm);
-void TM_sn(TM* tm ,int n);
-
-void TM_ls(TM* tm);
-void TM_lsn(TM* tm ,int n);
-
-int TM_head(TM* tm);
-int TM_len(TM* tm);
-
-#endif
-
-/* ========================================================= */
-/* IMPLEMENTATION */
-/* ========================================================= */
-#ifdef IMPL
-
-struct TM {
- int* tape;
- int size;
- int head;
-};
-
-TM* TM_new(int size ,int* initial_data){
- TM* tm = malloc(sizeof(TM));
- if( !tm ) return NULL;
-
- tm->tape = calloc(size ,sizeof(int));
- tm->size = size;
- tm->head = 0;
-
- if( initial_data ){
- memcpy(tm->tape ,initial_data ,size * sizeof(int));
- }
-
- return tm;
-}
-
-void TM_free(TM* tm){
- if( tm ){
- if( tm->tape ) free(tm->tape);
- free(tm);
- }
-}
-
-int TM_r(TM* tm){
- /* Unchecked read for speed */
- return tm->tape[tm->head];
-}
-
-void TM_rn(TM* tm ,int n ,int* buffer){
- /* Bulk copy (memcpy) */
- memcpy(buffer ,tm->tape + tm->head ,n * sizeof(int));
-}
-
-void TM_w(TM* tm ,int v){
- tm->tape[tm->head] = v;
-}
-
-void TM_wn(TM* tm ,int n ,int* v){
- memcpy(tm->tape + tm->head ,v ,n * sizeof(int));
-}
-
-void TM_s(TM* tm){
- tm->head++;
-}
-
-void TM_sn(TM* tm ,int n){
- tm->head += n;
-}
-
-void TM_ls(TM* tm){
- tm->head--;
-}
-
-void TM_lsn(TM* tm ,int n){
- tm->head -= n;
-}
-
-int TM_head(TM* tm){
- return tm->head;
-}
-
-int TM_len(TM* tm){
- return tm->size;
-}
-
-#endif
+++ /dev/null
-#!/usr/bin/env python3
-import copy
-
-class TapeMachine:
- """
- TTCA Tape Machine Implementation.
- Adapts List, Map, and Set to a common Tape Interface.
- """
- def __init__(self, tape_ref, path=None, point=0, iterator=None):
- self.tape = tape_ref # The 'Memory' (Shared)
- self.path = path or [] # The 'Stack' (Hierarchy context)
-
- # 'point' is the Address.
- # For Lists: Integer Index
- # For Maps: Key (Symbol)
- # For Sets: The Item itself
- self.point = point
-
- # For Maps/Sets, we need an iterator to support 'Step' (s)
- self._iter = iterator
-
- # --- (e) Entangle ---
- def e(self):
- """
- Entangled Copy.
- Returns a new head sharing the same tape memory.
- """
- # We must clone the iterator state if possible,
- # though Python iterators are hard to clone.
- # We usually restart iteration or assume random access.
- return TapeMachine(self.tape, self.path, self.point)
-
- # --- (r) Read ---
- def r(self):
- """Reads the cell under the head."""
- container = self._resolve_container()
-
- if isinstance(container, list):
- if 0 <= self.point < len(container):
- return container[self.point]
-
- elif isinstance(container, dict):
- return container.get(self.point, None)
-
- elif isinstance(container, set):
- # In a set, if we are 'at' a point, the value IS the point.
- # But we must verify it still exists.
- return self.point if self.point in container else None
-
- return None
-
- # --- (w) Write ---
- def w(self, value):
- """Writes to the cell under the head."""
- container = self._resolve_container()
-
- if isinstance(container, list):
- container[self.point] = value
-
- elif isinstance(container, dict):
- container[self.point] = value
-
- elif isinstance(container, set):
- raise TypeError("Cannot 'Write' to a Set cell. Use 'd' (Delete) and 'a' (Add).")
-
- # --- (s) Step ---
- def s(self, direction=1):
- """
- Move relative to current position.
- Direction +1 = Next, -1 = Previous.
- """
- container = self._resolve_container()
-
- if isinstance(container, list):
- self.point += direction
-
- elif isinstance(container, (dict, set)):
- # Maps/Sets require iteration to step.
- # This is expensive (O(N)) unless we maintain an active iterator.
- # Simplified Logic:
- try:
- # In a real engine, we'd cache the list of keys
- keys = list(container.keys()) if isinstance(container, dict) else list(container)
-
- # Find current index
- try:
- current_idx = keys.index(self.point)
- next_idx = current_idx + direction
- if 0 <= next_idx < len(keys):
- self.point = keys[next_idx]
- except ValueError:
- # Current point no longer in set/map, reset to start
- if keys: self.point = keys[0]
- except:
- pass
- return self
-
- # --- (m) Move ---
- def m(self, address):
- """
- Absolute jump to an address.
- List: index (int), Map: key (symbol), Set: member (symbol).
- """
- self.point = address
- return self
-
- # --- (a) Allocate / Add ---
- def a(self, value, key=None):
- """
- Appends or Inserts.
- List: Append value.
- Map: Insert key:value.
- Set: Add value.
- """
- container = self._resolve_container()
-
- if isinstance(container, list):
- container.append(value)
-
- elif isinstance(container, dict):
- if key is None: raise ValueError("Map allocation requires key")
- container[key] = value
-
- elif isinstance(container, set):
- container.add(value)
-
- # --- Hierarchy Navigation (Enter/Exit) ---
- def enter(self):
- """Descends into the current cell."""
- current_val = self.r()
-
- # Valid container?
- if isinstance(current_val, (list, dict, set)):
- # Push context
- new_path = self.path + [(self._resolve_container(), self.point)]
-
- # Determine starting point for new container
- start_point = 0
- if isinstance(current_val, (dict, set)) and len(current_val) > 0:
- # Start at the first key/member
- start_point = next(iter(current_val))
-
- return TapeMachine(self.tape, new_path, start_point)
- return None
-
- def exit(self):
- """Ascends to parent."""
- if not self.path: return None
-
- # Pop context
- parent_container, parent_point = self.path[-1]
- new_path = self.path[:-1]
-
- return TapeMachine(self.tape, new_path, parent_point)
-
- # --- Internal ---
- def _resolve_container(self):
- """Drills down the path stack to find current container."""
- curr = self.tape
- for container, index in self.path:
- if isinstance(container, list): curr = container[index]
- elif isinstance(container, dict): curr = container[index]
- # Set traversal in path stack implies we 'entered' a member
- # (which must be a container itself)
- return curr
+++ /dev/null
-#!/usr/bin/env bash
-set -euo pipefail
-
-# Compile with FACE and IMPL defined to generate the full library
-gcc -shared -fPIC -o libTM.so -D FACE -D IMPL TM.c
-
-echo "Built libTM.so"
+++ /dev/null
-#!/usr/bin/env python3
-import weakref
-# Assuming SymbolSpace is in the same package or path
-from SymbolSpace import SymbolSpace
-
-class Binder:
- """
- Maps transient Runtime Objects to persistent Epimetheus Symbols.
- """
-
- def __init__(self):
- # Weak Key: If the Object dies, this entry disappears automatically.
- # Value: The Symbol (Strong reference).
- self._obj_to_sym = weakref.WeakKeyDictionary()
-
- def get_symbol(self ,obj) -> SymbolSpace.Instance:
- """
- Returns the symbol for the object.
- If none exists, mints a new one and binds it.
- """
- # Check if we already know this object
- if obj in self._obj_to_sym:
- return self._obj_to_sym[obj]
-
- # Mint new identity
- sym = SymbolSpace.alloc()
- self._obj_to_sym[obj] = sym
-
- return sym
-
- def lookup(self ,obj) -> SymbolSpace.Instance:
- """
- Non-allocating lookup. Returns None if object is unknown.
- """
- return self._obj_to_sym.get(obj ,None)
-
-# --- Work & CLI ---
-
-def verify_binder():
- print("--- Binder Verification ---")
- binder = Binder()
-
- # 1. Create a transient object
- class Bike: pass
- my_bike = Bike()
-
- # 2. Bind it
- sym = binder.get_symbol(my_bike)
- print(f"Bike is bound to: {sym}")
-
- # 3. Verify stability
- sym2 = binder.get_symbol(my_bike)
- assert sym == sym2
- print("Symbol is stable for same object.")
-
- # 4. Garbage Collection Test
- import gc
- del my_bike
- gc.collect()
-
- # The binder should be empty now because the key is dead
- # Note: The 'sym' variable still holds the integer,
- # so the Concept survives even though the Implementation is gone.
- print("Object deleted. Binder entry should be gone (internal check).")
- print(f"Binder size: {len(binder._obj_to_sym)}")
-
-def CLI():
- verify_binder()
-
-if __name__ == "__main__":
- CLI()
-
+++ /dev/null
-#!/usr/bin/env python3
-from SymbolSpace import SymbolSpace
-
-# ==========================================
-# THE GRAPH (Discrete Function)
-# ==========================================
-
-class DiscreteFunction:
- """
- The Knowledge Store.
- Supports 'Smart Postings' to Parent Symbols.
- """
- def __init__(self):
- self._rev = {} # reverse map: Symbol -> Set of Objects
-
- def _add_posting(self ,sym ,obj):
- if sym not in self._rev: self._rev[sym] = set()
- self._rev[sym].add(obj)
-
- def set(self ,obj_sym ,prop_sym):
- """
- Assigns a property. Updates indexes for the specific property
- AND its namespace (Parent).
- """
- # 1. Index Specific (e.g., #105 'Red')
- self._add_posting(prop_sym ,obj_sym)
-
- # 2. Index General (e.g., #50 'Color')
- parent = SymbolSpace.get_parent(prop_sym)
- if parent:
- self._add_posting(parent ,obj_sym)
-
- def find(self ,sym):
- """Returns the set of objects associated with this symbol."""
- return self._rev.get(sym ,set())
-
-# --- Work Function ---
-
-def verify_graph():
- print("--- DiscreteFunction Verification ---")
- # 1. Create Symbols
- sym_obj = SymbolSpace.alloc()
- sym_prop = SymbolSpace.alloc()
- sym_parent = SymbolSpace.alloc()
-
- # 2. Setup Hierarchy
- SymbolSpace.set_parent(sym_prop, sym_parent)
-
- # 3. Set Fact
- df = DiscreteFunction()
- df.set(sym_obj, sym_prop)
-
- # 4. Check Smart Posting
- print(f"Finding specific property: {len(df.find(sym_prop))} (Expected 1)")
- print(f"Finding parent category: {len(df.find(sym_parent))} (Expected 1)")
-
-def CLI():
- verify_graph()
-
-if __name__ == "__main__":
- CLI()
+++ /dev/null
-#!/usr/bin/env python3
-from SymbolSpace import SymbolSpace
-from DiscreteFunction import DiscreteFunction
-from Binder import Binder
-import bisect
-
-# --- Base Factory ---
-class DifferentiatedSymbol:
- def __init__(self, name):
- self.root_symbol = SymbolSpace.alloc()
- self._intern_map = {}
-
- def __call__(self, value):
- if value not in self._intern_map:
- sym = SymbolSpace.alloc()
- self._intern_map[value] = sym
- SymbolSpace.set_parent(sym, self.root_symbol)
- self.on_new_symbol(value, sym) # Hook for subclasses
- return self._intern_map[value]
-
- def on_new_symbol(self, value, sym): pass
-
-# --- The "Interval Tree" Upgrade ---
-class OrderedNamespace(DifferentiatedSymbol):
- """
- A Namespace that maintains a Sorted Index for Range Queries.
- """
- def __init__(self, name):
- super().__init__(name)
- # Stores tuples of (Value, Symbol), sorted by Value
- self._sorted_index = []
-
- def on_new_symbol(self, value, sym):
- # Maintain sorted order (O(N) insertion, but fast reads)
- # In a real DB, this would be a B-Tree insert (O(log N))
- bisect.insort(self._sorted_index, (value, sym))
-
- def find_range(self, min_val, max_val):
- """
- Returns all symbols whose values fall in [min_val, max_val].
- Complexity: O(log N) to find bounds + O(K) to collect K matches.
- """
- # 1. Binary Search for the start point
- # We create a dummy tuple for comparison
- start_idx = bisect.bisect_left(self._sorted_index, (min_val, None))
-
- # 2. Binary Search for the end point
- # We use a dummy symbol that is "infinite" to ensure we catch duplicates of max_val
- # (or just rely on the tuple comparison logic)
- end_idx = bisect.bisect_right(self._sorted_index, (max_val, object()))
-
- # 3. Slice and Return Symbols
- results = []
- for i in range(start_idx, end_idx):
- val, sym = self._sorted_index[i]
- results.append(sym)
-
- return results
-
-# --- Work Function ---
-
-def verify_range_query():
- print("--- Range Query Verification ---")
-
- # 1. Setup
- Weight = OrderedNamespace("Weight")
- K = DiscreteFunction() # Knowledge Graph
- binder = Binder()
-
- # 2. Objects (Bikes with different weights)
- bike_light = object() # 50kg
- bike_med = object() # 150kg
- bike_heavy = object() # 250kg
-
- sym_light = binder.get_symbol(bike_light)
- sym_med = binder.get_symbol(bike_med)
- sym_heavy = binder.get_symbol(bike_heavy)
-
- # 3. Facts
- K.set(sym_light, Weight(50))
- K.set(sym_med, Weight(150))
- K.set(sym_heavy, Weight(250))
-
- # 4. Range Query: 100kg to 200kg
- print("\nQuery: Find bikes between 100kg and 200kg")
-
- # Step A: Expansion (Ask Namespace)
- target_symbols = Weight.find_range(100, 200)
- print(f" -> Namespace found {len(target_symbols)} relevant symbols.")
-
- # Step B: Intersection (Ask Graph)
- found_objects = []
- for sym in target_symbols:
- # Use the Reverse Map
- objs = K.find(sym)
- found_objects.extend(objs)
-
- print(f" -> Graph found {len(found_objects)} objects.")
-
- # Verification
- # Should find only the medium bike
- assert sym_med in found_objects
- assert sym_light not in found_objects
- assert sym_heavy not in found_objects
- print(" -> SUCCESS: Only the 150kg bike was returned.")
-
-def CLI():
- verify_range_query()
-
-if __name__ == "__main__":
- CLI()
+++ /dev/null
-#!/usr/bin/env python3
-from collections import deque as FIFO
-
-class SymbolSpace:
- """
- The manager of the Epimetheus integer namespace.
- """
-
- _counter = 0
- _dealloc_queue = FIFO()
-
- # HIERARCHY SUPPORT (Added)
- _parents = {} # Map: Child_Sym -> Parent_Sym
-
- class Instance:
- """The handle for a symbol."""
- __slots__ = ('_value' ,)
-
- def __init__(self ,value):
- self._value = value
-
- def __eq__(self ,other):
- # Compare value, not identity
- if isinstance(other ,SymbolSpace.Instance): return self._value == other._value
- return False
-
- def __hash__(self):
- return hash(self._value)
-
- def __repr__(self):
- return f"<Sym {self._value}>"
-
- @classmethod
- def alloc(cls) -> 'SymbolSpace.Instance':
- val = 0
- if cls._dealloc_queue:
- val = cls._dealloc_queue.popleft()
- else:
- cls._counter += 1
- val = cls._counter
- return cls.Instance(val)
-
- @classmethod
- def dealloc(cls ,sym: 'SymbolSpace.Instance'):
- val = sym._value
- if val == 0: raise ValueError("Null symbol (0) cannot be deallocated.")
-
- if val == cls._counter:
- cls._counter -= 1
- while cls._counter > 0 and cls._counter in cls._dealloc_queue:
- cls._dealloc_queue.remove(cls._counter)
- cls._counter -= 1
- else:
- cls._dealloc_queue.append(val)
-
- @classmethod
- def get_null(cls) -> 'SymbolSpace.Instance':
- return cls.Instance(0)
-
- # --- Hierarchy Methods ---
-
- @classmethod
- def set_parent(cls ,child ,parent):
- cls._parents[child] = parent
-
- @classmethod
- def get_parent(cls ,child):
- return cls._parents.get(child)
-
-def verify():
- print(f"Allocating 3 symbols...")
- s1 = SymbolSpace.alloc()
- s2 = SymbolSpace.alloc()
-
- # Test Hierarchy
- SymbolSpace.set_parent(s2, s1)
- assert SymbolSpace.get_parent(s2) == s1
- print("Hierarchy check passed.")
-
-def CLI():
- verify()
-
-if __name__ == "__main__":
- CLI()
+++ /dev/null
-from .Epimetheus import Epimetheus
-
+++ /dev/null
-#!/usr/bin/env python3
-from SymbolSpace import SymbolSpace
-from Binder import Binder
-from DiscreteFunction import DiscreteFunction
-from Namespace import DifferentiatedSymbol ,OrderedNamespace
-
-def example_queries():
- print("--- Epimetheus Architecture Example ---")
-
- # 1. System Initialization
- binder = Binder()
- graph = DiscreteFunction()
-
- # 2. Ontology Definition (The Factories)
- Frame = DifferentiatedSymbol("FrameMaterial")
- Price = OrderedNamespace("Price")
-
- # 3. Data Ingestion (Transient Objects)
- data_source = [
- ("Bike_A" ,"Carbon" ,3500),
- ("Bike_B" ,"Steel" ,800),
- ("Bike_C" ,"Alum" ,1200),
- ("Bike_D" ,"Carbon" ,1500),
- ]
-
- print(f"Ingesting {len(data_source)} items...")
-
- # Keep references to prevent GC during ingestion for this example
- start_objects = []
-
- for label, material, cost in data_source:
- # A. Create the Python Object
- obj = type("Bike", (), {"label": label})()
- start_objects.append(obj)
-
- # B. Bind: Object -> Symbol
- sym_bike = binder.get_symbol(obj)
-
- # C. Describe: Symbol -> Properties
- graph.set(sym_bike ,Frame(material))
- graph.set(sym_bike ,Price(cost))
-
- # ---------------------------------------------------------
- # Example 1: Exact Query ("Find Carbon Frames")
- # ---------------------------------------------------------
- print("\n[Example 1] Exact Match: Frame('Carbon')")
-
- # We ask the Factory for the symbol representing 'Carbon'
- sym_carbon = Frame("Carbon")
-
- # We ask the Graph for entities with that symbol
- results = graph.find(sym_carbon)
- print(f" -> Found {len(results)} bikes with Carbon frames.")
-
- # ---------------------------------------------------------
- # Example 2: Range Query ("Find Price 1000..2000")
- # ---------------------------------------------------------
- print("\n[Example 2] Range Match: Price(1000..2000)")
-
- # Step A: Ask Namespace for symbols in range
- # The OrderedNamespace uses bisect to find symbols efficiently
- price_symbols = Price.find_range(1000 ,2000)
- print(f" -> Namespace identified {len(price_symbols)} relevant price points.")
-
- # Step B: Ask Graph for objects having ANY of those symbols
- matches = set()
- for p_sym in price_symbols:
- found = graph.find(p_sym)
- matches.update(found)
-
- print(f" -> Graph resolved {len(matches)} bikes in price range.")
-
- # ---------------------------------------------------------
- # Example 3: Hierarchy Query ("Find Priced Things")
- # ---------------------------------------------------------
- print("\n[Example 3] Hierarchy Match: Has Price")
-
- # We query the Root Symbol of the Price namespace.
- # This works because the Graph automatically 'posts' up to the parent.
- # FIXED: Changed .root to .root_symbol to match Namespace.py
- all_priced = graph.find(Price.root_symbol)
- print(f" -> Found {len(all_priced)} objects that have a price.")
-
-def CLI():
- example_queries()
-
-if __name__ == "__main__":
- CLI()
--- /dev/null
+
+**RT Code Format Enforcement:**
+1. **Format:** Pre-space commas `(a ,b)`. 2-space indent.
+2. **Enclosures:** Space padding ONLY for nested/multi-level enclosures (e.g., `if( (a) )` or `if( func() )`, but `if( a )`).
+3. **Naming:** `PascalCase` for Types/Modules. `snake_case` for Functions/Vars.
+4. **Acronyms:** MUST be capitalized in `snake_case` (e.g., `TM_module`, `JSON_parser`, `CLI_func`).
+5. **Plurals:** Forbidden in identifiers. Use container suffixes (e.g., `item_list`, `arg_tuple`, `peer_set`).
+