zexus 1.6.2

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.
Files changed (227) hide show
  1. package/LICENSE +0 -0
  2. package/README.md +2513 -0
  3. package/bin/zexus +2 -0
  4. package/bin/zpics +2 -0
  5. package/bin/zpm +2 -0
  6. package/bin/zx +2 -0
  7. package/bin/zx-deploy +2 -0
  8. package/bin/zx-dev +2 -0
  9. package/bin/zx-run +2 -0
  10. package/package.json +66 -0
  11. package/scripts/README.md +24 -0
  12. package/scripts/postinstall.js +44 -0
  13. package/shared_config.json +24 -0
  14. package/src/README.md +1525 -0
  15. package/src/tests/run_zexus_tests.py +117 -0
  16. package/src/tests/test_all_phases.zx +346 -0
  17. package/src/tests/test_blockchain_features.zx +306 -0
  18. package/src/tests/test_complexity_features.zx +321 -0
  19. package/src/tests/test_core_integration.py +185 -0
  20. package/src/tests/test_phase10_ecosystem.zx +177 -0
  21. package/src/tests/test_phase1_modifiers.zx +87 -0
  22. package/src/tests/test_phase2_plugins.zx +80 -0
  23. package/src/tests/test_phase3_security.zx +97 -0
  24. package/src/tests/test_phase4_vfs.zx +116 -0
  25. package/src/tests/test_phase5_types.zx +117 -0
  26. package/src/tests/test_phase6_metaprogramming.zx +125 -0
  27. package/src/tests/test_phase7_optimization.zx +132 -0
  28. package/src/tests/test_phase9_advanced_types.zx +157 -0
  29. package/src/tests/test_security_features.py +419 -0
  30. package/src/tests/test_security_features.zx +276 -0
  31. package/src/tests/test_simple_zx.zx +1 -0
  32. package/src/tests/test_verification_simple.zx +69 -0
  33. package/src/zexus/__init__.py +28 -0
  34. package/src/zexus/__main__.py +5 -0
  35. package/src/zexus/__pycache__/__init__.cpython-312.pyc +0 -0
  36. package/src/zexus/__pycache__/advanced_types.cpython-312.pyc +0 -0
  37. package/src/zexus/__pycache__/builtin_modules.cpython-312.pyc +0 -0
  38. package/src/zexus/__pycache__/capability_system.cpython-312.pyc +0 -0
  39. package/src/zexus/__pycache__/complexity_system.cpython-312.pyc +0 -0
  40. package/src/zexus/__pycache__/concurrency_system.cpython-312.pyc +0 -0
  41. package/src/zexus/__pycache__/config.cpython-312.pyc +0 -0
  42. package/src/zexus/__pycache__/dependency_injection.cpython-312.pyc +0 -0
  43. package/src/zexus/__pycache__/ecosystem.cpython-312.pyc +0 -0
  44. package/src/zexus/__pycache__/environment.cpython-312.pyc +0 -0
  45. package/src/zexus/__pycache__/error_reporter.cpython-312.pyc +0 -0
  46. package/src/zexus/__pycache__/hybrid_orchestrator.cpython-312.pyc +0 -0
  47. package/src/zexus/__pycache__/lexer.cpython-312.pyc +0 -0
  48. package/src/zexus/__pycache__/metaprogramming.cpython-312.pyc +0 -0
  49. package/src/zexus/__pycache__/module_cache.cpython-312.pyc +0 -0
  50. package/src/zexus/__pycache__/object.cpython-312.pyc +0 -0
  51. package/src/zexus/__pycache__/optimization.cpython-312.pyc +0 -0
  52. package/src/zexus/__pycache__/plugin_system.cpython-312.pyc +0 -0
  53. package/src/zexus/__pycache__/policy_engine.cpython-312.pyc +0 -0
  54. package/src/zexus/__pycache__/security.cpython-312.pyc +0 -0
  55. package/src/zexus/__pycache__/stdlib_integration.cpython-312.pyc +0 -0
  56. package/src/zexus/__pycache__/strategy_recovery.cpython-312.pyc +0 -0
  57. package/src/zexus/__pycache__/syntax_validator.cpython-312.pyc +0 -0
  58. package/src/zexus/__pycache__/type_system.cpython-312.pyc +0 -0
  59. package/src/zexus/__pycache__/virtual_filesystem.cpython-312.pyc +0 -0
  60. package/src/zexus/__pycache__/zexus_ast.cpython-312.pyc +0 -0
  61. package/src/zexus/__pycache__/zexus_token.cpython-312.pyc +0 -0
  62. package/src/zexus/advanced_types.py +401 -0
  63. package/src/zexus/blockchain/__init__.py +40 -0
  64. package/src/zexus/blockchain/__pycache__/__init__.cpython-312.pyc +0 -0
  65. package/src/zexus/blockchain/__pycache__/crypto.cpython-312.pyc +0 -0
  66. package/src/zexus/blockchain/__pycache__/ledger.cpython-312.pyc +0 -0
  67. package/src/zexus/blockchain/__pycache__/transaction.cpython-312.pyc +0 -0
  68. package/src/zexus/blockchain/crypto.py +463 -0
  69. package/src/zexus/blockchain/ledger.py +255 -0
  70. package/src/zexus/blockchain/transaction.py +267 -0
  71. package/src/zexus/builtin_modules.py +284 -0
  72. package/src/zexus/builtin_plugins.py +317 -0
  73. package/src/zexus/capability_system.py +372 -0
  74. package/src/zexus/cli/__init__.py +2 -0
  75. package/src/zexus/cli/__pycache__/__init__.cpython-312.pyc +0 -0
  76. package/src/zexus/cli/__pycache__/main.cpython-312.pyc +0 -0
  77. package/src/zexus/cli/main.py +707 -0
  78. package/src/zexus/cli/zpm.py +203 -0
  79. package/src/zexus/compare_interpreter_compiler.py +146 -0
  80. package/src/zexus/compiler/__init__.py +169 -0
  81. package/src/zexus/compiler/__pycache__/__init__.cpython-312.pyc +0 -0
  82. package/src/zexus/compiler/__pycache__/lexer.cpython-312.pyc +0 -0
  83. package/src/zexus/compiler/__pycache__/parser.cpython-312.pyc +0 -0
  84. package/src/zexus/compiler/__pycache__/zexus_ast.cpython-312.pyc +0 -0
  85. package/src/zexus/compiler/bytecode.py +266 -0
  86. package/src/zexus/compiler/compat_runtime.py +277 -0
  87. package/src/zexus/compiler/lexer.py +257 -0
  88. package/src/zexus/compiler/parser.py +779 -0
  89. package/src/zexus/compiler/semantic.py +118 -0
  90. package/src/zexus/compiler/zexus_ast.py +454 -0
  91. package/src/zexus/complexity_system.py +575 -0
  92. package/src/zexus/concurrency_system.py +493 -0
  93. package/src/zexus/config.py +201 -0
  94. package/src/zexus/crypto_bridge.py +19 -0
  95. package/src/zexus/dependency_injection.py +423 -0
  96. package/src/zexus/ecosystem.py +434 -0
  97. package/src/zexus/environment.py +101 -0
  98. package/src/zexus/environment_manager.py +119 -0
  99. package/src/zexus/error_reporter.py +314 -0
  100. package/src/zexus/evaluator/__init__.py +12 -0
  101. package/src/zexus/evaluator/__pycache__/__init__.cpython-312.pyc +0 -0
  102. package/src/zexus/evaluator/__pycache__/bytecode_compiler.cpython-312.pyc +0 -0
  103. package/src/zexus/evaluator/__pycache__/core.cpython-312.pyc +0 -0
  104. package/src/zexus/evaluator/__pycache__/expressions.cpython-312.pyc +0 -0
  105. package/src/zexus/evaluator/__pycache__/functions.cpython-312.pyc +0 -0
  106. package/src/zexus/evaluator/__pycache__/integration.cpython-312.pyc +0 -0
  107. package/src/zexus/evaluator/__pycache__/statements.cpython-312.pyc +0 -0
  108. package/src/zexus/evaluator/__pycache__/utils.cpython-312.pyc +0 -0
  109. package/src/zexus/evaluator/bytecode_compiler.py +700 -0
  110. package/src/zexus/evaluator/core.py +891 -0
  111. package/src/zexus/evaluator/expressions.py +827 -0
  112. package/src/zexus/evaluator/functions.py +3989 -0
  113. package/src/zexus/evaluator/integration.py +396 -0
  114. package/src/zexus/evaluator/statements.py +4303 -0
  115. package/src/zexus/evaluator/utils.py +126 -0
  116. package/src/zexus/evaluator_original.py +2041 -0
  117. package/src/zexus/external_bridge.py +16 -0
  118. package/src/zexus/find_affected_imports.sh +155 -0
  119. package/src/zexus/hybrid_orchestrator.py +152 -0
  120. package/src/zexus/input_validation.py +259 -0
  121. package/src/zexus/lexer.py +571 -0
  122. package/src/zexus/logging.py +89 -0
  123. package/src/zexus/lsp/__init__.py +9 -0
  124. package/src/zexus/lsp/completion_provider.py +207 -0
  125. package/src/zexus/lsp/definition_provider.py +22 -0
  126. package/src/zexus/lsp/hover_provider.py +71 -0
  127. package/src/zexus/lsp/server.py +269 -0
  128. package/src/zexus/lsp/symbol_provider.py +31 -0
  129. package/src/zexus/metaprogramming.py +321 -0
  130. package/src/zexus/module_cache.py +89 -0
  131. package/src/zexus/module_manager.py +107 -0
  132. package/src/zexus/object.py +973 -0
  133. package/src/zexus/optimization.py +424 -0
  134. package/src/zexus/parser/__init__.py +31 -0
  135. package/src/zexus/parser/__pycache__/__init__.cpython-312.pyc +0 -0
  136. package/src/zexus/parser/__pycache__/parser.cpython-312.pyc +0 -0
  137. package/src/zexus/parser/__pycache__/strategy_context.cpython-312.pyc +0 -0
  138. package/src/zexus/parser/__pycache__/strategy_structural.cpython-312.pyc +0 -0
  139. package/src/zexus/parser/integration.py +86 -0
  140. package/src/zexus/parser/parser.py +3977 -0
  141. package/src/zexus/parser/strategy_context.py +7254 -0
  142. package/src/zexus/parser/strategy_structural.py +1033 -0
  143. package/src/zexus/persistence.py +391 -0
  144. package/src/zexus/plugin_system.py +290 -0
  145. package/src/zexus/policy_engine.py +365 -0
  146. package/src/zexus/profiler/__init__.py +5 -0
  147. package/src/zexus/profiler/profiler.py +233 -0
  148. package/src/zexus/purity_system.py +398 -0
  149. package/src/zexus/runtime/__init__.py +20 -0
  150. package/src/zexus/runtime/async_runtime.py +324 -0
  151. package/src/zexus/search_old_imports.sh +65 -0
  152. package/src/zexus/security.py +1407 -0
  153. package/src/zexus/stack_trace.py +233 -0
  154. package/src/zexus/stdlib/__init__.py +27 -0
  155. package/src/zexus/stdlib/blockchain.py +341 -0
  156. package/src/zexus/stdlib/compression.py +167 -0
  157. package/src/zexus/stdlib/crypto.py +124 -0
  158. package/src/zexus/stdlib/datetime.py +163 -0
  159. package/src/zexus/stdlib/db_mongo.py +199 -0
  160. package/src/zexus/stdlib/db_mysql.py +162 -0
  161. package/src/zexus/stdlib/db_postgres.py +163 -0
  162. package/src/zexus/stdlib/db_sqlite.py +133 -0
  163. package/src/zexus/stdlib/encoding.py +230 -0
  164. package/src/zexus/stdlib/fs.py +195 -0
  165. package/src/zexus/stdlib/http.py +219 -0
  166. package/src/zexus/stdlib/http_server.py +248 -0
  167. package/src/zexus/stdlib/json_module.py +61 -0
  168. package/src/zexus/stdlib/math.py +360 -0
  169. package/src/zexus/stdlib/os_module.py +265 -0
  170. package/src/zexus/stdlib/regex.py +148 -0
  171. package/src/zexus/stdlib/sockets.py +253 -0
  172. package/src/zexus/stdlib/test_framework.zx +208 -0
  173. package/src/zexus/stdlib/test_runner.zx +119 -0
  174. package/src/zexus/stdlib_integration.py +341 -0
  175. package/src/zexus/strategy_recovery.py +256 -0
  176. package/src/zexus/syntax_validator.py +356 -0
  177. package/src/zexus/testing/zpics.py +407 -0
  178. package/src/zexus/testing/zpics_runtime.py +369 -0
  179. package/src/zexus/type_system.py +374 -0
  180. package/src/zexus/validation_system.py +569 -0
  181. package/src/zexus/virtual_filesystem.py +355 -0
  182. package/src/zexus/vm/__init__.py +8 -0
  183. package/src/zexus/vm/__pycache__/__init__.cpython-312.pyc +0 -0
  184. package/src/zexus/vm/__pycache__/async_optimizer.cpython-312.pyc +0 -0
  185. package/src/zexus/vm/__pycache__/bytecode.cpython-312.pyc +0 -0
  186. package/src/zexus/vm/__pycache__/cache.cpython-312.pyc +0 -0
  187. package/src/zexus/vm/__pycache__/jit.cpython-312.pyc +0 -0
  188. package/src/zexus/vm/__pycache__/memory_manager.cpython-312.pyc +0 -0
  189. package/src/zexus/vm/__pycache__/memory_pool.cpython-312.pyc +0 -0
  190. package/src/zexus/vm/__pycache__/optimizer.cpython-312.pyc +0 -0
  191. package/src/zexus/vm/__pycache__/parallel_vm.cpython-312.pyc +0 -0
  192. package/src/zexus/vm/__pycache__/peephole_optimizer.cpython-312.pyc +0 -0
  193. package/src/zexus/vm/__pycache__/profiler.cpython-312.pyc +0 -0
  194. package/src/zexus/vm/__pycache__/register_allocator.cpython-312.pyc +0 -0
  195. package/src/zexus/vm/__pycache__/register_vm.cpython-312.pyc +0 -0
  196. package/src/zexus/vm/__pycache__/ssa_converter.cpython-312.pyc +0 -0
  197. package/src/zexus/vm/__pycache__/vm.cpython-312.pyc +0 -0
  198. package/src/zexus/vm/async_optimizer.py +420 -0
  199. package/src/zexus/vm/bytecode.py +428 -0
  200. package/src/zexus/vm/bytecode_converter.py +297 -0
  201. package/src/zexus/vm/cache.py +532 -0
  202. package/src/zexus/vm/jit.py +720 -0
  203. package/src/zexus/vm/memory_manager.py +520 -0
  204. package/src/zexus/vm/memory_pool.py +511 -0
  205. package/src/zexus/vm/optimizer.py +478 -0
  206. package/src/zexus/vm/parallel_vm.py +899 -0
  207. package/src/zexus/vm/peephole_optimizer.py +452 -0
  208. package/src/zexus/vm/profiler.py +527 -0
  209. package/src/zexus/vm/register_allocator.py +462 -0
  210. package/src/zexus/vm/register_vm.py +520 -0
  211. package/src/zexus/vm/ssa_converter.py +757 -0
  212. package/src/zexus/vm/vm.py +1392 -0
  213. package/src/zexus/zexus_ast.py +1782 -0
  214. package/src/zexus/zexus_token.py +253 -0
  215. package/src/zexus/zpm/__init__.py +15 -0
  216. package/src/zexus/zpm/installer.py +116 -0
  217. package/src/zexus/zpm/package_manager.py +208 -0
  218. package/src/zexus/zpm/publisher.py +98 -0
  219. package/src/zexus/zpm/registry.py +110 -0
  220. package/src/zexus.egg-info/PKG-INFO +2235 -0
  221. package/src/zexus.egg-info/SOURCES.txt +876 -0
  222. package/src/zexus.egg-info/dependency_links.txt +1 -0
  223. package/src/zexus.egg-info/entry_points.txt +3 -0
  224. package/src/zexus.egg-info/not-zip-safe +1 -0
  225. package/src/zexus.egg-info/requires.txt +14 -0
  226. package/src/zexus.egg-info/top_level.txt +2 -0
  227. package/zexus.json +14 -0
