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,203 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ ZPM - Zexus Package Manager CLI
4
+ """
5
+ import click
6
+ import sys
7
+ from pathlib import Path
8
+ from rich.console import Console
9
+ from rich.table import Table
10
+ from rich.panel import Panel
11
+
12
+ # Add src to path
13
+ sys.path.insert(0, str(Path(__file__).parent.parent))
14
+
15
+ from zexus.zpm import PackageManager
16
+
17
+ console = Console()
18
+
19
+
20
+ @click.group()
21
+ @click.version_option(version="1.6.2", prog_name="ZPM")
22
+ def cli():
23
+ """ZPM - Zexus Package Manager
24
+
25
+ Manage packages for your Zexus projects.
26
+ """
27
+ pass
28
+
29
+
30
+ @cli.command()
31
+ @click.option('--name', '-n', help='Package name')
32
+ @click.option('--version', '-v', default='1.5.0', help='Initial version')
33
+ def init(name, version):
34
+ """Initialize a new Zexus project"""
35
+ pm = PackageManager()
36
+ config = pm.init(name=name, version=version)
37
+
38
+ console.print(Panel.fit(
39
+ f"[bold green]Project initialized![/bold green]\n\n"
40
+ f"📦 Name: {config['name']}\n"
41
+ f"🏷️ Version: {config['version']}\n"
42
+ f"📄 Config: zexus.json",
43
+ title="ZPM",
44
+ border_style="green"
45
+ ))
46
+
47
+
48
+ @cli.command()
49
+ @click.argument('package', required=False)
50
+ @click.option('--dev', '-D', is_flag=True, help='Save to devDependencies')
51
+ @click.option('--save', '-S', is_flag=True, default=True, help='Save to dependencies')
52
+ def install(package, dev, save):
53
+ """Install a package or all packages from zexus.json
54
+
55
+ Examples:
56
+ zpm install # Install all dependencies
57
+ zpm install std # Install std package
58
+ zpm install web@0.2.0 # Install specific version
59
+ zpm install crypto -D # Install as dev dependency
60
+ """
61
+ pm = PackageManager()
62
+
63
+ if package:
64
+ success = pm.install(package, dev=dev)
65
+ else:
66
+ success = pm.install_all()
67
+
68
+ if not success:
69
+ sys.exit(1)
70
+
71
+
72
+ @cli.command()
73
+ @click.argument('package')
74
+ def uninstall(package):
75
+ """Uninstall a package
76
+
77
+ Example:
78
+ zpm uninstall std
79
+ """
80
+ pm = PackageManager()
81
+ success = pm.uninstall(package)
82
+
83
+ if not success:
84
+ sys.exit(1)
85
+
86
+
87
+ @cli.command(name='list')
88
+ def list_packages():
89
+ """List installed packages"""
90
+ pm = PackageManager()
91
+ packages = pm.list()
92
+
93
+ if not packages:
94
+ console.print("📦 No packages installed")
95
+ return
96
+
97
+ table = Table(title=f"Installed Packages ({len(packages)})")
98
+ table.add_column("Name", style="cyan")
99
+ table.add_column("Version", style="green")
100
+ table.add_column("Path", style="dim")
101
+
102
+ for pkg in packages:
103
+ table.add_row(pkg["name"], pkg["version"], pkg["path"])
104
+
105
+ console.print(table)
106
+
107
+
108
+ @cli.command()
109
+ @click.argument('query')
110
+ def search(query):
111
+ """Search for packages
112
+
113
+ Example:
114
+ zpm search crypto
115
+ """
116
+ pm = PackageManager()
117
+ results = pm.search(query)
118
+
119
+ if not results:
120
+ console.print(f"🔍 No packages found for '{query}'")
121
+ return
122
+
123
+ table = Table(title=f"Search Results for '{query}'")
124
+ table.add_column("Name", style="cyan")
125
+ table.add_column("Version", style="green")
126
+ table.add_column("Description", style="white")
127
+
128
+ for pkg in results:
129
+ table.add_row(
130
+ pkg["name"],
131
+ pkg["version"],
132
+ pkg.get("description", "")
133
+ )
134
+
135
+ console.print(table)
136
+
137
+
138
+ @cli.command()
139
+ def publish():
140
+ """Publish package to registry
141
+
142
+ Publishes the current package to the ZPM registry.
143
+ Requires a valid zexus.json with name and version.
144
+ """
145
+ pm = PackageManager()
146
+ success = pm.publish()
147
+
148
+ if not success:
149
+ sys.exit(1)
150
+
151
+
152
+ @cli.command()
153
+ def info():
154
+ """Show project information"""
155
+ pm = PackageManager()
156
+ config = pm.load_config()
157
+
158
+ if not config:
159
+ console.print("❌ No zexus.json found. Run 'zpm init' first.")
160
+ sys.exit(1)
161
+
162
+ console.print(Panel.fit(
163
+ f"[bold cyan]Project Information[/bold cyan]\n\n"
164
+ f"📦 Name: {config.get('name', 'N/A')}\n"
165
+ f"🏷️ Version: {config.get('version', 'N/A')}\n"
166
+ f"📝 Description: {config.get('description', 'N/A')}\n"
167
+ f"👤 Author: {config.get('author', 'N/A')}\n"
168
+ f"📜 License: {config.get('license', 'N/A')}\n"
169
+ f"📄 Main: {config.get('main', 'N/A')}",
170
+ title="ZPM Info",
171
+ border_style="cyan"
172
+ ))
173
+
174
+ # Show dependencies
175
+ deps = config.get('dependencies', {})
176
+ if deps:
177
+ console.print("\n[bold]Dependencies:[/bold]")
178
+ for name, version in deps.items():
179
+ console.print(f" • {name}@{version}")
180
+
181
+ dev_deps = config.get('devDependencies', {})
182
+ if dev_deps:
183
+ console.print("\n[bold]Dev Dependencies:[/bold]")
184
+ for name, version in dev_deps.items():
185
+ console.print(f" • {name}@{version}")
186
+
187
+
188
+ @cli.command()
189
+ def clean():
190
+ """Remove zpm_modules directory"""
191
+ pm = PackageManager()
192
+
193
+ if not pm.zpm_dir.exists():
194
+ console.print("✅ Already clean (no zpm_modules)")
195
+ return
196
+
197
+ import shutil
198
+ shutil.rmtree(pm.zpm_dir)
199
+ console.print(f"✅ Removed {pm.zpm_dir}")
200
+
201
+
202
+ if __name__ == '__main__':
203
+ cli()
@@ -0,0 +1,146 @@
1
+ """Compare top-level symbols between the interpreter (`evaluator/`) and
2
+ the compiler package (`src/zexus/compiler`) and print a simple report.
3
+
4
+ This script is intentionally conservative: it only considers top-level
5
+ FunctionDef, ClassDef, Assign/AnnAssign targets and simple name exports.
6
+ It helps quickly discover API surface differences so we can decide what the
7
+ compiler lacks compared to the interpreter.
8
+ """
9
+ import ast
10
+ import os
11
+ import sys
12
+
13
+
14
+ def collect_top_level_symbols(path):
15
+ """Return a set of top-level symbol names defined in the Python file at path."""
16
+ symbols = set()
17
+ try:
18
+ with open(path, 'r', encoding='utf-8') as f:
19
+ src = f.read()
20
+ except Exception as e:
21
+ print(f"ERROR: could not read {path}: {e}")
22
+ return symbols
23
+
24
+ try:
25
+ tree = ast.parse(src, filename=path)
26
+ except SyntaxError as e:
27
+ print(f"ERROR: could not parse {path}: {e}")
28
+ return symbols
29
+
30
+ for node in tree.body:
31
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
32
+ symbols.add(node.name)
33
+ elif isinstance(node, ast.Assign):
34
+ for target in node.targets:
35
+ if isinstance(target, ast.Name):
36
+ symbols.add(target.id)
37
+ elif isinstance(target, ast.Tuple):
38
+ for elt in target.elts:
39
+ if isinstance(elt, ast.Name):
40
+ symbols.add(elt.id)
41
+ elif isinstance(node, ast.AnnAssign):
42
+ target = node.target
43
+ if isinstance(target, ast.Name):
44
+ symbols.add(target.id)
45
+ return symbols
46
+
47
+
48
+ def collect_package_symbols(dirpath):
49
+ """Walk dirpath and collect top-level symbols from all .py files."""
50
+ pkg_symbols = {}
51
+ for root, dirs, files in os.walk(dirpath):
52
+ for fn in files:
53
+ if not fn.endswith('.py'):
54
+ continue
55
+ if fn.startswith('__') and fn.endswith('.py'):
56
+ # still include __init__ possibly
57
+ pass
58
+ full = os.path.join(root, fn)
59
+ rel = os.path.relpath(full, dirpath)
60
+ pkg_symbols[rel] = collect_top_level_symbols(full)
61
+ return pkg_symbols
62
+
63
+
64
+ def main():
65
+ repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
66
+
67
+ # OLD: interp_path = os.path.join(repo_root, 'src', 'zexus', 'evaluator.py')
68
+ # NEW: interp_path is now the directory
69
+ interp_dir = os.path.join(repo_root, 'src', 'zexus', 'evaluator')
70
+ compiler_dir = os.path.join(repo_root, 'src', 'zexus', 'compiler')
71
+
72
+ # Update the check to look for the directory instead of a file
73
+ if not os.path.isdir(interp_dir):
74
+ print('Interpreter directory not found:', interp_dir)
75
+ # Try to look for evaluator modules (Your provided check for directory content)
76
+ evaluator_files = []
77
+ if os.path.isdir(interp_dir):
78
+ evaluator_files = [os.path.join(interp_dir, f) for f in os.listdir(interp_dir)
79
+ if f.endswith('.py') and not f.startswith('__')]
80
+ if evaluator_files:
81
+ print('Found evaluator modules:', evaluator_files)
82
+ sys.exit(2)
83
+
84
+ if not os.path.isdir(compiler_dir):
85
+ print('Compiler directory not found:', compiler_dir)
86
+ sys.exit(2)
87
+
88
+ # Collect symbols from the interpreter package
89
+ interp_pkg = collect_package_symbols(interp_dir)
90
+
91
+ # Collect symbols from the compiler package
92
+ compiler_pkg = collect_package_symbols(compiler_dir)
93
+
94
+ # union all interpreter symbols
95
+ interp_symbols_union = set()
96
+ for fn, syms in interp_pkg.items():
97
+ interp_symbols_union.update(syms)
98
+
99
+ # union all compiler symbols
100
+ compiler_symbols_union = set()
101
+ for fn, syms in compiler_pkg.items():
102
+ compiler_symbols_union.update(syms)
103
+
104
+ only_in_interp = sorted(interp_symbols_union - compiler_symbols_union)
105
+ only_in_compiler = sorted(compiler_symbols_union - interp_symbols_union)
106
+ common = sorted(interp_symbols_union & compiler_symbols_union)
107
+
108
+ print('\nComparison report: interpreter package vs compiler package')
109
+ print('Interpreter package dir:', interp_dir)
110
+ print('Compiler package dir:', compiler_dir)
111
+ print('\nCounts:')
112
+ print(' interpreter union symbols:', len(interp_symbols_union))
113
+ print(' compiler union symbols:', len(compiler_symbols_union))
114
+ print('\nOnly in interpreter ({}):'.format(len(only_in_interp)))
115
+ for name in only_in_interp:
116
+ print(' -', name)
117
+
118
+ print('\nOnly in compiler ({}):'.format(len(only_in_compiler)))
119
+ for name in only_in_compiler[:200]:
120
+ print(' -', name)
121
+
122
+ print('\nCommon symbols ({}):'.format(len(common)))
123
+ for name in common[:200]:
124
+ print(' -', name)
125
+
126
+ print('\nPer-file interpreter symbol breakdown:')
127
+ for fn, syms in sorted(interp_pkg.items()):
128
+ print(f' {fn}: {len(syms)} symbols')
129
+
130
+ print('\nPer-file compiler symbol breakdown:')
131
+ for fn, syms in sorted(compiler_pkg.items()):
132
+ print(f' {fn}: {len(syms)} symbols')
133
+
134
+ # Quick hints
135
+ if only_in_interp:
136
+ print("""
137
+ HINT: The interpreter package defines top-level symbols that are not present in the compiler package.
138
+ Start by inspecting the names listed above to decide which functionality should be implemented
139
+ or refactored into the compiler. This tool is conservative (top-level only) and may miss
140
+ runtime/exported symbols. For a deeper comparison we can compare call-sites, used imports,
141
+ or run tests that exercise both codepaths.
142
+ """)
143
+
144
+
145
+ if __name__ == '__main__':
146
+ main()
@@ -0,0 +1,169 @@
1
+ # src/zexus/compiler/__init__.py
2
+
3
+ """
4
+ Zexus Compiler Phase - Frontend compilation with semantic analysis
5
+ """
6
+
7
+ # Minimal top-level exports to avoid import-time cycles/errors.
8
+ # Do not import .parser, .semantic, .bytecode at module import time unconditionally.
9
+ # They will be imported lazily inside ZexusCompiler.compile().
10
+
11
+ Parser = None # will be set if parser import succeeds below (best-effort)
12
+ ZexusCompiler = None # defined below
13
+
14
+ # UPDATED: Get builtins from evaluator.functions module
15
+ try:
16
+ from ..evaluator.functions import FunctionEvaluatorMixin
17
+ # Create instance and get builtins
18
+ fe = FunctionEvaluatorMixin()
19
+ fe.__init__() # Initialize to register builtins
20
+ BUILTINS = fe.builtins
21
+ except Exception as e:
22
+ print(f"⚠️ Could not import builtins from evaluator: {e}")
23
+ BUILTINS = {}
24
+
25
+ # Try to import ProductionParser now but don't fail if it errors (best-effort).
26
+ try:
27
+ from .parser import ProductionParser as _ProductionParser
28
+ Parser = _ProductionParser
29
+ except Exception:
30
+ # Leave Parser as None; consumers should handle None and provide helpful messages.
31
+ Parser = None
32
+
33
+ # --- Compiler class (lazy imports inside compile) --------------------------------
34
+ class ZexusCompiler:
35
+ def __init__(self, source, enable_optimizations=True):
36
+ self.source = source
37
+ self.enable_optimizations = enable_optimizations
38
+ self.ast = None
39
+ self.bytecode = None
40
+ self.errors = []
41
+ self.analyzer = None # store SemanticAnalyzer instance after compile
42
+
43
+ def compile(self):
44
+ """Full compilation pipeline with enhanced error reporting (lazy module imports)"""
45
+ # Import frontend components lazily to avoid import-time circular issues.
46
+ try:
47
+ from .lexer import Lexer
48
+ except Exception as e:
49
+ self.errors.append(f"Compilation import error (lexer): {e}")
50
+ return None
51
+
52
+ try:
53
+ from .parser import ProductionParser
54
+ # if parser import fails, record the error and provide a helpful fallback
55
+ except Exception as e:
56
+ self.errors.append(f"Compilation import error (parser): {e}")
57
+ return None
58
+
59
+ try:
60
+ from .semantic import SemanticAnalyzer
61
+ except Exception as e:
62
+ self.errors.append(f"Compilation import error (semantic): {e}")
63
+ return None
64
+
65
+ try:
66
+ from .bytecode import BytecodeGenerator
67
+ except Exception as e:
68
+ self.errors.append(f"Compilation import error (bytecode): {e}")
69
+ return None
70
+
71
+ try:
72
+ # Phase 1: Lexical Analysis
73
+ lexer = Lexer(self.source)
74
+
75
+ # Phase 2: Syntax Analysis
76
+ parser = ProductionParser(lexer)
77
+ self.ast = parser.parse_program()
78
+ # propagate parser errors
79
+ if getattr(parser, "errors", None):
80
+ self.errors.extend(parser.errors)
81
+
82
+ if self.errors:
83
+ return None
84
+
85
+ # Phase 3: Semantic Analysis
86
+ analyzer = SemanticAnalyzer()
87
+ self.analyzer = analyzer
88
+
89
+ # Best-effort: inject BUILTINS into analyzer environment
90
+ try:
91
+ if BUILTINS:
92
+ if hasattr(analyzer, "register_builtins") and callable(getattr(analyzer, "register_builtins")):
93
+ analyzer.register_builtins(BUILTINS)
94
+ elif hasattr(analyzer, "environment"):
95
+ env = getattr(analyzer, "environment")
96
+ # env could be Environment object with set(), or a plain dict
97
+ if hasattr(env, "set") and callable(getattr(env, "set")):
98
+ for k, v in BUILTINS.items():
99
+ try:
100
+ env.set(k, v)
101
+ except Exception:
102
+ # best-effort injection — non-fatal
103
+ pass
104
+ elif isinstance(env, dict):
105
+ for k, v in BUILTINS.items():
106
+ env.setdefault(k, v)
107
+ except Exception:
108
+ pass
109
+
110
+ semantic_errors = analyzer.analyze(self.ast)
111
+ if semantic_errors:
112
+ self.errors.extend(semantic_errors)
113
+
114
+ if self.errors:
115
+ return None
116
+
117
+ # Phase 4: Bytecode Generation
118
+ generator = BytecodeGenerator()
119
+ self.bytecode = generator.generate(self.ast)
120
+
121
+ return self.bytecode
122
+
123
+ except Exception as e:
124
+ self.errors.append(f"Compilation error: {str(e)}")
125
+ return None
126
+
127
+ # NEW: run compiled bytecode using small VM
128
+ def run_bytecode(self, debug=False):
129
+ """Execute the compiled bytecode ops using the small VM.
130
+ Requires compile() to have been called successfully (self.bytecode set).
131
+ Returns VM execution result or None."""
132
+ if not self.bytecode:
133
+ self.errors.append("No bytecode to run")
134
+ return None
135
+ try:
136
+ # Lazy import VM to avoid cycles
137
+ from ..vm.vm import VM
138
+ except Exception as e:
139
+ self.errors.append(f"VM import error: {e}")
140
+ return None
141
+
142
+ # Provide builtins mapping to VM if analyzer has environment dict or via compiler BUILTINS
143
+ builtins_map = {}
144
+ if self.analyzer and hasattr(self.analyzer, "environment") and isinstance(self.analyzer.environment, dict):
145
+ builtins_map = {k: v for k, v in self.analyzer.environment.items() if k in BUILTINS}
146
+ else:
147
+ # fallback to compiler.BUILTINS (may be dict)
148
+ try:
149
+ builtins_map = BUILTINS if isinstance(BUILTINS, dict) else {}
150
+ except Exception:
151
+ builtins_map = {}
152
+
153
+ # environment mapping passed to VM (start from analyzer.environment if dict)
154
+ vm_env = {}
155
+ if self.analyzer and hasattr(self.analyzer, "environment") and isinstance(self.analyzer.environment, dict):
156
+ vm_env.update(self.analyzer.environment)
157
+
158
+ vm = VM(builtins=builtins_map, env=vm_env)
159
+ return vm.execute(self.bytecode, debug=debug)
160
+
161
+ # Provide Parser alias for external code expecting it (best-effort)
162
+ try:
163
+ from .parser import ProductionParser as _ParserAlias
164
+ Parser = _ParserAlias
165
+ except Exception:
166
+ # keep existing Parser (possibly None) and avoid raising on import
167
+ pass
168
+
169
+ Parser = Parser or None