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,575 @@
1
+ """
2
+ Complexity & Large Project Management System for Zexus.
3
+
4
+ Provides features for organizing large, complex projects:
5
+ 1. Formal Interfaces/Type Classes - Define contracts without implementation
6
+ 2. Type Aliases - Simplify complex type signatures
7
+ 3. Module/Package Scoping - Organize code into logical units with visibility control
8
+ 4. Resource Management - Ensure proper cleanup of resources (RAII pattern)
9
+
10
+ These features enable:
11
+ - Better code organization and readability
12
+ - Type safety and correctness
13
+ - Prevention of naming conflicts
14
+ - Deterministic resource cleanup
15
+ - Clear separation of concerns
16
+ """
17
+
18
+ from typing import Dict, List, Set, Optional, Any, Callable
19
+ from dataclasses import dataclass, field
20
+ from enum import Enum
21
+
22
+
23
+ class Visibility(Enum):
24
+ """Visibility/access levels for module members."""
25
+ PUBLIC = "public" # Accessible from outside module
26
+ INTERNAL = "internal" # Only accessible within module
27
+ PROTECTED = "protected" # Accessible by submodules
28
+
29
+
30
+ @dataclass
31
+ class InterfaceMethod:
32
+ """Definition of a method required by an interface."""
33
+ name: str
34
+ parameters: List[str] = field(default_factory=list)
35
+ return_type: Optional[str] = None
36
+ description: str = ""
37
+
38
+ def __repr__(self):
39
+ params = ", ".join(self.parameters)
40
+ return f"InterfaceMethod({self.name}({params}))"
41
+
42
+
43
+ @dataclass
44
+ class Interface:
45
+ """
46
+ Formal interface/type class defining a contract.
47
+
48
+ An interface specifies what methods/properties an implementing type must have,
49
+ without providing implementation details.
50
+
51
+ Example:
52
+ interface Drawable {
53
+ draw(canvas);
54
+ bounds();
55
+ }
56
+
57
+ interface Serializable {
58
+ to_string();
59
+ from_string(str);
60
+ }
61
+ """
62
+ name: str
63
+ methods: List[InterfaceMethod] = field(default_factory=list)
64
+ properties: Dict[str, str] = field(default_factory=dict) # name -> type
65
+ extends: List[str] = field(default_factory=list) # Other interfaces this extends
66
+ documentation: str = ""
67
+ generic_parameters: List[str] = field(default_factory=list) # For generic interfaces
68
+
69
+ def add_method(self, method: InterfaceMethod):
70
+ """Add a method to the interface."""
71
+ self.methods.append(method)
72
+
73
+ def add_property(self, name: str, type_name: str):
74
+ """Add a property to the interface."""
75
+ self.properties[name] = type_name
76
+
77
+ def get_all_methods(self) -> List[InterfaceMethod]:
78
+ """Get all methods including inherited ones."""
79
+ return self.methods.copy()
80
+
81
+ def requires_implementation(self) -> Dict[str, Any]:
82
+ """Return what needs to be implemented."""
83
+ return {
84
+ "methods": [m.name for m in self.methods],
85
+ "properties": list(self.properties.keys())
86
+ }
87
+
88
+ def __repr__(self):
89
+ return f"Interface({self.name}, methods={len(self.methods)}, properties={len(self.properties)})"
90
+
91
+
92
+ @dataclass
93
+ class TypeAlias:
94
+ """
95
+ Type alias providing a simpler name for complex types.
96
+
97
+ Example:
98
+ type_alias UserID = integer;
99
+ type_alias Point = { x: float, y: float };
100
+ type_alias Handler = function(request) -> response;
101
+ """
102
+ name: str
103
+ base_type: str # The actual type this is an alias for
104
+ documentation: str = ""
105
+ generic_parameters: List[str] = field(default_factory=list)
106
+
107
+ def __repr__(self):
108
+ return f"TypeAlias({self.name} = {self.base_type})"
109
+
110
+
111
+ @dataclass
112
+ class ModuleMember:
113
+ """A member (function, variable, class) within a module."""
114
+ name: str
115
+ member_type: str # "function", "class", "variable", "interface", etc.
116
+ visibility: Visibility = Visibility.PUBLIC
117
+ value: Any = None
118
+ documentation: str = ""
119
+
120
+ def __repr__(self):
121
+ return f"ModuleMember({self.name}: {self.member_type}, visibility={self.visibility.value})"
122
+
123
+
124
+ class Module:
125
+ """
126
+ Logical code organization unit with visibility control.
127
+
128
+ Modules provide:
129
+ - Namespace separation (prevent naming conflicts)
130
+ - Visibility control (public/internal/protected)
131
+ - Clear organization of related functionality
132
+ - Import/export boundaries
133
+
134
+ Example:
135
+ module database {
136
+ // internal functions
137
+ internal function connect_db(path) { ... }
138
+
139
+ // public API
140
+ public function query(sql) { ... }
141
+ public function execute(sql, params) { ... }
142
+ }
143
+ """
144
+
145
+ def __init__(self, name: str, parent: Optional['Module'] = None):
146
+ self.name = name
147
+ self.parent = parent
148
+ self.members: Dict[str, ModuleMember] = {}
149
+ self.submodules: Dict[str, 'Module'] = {}
150
+ self.imports: List[str] = []
151
+ self.exports: List[str] = []
152
+ self.documentation = ""
153
+
154
+ def get_full_name(self) -> str:
155
+ """Get fully qualified module name."""
156
+ if self.parent:
157
+ return f"{self.parent.get_full_name()}.{self.name}"
158
+ return self.name
159
+
160
+ def add_member(self, member: ModuleMember):
161
+ """Add a member to the module."""
162
+ self.members[member.name] = member
163
+
164
+ def get_member(self, name: str) -> Optional[ModuleMember]:
165
+ """Get a member by name."""
166
+ return self.members.get(name)
167
+
168
+ def get(self, name: str):
169
+ """Get a member's value by name (for compatibility with property access).
170
+ Returns the value directly, not the ModuleMember wrapper."""
171
+ member = self.get_member(name)
172
+ if member:
173
+ return member.value
174
+ return None
175
+
176
+ def type(self):
177
+ """Return the type name for this object (for compatibility with evaluator)."""
178
+ return f"Module[{self.name}]"
179
+
180
+ def get_public_members(self) -> List[ModuleMember]:
181
+ """Get all public members."""
182
+ return [m for m in self.members.values() if m.visibility == Visibility.PUBLIC]
183
+
184
+ def add_submodule(self, module: 'Module'):
185
+ """Add a submodule."""
186
+ module.parent = self
187
+ self.submodules[module.name] = module
188
+
189
+ def get_submodule(self, name: str) -> Optional['Module']:
190
+ """Get a submodule by name."""
191
+ return self.submodules.get(name)
192
+
193
+ def add_import(self, module_path: str):
194
+ """Add an import."""
195
+ if module_path not in self.imports:
196
+ self.imports.append(module_path)
197
+
198
+ def add_export(self, name: str):
199
+ """Mark a member as exported."""
200
+ if name not in self.exports:
201
+ self.exports.append(name)
202
+
203
+ def can_access(self, member: ModuleMember, from_module: 'Module') -> bool:
204
+ """Check if a module can access a member."""
205
+ if member.visibility == Visibility.PUBLIC:
206
+ return True
207
+
208
+ if member.visibility == Visibility.INTERNAL:
209
+ # Only accessible within same module
210
+ return from_module.name == self.name
211
+
212
+ if member.visibility == Visibility.PROTECTED:
213
+ # Accessible within module and submodules
214
+ return from_module.get_full_name().startswith(self.get_full_name())
215
+
216
+ return False
217
+
218
+ def __repr__(self):
219
+ return f"Module({self.get_full_name()}, members={len(self.members)}, submodules={len(self.submodules)})"
220
+
221
+
222
+ class Package:
223
+ """
224
+ Top-level organization unit containing multiple modules.
225
+
226
+ Packages represent a cohesive unit of functionality.
227
+
228
+ Example:
229
+ package myapp.database {
230
+ module connection { ... }
231
+ module query { ... }
232
+ module migration { ... }
233
+ }
234
+ """
235
+
236
+ def __init__(self, name: str):
237
+ self.name = name
238
+ self.modules: Dict[str, Module] = {}
239
+ self.version = "0.0.1"
240
+ self.documentation = ""
241
+ self.dependencies: List[str] = []
242
+
243
+ def add_module(self, module: Module):
244
+ """Add a module to the package."""
245
+ self.modules[module.name] = module
246
+
247
+ def get_module(self, name: str) -> Optional[Module]:
248
+ """Get a module by name."""
249
+ return self.modules.get(name)
250
+
251
+ def get(self, name: str):
252
+ """Get a module or sub-package by name (for property access)."""
253
+ return self.modules.get(name)
254
+
255
+ def add_dependency(self, package_name: str):
256
+ """Add a package dependency."""
257
+ if package_name not in self.dependencies:
258
+ self.dependencies.append(package_name)
259
+
260
+ def __repr__(self):
261
+ return f"Package({self.name}, modules={len(self.modules)}, version={self.version})"
262
+
263
+
264
+ class ResourceManager:
265
+ """
266
+ Manages resource lifecycle following RAII (Resource Acquisition Is Initialization) pattern.
267
+
268
+ Ensures deterministic resource cleanup, even if exceptions occur.
269
+
270
+ Example:
271
+ using(file = open("/path/to/file.txt")) {
272
+ content = file.read();
273
+ // file is automatically closed here
274
+ }
275
+
276
+ using(connection = db.connect()) {
277
+ result = connection.query("SELECT * FROM users");
278
+ // connection is automatically closed here
279
+ }
280
+ """
281
+
282
+ def __init__(self):
283
+ self.resource_stack: List[Dict[str, Any]] = []
284
+
285
+ def acquire_resource(self, resource_name: str, resource: Any,
286
+ cleanup_fn: Callable[[Any], None]):
287
+ """
288
+ Acquire a resource with automatic cleanup.
289
+
290
+ Args:
291
+ resource_name: Name/identifier for the resource
292
+ resource: The resource object
293
+ cleanup_fn: Function to call when resource should be released
294
+ """
295
+ self.resource_stack.append({
296
+ "name": resource_name,
297
+ "resource": resource,
298
+ "cleanup": cleanup_fn,
299
+ "acquired": True
300
+ })
301
+
302
+ return resource
303
+
304
+ def release_resource(self, resource_name: str):
305
+ """Explicitly release a resource."""
306
+ for i, entry in enumerate(self.resource_stack):
307
+ if entry["name"] == resource_name:
308
+ try:
309
+ entry["cleanup"](entry["resource"])
310
+ entry["acquired"] = False
311
+ except Exception as e:
312
+ raise ResourceCleanupError(f"Error cleaning up {resource_name}: {e}")
313
+ break
314
+
315
+ def cleanup_all(self):
316
+ """Clean up all acquired resources (called on exit)."""
317
+ # Release in reverse order (LIFO)
318
+ for entry in reversed(self.resource_stack):
319
+ if entry["acquired"]:
320
+ try:
321
+ entry["cleanup"](entry["resource"])
322
+ entry["acquired"] = False
323
+ except Exception as e:
324
+ # Log but don't raise - ensure all resources are cleaned
325
+ print(f"Warning: Error cleaning up {entry['name']}: {e}")
326
+
327
+ def get_resource(self, resource_name: str) -> Optional[Any]:
328
+ """Get a currently acquired resource."""
329
+ for entry in self.resource_stack:
330
+ if entry["name"] == resource_name and entry["acquired"]:
331
+ return entry["resource"]
332
+ return None
333
+
334
+ def __enter__(self):
335
+ """Context manager entry."""
336
+ return self
337
+
338
+ def __exit__(self, exc_type, exc_val, exc_tb):
339
+ """Context manager exit - clean up all resources."""
340
+ self.cleanup_all()
341
+ return False # Don't suppress exceptions
342
+
343
+
344
+ class InterfaceValidator:
345
+ """
346
+ Validates that types properly implement interfaces.
347
+
348
+ Checks:
349
+ - All required methods are present
350
+ - Method signatures match
351
+ - All required properties exist
352
+ """
353
+
354
+ def __init__(self):
355
+ self.interfaces: Dict[str, Interface] = {}
356
+ self.implementations: Dict[str, Set[str]] = {} # type_name -> interfaces
357
+
358
+ def register_interface(self, interface: Interface):
359
+ """Register an interface."""
360
+ self.interfaces[interface.name] = interface
361
+
362
+ def register_implementation(self, type_name: str, interface_name: str):
363
+ """Register that a type implements an interface."""
364
+ if type_name not in self.implementations:
365
+ self.implementations[type_name] = set()
366
+ self.implementations[type_name].add(interface_name)
367
+
368
+ def validate_implementation(self, type_name: str, interface_name: str,
369
+ implementation: Dict[str, Any]) -> List[str]:
370
+ """
371
+ Validate that a type properly implements an interface.
372
+
373
+ Args:
374
+ type_name: Name of the type
375
+ interface_name: Name of the interface
376
+ implementation: The actual implementation (dict of methods/properties)
377
+
378
+ Returns:
379
+ List of errors (empty if valid)
380
+ """
381
+ interface = self.interfaces.get(interface_name)
382
+ if not interface:
383
+ return [f"Interface '{interface_name}' not found"]
384
+
385
+ errors = []
386
+
387
+ # Check methods
388
+ for method in interface.methods:
389
+ if method.name not in implementation:
390
+ errors.append(f"Missing method: {method.name}")
391
+ else:
392
+ impl_method = implementation[method.name]
393
+ # Basic signature checking
394
+ if not callable(impl_method):
395
+ errors.append(f"'{method.name}' is not callable")
396
+
397
+ # Check properties
398
+ for prop_name, prop_type in interface.properties.items():
399
+ if prop_name not in implementation:
400
+ errors.append(f"Missing property: {prop_name}")
401
+
402
+ return errors
403
+
404
+ def get_interface_requirements(self, interface_name: str) -> Optional[Dict[str, Any]]:
405
+ """Get what's required by an interface."""
406
+ interface = self.interfaces.get(interface_name)
407
+ if not interface:
408
+ return None
409
+
410
+ return interface.requires_implementation()
411
+
412
+
413
+ class TypeAliasRegistry:
414
+ """Registry for type aliases."""
415
+
416
+ def __init__(self):
417
+ self.aliases: Dict[str, TypeAlias] = {}
418
+
419
+ def register_alias(self, alias: TypeAlias):
420
+ """Register a type alias.
421
+
422
+ Allows re-registration of the same type alias name.
423
+ This enables type aliases to be redefined in different scopes
424
+ or updated during development/testing.
425
+ """
426
+ # Allow re-registration - just update the alias
427
+ self.aliases[alias.name] = alias
428
+
429
+ def get_alias(self, name: str) -> Optional[TypeAlias]:
430
+ """Get a type alias by name."""
431
+ return self.aliases.get(name)
432
+
433
+ def resolve_type(self, type_name: str) -> str:
434
+ """Resolve a type name to its actual type (following aliases)."""
435
+ alias = self.aliases.get(type_name)
436
+ if alias:
437
+ # Recursively resolve in case of nested aliases
438
+ return self.resolve_type(alias.base_type)
439
+ return type_name
440
+
441
+ def list_aliases(self) -> List[TypeAlias]:
442
+ """List all registered aliases."""
443
+ return list(self.aliases.values())
444
+
445
+
446
+ class ComplexityManager:
447
+ """
448
+ Central manager for project complexity features.
449
+
450
+ Coordinates:
451
+ - Interfaces and type classes
452
+ - Type aliases
453
+ - Modules and packages
454
+ - Resource management
455
+ - Visibility and access control
456
+ """
457
+
458
+ def __init__(self):
459
+ self.root_module = Module("root")
460
+ self.packages: Dict[str, Package] = {}
461
+ self.interface_validator = InterfaceValidator()
462
+ self.type_alias_registry = TypeAliasRegistry()
463
+ self.resource_manager = ResourceManager()
464
+
465
+ def create_package(self, name: str) -> Package:
466
+ """Create a new package."""
467
+ pkg = Package(name)
468
+ self.packages[name] = pkg
469
+ return pkg
470
+
471
+ def get_package(self, name: str) -> Optional[Package]:
472
+ """Get a package by name."""
473
+ return self.packages.get(name)
474
+
475
+ def create_module(self, name: str, parent: Optional[Module] = None) -> Module:
476
+ """Create a new module."""
477
+ module = Module(name, parent)
478
+ return module
479
+
480
+ def register_interface(self, interface: Interface):
481
+ """Register an interface."""
482
+ self.interface_validator.register_interface(interface)
483
+
484
+ def register_type_alias(self, alias: TypeAlias):
485
+ """Register a type alias."""
486
+ self.type_alias_registry.register_alias(alias)
487
+
488
+ def validate_interface_implementation(self, type_name: str,
489
+ interface_name: str,
490
+ implementation: Dict[str, Any]) -> bool:
491
+ """Validate interface implementation."""
492
+ errors = self.interface_validator.validate_implementation(
493
+ type_name, interface_name, implementation
494
+ )
495
+ return len(errors) == 0
496
+
497
+ def get_implementation_errors(self, type_name: str,
498
+ interface_name: str,
499
+ implementation: Dict[str, Any]) -> List[str]:
500
+ """Get list of implementation errors."""
501
+ return self.interface_validator.validate_implementation(
502
+ type_name, interface_name, implementation
503
+ )
504
+
505
+
506
+ # Global instance
507
+ _complexity_manager = ComplexityManager()
508
+
509
+
510
+ def get_complexity_manager() -> ComplexityManager:
511
+ """Get the global complexity manager instance."""
512
+ return _complexity_manager
513
+
514
+
515
+ class ResourceCleanupError(Exception):
516
+ """Exception raised when resource cleanup fails."""
517
+ pass
518
+
519
+
520
+ class InterfaceImplementationError(Exception):
521
+ """Exception raised when interface implementation is invalid."""
522
+ pass
523
+
524
+
525
+ class ModuleAccessError(Exception):
526
+ """Exception raised when accessing private/internal module members."""
527
+ pass
528
+
529
+
530
+ # Example usage patterns
531
+ """
532
+ # 1. Define an interface
533
+ interface Drawable {
534
+ draw(canvas);
535
+ get_bounds();
536
+ }
537
+
538
+ # 2. Implement the interface
539
+ class Circle {
540
+ radius: float;
541
+
542
+ public function draw(canvas) {
543
+ canvas.draw_circle(this.radius);
544
+ }
545
+
546
+ public function get_bounds() {
547
+ return { x: 0, y: 0, width: this.radius * 2, height: this.radius * 2 };
548
+ }
549
+ }
550
+
551
+ # 3. Use type alias for clarity
552
+ type_alias UserID = integer;
553
+ type_alias Point = { x: float, y: float };
554
+
555
+ # 4. Organize with modules
556
+ module graphics {
557
+ internal function initialize_graphics() { ... }
558
+
559
+ public function render(drawable) {
560
+ drawable.draw(current_canvas);
561
+ }
562
+ }
563
+
564
+ # 5. Manage resources with using
565
+ using(file = open("data.txt")) {
566
+ content = file.read();
567
+ process(content);
568
+ // file is automatically closed
569
+ }
570
+
571
+ using(conn = database.connect()) {
572
+ results = conn.query("SELECT * FROM users");
573
+ // connection is automatically closed
574
+ }
575
+ """