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
package/README.md ADDED
@@ -0,0 +1,2513 @@
1
+ # Zexus Programming Language
2
+
3
+ <div align="center">
4
+
5
+ ![Zexus Logo](https://img.shields.io/badge/Zexus-v1.6.2-FF6B35?style=for-the-badge)
6
+ [![License](https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge)](LICENSE)
7
+ [![Python](https://img.shields.io/badge/Python-3.8+-3776AB?style=for-the-badge&logo=python)](https://python.org)
8
+ [![GitHub](https://img.shields.io/badge/GitHub-Zaidux/zexus--interpreter-181717?style=for-the-badge&logo=github)](https://github.com/Zaidux/zexus-interpreter)
9
+
10
+ **A modern, security-first programming language with built-in blockchain support, VM-accelerated execution, advanced memory management, and policy-as-code**
11
+
12
+ [What's New](#-whats-new-in-v150) • [Features](#-key-features) • [Installation](#-installation) • [Quick Start](#-quick-start) • [Keywords](#-complete-keyword-reference) • [Documentation](#-documentation) • [Examples](#-examples) • [Troubleshooting](#-getting-help--troubleshooting)
13
+
14
+ </div>
15
+
16
+ ---
17
+
18
+ ## 📋 Table of Contents
19
+
20
+ - [What is Zexus?](#-what-is-zexus)
21
+ - [What's New](#-whats-new-in-v150)
22
+ - [Key Features](#-key-features)
23
+ - [VM-Accelerated Performance](#-vm-accelerated-performance-new)
24
+ - [Security & Policy-as-Code](#-security--policy-as-code--verify-enhanced)
25
+ - [Blockchain Support](#️-native-blockchain-support)
26
+ - [Persistent Memory](#-persistent-memory-management)
27
+ - [Dependency Injection](#-dependency-injection--testing)
28
+ - [Reactive State](#-reactive-state-management)
29
+ - [Advanced Features](#-advanced-features)
30
+ - [Installation](#-installation)
31
+ - [Quick Start](#-quick-start)
32
+ - [Examples](#-examples)
33
+ - [Complete Feature Reference](#-complete-feature-reference)
34
+ - [Complete Keyword Reference](#-complete-keyword-reference)
35
+ - [Built-in Functions](#built-in-functions-100)
36
+ - [CLI Commands](#-cli-commands)
37
+ - [Architecture](#️-architecture)
38
+ - [Documentation](#-documentation)
39
+ - [Contributing](#-contributing)
40
+ - [Testing](#-testing)
41
+ - [Getting Help & Troubleshooting](#-getting-help--troubleshooting)
42
+ - [License](#-license)
43
+ - [Roadmap](#️-roadmap)
44
+ - [Project Stats](#-project-stats)
45
+
46
+
47
+
48
+ ---
49
+
50
+ ## 🎯 What is Zexus?
51
+
52
+ Zexus is a next-generation, general-purpose programming language designed for security-conscious developers who need:
53
+
54
+ - **🎨 World-Class Error Messages** - Beginner-friendly errors with helpful suggestions (NEW in v1.5!)
55
+ - **🔐 Policy-as-code** - Declarative security rules and access control
56
+ - **⚡ VM-Accelerated Execution** - Hybrid interpreter/compiler with bytecode VM
57
+ - **📦 Advanced Type System** - Generic types, pattern matching, and dataclasses (NEW in v1.5!)
58
+ - **⛓️ Built-in Blockchain** - Native smart contracts and DApp primitives
59
+ - **💾 Persistent Memory** - Cross-session data with automatic leak detection
60
+ - **🔌 Dependency Injection** - Powerful DI system with mocking for testing
61
+ - **👀 Reactive State** - WATCH for automatic state change reactions
62
+ - **🎭 Flexible Syntax** - Support for both universal (`{}`) and tolerant (`:`) styles
63
+ - **📦 Package Manager** - ZPM for dependency management
64
+ - **🚀 Main Entry Point** - Python-style `if __name__ == "__main__"` pattern support
65
+ - **🎨 UI Rendering** - Built-in screen, component, and theme system
66
+ - **🔒 Enterprise Features** - Middleware, authentication, throttling, and caching
67
+
68
+ ---
69
+
70
+ ## 🎉 What's New in v1.6.2
71
+
72
+ ### Latest Features (v1.6.2)
73
+
74
+ ✅ **Complete Database Ecosystem** - Production-ready database drivers
75
+ ✅ **4 Database Drivers** - SQLite, PostgreSQL, MySQL, MongoDB fully tested
76
+ ✅ **HTTP Server** - Build web servers with routing (GET, POST, PUT, DELETE)
77
+ ✅ **Socket/TCP Primitives** - Low-level network programming
78
+ ✅ **Testing Framework** - Write and run tests with assertions
79
+ ✅ **ZPM Package Manager** - Fully functional package management system
80
+ ✅ **Comprehensive Documentation** - 900+ lines of ecosystem guides
81
+
82
+ ### Previous Features (v1.5.0)
83
+
84
+ ✅ **World-Class Error Reporting** - Production-grade error messages rivaling Rust
85
+ ✅ **Advanced DATA System** - Generic types, pattern matching, operator overloading
86
+ ✅ **Stack Trace Formatter** - Beautiful, readable stack traces with source context
87
+ ✅ **Smart Error Suggestions** - Actionable hints for fixing common errors
88
+ ✅ **Pattern Matching** - Complete pattern matching with exhaustiveness checking
89
+ ✅ **CONTINUE Keyword** - Error recovery mode for graceful degradation and batch processing
90
+
91
+ ### Recent Enhancements (v0.1.3)
92
+
93
+ ✅ **130+ Keywords Fully Operational** - All core language features tested and verified
94
+ ✅ **Dual-Mode DEBUG** - Function mode (`debug(x)`) and statement mode (`debug x;`)
95
+ ✅ **Conditional Print** - `print(condition, message)` for dynamic output control
96
+ ✅ **Multiple Syntax Styles** - `let x = 5`, `let x : 5`, `let x : int = 5` all supported
97
+ ✅ **Enterprise Keywords** - MIDDLEWARE, AUTH, THROTTLE, CACHE, INJECT fully functional
98
+ ✅ **Async/Await Runtime** - Complete Promise-based async system with context propagation
99
+ ✅ **Main Entry Point** - 15+ builtins for program lifecycle management
100
+ ✅ **UI Renderer** - SCREEN, COMPONENT, THEME keywords with 120+ tests
101
+ ✅ **Enhanced VERIFY** - Email, URL, phone validation, pattern matching, database checks
102
+ ✅ **Blockchain Keywords** - implements, pure, view, payable, modifier, this, emit
103
+ ✅ **Loop Control** - BREAK keyword for early loop exit
104
+ ✅ **Error Handling** - THROW keyword for explicit error raising, THIS for instance reference
105
+ ✅ **100+ Built-in Functions** - Comprehensive standard library
106
+ ✅ **LOG Keyword Enhancements** - `read_file()` and `eval_file()` for dynamic code generation
107
+ ✅ **REQUIRE Tolerance Blocks** - Conditional bypasses for VIP/admin/emergency scenarios
108
+ ✅ **Function-Level Scoping** - LET/CONST documented with scope behavior and shadowing rules
109
+ ✅ **Advanced Error Patterns** - Retry, circuit breaker, error aggregation patterns
110
+
111
+ ### Bug Fixes & Improvements
112
+
113
+ ✅ Fixed array literal parsing (no more duplicate elements)
114
+ ✅ Fixed ENUM value accessibility
115
+ ✅ Fixed WHILE condition parsing without parentheses
116
+ ✅ Fixed loop execution and variable reassignment
117
+ ✅ Fixed DEFER cleanup execution
118
+ ✅ Fixed SANDBOX return values
119
+ ✅ Fixed dependency injection container creation
120
+ ✅ Added tolerance blocks for REQUIRE
121
+ ✅ Improved error messages and debugging output
122
+
123
+ ---
124
+
125
+ ## ✨ Key Features
126
+
127
+ ### 🎨 **NEW!** World-Class Error Reporting (v1.5.0)
128
+
129
+ Zexus now features **production-grade error messages** that rival Rust and surpass Python:
130
+
131
+ ```
132
+ ERROR: SyntaxError[SYNTAX]
133
+ → myfile.zx:10:16
134
+
135
+ 10 | let message = "Hello world
136
+ ^
137
+
138
+ Unterminated string literal
139
+
140
+ 💡 Suggestion: Add a closing quote " to terminate the string.
141
+ ```
142
+
143
+ **Error Reporting Features:**
144
+ - ✅ **Color-coded output** - Errors in red, warnings in yellow, info in blue
145
+ - ✅ **Source code context** - See exactly where the error occurred
146
+ - ✅ **Helpful suggestions** - Actionable hints for fixing errors
147
+ - ✅ **Beginner-friendly** - Clear messages, no cryptic codes
148
+ - ✅ **Category distinction** - Know if it's your code or an interpreter bug
149
+ - ✅ **Smart detection** - Single `&` suggests `&&`, unclosed strings, etc.
150
+
151
+ **Better than Python**: No confusing indentation errors!
152
+ **On par with Rust**: Same quality formatting and helpful suggestions!
153
+ **Better than TypeScript**: More informative with built-in fix suggestions!
154
+
155
+ [Learn more about error reporting →](docs/ERROR_REPORTING.md)
156
+
157
+ ### 📦 **NEW!** Advanced DATA Features (v1.5.0)
158
+
159
+ Complete dataclass system with **8/8 features** including generics and pattern matching:
160
+
161
+ #### Generic Types
162
+ ```zexus
163
+ data Box<T> {
164
+ value: T
165
+
166
+ unwrap() { this.value }
167
+ }
168
+
169
+ data Pair<K, V> {
170
+ key: K
171
+ value: V
172
+
173
+ operator + (other) {
174
+ Pair(this.key, this.value + other.value)
175
+ }
176
+ }
177
+
178
+ let numberBox = Box<number>(42)
179
+ let stringBox = Box<string>("hello")
180
+ let pair = Pair<string, number>("age", 30)
181
+ ```
182
+
183
+ #### Pattern Matching
184
+ ```zexus
185
+ data Shape {
186
+ // Base shape
187
+ }
188
+
189
+ data Circle extends Shape {
190
+ radius: number
191
+ }
192
+
193
+ data Rectangle extends Shape {
194
+ width: number
195
+ height: number
196
+ }
197
+
198
+ action calculateArea(shape) {
199
+ match shape {
200
+ Circle(r) => 3.14 * r * r,
201
+ Rectangle(w, h) => w * h,
202
+ _ => 0
203
+ }
204
+ }
205
+ ```
206
+
207
+ **DATA Features:**
208
+ - ✅ Generic type parameters (`<T>`, `<K, V>`)
209
+ - ✅ Pattern matching with destructuring
210
+ - ✅ Operator overloading
211
+ - ✅ Inheritance and extends
212
+ - ✅ Instance methods
213
+ - ✅ Static methods
214
+ - ✅ Property validation
215
+ - ✅ Immutability options
216
+
217
+ [Learn more about DATA keyword →](docs/keywords/DATA.md)
218
+
219
+
220
+
221
+ let circle = Circle(5)
222
+ let area = calculateArea(circle) // 78.5
223
+ ```
224
+
225
+ **Complete Feature Set:**
226
+ 1. ✅ Static `default()` method
227
+ 2. ✅ Computed properties with `get`
228
+ 3. ✅ Method definitions
229
+ 4. ✅ Operator overloading
230
+ 5. ✅ Inheritance with `extends`
231
+ 6. ✅ Decorators
232
+ 7. ✅ **Generic types** (NEW!)
233
+ 8. ✅ **Pattern matching** (NEW!)
234
+
235
+ [Learn more about DATA features →](docs/keywords/DATA.md)
236
+
237
+ ### ⚡ VM-Accelerated Performance
238
+
239
+ Zexus now includes a sophisticated Virtual Machine for optimized execution:
240
+
241
+ ```zexus
242
+ # Automatically optimized via VM
243
+ let sum = 0
244
+ let i = 0
245
+ while (i < 1000) {
246
+ sum = sum + i
247
+ i = i + 1
248
+ }
249
+ # ↑ This loop executes 2-10x faster via bytecode!
250
+ ```
251
+
252
+ **VM Features:**
253
+ - ✅ Stack-based bytecode execution
254
+ - ✅ Automatic optimization for loops and math-heavy code
255
+ - ✅ Async/await support (SPAWN, AWAIT opcodes)
256
+ - ✅ Function call optimization
257
+ - ✅ Collection operations (lists, maps)
258
+ - ✅ Event system
259
+ - ✅ Module imports
260
+ - ✅ Smart fallback to interpreter for unsupported features
261
+
262
+ [Learn more about VM integration →](VM_INTEGRATION_SUMMARY.md)
263
+
264
+ ### 🔐 Security & Policy-as-Code (✨ VERIFY Enhanced!)
265
+ ```zexus
266
+ # Define security policies declaratively
267
+ protect(transfer_funds, {
268
+ rate_limit: 100,
269
+ auth_required: true,
270
+ require_https: true,
271
+ allowed_ips: ["10.0.0.0/8"]
272
+ }, "strict")
273
+
274
+ # Enhanced runtime verification with custom logic
275
+ verify is_email(email) {
276
+ log_error("Invalid email attempt");
277
+ block_submission();
278
+ }
279
+
280
+ # Access control with blocking
281
+ verify userRole == "admin" {
282
+ log_unauthorized_access(user);
283
+ block_request();
284
+ }
285
+
286
+ # Database and environment verification
287
+ verify:db userId exists_in "users", "User not found"
288
+ verify:env "API_KEY" is_set, "API_KEY not configured"
289
+
290
+ # Data constraints
291
+ restrict(amount, {
292
+ range: [0, 10000],
293
+ type: "integer"
294
+ })
295
+ ```
296
+ **NEW**: VERIFY now includes email/URL/phone validation, pattern matching, database checks, environment variables, input sanitization, and custom logic blocks! [See VERIFY Guide →](docs/VERIFY_ENHANCEMENT_GUIDE.md)
297
+
298
+ ### ⛓️ Native Blockchain Support
299
+ ```zexus
300
+ # Smart contracts made easy
301
+ contract Token {
302
+ persistent storage balances: Map<Address, integer>
303
+
304
+ action transfer(from: Address, to: Address, amount: integer) {
305
+ require(balances[from] >= amount, "Insufficient balance")
306
+ balances[from] = balances[from] - amount
307
+ balances[to] = balances.get(to, 0) + amount
308
+ emit Transfer(from, to, amount)
309
+ }
310
+ }
311
+ ```
312
+
313
+ ### 💾 Persistent Memory Management
314
+ ```zexus
315
+ # Store data across program runs
316
+ persist_set("user_preferences", preferences)
317
+ let prefs = persist_get("user_preferences")
318
+
319
+ # Automatic memory tracking
320
+ track_memory() # Detects leaks automatically
321
+ ```
322
+
323
+ ### 🔌 Dependency Injection & Testing
324
+ ```zexus
325
+ # Register dependencies
326
+ register_dependency("database", ProductionDB())
327
+
328
+ # Inject at runtime
329
+ inject database
330
+
331
+ # Mock for testing
332
+ test_mode(true)
333
+ mock_dependency("database", MockDB())
334
+ ```
335
+
336
+ ### 👀 Reactive State Management
337
+ ```zexus
338
+ # Watch variables for changes
339
+ let count = 0
340
+ watch count {
341
+ print("Count changed to: " + string(count))
342
+ }
343
+
344
+ count = 5 # Automatically triggers watch callback
345
+ ```
346
+
347
+ ### 🚀 Advanced Features
348
+
349
+ - **Multi-strategy parsing**: Tolerates syntax variations
350
+ - **Hybrid execution**: Auto-selects interpreter or compiler/VM
351
+ - **Type safety**: Strong typing with inference
352
+ - **Pattern matching**: Powerful match expressions
353
+ - **Async/await**: Built-in concurrency primitives
354
+ - **Module system**: Import/export with access control
355
+ - **Rich built-ins**: 100+ built-in functions
356
+ - **Plugin system**: Extensible architecture
357
+ - **Advanced types**: Entities, Contracts, Enums, Protocols
358
+ - **Syntax flexibility**: Multiple syntax styles (`:` and `=` for assignments)
359
+ - **130+ keywords**: Comprehensive language features
360
+ - **Main entry point**: Run/execute patterns like Python's `if __name__ == "__main__"`
361
+
362
+ ---
363
+
364
+ ## 🔍 Why Choose Zexus?
365
+
366
+ ### Language Comparison
367
+
368
+ | Feature | Zexus | Python | Solidity | Rust | TypeScript |
369
+ |---------|-------|--------|----------|------|------------|
370
+ | **Blockchain Native** | ✅ Built-in | ❌ Libraries | ✅ Native | ❌ Libraries | ❌ Libraries |
371
+ | **Policy-as-Code** | ✅ Native | ⚠️ Manual | ⚠️ Modifiers | ❌ None | ❌ None |
372
+ | **VM Execution** | ✅ Hybrid | ✅ Bytecode | ✅ EVM | ✅ Native | ⚠️ V8/Node |
373
+ | **Type Safety** | ✅ Strong+Inference | ⚠️ Optional | ✅ Strong | ✅ Strong | ✅ Strong |
374
+ | **Async/Await** | ✅ Native | ✅ Native | ❌ None | ✅ Native | ✅ Native |
375
+ | **Dependency Injection** | ✅ Built-in | ⚠️ Libraries | ❌ None | ⚠️ Manual | ⚠️ Libraries |
376
+ | **Reactive State** | ✅ WATCH | ⚠️ Libraries | ❌ None | ⚠️ Libraries | ⚠️ Libraries |
377
+ | **Memory Tracking** | ✅ Automatic | ⚠️ Manual | ⚠️ Gas-based | ✅ Ownership | ⚠️ Manual |
378
+ | **Security Features** | ✅✅✅ Extensive | ⚠️ Libraries | ⚠️ Limited | ✅ Safe | ⚠️ Libraries |
379
+ | **Syntax Flexibility** | ✅ Multiple styles | ✅ PEP-8 | ✅ Solidity | ✅ Strict | ✅ Strict |
380
+ | **Learning Curve** | 🟢 Easy | 🟢 Easy | 🟡 Medium | 🔴 Hard | 🟡 Medium |
381
+
382
+ ### Use Zexus When You Need
383
+
384
+ ✅ **Smart contracts without EVM complexity** - Cleaner syntax than Solidity
385
+ ✅ **Security-first development** - Built-in policy enforcement
386
+ ✅ **Rapid prototyping with production-ready features** - Faster than Rust
387
+ ✅ **Cross-platform blockchain apps** - No separate contracts needed
388
+ ✅ **Enterprise features out-of-the-box** - DI, middleware, auth, caching
389
+ ✅ **Reactive applications** - Built-in WATCH for state management
390
+ ✅ **Memory-safe applications** - Automatic leak detection
391
+
392
+ ### Zexus = Python's Ease + Solidity's Blockchain + Rust's Safety
393
+
394
+ ```zexus
395
+ # Python-like simplicity
396
+ let users = []
397
+ for each user in get_users() {
398
+ print(user.name)
399
+ }
400
+
401
+ # Solidity-like contracts
402
+ contract Token {
403
+ persistent storage balances: Map<Address, integer>
404
+ action payable transfer(to, amount) { ... }
405
+ }
406
+
407
+ # Rust-like safety
408
+ verify balance >= amount {
409
+ log_error("Insufficient balance")
410
+ revert("Not enough funds")
411
+ }
412
+ ```
413
+
414
+ ---
415
+
416
+ ## 📦 Installation
417
+
418
+ ### Quick Install (Recommended)
419
+
420
+ ```bash
421
+ pip install zexus
422
+ ```
423
+
424
+ **Includes:**
425
+ - `zx` - Main Zexus CLI
426
+ - `zpm` - Zexus Package Manager
427
+
428
+ ### From Source
429
+
430
+ ```bash
431
+ git clone https://github.com/Zaidux/zexus-interpreter.git
432
+ cd zexus-interpreter
433
+ pip install -e .
434
+ ```
435
+
436
+ ### Verify Installation
437
+
438
+ ```bash
439
+ zx --version # Should show: Zexus v1.6.2
440
+ zpm --version # Should show: ZPM v1.6.2
441
+ ```
442
+
443
+ ---
444
+
445
+ ## 🚀 Quick Start
446
+
447
+ ### 1. Hello World
448
+
449
+ ```zexus
450
+ # hello.zx
451
+ let name = "World"
452
+ print("Hello, " + name + "!")
453
+ ```
454
+
455
+ Run it:
456
+ ```bash
457
+ zx run hello.zx
458
+ ```
459
+
460
+ ### 2. Interactive REPL
461
+
462
+ ```bash
463
+ zx repl
464
+ ```
465
+
466
+ ```zexus
467
+ >> let x = 10 + 5
468
+ >> print(x * 2)
469
+ 30
470
+ ```
471
+
472
+ ### 3. Create a Project
473
+
474
+ ```bash
475
+ zx init my-app
476
+ cd my-app
477
+ zx run main.zx
478
+ ```
479
+
480
+ ---
481
+
482
+ ## 💡 Examples
483
+
484
+ ### Example 1: Secure API with Policy-as-Code
485
+
486
+ ```zexus
487
+ entity ApiRequest {
488
+ endpoint: string,
489
+ method: string,
490
+ user_id: integer
491
+ }
492
+
493
+ action handle_request(request: ApiRequest) -> string {
494
+ # Verify authentication
495
+ verify(request.user_id > 0)
496
+
497
+ # Restrict input
498
+ restrict(request.method, {
499
+ allowed: ["GET", "POST", "PUT", "DELETE"]
500
+ })
501
+
502
+ return "Request handled successfully"
503
+ }
504
+
505
+ # Protect the endpoint
506
+ protect(handle_request, {
507
+ rate_limit: 100,
508
+ auth_required: true,
509
+ require_https: true
510
+ }, "strict")
511
+ ```
512
+
513
+ ### Example 2: Blockchain Token
514
+
515
+ ```zexus
516
+ contract ERC20Token {
517
+ persistent storage total_supply: integer
518
+ persistent storage balances: Map<Address, integer>
519
+
520
+ action constructor(initial_supply: integer) {
521
+ total_supply = initial_supply
522
+ balances[msg.sender] = initial_supply
523
+ }
524
+
525
+ action transfer(to: Address, amount: integer) -> boolean {
526
+ require(balances[msg.sender] >= amount, "Insufficient balance")
527
+ balances[msg.sender] = balances[msg.sender] - amount
528
+ balances[to] = balances.get(to, 0) + amount
529
+ emit Transfer(msg.sender, to, amount)
530
+ return true
531
+ }
532
+
533
+ action balance_of(account: Address) -> integer {
534
+ return balances.get(account, 0)
535
+ }
536
+ }
537
+ ```
538
+
539
+ ### Example 3: Reactive State Management
540
+
541
+ ```zexus
542
+ # E-commerce cart with reactive updates
543
+ let cart_items = []
544
+ let cart_total = 0
545
+
546
+ watch cart_items {
547
+ # Recalculate total when cart changes
548
+ cart_total = cart_items.reduce(
549
+ initial: 0,
550
+ transform: total + item.price
551
+ )
552
+ print("Cart updated! New total: $" + string(cart_total))
553
+ }
554
+
555
+ # Add items (automatically triggers watch)
556
+ cart_items.push({name: "Laptop", price: 999})
557
+ cart_items.push({name: "Mouse", price: 29})
558
+ ```
559
+
560
+ ### Example 4: VM-Optimized Computation
561
+
562
+ ```zexus
563
+ # Fibonacci with automatic VM optimization
564
+ action fibonacci(n: integer) -> integer {
565
+ if n <= 1 {
566
+ return n
567
+ }
568
+
569
+ let a = 0
570
+ let b = 1
571
+ let i = 2
572
+
573
+ while (i <= n) {
574
+ let temp = a + b
575
+ a = b
576
+ b = temp
577
+ i = i + 1
578
+ }
579
+
580
+ return b
581
+ }
582
+
583
+ # VM automatically compiles this for faster execution
584
+ let result = fibonacci(100)
585
+ print(result)
586
+ ```
587
+
588
+ ### Example 5: Main Entry Point Pattern
589
+
590
+ ```zexus
591
+ # Similar to Python's if __name__ == "__main__"
592
+ action main() {
593
+ print("Running main program")
594
+ let result = process_data()
595
+ print("Result: " + string(result))
596
+ }
597
+
598
+ # Only runs if this is the main module
599
+ if is_main() {
600
+ run(main)
601
+ }
602
+ ```
603
+
604
+ ### Example 6: Middleware & Enterprise Features
605
+
606
+ ```zexus
607
+ # Define authentication middleware
608
+ middleware("auth", action(req, res) {
609
+ if !req.has_token {
610
+ return {status: 401, message: "Unauthorized"}
611
+ }
612
+ return true
613
+ })
614
+
615
+ # Configure authentication
616
+ auth {
617
+ provider: "oauth2",
618
+ scopes: ["read", "write"],
619
+ token_expiry: 3600
620
+ }
621
+
622
+ # Apply rate limiting
623
+ throttle(api_endpoint, {
624
+ requests_per_minute: 100,
625
+ burst: 20
626
+ })
627
+
628
+ # Enable caching
629
+ cache(expensive_query, {
630
+ ttl: 300,
631
+ strategy: "lru"
632
+ })
633
+ ```
634
+
635
+ ### Example 7: Concurrency with Channels
636
+
637
+ ```zexus
638
+ # Create typed channel
639
+ channel<integer> numbers
640
+
641
+ # Producer
642
+ action producer() {
643
+ for each i in range(0, 10) {
644
+ send(numbers, i)
645
+ sleep(0.1)
646
+ }
647
+ close_channel(numbers)
648
+ }
649
+
650
+ # Consumer
651
+ action consumer() {
652
+ while true {
653
+ let value = receive(numbers)
654
+ if value == null {
655
+ break
656
+ }
657
+ print("Received: " + string(value))
658
+ }
659
+ }
660
+
661
+ # Run concurrently
662
+ async producer()
663
+ async consumer()
664
+ ```
665
+
666
+ ### Example 8: Output Redirection & Code Generation with LOG
667
+
668
+ ```zexus
669
+ # Redirect output to file for logging
670
+ action processData(items) {
671
+ log > "processing.log"
672
+ print("Processing started at: " + timestamp())
673
+
674
+ for each item in items {
675
+ print("Processing item: " + item)
676
+ }
677
+
678
+ print("Processing complete")
679
+ # Output automatically restored when action exits
680
+ }
681
+
682
+ # Generate Python code dynamically
683
+ action generatePythonModule() {
684
+ log >> "calculator.py"
685
+ print("def add(a, b):")
686
+ print(" return a + b")
687
+ print("")
688
+ print("def multiply(a, b):")
689
+ print(" return a * b")
690
+ print("")
691
+ print("# Generated by Zexus")
692
+ }
693
+
694
+ # Generate and execute code
695
+ generatePythonModule()
696
+ eval_file("calculator.py", "python")
697
+
698
+ # Multiple outputs to different files
699
+ action generateReports() {
700
+ log >> "summary.txt"
701
+ print("Summary Report")
702
+ print("==============")
703
+
704
+ log >> "details.txt"
705
+ print("Detailed Report")
706
+ print("===============")
707
+ }
708
+ ```
709
+
710
+ ### Example 9: Advanced Error Handling with Tolerance Blocks
711
+
712
+ ```zexus
713
+ # REQUIRE with tolerance blocks - VIP bypass
714
+ action processPremiumAccess(user, balance, isVIP) {
715
+ # Standard users need 1.0 ETH, VIP bypass
716
+ require balance >= 1.0 {
717
+ if (isVIP) return true;
718
+ }
719
+
720
+ print("Premium access granted to: " + user)
721
+ return true
722
+ }
723
+
724
+ # Advanced error patterns - Circuit breaker
725
+ let failureCount = 0
726
+ let circuitOpen = false
727
+
728
+ action protectedOperation(data) {
729
+ try {
730
+ if (circuitOpen) {
731
+ revert("Circuit breaker activated - too many failures")
732
+ }
733
+
734
+ # Process operation
735
+ let result = processData(data)
736
+ failureCount = 0 # Reset on success
737
+ return result
738
+ } catch (error) {
739
+ failureCount = failureCount + 1
740
+ if (failureCount >= 3) {
741
+ circuitOpen = true
742
+ }
743
+ return null
744
+ }
745
+ }
746
+
747
+ # Retry pattern with error aggregation
748
+ action retryableOperation(maxAttempts) {
749
+ let attempts = 0
750
+ let errors = []
751
+
752
+ while (attempts < maxAttempts) {
753
+ try {
754
+ return performOperation()
755
+ } catch (e) {
756
+ attempts = attempts + 1
757
+ errors = errors + [e]
758
+ if (attempts < maxAttempts) {
759
+ sleep(1) # Wait before retry
760
+ }
761
+ }
762
+ }
763
+
764
+ print("Failed after " + attempts + " attempts")
765
+ return null
766
+ }
767
+ ```
768
+
769
+ ### Example 10: Error Recovery with CONTINUE Keyword
770
+
771
+ ```zexus
772
+ # Enable error recovery mode - continue execution despite errors
773
+ print "=== Batch Processing with Error Recovery ==="
774
+ continue;
775
+
776
+ # Process multiple records, logging errors but not stopping
777
+ action processRecord(id, data) {
778
+ if (data < 0) {
779
+ revert("Invalid data for record " + id);
780
+ return null; # This executes with CONTINUE
781
+ }
782
+ return "Processed: " + data;
783
+ }
784
+
785
+ let records = [
786
+ {id: 1, data: 100},
787
+ {id: 2, data: -50}, # Error - but continues
788
+ {id: 3, data: 200},
789
+ {id: 4, data: -30}, # Error - but continues
790
+ {id: 5, data: 300}
791
+ ];
792
+
793
+ let successCount = 0;
794
+ for each record in records {
795
+ let result = processRecord(record.id, record.data);
796
+ if (result != null) {
797
+ successCount = successCount + 1;
798
+ }
799
+ }
800
+
801
+ print "Processed " + successCount + " out of " + length(records) + " records";
802
+ print "Program completed despite errors!";
803
+
804
+ # Use case: Testing framework
805
+ action runTests() {
806
+ continue; # Run all tests even if some fail
807
+
808
+ test_addition(); # Pass
809
+ test_subtraction(); # Fail - but continue
810
+ test_multiplication(); # Pass
811
+ test_division(); # Fail - but continue
812
+
813
+ print "All tests executed!";
814
+ }
815
+ ```
816
+
817
+ ---
818
+
819
+ ## 📚 Complete Feature Reference
820
+
821
+ ### Core Language Features
822
+
823
+ #### Variables & Constants
824
+ ```zexus
825
+ # Multiple syntax options supported
826
+ let mutable_var = 42 # Standard assignment
827
+ let mutable_var : 42 # Colon syntax (tolerant style)
828
+ let typed_var : int = 42 # With type annotation
829
+ const IMMUTABLE = 3.14159 # Immutable constant
830
+ ```
831
+
832
+ **Variable Scoping**: Zexus uses function-level scoping (not block-level). Variables can only be shadowed within function boundaries.
833
+
834
+ #### Data Types
835
+ - **Primitives**: Integer, Float, String, Boolean, Null
836
+ - **Collections**: List, Map, Set
837
+ - **Advanced**: Entity, Contract, Action, Lambda
838
+ - **Special**: DateTime, File, Math
839
+
840
+ #### Functions
841
+ ```zexus
842
+ action greet(name: string) -> string {
843
+ return "Hello, " + name
844
+ }
845
+
846
+ # Lambda functions
847
+ let double = lambda(x) { x * 2 }
848
+
849
+ # Deferred cleanup (executes on scope exit)
850
+ defer {
851
+ cleanup_resources()
852
+ }
853
+ ```
854
+
855
+ #### Debugging
856
+ ```zexus
857
+ # DUAL-MODE DEBUG:
858
+ # Function mode - returns value, usable in expressions
859
+ let x = debug(42) # Outputs: [DEBUG] 42, x = 42
860
+
861
+ # Statement mode - logs with metadata
862
+ debug myVariable; # Outputs: 🔍 DEBUG: <value> with context
863
+
864
+ # CONDITIONAL PRINT (NEW!):
865
+ # Only prints if condition is true
866
+ let debugMode = true
867
+ print(debugMode, "Debug mode active") # Prints: "Debug mode active"
868
+
869
+ let verbose = false
870
+ print(verbose, "Verbose output") # Does NOT print
871
+
872
+ # Multi-argument print
873
+ print("Value:", x, "Result:", y) # Outputs all separated by spaces
874
+
875
+ # Other debug tools
876
+ debug_log("message", context)
877
+ debug_trace() # Stack trace
878
+ ```
879
+
880
+ #### Control Flow
881
+ ```zexus
882
+ # Conditionals
883
+ if condition {
884
+ # code
885
+ } elif other_condition {
886
+ # code
887
+ } else {
888
+ # code
889
+ }
890
+
891
+ # Loops
892
+ while condition {
893
+ # code
894
+ }
895
+
896
+ for each item in collection {
897
+ # code
898
+ }
899
+
900
+ # Loop Control - BREAK
901
+ while true {
902
+ if shouldExit {
903
+ break # Exit loop immediately
904
+ }
905
+ # process data
906
+ }
907
+
908
+ # Pattern Matching
909
+ match value {
910
+ case 1: print("One")
911
+ case 2: print("Two")
912
+ default: print("Other")
913
+ }
914
+ ```
915
+
916
+ #### Error Handling - THROW
917
+ ```zexus
918
+ # Throw errors explicitly
919
+ action validateAge(age) {
920
+ if age < 0 {
921
+ throw "Age cannot be negative"
922
+ }
923
+ if age > 150 {
924
+ throw "Age is unrealistic"
925
+ }
926
+ return age
927
+ }
928
+
929
+ # Combine with try-catch
930
+ try {
931
+ let userAge = validateAge(-5)
932
+ print("Valid age: " + string(userAge))
933
+ } catch (error) {
934
+ print("Error: " + error)
935
+ }
936
+ ```
937
+
938
+ #### Contract Self-Reference - THIS
939
+ ```zexus
940
+ # Access current instance in contracts
941
+ contract Token {
942
+ state balances: Map<Address, integer>
943
+
944
+ action transfer(to, amount) {
945
+ # Use 'this' to access instance state
946
+ let senderBalance = this.balances[TX.caller]
947
+ require senderBalance >= amount, "Insufficient balance"
948
+
949
+ this.balances[TX.caller] = senderBalance - amount
950
+ this.balances[to] = this.balances.get(to, 0) + amount
951
+ }
952
+ }
953
+
954
+ # Use in data classes
955
+ data Rectangle {
956
+ width: number
957
+ height: number
958
+
959
+ area() {
960
+ return this.width * this.height
961
+ }
962
+ }
963
+ ```
964
+
965
+ #### Entities & Contracts
966
+ ```zexus
967
+ entity User {
968
+ name: string,
969
+ age: integer,
970
+ email: string
971
+ }
972
+
973
+ contract MyContract {
974
+ persistent storage state: integer
975
+
976
+ action update(new_value: integer) {
977
+ state = new_value
978
+ }
979
+ }
980
+ ```
981
+
982
+ ### Advanced Features
983
+
984
+ #### 🔐 Security Features
985
+
986
+ **PROTECT** - Policy-as-code security:
987
+ ```zexus
988
+ protect(function_name, {
989
+ rate_limit: 100, # Max calls per minute
990
+ auth_required: true, # Require authentication
991
+ require_https: true, # HTTPS only
992
+ allowed_ips: ["10.0.0.0/8"], # IP allowlist
993
+ blocked_ips: ["192.168.1.100"], # IP blocklist
994
+ log_access: true # Audit logging
995
+ }, "strict") # Enforcement mode: strict, warn, log
996
+ ```
997
+
998
+ **VERIFY** - Runtime assertions:
999
+ ```zexus
1000
+ verify(user.is_admin)
1001
+ verify(amount > 0 and amount < 1000)
1002
+ ```
1003
+
1004
+ **RESTRICT** - Input validation:
1005
+ ```zexus
1006
+ restrict(input_value, {
1007
+ type: "string",
1008
+ min_length: 5,
1009
+ max_length: 100,
1010
+ pattern: "^[a-zA-Z0-9]+$",
1011
+ range: [0, 100], # For numbers
1012
+ allowed: ["GET", "POST"] # Enum values
1013
+ })
1014
+ ```
1015
+
1016
+ **SEAL** - Immutable objects:
1017
+ ```zexus
1018
+ seal(config) # Make config immutable
1019
+ ```
1020
+
1021
+ **SANDBOX** - Isolated execution:
1022
+ ```zexus
1023
+ sandbox {
1024
+ # Code runs in restricted environment
1025
+ # Limited file system, network access
1026
+ }
1027
+ ```
1028
+
1029
+ **TRAIL** - Audit logging:
1030
+ ```zexus
1031
+ trail(operation, "user_action", {
1032
+ user_id: user.id,
1033
+ action: "transfer",
1034
+ amount: 1000
1035
+ })
1036
+ ```
1037
+
1038
+ #### 💾 Persistence & Memory
1039
+
1040
+ **Persistent Storage:**
1041
+ ```zexus
1042
+ persist_set("key", value)
1043
+ let value = persist_get("key")
1044
+ persist_clear("key")
1045
+ let all_keys = persist_list()
1046
+ ```
1047
+
1048
+ **Memory Tracking:**
1049
+ ```zexus
1050
+ track_memory() # Enable tracking
1051
+ let stats = memory_stats() # Get statistics
1052
+ ```
1053
+
1054
+ #### 🔌 Dependency Injection
1055
+
1056
+ **Register Dependencies:**
1057
+ ```zexus
1058
+ register_dependency("logger", FileLogger("/var/log/app.log"))
1059
+ register_dependency("database", PostgresDB("localhost:5432"))
1060
+ ```
1061
+
1062
+ **Inject Dependencies:**
1063
+ ```zexus
1064
+ inject logger
1065
+ inject database
1066
+
1067
+ action save_user(user: Entity) {
1068
+ logger.info("Saving user: " + user.name)
1069
+ database.insert("users", user)
1070
+ }
1071
+ ```
1072
+
1073
+ **Mocking for Tests:**
1074
+ ```zexus
1075
+ test_mode(true)
1076
+ mock_dependency("logger", MockLogger())
1077
+ mock_dependency("database", MockDB())
1078
+
1079
+ # Now all injected dependencies use mocks
1080
+ ```
1081
+
1082
+ #### 👀 Reactive State (WATCH)
1083
+
1084
+ ```zexus
1085
+ let counter = 0
1086
+
1087
+ watch counter {
1088
+ print("Counter changed to: " + string(counter))
1089
+ # Can trigger other logic
1090
+ if counter > 10 {
1091
+ send_alert()
1092
+ }
1093
+ }
1094
+
1095
+ counter = counter + 1 # Triggers watch
1096
+ ```
1097
+
1098
+ #### ⛓️ Blockchain Features
1099
+
1100
+ **Transactions:**
1101
+ ```zexus
1102
+ let tx = transaction({
1103
+ from: sender_address,
1104
+ to: recipient_address,
1105
+ value: 100,
1106
+ data: "0x1234"
1107
+ })
1108
+ ```
1109
+
1110
+ **Events:**
1111
+ ```zexus
1112
+ emit Transfer(from, to, amount)
1113
+ ```
1114
+
1115
+ **Smart Contract Primitives:**
1116
+ ```zexus
1117
+ require(condition, "Error message") # Revert if false
1118
+ assert(condition) # Always check
1119
+ revert("Reason") # Explicit revert
1120
+ let balance = balance_of(address)
1121
+ ```
1122
+
1123
+ **Cryptographic Functions:**
1124
+ ```zexus
1125
+ let hash = keccak256(data)
1126
+ let sig = signature(data, private_key)
1127
+ let valid = verify_sig(data, sig, public_key)
1128
+ ```
1129
+
1130
+ #### 🔄 Concurrency
1131
+
1132
+ **Async/Await:**
1133
+ ```zexus
1134
+ async action fetch_data(url: string) -> string {
1135
+ let response = await http_get(url)
1136
+ return response.body
1137
+ }
1138
+
1139
+ let data = await fetch_data("https://api.example.com/data")
1140
+ ```
1141
+
1142
+ **Channels:**
1143
+ ```zexus
1144
+ channel messages
1145
+
1146
+ # Send
1147
+ messages.send("Hello")
1148
+
1149
+ # Receive
1150
+ let msg = messages.receive()
1151
+ ```
1152
+
1153
+ **Atomic Operations:**
1154
+ ```zexus
1155
+ atomic {
1156
+ # Thread-safe operations
1157
+ counter = counter + 1
1158
+ }
1159
+ ```
1160
+
1161
+ #### 📦 Module System
1162
+
1163
+ ```zexus
1164
+ # Export from module
1165
+ export action public_function() {
1166
+ return "accessible"
1167
+ }
1168
+
1169
+ private action internal_function() {
1170
+ return "not exported"
1171
+ }
1172
+
1173
+ # Import in another file
1174
+ use {public_function} from "mymodule"
1175
+
1176
+ # Import with alias
1177
+ use {public_function as pf} from "mymodule"
1178
+
1179
+ # Import entire module
1180
+ use * from "utilities"
1181
+ ```
1182
+
1183
+ #### 🎨 Pattern Matching
1184
+
1185
+ ```zexus
1186
+ match response_code {
1187
+ case 200: print("Success")
1188
+ case 404: print("Not Found")
1189
+ case 500: print("Server Error")
1190
+ case x where x >= 400 and x < 500: print("Client Error")
1191
+ default: print("Unknown status")
1192
+ }
1193
+
1194
+ # Pattern matching with destructuring
1195
+ match request {
1196
+ case {method: "GET", path: p}: handle_get(p)
1197
+ case {method: "POST", body: b}: handle_post(b)
1198
+ default: handle_other()
1199
+ }
1200
+ ```
1201
+
1202
+ #### 🔧 Advanced Types
1203
+
1204
+ **Enums:**
1205
+ ```zexus
1206
+ enum Status {
1207
+ PENDING,
1208
+ ACTIVE,
1209
+ COMPLETED,
1210
+ CANCELLED
1211
+ }
1212
+
1213
+ let status = Status.ACTIVE
1214
+ ```
1215
+
1216
+ **Protocols (Interfaces):**
1217
+ ```zexus
1218
+ protocol Serializable {
1219
+ action serialize() -> string
1220
+ action deserialize(data: string) -> Entity
1221
+ }
1222
+ ```
1223
+
1224
+ **Type Aliases:**
1225
+ ```zexus
1226
+ type_alias UserId = integer
1227
+ type_alias UserMap = Map<UserId, User>
1228
+ ```
1229
+
1230
+ ### Built-in Functions (100+)
1231
+
1232
+ #### I/O Functions
1233
+ ```zexus
1234
+ print(value) # Print without newline
1235
+ println(value) # Print with newline
1236
+ input(prompt) # Get user input
1237
+ read_text(path) # Read text file
1238
+ write_text(path, content) # Write text file
1239
+ ```
1240
+
1241
+ #### Type Conversion
1242
+ ```zexus
1243
+ string(value) # Convert to string
1244
+ int(value) # Convert to integer
1245
+ float(value) # Convert to float
1246
+ bool(value) # Convert to boolean
1247
+ ```
1248
+
1249
+ #### Collection Operations
1250
+ ```zexus
1251
+ len(collection) # Length/size
1252
+ list(items...) # Create list
1253
+ map(pairs...) # Create map
1254
+ set(items...) # Create set
1255
+ range(start, end, step) # Generate range
1256
+ ```
1257
+
1258
+ #### Functional Programming
1259
+ ```zexus
1260
+ filter(collection, predicate) # Filter elements
1261
+ map(collection, transform) # Transform elements
1262
+ reduce(collection, fn, initial) # Reduce to single value
1263
+ sort(collection, comparator) # Sort elements
1264
+ reverse(collection) # Reverse order
1265
+ ```
1266
+
1267
+ #### String Operations
1268
+ ```zexus
1269
+ join(array, separator) # Join strings
1270
+ split(string, delimiter) # Split string
1271
+ replace(string, old, new) # Replace substring
1272
+ uppercase(string) # Convert to uppercase
1273
+ lowercase(string) # Convert to lowercase
1274
+ trim(string) # Remove whitespace
1275
+ substring(string, start, end) # Extract substring
1276
+ ```
1277
+
1278
+ #### Math Operations
1279
+ ```zexus
1280
+ abs(number) # Absolute value
1281
+ ceil(number) # Ceiling
1282
+ floor(number) # Floor
1283
+ round(number, decimals) # Round
1284
+ min(numbers...) # Minimum
1285
+ max(numbers...) # Maximum
1286
+ sum(numbers) # Sum
1287
+ sqrt(number) # Square root
1288
+ pow(base, exponent) # Power
1289
+ random() # Random number
1290
+ random(max) # Random 0 to max
1291
+ random(min, max) # Random in range
1292
+ ```
1293
+
1294
+ #### Date & Time
1295
+ ```zexus
1296
+ now() # Current datetime
1297
+ timestamp() # Unix timestamp
1298
+ ```
1299
+
1300
+ #### File I/O
1301
+ ```zexus
1302
+ file_read_text(path) # Read text file
1303
+ file_write_text(path, content) # Write text file
1304
+ file_exists(path) # Check if file exists
1305
+ file_read_json(path) # Read JSON file
1306
+ file_write_json(path, data) # Write JSON file
1307
+ file_append(path, content) # Append to file
1308
+ file_list_dir(path) # List directory
1309
+ read_file(path) # Read file contents (alias for file_read_text)
1310
+ eval_file(path, [language]) # Execute code from file (Zexus, Python, JS)
1311
+ ```
1312
+
1313
+ **New in v0.1.3**: `read_file()` and `eval_file()` enable dynamic code generation and multi-language execution:
1314
+ ```zexus
1315
+ # Generate and execute Zexus code
1316
+ log >> "helper.zx"
1317
+ print("action add(a, b) { return a + b; }")
1318
+ eval_file("helper.zx")
1319
+ let result = add(5, 10) # Uses generated function
1320
+
1321
+ # Execute Python code
1322
+ log >> "script.py"
1323
+ print("print('Hello from Python!')")
1324
+ eval_file("script.py", "python")
1325
+ ```
1326
+
1327
+ #### Persistence
1328
+ ```zexus
1329
+ persist_set(key, value) # Store persistent data
1330
+ persist_get(key) # Retrieve persistent data
1331
+ persist_clear(key) # Delete persistent data
1332
+ persist_list() # List all keys
1333
+ ```
1334
+
1335
+ #### Memory Management
1336
+ ```zexus
1337
+ track_memory() # Enable memory tracking
1338
+ memory_stats() # Get memory statistics
1339
+ ```
1340
+
1341
+ #### Security & Policy
1342
+ ```zexus
1343
+ protect(function, policy, mode) # Apply security policy
1344
+ verify(condition) # Runtime verification
1345
+ restrict(value, constraints) # Validate input
1346
+ create_policy(rules) # Create custom policy
1347
+ enforce_policy(policy, value) # Apply policy
1348
+ ```
1349
+
1350
+ #### Dependency Injection
1351
+ ```zexus
1352
+ register_dependency(name, impl) # Register dependency
1353
+ inject_dependency(name) # Inject dependency
1354
+ mock_dependency(name, mock) # Mock for testing
1355
+ test_mode(enabled) # Enable/disable test mode
1356
+ ```
1357
+
1358
+ #### Concurrency & Channels
1359
+ ```zexus
1360
+ channel<type> name # Create typed channel
1361
+ send(channel, value) # Send to channel
1362
+ receive(channel) # Receive from channel
1363
+ close_channel(channel) # Close channel
1364
+ atomic { } # Atomic operation block
1365
+ ```
1366
+ emit(event, ...args) # Emit event
1367
+ require(condition, message) # Assert with revert
1368
+ assert(condition) # Assert
1369
+ balance_of(address) # Get balance
1370
+ transfer(to, amount) # Transfer value
1371
+ hash(data) # Hash data
1372
+ keccak256(data) # Keccak-256 hash
1373
+ signature(data, key) # Sign data
1374
+ verify_sig(data, sig, key) # Verify signature
1375
+ ```
1376
+
1377
+ #### Renderer (UI)
1378
+ ```zexus
1379
+ define_screen(name, props) # Define UI screen
1380
+ define_component(name, props) # Define component
1381
+ render_screen(name) # Render screen
1382
+ set_theme(theme) # Set UI theme
1383
+ create_canvas(width, height) # Create drawing canvas
1384
+ draw_line(canvas, x1, y1, x2, y2) # Draw line
1385
+ draw_text(canvas, text, x, y) # Draw text
1386
+ ```
1387
+
1388
+ #### Debug & Development
1389
+ ```zexus
1390
+ debug(value) # Debug function (returns value)
1391
+ debug value; # Debug statement (logs with metadata)
1392
+ debug_log(message, context) # Debug logging
1393
+ debug_trace() # Stack trace
1394
+ is_main() # Check if module is main entry point
1395
+ exit_program(code) # Exit with status code
1396
+ module_info() # Get module metadata
1397
+ ```
1398
+
1399
+ #### Main Entry Point Features
1400
+ ```zexus
1401
+ run(task_fn) # Execute task function
1402
+ execute(fn) # Execute function immediately
1403
+ is_main() # True if current module is main
1404
+ exit_program(code) # Exit with status code
1405
+ on_start(fn) # Register startup handler
1406
+ on_exit(fn) # Register cleanup handler
1407
+ signal_handler(signal, fn) # Handle OS signals
1408
+ schedule(fn, delay) # Schedule delayed execution
1409
+ sleep(seconds) # Sleep for duration
1410
+ daemonize(fn) # Run as background daemon
1411
+ watch_and_reload(path) # Auto-reload on file changes
1412
+ get_module_name() # Get current module name
1413
+ get_module_path() # Get current module path
1414
+ list_imports() # List imported modules
1415
+ get_exported_names() # List exported names
1416
+ ```
1417
+
1418
+ #### Validation & Verification
1419
+ ```zexus
1420
+ is_email(string) # Validate email format
1421
+ is_url(string) # Validate URL format
1422
+ is_phone(string) # Validate phone format
1423
+ is_numeric(string) # Check if numeric
1424
+ is_alpha(string) # Check if alphabetic
1425
+ is_alphanumeric(string) # Check if alphanumeric
1426
+ matches_pattern(str, pattern) # Regex pattern matching
1427
+ password_strength(password) # Check password strength
1428
+ sanitize_input(text, type) # Sanitize user input
1429
+ validate_length(str, min, max) # Validate string length
1430
+ env_get(name) # Get environment variable
1431
+ env_set(name, value) # Set environment variable
1432
+ env_exists(name) # Check if env var exists
1433
+ ```
1434
+
1435
+ #### Standard Library Modules
1436
+
1437
+ Zexus provides **130+ functions** across **10 standard library modules**:
1438
+
1439
+ ##### File System (fs)
1440
+ ```zexus
1441
+ use {read_file, write_file, exists, mkdir} from "fs"
1442
+
1443
+ write_file("data.txt", "Hello!")
1444
+ let content = read_file("data.txt")
1445
+ if exists("data.txt") {
1446
+ print("File exists!")
1447
+ }
1448
+ ```
1449
+
1450
+ **30+ functions**: `read_file`, `write_file`, `append_file`, `exists`, `mkdir`, `rmdir`, `list_dir`, `walk`, `glob`, `copy_file`, `rename`, `remove`, and more.
1451
+
1452
+ ##### HTTP Client (http)
1453
+ ```zexus
1454
+ use {get, post} from "http"
1455
+
1456
+ let response = get("https://api.example.com/data")
1457
+ print(response.status)
1458
+ print(response.body)
1459
+ ```
1460
+
1461
+ ##### HTTP Server (NEW! v1.0)
1462
+ ```zexus
1463
+ # Create HTTP server with routing
1464
+ let server = http_server(3000)
1465
+
1466
+ server["get"]("/", action(req, res) {
1467
+ res["send"]("Hello World!")
1468
+ })
1469
+
1470
+ server["post"]("/api/users", action(req, res) {
1471
+ res["json"]({"message": "User created"})
1472
+ })
1473
+
1474
+ server["listen"]()
1475
+ ```
1476
+
1477
+ **Functions**: `http_server`, routing methods (get, post, put, delete), response methods (send, json, status)
1478
+
1479
+ ##### Socket/TCP (NEW! v1.0)
1480
+ ```zexus
1481
+ # TCP server
1482
+ let server = socket_listen(8080)
1483
+ let client = server["accept"]()
1484
+ let data = client["recv"](1024)
1485
+ client["send"]("Echo: " + data)
1486
+
1487
+ # TCP client
1488
+ let conn = socket_connect("localhost", 8080)
1489
+ conn["send"]("Hello!")
1490
+ let response = conn["recv"](1024)
1491
+ ```
1492
+
1493
+ **Functions**: `socket_listen`, `socket_connect`, send/receive operations
1494
+
1495
+ ##### Databases (NEW! v1.0)
1496
+ ```zexus
1497
+ # SQLite (built-in, no deps)
1498
+ let db = sqlite_connect("app.db")
1499
+ db["execute"]("CREATE TABLE users (...)")
1500
+ let users = db["query"]("SELECT * FROM users")
1501
+
1502
+ # PostgreSQL (requires psycopg2-binary)
1503
+ let db = postgres_connect("mydb", "user", "pass")
1504
+
1505
+ # MySQL (requires mysql-connector-python)
1506
+ let db = mysql_connect("mydb", "root", "pass")
1507
+
1508
+ # MongoDB (requires pymongo)
1509
+ let db = mongo_connect("myapp")
1510
+ db["insert_one"]("users", {"name": "Alice"})
1511
+ let docs = db["find"]("users", {"age": 30})
1512
+ ```
1513
+
1514
+ **Functions**: Database connection functions, execute/query/update/delete operations for SQL databases, MongoDB NoSQL operations
1515
+
1516
+ ##### Testing Framework (NEW! v1.0)
1517
+ ```zexus
1518
+ # Load test framework
1519
+ eval_file("src/zexus/stdlib/test.zx")
1520
+
1521
+ # Write assertions
1522
+ assert_eq(1 + 1, 2, "Addition works")
1523
+ assert_true(x > 0, "Positive number")
1524
+ assert_type(value, "Integer", "Type check")
1525
+
1526
+ # Get results
1527
+ print_test_results()
1528
+ ```
1529
+
1530
+ **Functions**: `assert_eq`, `assert_true`, `assert_false`, `assert_null`, `assert_type`, `print_test_results`
1531
+
1532
+ **5 functions**: `get`, `post`, `put`, `delete`, `request`
1533
+
1534
+ ##### JSON (json)
1535
+ ```zexus
1536
+ use {parse, stringify} from "json"
1537
+
1538
+ let data = {name: "Alice", age: 30}
1539
+ let json_str = stringify(data)
1540
+ let parsed = parse(json_str)
1541
+ ```
1542
+
1543
+ **7 functions**: `parse`, `stringify`, `load`, `save`, `validate`, `merge`, `pretty_print`
1544
+
1545
+ ##### Date & Time (datetime)
1546
+ ```zexus
1547
+ use {now, timestamp, add_days} from "datetime"
1548
+
1549
+ let current = now()
1550
+ let ts = timestamp()
1551
+ let tomorrow = add_days(current, 1)
1552
+ ```
1553
+
1554
+ **25+ functions**: `now`, `utc_now`, `timestamp`, `format`, `parse`, `add_days`, `add_hours`, `diff_seconds`, `is_before`, `is_after`, and more.
1555
+
1556
+ ##### Cryptography (crypto)
1557
+ ```zexus
1558
+ use {hash_sha256, keccak256, random_bytes} from "crypto"
1559
+
1560
+ let hash = hash_sha256("Hello World")
1561
+ let keccak = keccak256("Hello World")
1562
+ let random = random_bytes(32)
1563
+ ```
1564
+
1565
+ **15+ functions**: `hash_sha256`, `hash_sha512`, `keccak256`, `sha3_256`, `hmac_sha256`, `random_bytes`, `random_int`, `pbkdf2`, `generate_salt`, `compare_digest`, and more.
1566
+
1567
+ ##### Blockchain (blockchain)
1568
+ ```zexus
1569
+ use {create_address, validate_address, calculate_merkle_root} from "blockchain"
1570
+
1571
+ let address = create_address("public_key")
1572
+ let is_valid = validate_address(address)
1573
+ let merkle = calculate_merkle_root(["hash1", "hash2"])
1574
+ ```
1575
+
1576
+ **12+ functions**: `create_address`, `validate_address`, `calculate_merkle_root`, `create_block`, `hash_block`, `validate_block`, `create_genesis_block`, `proof_of_work`, `validate_proof_of_work`, `create_transaction`, `hash_transaction`, `validate_chain`
1577
+
1578
+ [View complete stdlib documentation →](docs/stdlib/README.md)
1579
+
1580
+ ---
1581
+
1582
+ ## 📖 Complete Keyword Reference
1583
+
1584
+ Zexus supports **130+ keywords** organized into functional categories:
1585
+
1586
+ ### Core Language Keywords
1587
+
1588
+ #### Variable Declaration & Constants
1589
+ - **`let`** - Mutable variable declaration (supports `=` and `:` syntax)
1590
+ - **`const`** - Immutable constant declaration
1591
+ - **`immutable`** - Mark variable as permanently immutable
1592
+
1593
+ #### Control Flow
1594
+ - **`if`** / **`elif`** / **`else`** - Conditional execution
1595
+ - **`while`** - While loop
1596
+ - **`for`** / **`each`** / **`in`** - For-each iteration
1597
+ - **`match`** / **`case`** / **`default`** - Pattern matching
1598
+ - **`break`** - Exit current loop immediately
1599
+ - **`continue`** - Enable error recovery mode (different from loop continue)
1600
+ - **`return`** - Return from function
1601
+
1602
+ #### Functions & Actions
1603
+ - **`action`** - Define action (Zexus function)
1604
+ - **`function`** - Define function
1605
+ - **`lambda`** - Anonymous function
1606
+ - **`defer`** - Deferred cleanup execution
1607
+
1608
+ #### I/O & Output
1609
+ - **`print`** - Output to console (supports multi-argument and conditional printing)
1610
+ - **`debug`** - Debug output (dual-mode: function returns value, statement logs with metadata)
1611
+ - **`log`** - Redirect output to file (scope-aware, supports any extension)
1612
+
1613
+ #### Types & Structures
1614
+ - **`entity`** - Define data structure
1615
+ - **`data`** - Define dataclass with generics and pattern matching (v1.5.0)
1616
+ - **`enum`** - Define enumeration
1617
+ - **`protocol`** / **`interface`** - Define interface
1618
+ - **`type_alias`** - Create type alias
1619
+ - **`implements`** - Implement protocol
1620
+
1621
+ ### Module System Keywords
1622
+
1623
+ - **`use`** - Import modules/symbols
1624
+ - **`import`** - Alternative import syntax
1625
+ - **`export`** - Export symbols
1626
+ - **`module`** - Define module
1627
+ - **`package`** - Define package/namespace
1628
+ - **`from`** - Import from specific module
1629
+ - **`external`** - Declare external function
1630
+
1631
+ **Note**: All keywords link to detailed documentation with syntax examples and use cases. See the [Documentation](#-documentation) section below for comprehensive guides.
1632
+
1633
+ ### Security & Policy Keywords
1634
+
1635
+ #### Policy Enforcement
1636
+ - **`protect`** - Apply security policy to function
1637
+ - **`verify`** - Runtime verification with custom logic
1638
+ - **`restrict`** - Input validation and constraints
1639
+ - **`require`** - Assert condition (with tolerance blocks)
1640
+ - **`assert`** - Always-check assertion
1641
+
1642
+ #### Access Control & Isolation
1643
+ - **`seal`** - Make object immutable
1644
+ - **`sandbox`** - Isolated execution environment
1645
+ - **`audit`** - Compliance logging
1646
+ - **`trail`** - Event tracking and audit trails
1647
+ - **`capability`** - Define capability
1648
+ - **`grant`** / **`revoke`** - Capability management
1649
+
1650
+ #### Data Validation
1651
+ - **`validate`** - Schema validation
1652
+ - **`sanitize`** - Input sanitization
1653
+
1654
+ ### Blockchain Keywords
1655
+
1656
+ #### Smart Contracts
1657
+ - **`contract`** - Define smart contract
1658
+ - **`state`** - Mutable contract state
1659
+ - **`ledger`** - Immutable ledger
1660
+ - **`persistent`** / **`storage`** - Persistent storage
1661
+ - **`tx`** - Transaction context
1662
+ - **`gas`** - Gas tracking
1663
+ - **`limit`** - Gas/resource limits
1664
+
1665
+ #### Cryptography
1666
+ - **`hash`** - Cryptographic hashing
1667
+ - **`signature`** - Digital signatures
1668
+ - **`verify_sig`** - Signature verification
1669
+
1670
+ #### Contract Features
1671
+ - **`emit`** - Emit event
1672
+ - **`event`** - Event type
1673
+ - **`revert`** - Revert transaction
1674
+ - **`this`** - Current contract/data instance reference ([Full Docs →](docs/keywords/THIS.md))
1675
+
1676
+ ### Modifiers
1677
+
1678
+ #### Visibility
1679
+ - **`public`** - Public visibility (auto-export)
1680
+ - **`private`** - Private/module-only visibility
1681
+
1682
+ #### Contract Modifiers
1683
+ - **`pure`** / **`view`** - Read-only functions
1684
+ - **`payable`** - Can receive value
1685
+ - **`modifier`** - Define function modifier
1686
+ - **`sealed`** - Prevent override
1687
+ - **`secure`** - Security flag
1688
+
1689
+ ### Concurrency & Async Keywords
1690
+
1691
+ - **`async`** - Async function
1692
+ - **`await`** - Await promise/coroutine
1693
+ - **`channel`** - Create channel
1694
+ - **`send`** / **`receive`** - Channel operations
1695
+ - **`atomic`** - Atomic operation block
1696
+ - **`stream`** - Event streaming
1697
+ - **`watch`** - Reactive state monitoring
1698
+
1699
+ ### Error Handling Keywords
1700
+
1701
+ - **`try`** / **`catch`** - Exception handling
1702
+ - **`throw`** - Throw exception with custom message
1703
+ - **`finally`** - Cleanup block
1704
+ - **`require`** - Assert condition (with tolerance blocks for conditional bypasses)
1705
+ - **`revert`** - Revert transaction
1706
+ - **`continue`** - Enable error recovery mode (execution continues despite errors)
1707
+
1708
+ **BREAK Keyword** ([Full Documentation →](docs/keywords/BREAK.md)):
1709
+ ```zexus
1710
+ # Exit loops early
1711
+ while true {
1712
+ let data = fetchData()
1713
+ if data == null {
1714
+ break # Exits the loop
1715
+ }
1716
+ process(data)
1717
+ }
1718
+
1719
+ # Search with early termination
1720
+ for each item in items {
1721
+ if item == target {
1722
+ print("Found: " + string(target))
1723
+ break # Stop searching
1724
+ }
1725
+ }
1726
+ ```
1727
+
1728
+ **THROW Keyword** ([Full Documentation →](docs/keywords/THROW.md)):
1729
+ ```zexus
1730
+ # Throw explicit errors
1731
+ action validateInput(value) {
1732
+ if value < 0 {
1733
+ throw "Value cannot be negative"
1734
+ }
1735
+ if value > 100 {
1736
+ throw "Value exceeds maximum: 100"
1737
+ }
1738
+ return value
1739
+ }
1740
+
1741
+ # Use with try-catch
1742
+ try {
1743
+ let result = validateInput(-5)
1744
+ } catch (error) {
1745
+ print("Validation error: " + error)
1746
+ }
1747
+ ```
1748
+
1749
+ **THIS Keyword** ([Full Documentation →](docs/keywords/THIS.md)):
1750
+ ```zexus
1751
+ # Reference current contract/data instance
1752
+ contract Wallet {
1753
+ state balance: integer
1754
+
1755
+ action deposit(amount) {
1756
+ this.balance = this.balance + amount
1757
+ emit Deposit(TX.caller, amount)
1758
+ }
1759
+
1760
+ action withdraw(amount) {
1761
+ require this.balance >= amount, "Insufficient funds"
1762
+ this.balance = this.balance - amount
1763
+ }
1764
+ }
1765
+
1766
+ # Use in data classes for method chaining
1767
+ data Builder {
1768
+ value: number
1769
+
1770
+ add(n) {
1771
+ this.value = this.value + n
1772
+ return this # Enable chaining
1773
+ }
1774
+ }
1775
+ ```
1776
+
1777
+ **New in v1.5.0**: CONTINUE enables error recovery mode - program continues running even when errors occur:
1778
+ ```zexus
1779
+ # Enable error recovery mode
1780
+ continue;
1781
+
1782
+ # Errors are logged but don't halt execution
1783
+ revert("Error 1"); # Logged, execution continues
1784
+ print "Still running!";
1785
+
1786
+ revert("Error 2"); # Logged, execution continues
1787
+ print "Program completed despite errors!";
1788
+ ```
1789
+
1790
+ **New in v0.1.3**: REQUIRE supports tolerance blocks for conditional requirement bypasses:
1791
+ ```zexus
1792
+ # VIP users bypass balance requirement
1793
+ require balance >= 0.1 {
1794
+ if (isVIP) return true;
1795
+ }
1796
+
1797
+ # Emergency admin access overrides maintenance mode
1798
+ require !maintenanceMode {
1799
+ if (isAdmin && emergency) return true;
1800
+ }
1801
+ ```
1802
+
1803
+ ### Performance Optimization Keywords
1804
+
1805
+ - **`native`** - Native C/C++ FFI
1806
+ - **`inline`** - Function inlining hint
1807
+ - **`gc`** - Garbage collection control
1808
+ - **`buffer`** - Memory buffer operations
1809
+ - **`simd`** - SIMD vector operations
1810
+
1811
+ ### Advanced Language Features
1812
+
1813
+ - **`pattern`** - Pattern matching blocks
1814
+ - **`exactly`** - Exact matching block
1815
+ - **`embedded`** - Embed foreign language code
1816
+ - **`using`** - Resource management
1817
+
1818
+ ### Renderer/UI Keywords
1819
+
1820
+ - **`screen`** - Define UI screen
1821
+ - **`component`** - Define UI component
1822
+ - **`theme`** - Theme declaration
1823
+ - **`canvas`** - Canvas for drawing
1824
+ - **`graphics`** - Graphics context
1825
+ - **`animation`** - Animation definition
1826
+ - **`clock`** - Timing/clock
1827
+ - **`color`** - Color definition
1828
+
1829
+ ### Enterprise Features
1830
+
1831
+ - **`middleware`** - Request/response middleware
1832
+ - **`auth`** - Authentication configuration
1833
+ - **`throttle`** - Rate limiting
1834
+ - **`cache`** - Caching directive
1835
+ - **`inject`** - Dependency injection
1836
+
1837
+ ### Special Keywords
1838
+
1839
+ - **`true`** / **`false`** - Boolean literals
1840
+ - **`null`** - Null value
1841
+ - **`map`** - Map/object literal
1842
+
1843
+ ### Reserved Transaction Context
1844
+
1845
+ - **`TX`** - Global transaction context object with properties:
1846
+ - `TX.caller` - Transaction sender
1847
+ - `TX.value` - Sent value
1848
+ - `TX.timestamp` - Block timestamp
1849
+ - `TX.block_hash` - Current block hash
1850
+ - `TX.gas_used` - Gas consumed
1851
+ - `TX.gas_remaining` - Gas remaining
1852
+ - `TX.gas_limit` - Gas limit
1853
+
1854
+ [Complete keyword testing documentation →](docs/KEYWORD_TESTING_MASTER_LIST.md)
1855
+
1856
+ ---
1857
+
1858
+ ## 🎮 CLI Commands
1859
+
1860
+ ### Zexus CLI (`zx`)
1861
+
1862
+ ```bash
1863
+ # Execution
1864
+ zx run program.zx # Run a program
1865
+ zx run --debug program.zx # Run with debugging
1866
+ zx repl # Start interactive REPL
1867
+
1868
+ # Analysis
1869
+ zx check program.zx # Check syntax
1870
+ zx validate program.zx # Validate and auto-fix
1871
+ zx ast program.zx # Show AST
1872
+ zx tokens program.zx # Show tokens
1873
+
1874
+ # Project Management
1875
+ zx init my-project # Create new project
1876
+ zx test # Run tests
1877
+
1878
+ # Configuration
1879
+ zx debug on # Enable debugging
1880
+ zx debug off # Disable debugging
1881
+ ```
1882
+
1883
+ **Advanced Options:**
1884
+ ```bash
1885
+ # Syntax style
1886
+ zx --syntax-style=universal run program.zx
1887
+ zx --syntax-style=tolerable run program.zx
1888
+ zx --syntax-style=auto run program.zx # Auto-detect (default)
1889
+
1890
+ # Execution mode
1891
+ zx --execution-mode=interpreter run program.zx
1892
+ zx --execution-mode=compiler run program.zx
1893
+ zx --execution-mode=auto run program.zx # Auto-select (default)
1894
+
1895
+ # VM control
1896
+ zx --use-vm run program.zx # Use VM when beneficial (default)
1897
+ zx --no-vm run program.zx # Disable VM
1898
+ ```
1899
+
1900
+ ### Package Manager (`zpm`)
1901
+
1902
+ ```bash
1903
+ # Initialize
1904
+ zpm init # Create new project
1905
+
1906
+ # Install packages
1907
+ zpm install # Install all from zexus.json
1908
+ zpm install std # Install specific package
1909
+ zpm install web@0.2.0 # Install specific version
1910
+ zpm install testing -D # Install as dev dependency
1911
+
1912
+ # Manage packages
1913
+ zpm list # List installed packages
1914
+ zpm search <query> # Search for packages
1915
+ zpm uninstall <package> # Remove a package
1916
+ zpm clean # Remove zpm_modules/
1917
+
1918
+ # Publishing
1919
+ zpm info # Show project info
1920
+ zpm publish # Publish to registry
1921
+ ```
1922
+
1923
+ ---
1924
+
1925
+ ## 🏗️ Architecture
1926
+
1927
+ ```
1928
+ zexus-interpreter/
1929
+ ├── src/zexus/ # Core interpreter
1930
+ │ ├── lexer.py # Tokenization
1931
+ │ ├── parser/ # Parsing (multi-strategy)
1932
+ │ │ ├── parser.py # Main parser
1933
+ │ │ └── ... # Parser utilities
1934
+ │ ├── evaluator/ # Evaluation engine
1935
+ │ │ ├── core.py # Main evaluator
1936
+ │ │ ├── bytecode_compiler.py # VM bytecode compiler
1937
+ │ │ ├── expressions.py # Expression evaluation
1938
+ │ │ ├── statements.py # Statement evaluation
1939
+ │ │ └── functions.py # Function handling & builtins
1940
+ │ ├── vm/ # Virtual Machine
1941
+ │ │ ├── vm.py # VM execution engine
1942
+ │ │ ├── bytecode.py # Bytecode definitions
1943
+ │ │ └── jit.py # JIT compilation
1944
+ │ ├── compiler/ # Compiler frontend
1945
+ │ │ ├── __init__.py # Compiler main
1946
+ │ │ ├── parser.py # Production parser
1947
+ │ │ ├── semantic.py # Semantic analysis
1948
+ │ │ └── bytecode.py # Bytecode generation
1949
+ │ ├── object.py # Object system
1950
+ │ ├── zexus_ast.py # AST definitions
1951
+ │ ├── persistence.py # Persistent storage
1952
+ │ ├── policy_engine.py # Security policies
1953
+ │ ├── dependency_injection.py # DI system
1954
+ │ ├── blockchain/ # Blockchain features
1955
+ │ │ ├── transaction.py # Transaction handling
1956
+ │ │ ├── crypto.py # Cryptography
1957
+ │ │ └── ... # Other blockchain features
1958
+ │ ├── security.py # Security features
1959
+ │ ├── module_manager.py # Module system
1960
+ │ └── ... # Other components
1961
+ ├── tests/ # Test suite
1962
+ │ ├── unit/ # Unit tests
1963
+ │ ├── integration/ # Integration tests
1964
+ │ └── examples/ # Example programs
1965
+ ├── docs/ # Documentation
1966
+ │ ├── features/ # Feature docs
1967
+ │ ├── guides/ # User guides
1968
+ │ └── api/ # API reference
1969
+ ├── syntaxes/ # Syntax highlighting
1970
+ ├── zpm_modules/ # Installed packages
1971
+ └── examples/ # Example programs
1972
+ ```
1973
+
1974
+ ### Execution Flow
1975
+
1976
+ ```
1977
+ Source Code (.zx)
1978
+
1979
+ [Lexer] → Tokens
1980
+
1981
+ [Parser] → AST
1982
+
1983
+ [Evaluator] ←→ [Bytecode Compiler]
1984
+ ↓ ↓
1985
+ Direct Eval [VM Execution]
1986
+ ↓ ↓
1987
+ Result ←─────────┘
1988
+ ```
1989
+
1990
+ ---
1991
+
1992
+ ## 📖 Documentation
1993
+
1994
+ ### Complete Documentation
1995
+
1996
+ - **[Ecosystem Strategy](docs/ECOSYSTEM_STRATEGY.md)** - 🌐 Three-phase roadmap for building "anything"
1997
+ - **[Feature Guide](docs/ADVANCED_FEATURES_IMPLEMENTATION.md)** - Complete feature reference
1998
+ - **[Developer Guide](src/README.md)** - Internal architecture and API
1999
+ - **[Documentation Index](docs/INDEX.md)** - All documentation organized
2000
+ - **[Quick Start](docs/QUICK_START.md)** - Getting started tutorial
2001
+ - **[Architecture](docs/ARCHITECTURE.md)** - System design
2002
+ - **[Philosophy](docs/PHILOSOPHY.md)** - Design principles
2003
+
2004
+ ### Keyword & Syntax Documentation
2005
+
2006
+ - **[Keyword Testing Master List](docs/KEYWORD_TESTING_MASTER_LIST.md)** - Complete keyword reference with 130+ keywords
2007
+ - **[Blockchain Keywords](docs/BLOCKCHAIN_KEYWORDS.md)** - Smart contract keywords (implements, pure, view, payable, modifier, this, emit)
2008
+ - **[Advanced Keywords](docs/keywords/ADVANCED_KEYWORDS.md)** - Advanced language features
2009
+ - **[Modifiers](docs/MODIFIERS.md)** - Function and access modifiers
2010
+
2011
+ ### Language Features by Category
2012
+
2013
+ #### Core Language
2014
+ - **[LET](docs/keywords/LET.md)** - Variable declaration (multiple syntax styles)
2015
+ - **[CONST](docs/keywords/CONST.md)** - Constant declaration
2016
+ - **[ACTION/FUNCTION/LAMBDA/RETURN](docs/keywords/ACTION_FUNCTION_LAMBDA_RETURN.md)** - Function definitions
2017
+ - **[IF/ELIF/ELSE](docs/keywords/IF_ELIF_ELSE.md)** - Conditional execution
2018
+ - **[WHILE/FOR/EACH/IN](docs/keywords/WHILE_FOR_EACH_IN.md)** - Loops and iteration
2019
+ - **[BREAK](docs/keywords/BREAK.md)** - Loop control - exit loops early
2020
+ - **[PRINT/DEBUG](docs/keywords/PRINT_DEBUG.md)** - Output and debugging (includes conditional print)
2021
+ - **[LOG](docs/keywords/LOG.md)** - Output redirection and code generation
2022
+
2023
+ #### Error Handling
2024
+ - **[Error Handling](docs/keywords/ERROR_HANDLING.md)** - TRY/CATCH/REQUIRE/REVERT
2025
+ - **[THROW](docs/keywords/THROW.md)** - Explicit error throwing with custom messages
2026
+
2027
+ #### Object-Oriented & Contracts
2028
+ - **[THIS](docs/keywords/THIS.md)** - Current instance reference for contracts and data classes
2029
+
2030
+ #### Module System
2031
+ - **[MODULE_SYSTEM](docs/keywords/MODULE_SYSTEM.md)** - USE, IMPORT, EXPORT, MODULE, PACKAGE
2032
+ - **[Main Entry Point](docs/MAIN_ENTRY_POINT.md)** - run, execute, is_main patterns
2033
+
2034
+ #### Async & Concurrency
2035
+ - **[ASYNC/AWAIT](docs/keywords/ASYNC_AWAIT.md)** - Asynchronous programming
2036
+ - **[ASYNC_CONCURRENCY](docs/keywords/ASYNC_CONCURRENCY.md)** - Channels, send, receive, atomic
2037
+
2038
+ #### Events & Reactive
2039
+ - **[EVENTS_REACTIVE](docs/keywords/EVENTS_REACTIVE.md)** - Event system
2040
+ - **[WATCH](docs/keywords/COMMAND_watch.md)** - Reactive state management
2041
+
2042
+ #### Security Features
2043
+ - **[SECURITY](docs/keywords/SECURITY.md)** - Security features overview
2044
+ - **[RESTRICT](docs/keywords/COMMAND_restrict.md)** - Input validation
2045
+ - **[SANDBOX](docs/keywords/COMMAND_sandbox.md)** - Isolated execution
2046
+ - **[AUDIT](docs/keywords/COMMAND_audit.md)** - Compliance logging
2047
+ - **[TRAIL](docs/keywords/COMMAND_trail.md)** - Event tracking
2048
+
2049
+ #### Performance
2050
+ - **[PERFORMANCE](docs/keywords/PERFORMANCE.md)** - Performance features
2051
+ - **[NATIVE](docs/keywords/COMMAND_native.md)** - C/C++ FFI
2052
+ - **[INLINE](docs/keywords/COMMAND_inline.md)** - Function inlining
2053
+ - **[GC](docs/keywords/COMMAND_gc.md)** - Garbage collection control
2054
+ - **[BUFFER](docs/keywords/COMMAND_buffer.md)** - Memory buffers
2055
+ - **[SIMD](docs/keywords/COMMAND_simd.md)** - SIMD operations
2056
+
2057
+ #### Advanced Features
2058
+ - **[DEFER](docs/keywords/COMMAND_defer.md)** - Deferred cleanup
2059
+ - **[PATTERN](docs/keywords/COMMAND_pattern.md)** - Pattern matching
2060
+ - **[ENUM](docs/keywords/COMMAND_enum.md)** - Enumerations
2061
+ - **[STREAM](docs/keywords/COMMAND_stream.md)** - Event streaming
2062
+
2063
+ #### Blockchain & State
2064
+ - **[BLOCKCHAIN_STATE](docs/keywords/BLOCKCHAIN_STATE.md)** - State management
2065
+
2066
+ #### Renderer/UI
2067
+ - **[RENDERER_UI](docs/keywords/RENDERER_UI.md)** - UI and rendering system
2068
+
2069
+ ### Specific Features
2070
+
2071
+ - **[VM Integration](VM_INTEGRATION_SUMMARY.md)** - Virtual Machine details
2072
+ - **[VM Quick Reference](VM_QUICK_REFERENCE.md)** - VM API and usage
2073
+ - **[Blockchain](docs/BLOCKCHAIN_FEATURES.md)** - Smart contracts and DApps
2074
+ - **[Security](docs/SECURITY_FEATURES.md)** - Security features guide
2075
+ - **[Concurrency](docs/CONCURRENCY.md)** - Async/await and channels
2076
+ - **[Module System](docs/MODULE_SYSTEM.md)** - Import/export system
2077
+ - **[Plugin System](docs/PLUGIN_SYSTEM.md)** - Extending Zexus
2078
+ - **[ZPM Guide](docs/ZPM_GUIDE.md)** - Package manager
2079
+ - **[Performance](docs/PERFORMANCE_FEATURES.md)** - Optimization features
2080
+
2081
+ ### Command Documentation
2082
+
2083
+ Each advanced feature has detailed documentation:
2084
+ - [PROTECT](docs/keywords/COMMAND_protect.md) - Security policies
2085
+ - [WATCH](docs/keywords/COMMAND_watch.md) - Reactive state
2086
+ - [RESTRICT](docs/keywords/COMMAND_restrict.md) - Input validation
2087
+ - [SANDBOX](docs/keywords/COMMAND_sandbox.md) - Isolated execution
2088
+ - [TRAIL](docs/keywords/COMMAND_trail.md) - Audit logging
2089
+ - [DEFER](docs/keywords/COMMAND_defer.md) - Deferred execution
2090
+ - [PATTERN](docs/keywords/COMMAND_pattern.md) - Pattern matching
2091
+ - And many more in [docs/keywords/](docs/keywords/)
2092
+
2093
+ ---
2094
+
2095
+ ## 🤝 Contributing
2096
+
2097
+ We welcome contributions! Here's how:
2098
+
2099
+ 1. **Fork** the repository
2100
+ 2. **Create** a feature branch: `git checkout -b feature/amazing-feature`
2101
+ 3. **Commit** your changes: `git commit -m 'Add amazing feature'`
2102
+ 4. **Push** to the branch: `git push origin feature/amazing-feature`
2103
+ 5. **Open** a Pull Request
2104
+
2105
+ See [CONTRIBUTING.md](docs/CONTRIBUTING.md) for detailed guidelines.
2106
+
2107
+ ---
2108
+
2109
+ ## 🧪 Testing
2110
+
2111
+ ### Run Test Suite
2112
+
2113
+ ```bash
2114
+ # Unit tests
2115
+ pytest tests/unit/
2116
+
2117
+ # Integration tests
2118
+ cd tests/integration
2119
+ zx run test_builtins_simple.zx
2120
+ zx run test_advanced_features_complete.zx
2121
+
2122
+ # VM integration tests
2123
+ python test_vm_integration.py
2124
+ ```
2125
+
2126
+ ---
2127
+
2128
+ ## 💡 Best Practices
2129
+
2130
+ ### Code Organization
2131
+
2132
+ ```zexus
2133
+ # Use modules for organization
2134
+ module UserManagement {
2135
+ export action createUser(name, email) { ... }
2136
+ export action deleteUser(id) { ... }
2137
+
2138
+ private action hashPassword(password) { ... }
2139
+ }
2140
+
2141
+ # Import only what you need
2142
+ use {createUser, deleteUser} from "UserManagement"
2143
+ ```
2144
+
2145
+ ### Security First
2146
+
2147
+ ```zexus
2148
+ # Always validate inputs
2149
+ action processPayment(amount, recipient) {
2150
+ # Validate amount
2151
+ verify amount > 0, "Amount must be positive"
2152
+ restrict(amount, {
2153
+ type: "integer",
2154
+ range: [1, 1000000]
2155
+ })
2156
+
2157
+ # Validate recipient
2158
+ verify is_email(recipient), "Invalid email"
2159
+
2160
+ # Sanitize inputs
2161
+ let clean_recipient = sanitize(recipient, "email")
2162
+
2163
+ # Apply security policies
2164
+ protect(processPayment, {
2165
+ auth_required: true,
2166
+ rate_limit: 10,
2167
+ log_access: true
2168
+ }, "strict")
2169
+ }
2170
+ ```
2171
+
2172
+ ### Error Handling
2173
+
2174
+ ```zexus
2175
+ # Use try-catch for error recovery
2176
+ try {
2177
+ let data = file_read_json("config.json")
2178
+ process_config(data)
2179
+ } catch (error) {
2180
+ # Fallback to defaults
2181
+ let data = get_default_config()
2182
+ debug_log("Using default config", {error: error})
2183
+ }
2184
+
2185
+ # Use defer for cleanup
2186
+ action process_file(path) {
2187
+ let handle = open_file(path)
2188
+ defer {
2189
+ close_file(handle) # Always executes
2190
+ }
2191
+
2192
+ # Process file...
2193
+ return result
2194
+ }
2195
+ ```
2196
+
2197
+ ### Performance Optimization
2198
+
2199
+ ```zexus
2200
+ # Use native for CPU-intensive tasks
2201
+ native action calculate_hash(data: string) -> string {
2202
+ source: "crypto.cpp"
2203
+ function: "sha256_hash"
2204
+ }
2205
+
2206
+ # Mark read-only functions as pure
2207
+ action pure calculate_total(items) {
2208
+ return reduce(items, lambda(sum, item) { sum + item.price }, 0)
2209
+ }
2210
+
2211
+ # Use inline for small frequently-called functions
2212
+ inline action square(x) {
2213
+ return x * x
2214
+ }
2215
+ ```
2216
+
2217
+ ### Async Patterns
2218
+
2219
+ ```zexus
2220
+ # Use async/await for I/O operations
2221
+ async action fetch_user_data(user_id) {
2222
+ let profile = await http_get("/users/" + user_id)
2223
+ let posts = await http_get("/users/" + user_id + "/posts")
2224
+
2225
+ return {profile: profile, posts: posts}
2226
+ }
2227
+
2228
+ # Use channels for producer-consumer patterns
2229
+ channel<Task> work_queue
2230
+
2231
+ action producer() {
2232
+ for each task in pending_tasks {
2233
+ send(work_queue, task)
2234
+ }
2235
+ close_channel(work_queue)
2236
+ }
2237
+ ```
2238
+
2239
+ ### Testing with Dependency Injection
2240
+
2241
+ ```zexus
2242
+ # Production code
2243
+ register_dependency("database", ProductionDB())
2244
+
2245
+ action saveUser(user) {
2246
+ inject database
2247
+ database.insert("users", user)
2248
+ }
2249
+
2250
+ # Test code
2251
+ test_mode(true)
2252
+ mock_dependency("database", MockDB())
2253
+ # Now saveUser() uses mocks
2254
+ ```
2255
+
2256
+ ### Smart Contract Best Practices
2257
+
2258
+ ```zexus
2259
+ # Use modifiers for reusable guards
2260
+ contract Vault {
2261
+ state owner
2262
+
2263
+ modifier onlyOwner {
2264
+ require(TX.caller == owner, "Not authorized")
2265
+ }
2266
+
2267
+ action payable withdraw(amount) modifier onlyOwner {
2268
+ require(balance >= amount, "Insufficient balance")
2269
+ transfer(TX.caller, amount)
2270
+ emit Withdrawal(TX.caller, amount)
2271
+ }
2272
+ }
2273
+ ```
2274
+
2275
+ ### Code Style Guidelines
2276
+
2277
+ 1. **Naming**: `snake_case` for variables/functions, `PascalCase` for types
2278
+ 2. **Indentation**: 4 spaces (not tabs)
2279
+ 3. **Comments**: Use `#` for single-line comments
2280
+ 4. **Functions**: Keep under 50 lines when possible
2281
+ 5. **Error Messages**: Be descriptive and actionable
2282
+
2283
+ ---
2284
+
2285
+ ## 📄 License
2286
+
2287
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
2288
+
2289
+ ---
2290
+
2291
+ ## 🙏 Acknowledgments
2292
+
2293
+ - **Community Contributors** - Thank you for your support!
2294
+ - **Open Source Libraries** - Built with Python, Click, and Rich
2295
+ - **Inspiration** - From modern languages like Rust, Python, Solidity, TypeScript, and Go
2296
+
2297
+ ---
2298
+
2299
+ ## 📞 Contact & Support
2300
+
2301
+ - **Issues**: [GitHub Issues](https://github.com/Zaidux/zexus-interpreter/issues)
2302
+ - **Discussions**: [GitHub Discussions](https://github.com/Zaidux/zexus-interpreter/discussions)
2303
+ - **Email**: zaidux@example.com
2304
+
2305
+ ---
2306
+
2307
+ ## 🗺️ Roadmap
2308
+
2309
+ ### Completed ✅
2310
+ - [x] Core interpreter with hybrid execution
2311
+ - [x] VM-accelerated bytecode execution with JIT compilation
2312
+ - [x] 130+ language keywords fully implemented and tested
2313
+ - [x] Policy-as-code (PROTECT/VERIFY/RESTRICT)
2314
+ - [x] Enhanced VERIFY with validation builtins (email, URL, phone, patterns)
2315
+ - [x] Persistent memory management with leak detection
2316
+ - [x] Dependency injection system with auto-container creation
2317
+ - [x] Reactive state (WATCH) for automatic change reactions
2318
+ - [x] Blockchain primitives and smart contracts
2319
+ - [x] Blockchain modifiers (pure, view, payable, modifier, this, implements, emit)
2320
+ - [x] Module system (USE, EXPORT, MODULE, PACKAGE) with access control
2321
+ - [x] Package manager (ZPM) for dependency management
2322
+ - [x] 100+ built-in functions across all categories
2323
+ - [x] Advanced types (entities, contracts, protocols, enums, type_alias)
2324
+ - [x] Security features (sandbox, seal, trail, audit, capability, grant/revoke)
2325
+ - [x] Concurrency primitives (async/await with Promises, channels, send/receive, atomic)
2326
+ - [x] Main entry point system (run, execute, is_main, exit_program, on_start/on_exit)
2327
+ - [x] Enterprise features (middleware, auth, throttle, cache, inject)
2328
+ - [x] UI rendering system (screen, component, theme, canvas)
2329
+ - [x] Performance optimization (native, inline, gc, buffer, simd)
2330
+ - [x] Advanced features (defer, pattern, stream, exactly, embedded)
2331
+ - [x] Dual-mode DEBUG (function and statement modes)
2332
+ - [x] Multiple syntax styles (`:` and `=` for assignments)
2333
+ - [x] Tolerance blocks for enhanced REQUIRE
2334
+ - [x] Comprehensive test suite (1175+ tests)
2335
+ - [x] **World-class error reporting system (v1.5.0)**
2336
+ - [x] **Generic types and advanced DATA features (v1.5.0)**
2337
+ - [x] **Pattern matching with exhaustiveness checking (v1.5.0)**
2338
+ - [x] **Stack trace formatter with source context (v1.5.0)**
2339
+
2340
+ ### In Progress 🚧
2341
+ - [x] VS Code extension with full IntelliSense ✅
2342
+ - [x] Language Server Protocol (LSP) ✅
2343
+ - [x] Standard library expansion (fs, http, json, datetime, crypto, blockchain) ✅
2344
+ - [x] Performance profiling tools ✅
2345
+ - [ ] Debugger integration (Debug Adapter Protocol in progress)
2346
+
2347
+ ### Planned 🎯
2348
+ - [ ] WASM compilation target
2349
+ - [ ] JIT compilation for hot paths
2350
+ - [ ] Official package registry
2351
+ - [ ] CI/CD templates
2352
+ - [ ] Docker images
2353
+ - [ ] Production monitoring tools
2354
+
2355
+ ### Ecosystem Development 🌐
2356
+ See [Ecosystem Strategy](docs/ECOSYSTEM_STRATEGY.md) for detailed roadmap.
2357
+
2358
+ **Phase 1: Build WITH Zexus** (Q1-Q2 2025)
2359
+ - [ ] HTTP Server implementation
2360
+ - [ ] PostgreSQL, MySQL, MongoDB drivers
2361
+ - [ ] CLI Framework
2362
+ - [ ] Testing Framework
2363
+
2364
+ **Phase 2: Integrate INTO Zexus** (Q3-Q4 2025)
2365
+ - [ ] HTTP native keywords
2366
+ - [ ] DATABASE native keywords
2367
+ - [ ] AI/ML primitives
2368
+ - [ ] Enhanced GUI keywords
2369
+
2370
+ **Phase 3: Batteries Included** (2026+)
2371
+ - [ ] @zexus/web - Full-stack web framework
2372
+ - [ ] @zexus/db - Database ORM and drivers
2373
+ - [ ] @zexus/ai - Machine learning framework
2374
+ - [ ] @zexus/gui - Cross-platform GUI framework
2375
+ - [ ] Additional official packages
2376
+
2377
+ ### Future Enhancements 🚀
2378
+ - [ ] GPU acceleration for SIMD operations
2379
+ - [ ] Distributed computing primitives
2380
+ - [ ] Native mobile app support
2381
+ - [ ] WebAssembly interop
2382
+ - [ ] Advanced static analysis
2383
+
2384
+ ---
2385
+
2386
+ ## 📊 Project Stats
2387
+
2388
+ - **Language**: Python 3.8+
2389
+ - **Version**: 1.5.0 (Stable)
2390
+ - **Lines of Code**: ~50,000+
2391
+ - **Keywords**: 130+ language keywords
2392
+ - **Built-in Functions**: 100+ built-in functions
2393
+ - **Documentation Pages**: 100+
2394
+ - **Test Cases**: 1175+ comprehensive tests
2395
+ - **Features**: 100+ language features
2396
+ - **Supported Platforms**: Linux, macOS, Windows
2397
+
2398
+ ---
2399
+
2400
+ ## ❓ Getting Help & Troubleshooting
2401
+
2402
+ ### Common Issues
2403
+
2404
+ #### "Identifier not found" errors
2405
+ - Check variable spelling and case sensitivity
2406
+ - Ensure variable is declared in current or parent scope
2407
+ - Remember: Zexus uses function-level scoping (not block-level)
2408
+ - Variables declared in blocks persist in function scope
2409
+
2410
+ #### Import/Module errors
2411
+ - Use `use {symbol} from "module"` syntax for imports
2412
+ - Check that module file exists and has `.zx` extension
2413
+ - Ensure exported symbols are marked with `export` keyword
2414
+ - Use `zpm install` to install package dependencies
2415
+
2416
+ #### Syntax errors
2417
+ - Zexus supports multiple syntax styles: `let x = 5` or `let x : 5`
2418
+ - Ensure proper braces `{}` for blocks
2419
+ - Use `;` for statement termination (optional in some contexts)
2420
+ - Check for unmatched parentheses, brackets, or braces
2421
+
2422
+ #### Performance issues
2423
+ - Enable VM execution for compute-heavy code (default: auto)
2424
+ - Use `--use-vm` flag for explicit VM mode
2425
+ - Consider using `native` keyword for C/C++ FFI
2426
+ - Profile with `memory_stats()` to check for leaks
2427
+
2428
+ #### Blockchain/Contract issues
2429
+ - Remember `TX` is a global context object (uppercase)
2430
+ - Use `persistent storage` for contract state
2431
+ - Mark value-receiving functions as `payable`
2432
+ - Use `pure` or `view` for read-only functions
2433
+
2434
+ ### Documentation Quick Links
2435
+
2436
+ - **Beginner**: Start with [Quick Start Guide](docs/QUICK_START.md)
2437
+ - **Keywords**: See [Keyword Master List](docs/KEYWORD_TESTING_MASTER_LIST.md)
2438
+ - **Examples**: Check [examples/](examples/) directory
2439
+ - **API Reference**: Browse [docs/](docs/) for detailed docs
2440
+ - **Advanced**: Read [Advanced Features Guide](docs/ADVANCED_FEATURES_IMPLEMENTATION.md)
2441
+
2442
+ ### Debug Tools
2443
+
2444
+ ```zexus
2445
+ # Enable detailed debugging
2446
+ debug myVariable; # Logs with context
2447
+
2448
+ # Check execution context
2449
+ print(is_main()) # Am I the main module?
2450
+ print(get_module_name()) # Current module name
2451
+ print(module_info()) # Module metadata
2452
+
2453
+ # Memory debugging
2454
+ track_memory() # Enable tracking
2455
+ print(memory_stats()) # Check for leaks
2456
+
2457
+ # AST/Token inspection
2458
+ # Run: zx ast program.zx
2459
+ # Run: zx tokens program.zx
2460
+ ```
2461
+
2462
+ ### Getting Support
2463
+
2464
+ - **GitHub Issues**: [Report bugs or request features](https://github.com/Zaidux/zexus-interpreter/issues)
2465
+ - **Discussions**: [Ask questions and share ideas](https://github.com/Zaidux/zexus-interpreter/discussions)
2466
+ - **Documentation**: [Browse complete docs](docs/)
2467
+ - **Examples**: [See working code samples](examples/)
2468
+
2469
+ ### Community & Ecosystem
2470
+
2471
+ #### Official Resources
2472
+ - **GitHub Repository**: [Zaidux/zexus-interpreter](https://github.com/Zaidux/zexus-interpreter)
2473
+ - **Documentation Site**: [docs/](docs/)
2474
+ - **VS Code Extension**: [.vscode/extensions/zexus-language/](.vscode/extensions/zexus-language/)
2475
+ - **Syntax Highlighting**: [syntaxes/](syntaxes/)
2476
+
2477
+ #### Standard Library Packages
2478
+ - **zexus-blockchain**: Blockchain utilities and helpers
2479
+ - **zexus-network**: HTTP, WebSocket, and networking
2480
+ - **zexus-math**: Advanced mathematical operations
2481
+ - **zexus-stdlib**: Standard library modules
2482
+
2483
+ Install packages with ZPM:
2484
+ ```bash
2485
+ zpm install zexus-blockchain
2486
+ zpm install zexus-network
2487
+ zpm install zexus-math
2488
+ ```
2489
+
2490
+ #### Learning Resources
2491
+ - **Quick Start**: [docs/QUICK_START.md](docs/QUICK_START.md)
2492
+ - **Examples Directory**: [examples/](examples/)
2493
+ - **Test Suite**: [tests/](tests/) - 1175+ working examples
2494
+ - **Keyword Testing**: [docs/KEYWORD_TESTING_MASTER_LIST.md](docs/KEYWORD_TESTING_MASTER_LIST.md)
2495
+ - **Feature Guides**: [docs/features/](docs/features/)
2496
+
2497
+ #### Development Tools
2498
+ - **CLI**: `zx` for running programs
2499
+ - **Package Manager**: `zpm` for dependencies
2500
+ - **REPL**: Interactive shell with `zx repl`
2501
+ - **AST Inspector**: `zx ast program.zx`
2502
+ - **Token Viewer**: `zx tokens program.zx`
2503
+ - **Validator**: `zx validate program.zx`
2504
+
2505
+ ---
2506
+
2507
+ <div align="center">
2508
+
2509
+ **Made with ❤️ by the Zexus Team**
2510
+
2511
+ [⭐ Star us on GitHub](https://github.com/Zaidux/zexus-interpreter) | [📖 Read the Docs](docs/) | [🐛 Report Bug](https://github.com/Zaidux/zexus-interpreter/issues) | [💡 Request Feature](https://github.com/Zaidux/zexus-interpreter/issues/new)
2512
+
2513
+ </div>