@@ -0,0 +1,398 @@
1
+ """
2
+ Pure Function Enforcement System for Zexus.
3
+
4
+ Enforces referential transparency and side-effect detection to enable:
5
+ - Easier reasoning about code
6
+ - Better optimizations (caching, parallelization)
7
+ - Security analysis and sandboxing
8
+ - Concurrent and distributed execution
9
+
10
+ A pure function:
11
+ 1. Depends only on its input parameters
12
+ 2. Produces no side effects (no I/O, no global state modification, etc.)
13
+ 3. Returns the same output for the same input (deterministic)
14
+ 4. Does not throw exceptions (in strict mode)
15
+ """
16
+
17
+ from typing import Set, Dict, List, Optional, Callable, Tuple, Any
18
+ from dataclasses import dataclass, field
19
+ from enum import Enum
20
+ import inspect
21
+
22
+
23
+ class Purity(Enum):
24
+ """Levels of function purity."""
25
+ PURE = 3 # Fully pure, no side effects
26
+ RESTRICTED = 2 # Side effects only on local state
27
+ IMPURE = 1 # Has side effects
28
+ UNKNOWN = 0 # Purity not determined
29
+
30
+
31
+ class SideEffectType(Enum):
32
+ """Types of side effects."""
33
+ IO_READ = "io.read" # File/network read
34
+ IO_WRITE = "io.write" # File/network write
35
+ GLOBAL_READ = "global.read" # Read global state
36
+ GLOBAL_WRITE = "global.write" # Write global state
37
+ EXCEPTION = "exception" # Throws exception
38
+ EXTERNAL_CALL = "external" # Calls external/impure function
39
+ TIME_DEPENDENT = "time" # Depends on current time
40
+ RANDOM = "random" # Uses randomness
41
+ MEMORY_ALLOC = "memory" # Allocates memory
42
+ CONCURRENCY = "concurrency" # Uses threads/async
43
+
44
+
45
+ @dataclass
46
+ class SideEffect:
47
+ """Records a detected side effect."""
48
+ effect_type: SideEffectType
49
+ description: str = ""
50
+ location: str = "" # Function/line where side effect occurs
51
+ severity: str = "warning" # "warning", "error", "critical"
52
+
53
+ def __str__(self):
54
+ return f"{self.effect_type.value}: {self.description} at {self.location}"
55
+
56
+
57
+ @dataclass
58
+ class FunctionSignature:
59
+ """Signature of a function for purity analysis."""
60
+ name: str
61
+ parameters: List[str] = field(default_factory=list)
62
+ return_type: Optional[str] = None
63
+ declared_purity: Purity = Purity.UNKNOWN
64
+ actual_purity: Purity = Purity.UNKNOWN
65
+ side_effects: List[SideEffect] = field(default_factory=list)
66
+ immutable_inputs: Set[str] = field(default_factory=set)
67
+ immutable_locals: Set[str] = field(default_factory=set)
68
+
69
+
70
+ class PurityAnalyzer:
71
+ """
72
+ Analyzes function code to determine purity.
73
+
74
+ Detects:
75
+ - Global variable access
76
+ - I/O operations
77
+ - Exception throwing
78
+ - Calls to impure functions
79
+ - Non-deterministic operations (random, time)
80
+ - Memory allocation/deallocation
81
+ """
82
+
83
+ # Operations that indicate impurity
84
+ IMPURE_BUILTINS = {
85
+ # I/O operations
86
+ 'print', 'input', 'open', 'read', 'write', 'close',
87
+ 'os.remove', 'os.rename', 'os.system',
88
+
89
+ # Global state
90
+ 'globals', 'setattr', 'getattr',
91
+
92
+ # Non-deterministic
93
+ 'random', 'random.random', 'time.time', 'datetime.now',
94
+
95
+ # External
96
+ 'exec', 'eval', '__import__',
97
+
98
+ # Concurrency
99
+ 'Thread', 'Process', 'Lock', 'asyncio.run',
100
+ }
101
+
102
+ # Operations that indicate I/O
103
+ IO_OPERATIONS = {
104
+ 'open', 'read', 'write', 'close',
105
+ 'os.remove', 'os.rename', 'os.listdir',
106
+ 'socket', 'http.client', 'requests.get', 'requests.post',
107
+ }
108
+
109
+ # Operations that indicate global state access
110
+ GLOBAL_OPERATIONS = {
111
+ 'globals', 'vars', 'getattr', 'setattr', 'delattr',
112
+ }
113
+
114
+ def __init__(self):
115
+ self.function_cache: Dict[str, FunctionSignature] = {}
116
+ self.known_pure: Set[str] = set()
117
+ self.known_impure: Set[str] = set()
118
+
119
+ def analyze(self, func_name: str, func_code: str,
120
+ parameters: List[str]) -> FunctionSignature:
121
+ """
122
+ Analyze a function for purity.
123
+
124
+ Args:
125
+ func_name: Name of the function
126
+ func_code: Source code of the function body
127
+ parameters: List of parameter names
128
+
129
+ Returns:
130
+ FunctionSignature with purity information
131
+ """
132
+ if func_name in self.function_cache:
133
+ return self.function_cache[func_name]
134
+
135
+ sig = FunctionSignature(
136
+ name=func_name,
137
+ parameters=parameters,
138
+ immutable_inputs=set(parameters)
139
+ )
140
+
141
+ # Analyze for side effects
142
+ side_effects = self._detect_side_effects(func_code, parameters)
143
+ sig.side_effects = side_effects
144
+
145
+ # Determine purity level
146
+ if not side_effects:
147
+ sig.actual_purity = Purity.PURE
148
+ else:
149
+ # Check severity of side effects
150
+ has_critical = any(e.severity == "critical" for e in side_effects)
151
+ if has_critical:
152
+ sig.actual_purity = Purity.IMPURE
153
+ else:
154
+ sig.actual_purity = Purity.RESTRICTED
155
+
156
+ self.function_cache[func_name] = sig
157
+ return sig
158
+
159
+ def _detect_side_effects(self, func_code: str,
160
+ parameters: List[str]) -> List[SideEffect]:
161
+ """Detect side effects in function code."""
162
+ side_effects = []
163
+
164
+ # Check for impure function calls
165
+ for impure_call in self.IMPURE_BUILTINS:
166
+ if impure_call in func_code:
167
+ if any(io_op in impure_call for io_op in self.IO_OPERATIONS):
168
+ side_effects.append(SideEffect(
169
+ effect_type=SideEffectType.IO_WRITE,
170
+ description=f"Calls {impure_call}",
171
+ severity="critical"
172
+ ))
173
+ elif any(glob_op in impure_call for glob_op in self.GLOBAL_OPERATIONS):
174
+ side_effects.append(SideEffect(
175
+ effect_type=SideEffectType.GLOBAL_WRITE,
176
+ description=f"Accesses global state via {impure_call}",
177
+ severity="critical"
178
+ ))
179
+ else:
180
+ side_effects.append(SideEffect(
181
+ effect_type=SideEffectType.EXTERNAL_CALL,
182
+ description=f"Calls impure function {impure_call}",
183
+ severity="warning"
184
+ ))
185
+
186
+ # Check for exception raising
187
+ if 'raise ' in func_code or 'throw ' in func_code:
188
+ side_effects.append(SideEffect(
189
+ effect_type=SideEffectType.EXCEPTION,
190
+ description="Throws exception",
191
+ severity="warning"
192
+ ))
193
+
194
+ # Check for time/random
195
+ if 'time(' in func_code or 'time.' in func_code:
196
+ side_effects.append(SideEffect(
197
+ effect_type=SideEffectType.TIME_DEPENDENT,
198
+ description="Uses system time",
199
+ severity="warning"
200
+ ))
201
+
202
+ if 'random' in func_code:
203
+ side_effects.append(SideEffect(
204
+ effect_type=SideEffectType.RANDOM,
205
+ description="Uses randomness",
206
+ severity="warning"
207
+ ))
208
+
209
+ # Check for parameter mutation
210
+ for param in parameters:
211
+ mutation_patterns = [
212
+ f"{param}.", # Direct attribute modification
213
+ f"{param}[", # Index modification
214
+ f"append({param}",
215
+ f"extend({param}",
216
+ ]
217
+
218
+ if any(pattern in func_code for pattern in mutation_patterns):
219
+ side_effects.append(SideEffect(
220
+ effect_type=SideEffectType.GLOBAL_WRITE,
221
+ description=f"Mutates parameter '{param}'",
222
+ severity="warning"
223
+ ))
224
+
225
+ return side_effects
226
+
227
+ def declare_pure(self, func_name: str):
228
+ """Declare a function as pure (for external/built-in functions)."""
229
+ self.known_pure.add(func_name)
230
+
231
+ def declare_impure(self, func_name: str):
232
+ """Declare a function as impure (for external/built-in functions)."""
233
+ self.known_impure.add(func_name)
234
+
235
+ def is_known_pure(self, func_name: str) -> bool:
236
+ """Check if function is known to be pure."""
237
+ return func_name in self.known_pure
238
+
239
+ def is_known_impure(self, func_name: str) -> bool:
240
+ """Check if function is known to be impure."""
241
+ return func_name in self.known_impure
242
+
243
+
244
+ class PurityEnforcer:
245
+ """
246
+ Enforces purity constraints at runtime and compile-time.
247
+
248
+ - Validates that pure functions don't call impure functions
249
+ - Prevents side effects in pure function execution
250
+ - Tracks function calls for verification
251
+ """
252
+
253
+ def __init__(self, analyzer: PurityAnalyzer):
254
+ self.analyzer = analyzer
255
+ self.pure_functions: Dict[str, FunctionSignature] = {}
256
+ self.call_trace: List[Tuple[str, bool]] = [] # (func_name, is_pure)
257
+
258
+ def register_pure_function(self, sig: FunctionSignature):
259
+ """Register a function as pure."""
260
+ if sig.actual_purity == Purity.PURE:
261
+ self.pure_functions[sig.name] = sig
262
+ self.analyzer.declare_pure(sig.name)
263
+
264
+ def enforce_pure_execution(self, func_name: str,
265
+ func_code: str,
266
+ parameters: List[str]) -> bool:
267
+ """
268
+ Enforce that a function executes purely.
269
+
270
+ Raises:
271
+ PurityViolationError if impurity detected
272
+
273
+ Returns:
274
+ True if execution is pure
275
+ """
276
+ sig = self.analyzer.analyze(func_name, func_code, parameters)
277
+
278
+ if sig.actual_purity == Purity.IMPURE:
279
+ raise PurityViolationError(
280
+ f"Function {func_name} violates purity constraint: "
281
+ f"{sig.side_effects}"
282
+ )
283
+
284
+ self.pure_functions[func_name] = sig
285
+ return True
286
+
287
+ def validate_pure_call_chain(self, called_functions: List[str]) -> bool:
288
+ """
289
+ Validate that a pure function only calls other pure functions.
290
+
291
+ Args:
292
+ called_functions: List of functions called within a pure function
293
+
294
+ Returns:
295
+ True if all called functions are pure
296
+
297
+ Raises:
298
+ PurityViolationError if any called function is impure
299
+ """
300
+ for func in called_functions:
301
+ if self.analyzer.is_known_impure(func):
302
+ raise PurityViolationError(
303
+ f"Pure function calls impure function: {func}"
304
+ )
305
+
306
+ return True
307
+
308
+ def trace_call(self, func_name: str, is_pure: bool):
309
+ """Trace a function call."""
310
+ self.call_trace.append((func_name, is_pure))
311
+
312
+ def get_call_trace(self) -> List[Tuple[str, bool]]:
313
+ """Get the call trace."""
314
+ return self.call_trace.copy()
315
+
316
+ def clear_call_trace(self):
317
+ """Clear the call trace."""
318
+ self.call_trace = []
319
+
320
+
321
+ class Immutability:
322
+ """
323
+ Tracks and enforces immutability of data structures.
324
+
325
+ Immutable values:
326
+ - Cannot be modified after creation
327
+ - Are deeply immutable (including nested structures)
328
+ - Provide referential equality
329
+ """
330
+
331
+ def __init__(self):
332
+ self.immutable_objects: Set[int] = set() # id() -> immutable
333
+ self.frozen_values: Dict[int, Any] = {}
334
+
335
+ def mark_immutable(self, obj: Any) -> Any:
336
+ """Mark an object as immutable."""
337
+ obj_id = id(obj)
338
+ self.immutable_objects.add(obj_id)
339
+
340
+ # For sequences and mappings, recursively mark contents
341
+ if isinstance(obj, (list, dict)):
342
+ if isinstance(obj, list):
343
+ for item in obj:
344
+ self.mark_immutable(item)
345
+ else:
346
+ for key, value in obj.items():
347
+ self.mark_immutable(key)
348
+ self.mark_immutable(value)
349
+
350
+ return obj
351
+
352
+ def is_immutable(self, obj: Any) -> bool:
353
+ """Check if an object is immutable."""
354
+ return id(obj) in self.immutable_objects
355
+
356
+ def freeze(self, obj: Any) -> Any:
357
+ """Freeze an object to prevent modification."""
358
+ self.frozen_values[id(obj)] = obj
359
+ return self.mark_immutable(obj)
360
+
361
+ def unfreeze(self, obj: Any):
362
+ """Unfreeze an object."""
363
+ obj_id = id(obj)
364
+ if obj_id in self.frozen_values:
365
+ del self.frozen_values[obj_id]
366
+ if obj_id in self.immutable_objects:
367
+ self.immutable_objects.discard(obj_id)
368
+
369
+
370
+ class PurityViolationError(Exception):
371
+ """Exception raised when purity constraint is violated."""
372
+ pass
373
+
374
+
375
+ class ImmutabilityViolationError(Exception):
376
+ """Exception raised when immutability constraint is violated."""
377
+ pass
378
+
379
+
380
+ # Global instances
381
+ _purity_analyzer = PurityAnalyzer()
382
+ _purity_enforcer = PurityEnforcer(_purity_analyzer)
383
+ _immutability = Immutability()
384
+
385
+
386
+ def get_purity_analyzer() -> PurityAnalyzer:
387
+ """Get the global purity analyzer instance."""
388
+ return _purity_analyzer
389
+
390
+
391
+ def get_purity_enforcer() -> PurityEnforcer:
392
+ """Get the global purity enforcer instance."""
393
+ return _purity_enforcer
394
+
395
+
396
+ def get_immutability_manager() -> Immutability:
397
+ """Get the global immutability manager instance."""
398
+ return _immutability
@@ -0,0 +1,20 @@
1
+ """
2
+ Zexus Runtime Module
3
+ Provides async runtime and task management
4
+ """
5
+
6
+ from .async_runtime import (
7
+ EventLoop,
8
+ Task,
9
+ get_event_loop,
10
+ set_event_loop,
11
+ new_event_loop
12
+ )
13
+
14
+ __all__ = [
15
+ 'EventLoop',
16
+ 'Task',
17
+ 'get_event_loop',
18
+ 'set_event_loop',
19
+ 'new_event_loop'
20
+ ]