""" Language Core: Variables, Scopes, and Symbol Table Management. Handles variable lifecycle, mutability, lexical scopes, and shadow detection. """ from typing import Dict, Any, Optional, List from language_core.types import DataType, TYPE_ANY class Variable: """Represents a declared variable symbol.""" def __init__(self, name: str, data_type: DataType, value: Any = None, is_constant: bool = False): self.name = name self.data_type = data_type self.value = value self.is_constant = is_constant def __repr__(self) -> str: const_flag = "const" if self.is_constant else "var" return f"{const_flag} {self.name}: {self.data_type} = {self.value}" class Scope: """Represents an isolated lexical scope (global, function, or block).""" def __init__(self, name: str, parent: Optional['Scope'] = None): self.name = name self.parent = parent self.symbols: Dict[str, Variable] = {} def declare(self, variable: Variable): """Declares a variable in the current scope.""" if variable.name in self.symbols: raise ValueError(f"Variable '{variable.name}' already declared in scope '{self.name}'.") self.symbols[variable.name] = variable def lookup(self, name: str) -> Optional[Variable]: """Resolves variable from current scope outwards to parent scopes.""" if name in self.symbols: return self.symbols[name] if self.parent: return self.parent.lookup(name) return None class SymbolTable: """Manages hierarchical scope stacks during program composition and execution.""" def __init__(self): self.global_scope = Scope("global") self.current_scope = self.global_scope def enter_scope(self, scope_name: str) -> Scope: new_scope = Scope(scope_name, parent=self.current_scope) self.current_scope = new_scope return new_scope def exit_scope(self): if self.current_scope.parent is not None: self.current_scope = self.current_scope.parent else: raise RuntimeError("Cannot exit global scope.") def declare_variable(self, name: str, data_type: DataType, value: Any = None, is_constant: bool = False) -> Variable: var = Variable(name, data_type, value, is_constant) self.current_scope.declare(var) return var def get_variable(self, name: str) -> Optional[Variable]: return self.current_scope.lookup(name)