Zexus Programming Language
A modern, security-first programming language with built-in blockchain support, VM-accelerated execution, advanced memory management, and policy-as-code
What's New • Features • Installation • Quick Start • Keywords • Documentation • Examples • Troubleshooting
📋 Table of Contents
- What is Zexus?
- What's New
- Key Features
- Installation
- Quick Start
- Examples
- Complete Feature Reference
- Complete Keyword Reference
- Built-in Functions
- CLI Commands
- Architecture
- Documentation
- Contributing
- Testing
- Getting Help & Troubleshooting
- License
- Roadmap
- Project Stats
🎯 What is Zexus?
Zexus is a next-generation, general-purpose programming language designed for security-conscious developers who need:
- 🎨 World-Class Error Messages - Beginner-friendly errors with helpful suggestions (NEW in v1.5!)
- 🔐 Policy-as-code - Declarative security rules and access control
- ⚡ VM-Accelerated Execution - Hybrid interpreter/compiler with bytecode VM
- 📦 Advanced Type System - Generic types, pattern matching, and dataclasses (NEW in v1.5!)
- ⛓️ Built-in Blockchain - Native smart contracts and DApp primitives
- 💾 Persistent Memory - Cross-session data with automatic leak detection
- 🔌 Dependency Injection - Powerful DI system with mocking for testing
- 👀 Reactive State - WATCH for automatic state change reactions
- 🎭 Flexible Syntax - Support for both universal (
{}) and tolerant (:) styles - 📦 Package Manager - ZPM for dependency management
- 🚀 Main Entry Point - Python-style
if __name__ == "__main__"pattern support - 🎨 UI Rendering - Built-in screen, component, and theme system
- 🔒 Enterprise Features - Middleware, authentication, throttling, and caching
🎉 What's New
v1.8.4 — Blockchain VM, Modules, Concurrency, DX, Cybersecurity, Bug Fixes & Documentation (2026-04-12)
Major feature release implementing the Part 2 roadmap and Part 3 cybersecurity gap analysis.
Blockchain VM:
PriorityMempool— Gas-price priority queue with eviction, replace-by-fee, nonce validationGasPriceOracle— EIP-1559 dynamic base fee that adjusts to block utilizationABIEncoder— Function selectors, parameter encoding/decoding for Solidity-compatible types
New Stdlib Modules: cache, queue, template, testing — LRU/TTL caches, message queues, server-side templating, assertion library with mocking
Concurrency: select() channel multiplexing, TaskGroup structured concurrency, BackpressuredChannel overflow policies, TaskContext cross-task tracing
Developer Experience: LSP user-defined symbol completions + formatter, DAP conditional breakpoints + expression eval
Cybersecurity (7 new modules): fuzz (coverage-guided fuzzing), secrets (encrypted store + rotation), netsec (port scanner, TLS checker, DNS enum), payloads (XSS/SQLi/SSRF test vectors), pentest (service enum, brute-force, reporting), audit (SAST with SARIF output), contract_audit (reentrancy, overflow, access control detection)
Tests: 200+ new test cases, all 523 original tests pass.
Also includes the earlier v1.8.4 bug-fix/documentation work: compound assignment operators, for i in range(n) loops, entity constructors with positional args, the not operator fix, new ZEXUS_GUIDE.md / ZEXUS_RULES.md / keyword+builtin+CLI docs, and major repository cleanup.
See CHANGELOG.md for full details.
v1.8.3 — VM Hardening & Closure Scoping (2026-03-01)
Entity field access on VM, contract state compilation, diagnostic warnings, native fast-path calls, VMRuntimeError, stack overflow protection, Rust VM status indicator. Closure scoping fixes for declaration order, module-level side-effects, exported entity constructors. self/this alias, indexed for each, implicit coercion. 1852 tests, 0 regressions.
v1.8.2 — Concurrency & Channel Support (2026-02-25)
Channel VM compiler support, SPAWN/AWAIT opcodes, strategy parser handlers. Zero VM fallbacks.
v1.8.1 — Audit & Security Remediation (2026-02-23)
21 Phase 0 audit issues resolved. emit/protocol/implements working, entity VM compilation, persistent storage, 5 new builtins, security remediation Phases 0–5.
v1.8.0 — Rust VM Pipeline & Major Features (2026-02-23)
Compound assignment, string interpolation, block comments, destructuring. DAP server, GUI backend, concurrent EventLoop, WASM target. Rust-first execution achieving 102,000+ TPS with zero Python fallbacks.
v1.7.x — FIND/LOAD Keywords & Performance (2026-01)
- v1.7.2: Major interpreter speed improvements, smart storage for lists, optimized stack traces, blockchain perf fix
- v1.7.1: FIND keyword (declarative module search), LOAD keyword (provider-aware config loader), VM bytecode support for both, regression tests
v1.6.x — Database Ecosystem & Security (2025-12 – 2026-01)
- v1.6.8: Parser fix for indexed assignments on new lines; contract DATA member declarations
- v1.6.7: Semicolon handling fix, context-aware keyword recognition, standalone block statements
- v1.6.6: Repeated contract action calls, multiple indexed assignments
- v1.6.5: Entity property access, keyword restrictions (
from/toas params), multiple map assignments - v1.6.3: Comprehensive security remediation (10 OWASP categories), RBAC, bcrypt, input sanitization, resource limits, path traversal prevention
- v1.6.2: 4 database drivers (SQLite, PostgreSQL, MySQL, MongoDB), HTTP server, socket/TCP, testing framework, ZPM
v1.5.0 — Error Reporting & Type System (2025-12)
World-class error messages (rivaling Rust), generic types, pattern matching, operator overloading, stack trace formatter, smart suggestions, CONTINUE keyword.
v0.1.3 — Foundation (2025-11)
130+ keywords, dual-mode DEBUG, multi-argument print, multiple syntax styles, enterprise keywords, async/await, UI renderer, enhanced VERIFY, blockchain keywords, 100+ builtins.
🔒 Security Features
Zexus includes comprehensive security enhancements and developer-friendly safety features, making it one of the most secure interpreted languages available with enterprise-grade protection built into the language itself.
🛡️ Security Features Added
✅ Automatic Input Sanitization
All external inputs are automatically tracked and protected against injection attacks:
# Automatic protection against SQL injection, XSS, and command injection
let user_input = input("Enter search term: ") # Automatically marked as untrusted
let query = "SELECT * FROM users WHERE name = " + user_input
# ↑ ERROR: Unsafe tainted string in SQL context. Use sanitize() first.
# Safe version:
let safe_query = "SELECT * FROM users WHERE name = " + sanitize(user_input)
db_query(safe_query) # ✅ Protected!
Features:
- Automatic tainting of all external inputs (stdin, files, HTTP, database)
- Smart SQL/XSS/Shell injection detection
- Mandatory
sanitize()before dangerous operations - 90% reduction in false positives with intelligent pattern matching
✅ Contract Access Control (RBAC)
Built-in Role-Based Access Control for smart contracts and secure applications:
# Owner-only operations
function transfer_ownership(new_owner) {
require_owner() # Only contract owner can call
set_owner("MyContract", new_owner)
}
# Role-based permissions
function delete_user(user_id) {
require_role("ADMIN") # Only admins
# ... delete operations
}
# Fine-grained permissions
function modify_data() {
require_permission("WRITE") # Specific permission required
# ... write operations
}
Features:
- Owner management (
set_owner(),is_owner(),require_owner()) - Role-Based Access Control (
grant_role(),has_role(),require_role()) - Fine-grained permissions (
grant_permission(),require_permission()) - Multi-contract isolation
- Transaction context via
TX.caller
✅ Cryptographic Functions
Enterprise-grade password hashing and secure random number generation:
# Bcrypt password hashing
let hashed = bcrypt_hash("myPassword123")
let is_valid = bcrypt_verify("myPassword123", hashed) # true
# Cryptographically secure random numbers
let secure_token = crypto_rand(32) # 32 random bytes for auth tokens
✅ Type Safety Enhancements
Strict type checking prevents implicit coercion vulnerabilities:
# Requires explicit conversion (prevents bugs)
let message = "Total: " + 42 # ERROR: Cannot add String and Integer
let message = "Total: " + string(42) # ✅ Explicit conversion required
✅ Debug Info Sanitization
Automatic protection against credential leakage in error messages and logs:
# Credentials automatically masked in output
let db_url = "mysql://admin:password123@localhost/db"
print "Connecting to: " + db_url
# Output: Connecting to: mysql://***:***@localhost/db ✅
# API keys protected
let api_key = "sk_live_1234567890abcdef"
print "API key: " + api_key
# Output: API key: *** ✅
Production Mode:
export ZEXUS_ENV=production # Enables aggressive sanitization
./zx-run app.zx
✅ Resource Limits & Protection
Built-in protection against resource exhaustion and DoS attacks:
# Automatic limits (configurable via zexus.json)
- Maximum loop iterations: 1,000,000
- Maximum call stack depth: 1,000
- Execution timeout: 30 seconds
- Storage limits: 10MB per file, 100MB total
- Integer overflow detection (64-bit range)
✅ Path Traversal Prevention
File operations are automatically validated to prevent directory escaping:
file_read("../../etc/passwd") # ERROR: Path traversal detected
file_read("data/safe.txt") # ✅ Allowed
✅ Contract Safety
Built-in require() function for contract preconditions with automatic state rollback:
function transfer(to, amount) {
require(amount > 0, "Amount must be positive")
require(balance >= amount, "Insufficient balance")
# ... safe to proceed, state rolled back if require() fails
}
📊 Security Summary
| Feature | Status | Benefit |
|---|---|---|
| Input Sanitization | ✅ | Prevents SQL injection, XSS, command injection |
| Access Control (RBAC) | ✅ | Prevents unauthorized operations |
| Cryptographic Functions | ✅ | Secure password hashing, CSPRNG |
| Type Safety | ✅ | Prevents implicit coercion bugs |
| Debug Sanitization | ✅ | Prevents credential leaks |
| Resource Limits | ✅ | Prevents DoS attacks |
| Path Validation | ✅ | Prevents file system escapes |
| Contract Safety | ✅ | Automatic state rollback on errors |
| Integer Overflow Protection | ✅ | Prevents arithmetic overflow |
OWASP Top 10 Coverage: 10/10 categories addressed
Security Grade: A+
Test Coverage: 100% of security features
📚 Security Documentation
- Security Fixes Summary - Complete overview
- Security Features Guide - All security capabilities
- Contract Access Control - RBAC guide
- Input Sanitization - Injection prevention
- Debug Sanitization - Credential protection
- Cryptographic Functions - Password hashing & CSPRNG
- Type Safety - Strict type checking
- Resource Limits - DoS prevention
✨ Key Features
🎨 NEW! World-Class Error Reporting (v1.5.0)
Zexus now features production-grade error messages that rival Rust and surpass Python:
ERROR: SyntaxError[SYNTAX]
→ myfile.zx:10:16
10 | let message = "Hello world
^
Unterminated string literal
💡 Suggestion: Add a closing quote " to terminate the string.
Error Reporting Features:
- ✅ Color-coded output - Errors in red, warnings in yellow, info in blue
- ✅ Source code context - See exactly where the error occurred
- ✅ Helpful suggestions - Actionable hints for fixing errors
- ✅ Beginner-friendly - Clear messages, no cryptic codes
- ✅ Category distinction - Know if it's your code or an interpreter bug
- ✅ Smart detection - Single
&suggests&&, unclosed strings, etc.
Better than Python: No confusing indentation errors!
On par with Rust: Same quality formatting and helpful suggestions!
Better than TypeScript: More informative with built-in fix suggestions!
Learn more about error reporting →
📦 NEW! Advanced DATA Features (v1.5.0)
Complete dataclass system with 8/8 features including generics and pattern matching:
Generic Types
data Box<T> {
value: T
unwrap() { this.value }
}
data Pair<K, V> {
key: K
value: V
operator + (other) {
Pair(this.key, this.value + other.value)
}
}
let numberBox = Box<number>(42)
let stringBox = Box<string>("hello")
let pair = Pair<string, number>("age", 30)
Pattern Matching
data Shape {
// Base shape
}
data Circle extends Shape {
radius: number
}
data Rectangle extends Shape {
width: number
height: number
}
action calculateArea(shape) {
match shape {
Circle(r) => 3.14 * r * r,
Rectangle(w, h) => w * h,
_ => 0
}
}
DATA Features:
- ✅ Generic type parameters (
<T>,<K, V>) - ✅ Pattern matching with destructuring
- ✅ Operator overloading
- ✅ Inheritance and extends
- ✅ Instance methods
- ✅ Static methods
- ✅ Property validation
- ✅ Immutability options
Learn more about DATA keyword →
let circle = Circle(5) let area = calculateArea(circle) // 78.5
**Complete Feature Set:**
1. ✅ Static `default()` method
2. ✅ Computed properties with `get`
3. ✅ Method definitions
4. ✅ Operator overloading
5. ✅ Inheritance with `extends`
6. ✅ Decorators
7. ✅ **Generic types** (NEW!)
8. ✅ **Pattern matching** (NEW!)
[Learn more about DATA features →](docs/keywords/DATA.md)
### ⚡ VM-Accelerated Performance
Zexus now includes a sophisticated Virtual Machine for optimized execution:
```zexus
# Automatically optimized via VM
let sum = 0
let i = 0
while (i < 1000) {
sum = sum + i
i = i + 1
}
# ↑ This loop executes 2-10x faster via bytecode!
VM Features:
- ✅ Stack-based bytecode execution
- ✅ Automatic optimization for loops and math-heavy code
- ✅ Async/await support (SPAWN, AWAIT opcodes)
- ✅ Function call optimization
- ✅ Collection operations (lists, maps)
- ✅ Event system
- ✅ Module imports
- ✅ Smart fallback to interpreter for unsupported features
Learn more about VM integration →
🔐 Security & Policy-as-Code (✨ VERIFY Enhanced!)
# Define security policies declaratively
protect(transfer_funds, {
rate_limit: 100,
auth_required: true,
require_https: true,
allowed_ips: ["10.0.0.0/8"]
}, "strict")
# Enhanced runtime verification with custom logic
verify is_email(email) {
log_error("Invalid email attempt");
block_submission();
}
# Access control with blocking
verify userRole == "admin" {
log_unauthorized_access(user);
block_request();
}
# Database and environment verification
verify:db userId exists_in "users", "User not found"
verify:env "API_KEY" is_set, "API_KEY not configured"
# Data constraints
restrict(amount, {
range: [0, 10000],
type: "integer"
})
NEW: VERIFY now includes email/URL/phone validation, pattern matching, database checks, environment variables, input sanitization, and custom logic blocks! See VERIFY Guide →
⛓️ Native Blockchain Support
# Smart contracts made easy
contract Token {
persistent storage balances: Map<Address, integer>
action transfer(from: Address, to: Address, amount: integer) {
require(balances[from] >= amount, "Insufficient balance")
balances[from] = balances[from] - amount
balances[to] = balances.get(to, 0) + amount
emit Transfer(from, to, amount)
}
}
💾 Persistent Memory Management
# Store data across program runs
persist_set("user_preferences", preferences)
let prefs = persist_get("user_preferences")
# Automatic memory tracking
track_memory() # Detects leaks automatically
🔌 Dependency Injection & Testing
# Register dependencies
register_dependency("database", ProductionDB())
# Inject at runtime
inject database
# Mock for testing
test_mode(true)
mock_dependency("database", MockDB())
👀 Reactive State Management
# Watch variables for changes
let count = 0
watch count {
print("Count changed to: " + string(count))
}
count = 5 # Automatically triggers watch callback
🚀 Advanced Features
- Multi-strategy parsing: Tolerates syntax variations
- Hybrid execution: Auto-selects interpreter or compiler/VM
- Type safety: Strong typing with inference
- Pattern matching: Powerful match expressions
- Async/await: Built-in concurrency primitives
- Module system: Import/export with access control
- Rich built-ins: 100+ built-in functions
- Plugin system: Extensible architecture
- Advanced types: Entities, Contracts, Enums, Protocols
- Syntax flexibility: Multiple syntax styles (
:and=for assignments) - 130+ keywords: Comprehensive language features
- Main entry point: Run/execute patterns like Python's
if __name__ == "__main__"
🔍 Why Choose Zexus?
Language Comparison
| Feature | Zexus | Python | Solidity | Rust | TypeScript |
|---|---|---|---|---|---|
| Blockchain Native | ✅ Built-in | ❌ Libraries | ✅ Native | ❌ Libraries | ❌ Libraries |
| Policy-as-Code | ✅ Native | ⚠️ Manual | ⚠️ Modifiers | ❌ None | ❌ None |
| VM Execution | ✅ Hybrid | ✅ Bytecode | ✅ EVM | ✅ Native | ⚠️ V8/Node |
| Type Safety | ✅ Strong+Inference | ⚠️ Optional | ✅ Strong | ✅ Strong | ✅ Strong |
| Async/Await | ✅ Native | ✅ Native | ❌ None | ✅ Native | ✅ Native |
| Dependency Injection | ✅ Built-in | ⚠️ Libraries | ❌ None | ⚠️ Manual | ⚠️ Libraries |
| Reactive State | ✅ WATCH | ⚠️ Libraries | ❌ None | ⚠️ Libraries | ⚠️ Libraries |
| Memory Tracking | ✅ Automatic | ⚠️ Manual | ⚠️ Gas-based | ✅ Ownership | ⚠️ Manual |
| Security Features | ✅✅✅ Extensive | ⚠️ Libraries | ⚠️ Limited | ✅ Safe | ⚠️ Libraries |
| Syntax Flexibility | ✅ Multiple styles | ✅ PEP-8 | ✅ Solidity | ✅ Strict | ✅ Strict |
| Learning Curve | 🟢 Easy | 🟢 Easy | 🟡 Medium | 🔴 Hard | 🟡 Medium |
Use Zexus When You Need
✅ Smart contracts without EVM complexity - Cleaner syntax than Solidity
✅ Security-first development - Built-in policy enforcement
✅ Rapid prototyping with production-ready features - Faster than Rust
✅ Cross-platform blockchain apps - No separate contracts needed
✅ Enterprise features out-of-the-box - DI, middleware, auth, caching
✅ Reactive applications - Built-in WATCH for state management
✅ Memory-safe applications - Automatic leak detection
Zexus = Python's Ease + Solidity's Blockchain + Rust's Safety
# Python-like simplicity
let users = []
for each user in get_users() {
print(user.name)
}
# Solidity-like contracts
contract Token {
persistent storage balances: Map<Address, integer>
action payable transfer(to, amount) { ... }
}
# Rust-like safety
verify balance >= amount {
log_error("Insufficient balance")
revert("Not enough funds")
}
📦 Installation
Quick Install (Recommended)
pip install zexus
Full Install (Blockchain + Networking + Security Helpers)
pip install "zexus[full]"
Install Matrix
| Goal | Command | Notes |
|---|---|---|
| Minimal (interpreter + CLI) | pip install zexus |
Pure-Python install. |
| Full runtime features | pip install "zexus[full]" |
Installs optional deps for blockchain/network/security helpers. |
| From source | ./install.sh |
Installs .[full] and attempts Rust VM build when cargo exists. |
Optional Rust VM (zexus_core) |
pip install maturin && maturin develop -m rust_core/Cargo.toml --release |
Requires Rust toolchain; otherwise Zexus falls back automatically. |
| Node/npm distribution | npm i zexus |
Runs pip install --user "zexus[full]" and best-effort builds zexus_core if Rust is available. |
Includes:
zx- Main Zexus CLIzpm- Zexus Package Manager
From Source
git clone https://github.com/Zaidux/zexus-interpreter.git
cd zexus-interpreter
./install.sh
# Or, directly via pip:
pip install -e ".[full]"
Optional: Enable Rust VM (zexus_core)
If you have a Rust toolchain installed (cargo on PATH), you can build the Rust VM extension from source:
pip install maturin
maturin develop -m rust_core/Cargo.toml --release
Verify Installation
zx --version
zpm --version
🚀 Quick Start
1. Hello World
# hello.zx
let name = "World"
print("Hello, " + name + "!")
Run it:
zx run hello.zx
2. Interactive REPL
zx repl
>> let x = 10 + 5
>> print(x * 2)
30
3. Create a Project
zx init my-app
cd my-app
zx run main.zx
💡 Examples
Example 1: Secure API with Policy-as-Code
entity ApiRequest {
endpoint: string,
method: string,
user_id: integer
}
action handle_request(request: ApiRequest) -> string {
# Verify authentication
verify(request.user_id > 0)
# Restrict input
restrict(request.method, {
allowed: ["GET", "POST", "PUT", "DELETE"]
})
return "Request handled successfully"
}
# Protect the endpoint
protect(handle_request, {
rate_limit: 100,
auth_required: true,
require_https: true
}, "strict")
Example 2: Blockchain Token
contract ERC20Token {
persistent storage total_supply: integer
persistent storage balances: Map<Address, integer>
action constructor(initial_supply: integer) {
total_supply = initial_supply
balances[msg.sender] = initial_supply
}
action transfer(to: Address, amount: integer) -> boolean {
require(balances[msg.sender] >= amount, "Insufficient balance")
balances[msg.sender] = balances[msg.sender] - amount
balances[to] = balances.get(to, 0) + amount
emit Transfer(msg.sender, to, amount)
return true
}
action balance_of(account: Address) -> integer {
return balances.get(account, 0)
}
}
Example 3: Reactive State Management
# E-commerce cart with reactive updates
let cart_items = []
let cart_total = 0
watch cart_items {
# Recalculate total when cart changes
cart_total = cart_items.reduce(
initial: 0,
transform: total + item.price
)
print("Cart updated! New total: $" + string(cart_total))
}
# Add items (automatically triggers watch)
cart_items.push({name: "Laptop", price: 999})
cart_items.push({name: "Mouse", price: 29})
Example 4: VM-Optimized Computation
# Fibonacci with automatic VM optimization
action fibonacci(n: integer) -> integer {
if n <= 1 {
return n
}
let a = 0
let b = 1
let i = 2
while (i <= n) {
let temp = a + b
a = b
b = temp
i = i + 1
}
return b
}
# VM automatically compiles this for faster execution
let result = fibonacci(100)
print(result)
Example 5: Main Entry Point Pattern
# Similar to Python's if __name__ == "__main__"
action main() {
print("Running main program")
let result = process_data()
print("Result: " + string(result))
}
# Only runs if this is the main module
if is_main() {
run(main)
}
Example 6: Middleware & Enterprise Features
# Define authentication middleware
middleware("auth", action(req, res) {
if !req.has_token {
return {status: 401, message: "Unauthorized"}
}
return true
})
# Configure authentication
auth {
provider: "oauth2",
scopes: ["read", "write"],
token_expiry: 3600
}
# Apply rate limiting
throttle(api_endpoint, {
requests_per_minute: 100,
burst: 20
})
# Enable caching
cache(expensive_query, {
ttl: 300,
strategy: "lru"
})
Example 7: Concurrency with Channels
# Create typed channel
channel<integer> numbers
# Producer
action producer() {
for each i in range(0, 10) {
send(numbers, i)
sleep(0.1)
}
close_channel(numbers)
}
# Consumer
action consumer() {
while true {
let value = receive(numbers)
if value == null {
break
}
print("Received: " + string(value))
}
}
# Run concurrently
async producer()
async consumer()
Example 8: Output Redirection & Code Generation with LOG
# Redirect output to file for logging
action processData(items) {
log > "processing.log"
print("Processing started at: " + timestamp())
for each item in items {
print("Processing item: " + item)
}
print("Processing complete")
# Output automatically restored when action exits
}
# Generate Python code dynamically
action generatePythonModule() {
log >> "calculator.py"
print("def add(a, b):")
print(" return a + b")
print("")
print("def multiply(a, b):")
print(" return a * b")
print("")
print("# Generated by Zexus")
}
# Generate and execute code
generatePythonModule()
eval_file("calculator.py", "python")
# Multiple outputs to different files
action generateReports() {
log >> "summary.txt"
print("Summary Report")
print("==============")
log >> "details.txt"
print("Detailed Report")
print("===============")
}
Example 9: Advanced Error Handling with Tolerance Blocks
# REQUIRE with tolerance blocks - VIP bypass
action processPremiumAccess(user, balance, isVIP) {
# Standard users need 1.0 ETH, VIP bypass
require balance >= 1.0 {
if (isVIP) return true;
}
print("Premium access granted to: " + user)
return true
}
# Advanced error patterns - Circuit breaker
let failureCount = 0
let circuitOpen = false
action protectedOperation(data) {
try {
if (circuitOpen) {
revert("Circuit breaker activated - too many failures")
}
# Process operation
let result = processData(data)
failureCount = 0 # Reset on success
return result
} catch (error) {
failureCount = failureCount + 1
if (failureCount >= 3) {
circuitOpen = true
}
return null
}
}
# Retry pattern with error aggregation
action retryableOperation(maxAttempts) {
let attempts = 0
let errors = []
while (attempts < maxAttempts) {
try {
return performOperation()
} catch (e) {
attempts = attempts + 1
errors = errors + [e]
if (attempts < maxAttempts) {
sleep(1) # Wait before retry
}
}
}
print("Failed after " + attempts + " attempts")
return null
}
Example 10: Error Recovery with CONTINUE Keyword
# Enable error recovery mode - continue execution despite errors
print "=== Batch Processing with Error Recovery ==="
continue;
# Process multiple records, logging errors but not stopping
action processRecord(id, data) {
if (data < 0) {
revert("Invalid data for record " + id);
return null; # This executes with CONTINUE
}
return "Processed: " + data;
}
let records = [
{id: 1, data: 100},
{id: 2, data: -50}, # Error - but continues
{id: 3, data: 200},
{id: 4, data: -30}, # Error - but continues
{id: 5, data: 300}
];
let successCount = 0;
for each record in records {
let result = processRecord(record.id, record.data);
if (result != null) {
successCount = successCount + 1;
}
}
print "Processed " + successCount + " out of " + length(records) + " records";
print "Program completed despite errors!";
# Use case: Testing framework
action runTests() {
continue; # Run all tests even if some fail
test_addition(); # Pass
test_subtraction(); # Fail - but continue
test_multiplication(); # Pass
test_division(); # Fail - but continue
print "All tests executed!";
}
📚 Complete Feature Reference
Core Language Features
Variables & Constants
# Multiple syntax options supported
let mutable_var = 42 # Standard assignment
let mutable_var : 42 # Colon syntax (tolerant style)
let typed_var : int = 42 # With type annotation
const IMMUTABLE = 3.14159 # Immutable constant
Variable Scoping: Zexus uses function-level scoping (not block-level). Variables can only be shadowed within function boundaries.
Data Types
- Primitives: Integer, Float, String, Boolean, Null
- Collections: List, Map, Set
- Advanced: Entity, Contract, Action, Lambda
- Special: DateTime, File, Math
Functions
action greet(name: string) -> string {
return "Hello, " + name
}
# Lambda functions
let double = lambda(x) { x * 2 }
# Deferred cleanup (executes on scope exit)
defer {
cleanup_resources()
}
Debugging
# DUAL-MODE DEBUG:
# Function mode - returns value, usable in expressions
let x = debug(42) # Outputs: [DEBUG] 42, x = 42
# Statement mode - logs with metadata
debug myVariable; # Outputs: 🔍 DEBUG: <value> with context
# Multi-argument print
print("Value:", x, "Result:", y) # Outputs: Value: <x> Result: <y>
print("Hello", "World", 42) # Outputs: Hello World 42
# Other debug tools
debug_log("message", context)
debug_trace() # Stack trace
Control Flow
# Conditionals
if condition {
# code
} elif other_condition {
# code
} else {
# code
}
# Loops
while condition {
# code
}
for each item in collection {
# code
}
# Loop Control - BREAK
while true {
if shouldExit {
break # Exit loop immediately
}
# process data
}
# Pattern Matching
match value {
case 1: print("One")
case 2: print("Two")
default: print("Other")
}
Error Handling - THROW
# Throw errors explicitly
action validateAge(age) {
if age < 0 {
throw "Age cannot be negative"
}
if age > 150 {
throw "Age is unrealistic"
}
return age
}
# Combine with try-catch
try {
let userAge = validateAge(-5)
print("Valid age: " + string(userAge))
} catch (error) {
print("Error: " + error)
}
Contract Self-Reference - THIS
# Access current instance in contracts
contract Token {
state balances: Map<Address, integer>
action transfer(to, amount) {
# Use 'this' to access instance state
let senderBalance = this.balances[TX.caller]
require senderBalance >= amount, "Insufficient balance"
this.balances[TX.caller] = senderBalance - amount
this.balances[to] = this.balances.get(to, 0) + amount
}
}
# Use in data classes
data Rectangle {
width: number
height: number
area() {
return this.width * this.height
}
}
Entities & Contracts
entity User {
name: string,
age: integer,
email: string
}
contract MyContract {
persistent storage state: integer
action update(new_value: integer) {
state = new_value
}
}
Advanced Features
🔐 Security Features
PROTECT - Policy-as-code security:
protect(function_name, {
rate_limit: 100, # Max calls per minute
auth_required: true, # Require authentication
require_https: true, # HTTPS only
allowed_ips: ["10.0.0.0/8"], # IP allowlist
blocked_ips: ["192.168.1.100"], # IP blocklist
log_access: true # Audit logging
}, "strict") # Enforcement mode: strict, warn, log
VERIFY - Runtime assertions:
verify(user.is_admin)
verify(amount > 0 and amount < 1000)
RESTRICT - Input validation:
restrict(input_value, {
type: "string",
min_length: 5,
max_length: 100,
pattern: "^[a-zA-Z0-9]+$",
range: [0, 100], # For numbers
allowed: ["GET", "POST"] # Enum values
})
SEAL - Immutable objects:
seal(config) # Make config immutable
SANDBOX - Isolated execution:
sandbox {
# Code runs in restricted environment
# Limited file system, network access
}
TRAIL - Audit logging:
trail(operation, "user_action", {
user_id: user.id,
action: "transfer",
amount: 1000
})
💾 Persistence & Memory
Persistent Storage:
persist_set("key", value)
let value = persist_get("key")
persist_clear("key")
let all_keys = persist_list()
Memory Tracking:
track_memory() # Enable tracking
let stats = memory_stats() # Get statistics
🔌 Dependency Injection
Register Dependencies:
register_dependency("logger", FileLogger("/var/log/app.log"))
register_dependency("database", PostgresDB("localhost:5432"))
Inject Dependencies:
inject logger
inject database
action save_user(user: Entity) {
logger.info("Saving user: " + user.name)
database.insert("users", user)
}
Mocking for Tests:
test_mode(true)
mock_dependency("logger", MockLogger())
mock_dependency("database", MockDB())
# Now all injected dependencies use mocks
👀 Reactive State (WATCH)
let counter = 0
watch counter {
print("Counter changed to: " + string(counter))
# Can trigger other logic
if counter > 10 {
send_alert()
}
}
counter = counter + 1 # Triggers watch
⛓️ Blockchain Features
Transactions:
let tx = transaction({
from: sender_address,
to: recipient_address,
value: 100,
data: "0x1234"
})
Events:
emit Transfer(from, to, amount)
Smart Contract Primitives:
require(condition, "Error message") # Revert if false
assert(condition) # Always check
revert("Reason") # Explicit revert
let balance = balance_of(address)
Cryptographic Functions:
let hash = keccak256(data)
let sig = signature(data, private_key)
let valid = verify_sig(data, sig, public_key)
🔄 Concurrency
Async/Await:
async action fetch_data(url: string) -> string {
let response = await http_get(url)
return response.body
}
let data = await fetch_data("https://api.example.com/data")
Channels:
channel messages
# Send
messages.send("Hello")
# Receive
let msg = messages.receive()
Atomic Operations:
atomic {
# Thread-safe operations
counter = counter + 1
}
📦 Module System
# Export from module
export action public_function() {
return "accessible"
}
private action internal_function() {
return "not exported"
}
# Import in another file
use {public_function} from "mymodule"
# Import with alias
use {public_function as pf} from "mymodule"
# Import entire module
use * from "utilities"
🎨 Pattern Matching
match response_code {
case 200: print("Success")
case 404: print("Not Found")
case 500: print("Server Error")
case x where x >= 400 and x < 500: print("Client Error")
default: print("Unknown status")
}
# Pattern matching with destructuring
match request {
case {method: "GET", path: p}: handle_get(p)
case {method: "POST", body: b}: handle_post(b)
default: handle_other()
}
🔧 Advanced Types
Enums:
enum Status {
PENDING,
ACTIVE,
COMPLETED,
CANCELLED
}
let status = Status.ACTIVE
Protocols (Interfaces):
protocol Serializable {
action serialize() -> string
action deserialize(data: string) -> Entity
}
Type Aliases:
type_alias UserId = integer
type_alias UserMap = Map<UserId, User>
Built-in Functions (100+)
I/O Functions
print(value) # Print without newline
println(value) # Print with newline
input(prompt) # Get user input
read_text(path) # Read text file
write_text(path, content) # Write text file
Type Conversion
string(value) # Convert to string
int(value) # Convert to integer
float(value) # Convert to float
bool(value) # Convert to boolean
Collection Operations
len(collection) # Length/size
list(items...) # Create list
map(pairs...) # Create map
set(items...) # Create set
range(start, end, step) # Generate range
Functional Programming
filter(collection, predicate) # Filter elements
map(collection, transform) # Transform elements
reduce(collection, fn, initial) # Reduce to single value
sort(collection, comparator) # Sort elements
reverse(collection) # Reverse order
String Operations
join(array, separator) # Join strings
split(string, delimiter) # Split string
replace(string, old, new) # Replace substring
uppercase(string) # Convert to uppercase
lowercase(string) # Convert to lowercase
trim(string) # Remove whitespace
substring(string, start, end) # Extract substring
Math Operations
abs(number) # Absolute value
ceil(number) # Ceiling
floor(number) # Floor
round(number, decimals) # Round
min(numbers...) # Minimum
max(numbers...) # Maximum
sum(numbers) # Sum
sqrt(number) # Square root
pow(base, exponent) # Power
random() # Random number
random(max) # Random 0 to max
random(min, max) # Random in range
Date & Time
now() # Current datetime
timestamp() # Unix timestamp
File I/O
file_read_text(path) # Read text file
file_write_text(path, content) # Write text file
file_exists(path) # Check if file exists
file_read_json(path) # Read JSON file
file_write_json(path, data) # Write JSON file
file_append(path, content) # Append to file
file_list_dir(path) # List directory
read_file(path) # Read file contents (alias for file_read_text)
eval_file(path, [language]) # Execute code from file (Zexus, Python, JS)
New in v0.1.3: read_file() and eval_file() enable dynamic code generation and multi-language execution:
# Generate and execute Zexus code
log >> "helper.zx"
print("action add(a, b) { return a + b; }")
eval_file("helper.zx")
let result = add(5, 10) # Uses generated function
# Execute Python code
log >> "script.py"
print("print('Hello from Python!')")
eval_file("script.py", "python")
Persistence
persist_set(key, value) # Store persistent data
persist_get(key) # Retrieve persistent data
persist_clear(key) # Delete persistent data
persist_list() # List all keys
Memory Management
track_memory() # Enable memory tracking
memory_stats() # Get memory statistics
Security & Policy
protect(function, policy, mode) # Apply security policy
verify(condition) # Runtime verification
restrict(value, constraints) # Validate input
create_policy(rules) # Create custom policy
enforce_policy(policy, value) # Apply policy
Dependency Injection
register_dependency(name, impl) # Register dependency
inject_dependency(name) # Inject dependency
mock_dependency(name, mock) # Mock for testing
test_mode(enabled) # Enable/disable test mode
Concurrency & Channels
channel<type> name # Create typed channel
send(channel, value) # Send to channel
receive(channel) # Receive from channel
close_channel(channel) # Close channel
atomic { } # Atomic operation block
emit(event, ...args) # Emit event require(condition, message) # Assert with revert assert(condition) # Assert balance_of(address) # Get balance transfer(to, amount) # Transfer value hash(data) # Hash data keccak256(data) # Keccak-256 hash signature(data, key) # Sign data verify_sig(data, sig, key) # Verify signature
#### Renderer (UI)
```zexus
define_screen(name, props) # Define UI screen
define_component(name, props) # Define component
render_screen(name) # Render screen
set_theme(theme) # Set UI theme
create_canvas(width, height) # Create drawing canvas
draw_line(canvas, x1, y1, x2, y2) # Draw line
draw_text(canvas, text, x, y) # Draw text
Debug & Development
debug(value) # Debug function (returns value)
debug value; # Debug statement (logs with metadata)
debug_log(message, context) # Debug logging
debug_trace() # Stack trace
is_main() # Check if module is main entry point
exit_program(code) # Exit with status code
module_info() # Get module metadata
Main Entry Point Features
run(task_fn) # Execute task function
execute(fn) # Execute function immediately
is_main() # True if current module is main
exit_program(code) # Exit with status code
on_start(fn) # Register startup handler
on_exit(fn) # Register cleanup handler
signal_handler(signal, fn) # Handle OS signals
schedule(fn, delay) # Schedule delayed execution
sleep(seconds) # Sleep for duration
daemonize(fn) # Run as background daemon
watch_and_reload(path) # Auto-reload on file changes
get_module_name() # Get current module name
get_module_path() # Get current module path
list_imports() # List imported modules
get_exported_names() # List exported names
Validation & Verification
is_email(string) # Validate email format
is_url(string) # Validate URL format
is_phone(string) # Validate phone format
is_numeric(string) # Check if numeric
is_alpha(string) # Check if alphabetic
is_alphanumeric(string) # Check if alphanumeric
matches_pattern(str, pattern) # Regex pattern matching
password_strength(password) # Check password strength
sanitize_input(text, type) # Sanitize user input
validate_length(str, min, max) # Validate string length
env_get(name) # Get environment variable
env_set(name, value) # Set environment variable
env_exists(name) # Check if env var exists
Standard Library Modules
Zexus provides 130+ functions across 10 standard library modules:
File System (fs)
use {read_file, write_file, exists, mkdir} from "fs"
write_file("data.txt", "Hello!")
let content = read_file("data.txt")
if exists("data.txt") {
print("File exists!")
}
30+ functions: read_file, write_file, append_file, exists, mkdir, rmdir, list_dir, walk, glob, copy_file, rename, remove, and more.
HTTP Client (http)
use {get, post} from "http"
let response = get("https://api.example.com/data")
print(response.status)
print(response.body)
HTTP Server (NEW! v1.0)
# Create HTTP server with routing
let server = http_server(3000)
server["get"]("/", action(req, res) {
res["send"]("Hello World!")
})
server["post"]("/api/users", action(req, res) {
res["json"]({"message": "User created"})
})
server["listen"]()
Functions: http_server, routing methods (get, post, put, delete), response methods (send, json, status)
Socket/TCP (NEW! v1.0)
# TCP server
let server = socket_listen(8080)
let client = server["accept"]()
let data = client["recv"](1024)
client["send"]("Echo: " + data)
# TCP client
let conn = socket_connect("localhost", 8080)
conn["send"]("Hello!")
let response = conn["recv"](1024)
Functions: socket_listen, socket_connect, send/receive operations
Databases (NEW! v1.0)
# SQLite (built-in, no deps)
let db = sqlite_connect("app.db")
db["execute"]("CREATE TABLE users (...)")
let users = db["query"]("SELECT * FROM users")
# PostgreSQL (requires psycopg2-binary)
let db = postgres_connect("mydb", "user", "pass")
# MySQL (requires mysql-connector-python)
let db = mysql_connect("mydb", "root", "pass")
# MongoDB (requires pymongo)
let db = mongo_connect("myapp")
db["insert_one"]("users", {"name": "Alice"})
let docs = db["find"]("users", {"age": 30})
Functions: Database connection functions, execute/query/update/delete operations for SQL databases, MongoDB NoSQL operations
Testing Framework (NEW! v1.0)
# Load test framework
eval_file("src/zexus/stdlib/test.zx")
# Write assertions
assert_eq(1 + 1, 2, "Addition works")
assert_true(x > 0, "Positive number")
assert_type(value, "Integer", "Type check")
# Get results
print_test_results()
Functions: assert_eq, assert_true, assert_false, assert_null, assert_type, print_test_results
5 functions: get, post, put, delete, request
JSON (json)
use {parse, stringify} from "json"
let data = {name: "Alice", age: 30}
let json_str = stringify(data)
let parsed = parse(json_str)
7 functions: parse, stringify, load, save, validate, merge, pretty_print
Date & Time (datetime)
use {now, timestamp, add_days} from "datetime"
let current = now()
let ts = timestamp()
let tomorrow = add_days(current, 1)
25+ functions: now, utc_now, timestamp, format, parse, add_days, add_hours, diff_seconds, is_before, is_after, and more.
Cryptography (crypto)
use {hash_sha256, keccak256, random_bytes} from "crypto"
let hash = hash_sha256("Hello World")
let keccak = keccak256("Hello World")
let random = random_bytes(32)
15+ functions: hash_sha256, hash_sha512, keccak256, sha3_256, hmac_sha256, random_bytes, random_int, pbkdf2, generate_salt, compare_digest, and more.
Blockchain (blockchain)
use {create_address, validate_address, calculate_merkle_root} from "blockchain"
let address = create_address("public_key")
let is_valid = validate_address(address)
let merkle = calculate_merkle_root(["hash1", "hash2"])
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
View complete stdlib documentation →
📖 Complete Keyword Reference
Zexus supports 130+ keywords organized into functional categories:
Core Language Keywords
Variable Declaration & Constants
let- Mutable variable declaration (supports=and:syntax)const- Immutable constant declarationimmutable- Mark variable as permanently immutable
Control Flow
if/elif/else- Conditional executionwhile- While loopfor/each/in- For-each iterationmatch/case/default- Pattern matchingbreak- Exit current loop immediatelycontinue- Enable error recovery mode (different from loop continue)return- Return from function
Functions & Actions
action- Define action (Zexus function)function- Define functionlambda- Anonymous functiondefer- Deferred cleanup execution
I/O & Output
print- Output to console (supports multi-argument printing, space-separated)debug- Debug output (dual-mode: function returns value, statement logs with metadata)log- Redirect output to file (scope-aware, supports any extension)
Types & Structures
entity- Define data structuredata- Define dataclass with generics and pattern matching (v1.5.0)enum- Define enumerationprotocol/interface- Define interfacetype_alias- Create type aliasimplements- Implement protocol
Module System Keywords
use- Import modules/symbolsimport- Alternative import syntaxexport- Export symbolsmodule- Define modulepackage- Define package/namespacefrom- Import from specific moduleexternal- Declare external function
Note: All keywords link to detailed documentation with syntax examples and use cases. See the Documentation section below for comprehensive guides.
Security & Policy Keywords
Policy Enforcement
protect- Apply security policy to functionverify- Runtime verification with custom logicrestrict- Input validation and constraintsrequire- Assert condition (with tolerance blocks)assert- Always-check assertion
Access Control & Isolation
seal- Make object immutablesandbox- Isolated execution environmentaudit- Compliance loggingtrail- Event tracking and audit trailscapability- Define capabilitygrant/revoke- Capability management
Data Validation
validate- Schema validationsanitize- Input sanitization
Blockchain Keywords
Smart Contracts
contract- Define smart contractstate- Mutable contract stateledger- Immutable ledgerpersistent/storage- Persistent storagetx- Transaction contextgas- Gas trackinglimit- Gas/resource limits
Cryptography
hash- Cryptographic hashingsignature- Digital signaturesverify_sig- Signature verification
Contract Features
emit- Emit eventevent- Event typerevert- Revert transactionthis- Current contract/data instance reference (Full Docs →)
Modifiers
Visibility
public- Public visibility (auto-export)private- Private/module-only visibility
Contract Modifiers
pure/view- Read-only functionspayable- Can receive valuemodifier- Define function modifiersealed- Prevent overridesecure- Security flag
Concurrency & Async Keywords
async- Async functionawait- Await promise/coroutinechannel- Create channelsend/receive- Channel operationsatomic- Atomic operation blockstream- Event streamingwatch- Reactive state monitoring
Error Handling Keywords
try/catch- Exception handlingthrow- Throw exception with custom messagefinally- Cleanup blockrequire- Assert condition (with tolerance blocks for conditional bypasses)revert- Revert transactioncontinue- Enable error recovery mode (execution continues despite errors)
BREAK Keyword (Full Documentation →):
# Exit loops early
while true {
let data = fetchData()
if data == null {
break # Exits the loop
}
process(data)
}
# Search with early termination
for each item in items {
if item == target {
print("Found: " + string(target))
break # Stop searching
}
}
THROW Keyword (Full Documentation →):
# Throw explicit errors
action validateInput(value) {
if value < 0 {
throw "Value cannot be negative"
}
if value > 100 {
throw "Value exceeds maximum: 100"
}
return value
}
# Use with try-catch
try {
let result = validateInput(-5)
} catch (error) {
print("Validation error: " + error)
}
THIS Keyword (Full Documentation →):
# Reference current contract/data instance
contract Wallet {
state balance: integer
action deposit(amount) {
this.balance = this.balance + amount
emit Deposit(TX.caller, amount)
}
action withdraw(amount) {
require this.balance >= amount, "Insufficient funds"
this.balance = this.balance - amount
}
}
# Use in data classes for method chaining
data Builder {
value: number
add(n) {
this.value = this.value + n
return this # Enable chaining
}
}
New in v1.5.0: CONTINUE enables error recovery mode - program continues running even when errors occur:
# Enable error recovery mode
continue;
# Errors are logged but don't halt execution
revert("Error 1"); # Logged, execution continues
print "Still running!";
revert("Error 2"); # Logged, execution continues
print "Program completed despite errors!";
New in v0.1.3: REQUIRE supports tolerance blocks for conditional requirement bypasses:
# VIP users bypass balance requirement
require balance >= 0.1 {
if (isVIP) return true;
}
# Emergency admin access overrides maintenance mode
require !maintenanceMode {
if (isAdmin && emergency) return true;
}
Performance Optimization Keywords
native- Native C/C++ FFIinline- Function inlining hintgc- Garbage collection controlbuffer- Memory buffer operationssimd- SIMD vector operations
Advanced Language Features
pattern- Pattern matching blocksexactly- Exact matching blockembedded- Embed foreign language codeusing- Resource management
Renderer/UI Keywords
screen- Define UI screencomponent- Define UI componenttheme- Theme declarationcanvas- Canvas for drawinggraphics- Graphics contextanimation- Animation definitionclock- Timing/clockcolor- Color definition
Enterprise Features
middleware- Request/response middlewareauth- Authentication configurationthrottle- Rate limitingcache- Caching directiveinject- Dependency injection
Special Keywords
true/false- Boolean literalsnull- Null valuemap- Map/object literal
Reserved Transaction Context
TX- Global transaction context object with properties:TX.caller- Transaction senderTX.value- Sent valueTX.timestamp- Block timestampTX.block_hash- Current block hashTX.gas_used- Gas consumedTX.gas_remaining- Gas remainingTX.gas_limit- Gas limit
Complete keyword testing documentation →
🎮 CLI Commands
Zexus CLI (zx)
# Execution
zx run program.zx # Run a program
zx run --debug program.zx # Run with debugging
zx repl # Start interactive REPL
# Analysis
zx check program.zx # Check syntax
zx validate program.zx # Validate and auto-fix
zx ast program.zx # Show AST
zx tokens program.zx # Show tokens
# Project Management
zx init my-project # Create new project
zx test # Run tests
# Configuration
zx debug on # Enable debugging
zx debug off # Disable debugging
Advanced Options:
# Syntax style
zx --syntax-style=universal run program.zx
zx --syntax-style=tolerable run program.zx
zx --syntax-style=auto run program.zx # Auto-detect (default)
# Execution mode
zx --execution-mode=interpreter run program.zx
zx --execution-mode=compiler run program.zx
zx --execution-mode=auto run program.zx # Auto-select (default)
# VM control
zx --use-vm run program.zx # Use VM when beneficial (default)
zx --no-vm run program.zx # Disable VM
Package Manager (zpm)
# Initialize
zpm init # Create new project
# Install packages
zpm install # Install all from zexus.json
zpm install std # Install specific package
zpm install web@0.2.0 # Install specific version
zpm install testing -D # Install as dev dependency
# Manage packages
zpm list # List installed packages
zpm search <query> # Search for packages
zpm uninstall <package> # Remove a package
zpm clean # Remove zpm_modules/
# Publishing
zpm info # Show project info
zpm publish # Publish to registry
🏗️ Architecture
zexus-interpreter/
├── src/zexus/ # Core interpreter
│ ├── lexer.py # Tokenization
│ ├── parser/ # Parsing (multi-strategy)
│ │ ├── parser.py # Main parser
│ │ └── ... # Parser utilities
│ ├── evaluator/ # Evaluation engine
│ │ ├── core.py # Main evaluator
│ │ ├── bytecode_compiler.py # VM bytecode compiler
│ │ ├── expressions.py # Expression evaluation
│ │ ├── statements.py # Statement evaluation
│ │ └── functions.py # Function handling & builtins
│ ├── vm/ # Virtual Machine
│ │ ├── vm.py # VM execution engine
│ │ ├── bytecode.py # Bytecode definitions
│ │ └── jit.py # JIT compilation
│ ├── compiler/ # Compiler frontend
│ │ ├── __init__.py # Compiler main
│ │ ├── parser.py # Production parser
│ │ ├── semantic.py # Semantic analysis
│ │ └── bytecode.py # Bytecode generation
│ ├── object.py # Object system
│ ├── zexus_ast.py # AST definitions
│ ├── persistence.py # Persistent storage
│ ├── policy_engine.py # Security policies
│ ├── dependency_injection.py # DI system
│ ├── blockchain/ # Blockchain features
│ │ ├── transaction.py # Transaction handling
│ │ ├── crypto.py # Cryptography
│ │ └── ... # Other blockchain features
│ ├── security.py # Security features
│ ├── module_manager.py # Module system
│ └── ... # Other components
├── tests/ # Test suite
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ └── examples/ # Example programs
├── docs/ # Documentation
│ ├── features/ # Feature docs
│ ├── guides/ # User guides
│ └── api/ # API reference
├── syntaxes/ # Syntax highlighting
├── zpm_modules/ # Installed packages
└── examples/ # Example programs
Execution Flow
Source Code (.zx)
↓
[Lexer] → Tokens
↓
[Parser] → AST
↓
[Evaluator] ←→ [Bytecode Compiler]
↓ ↓
Direct Eval [VM Execution]
↓ ↓
Result ←─────────┘
📖 Documentation
Complete Documentation
- Ecosystem Strategy - 🌐 Three-phase roadmap for building "anything"
- Feature Guide - Complete feature reference
- Developer Guide - Internal architecture and API
- Documentation Index - All documentation organized
- Quick Start - Getting started tutorial
- Architecture - System design
- Philosophy - Design principles
Keyword & Syntax Documentation
- Keyword Testing Master List - Complete keyword reference with 130+ keywords
- Blockchain Keywords - Smart contract keywords (implements, pure, view, payable, modifier, this, emit)
- Advanced Keywords - Advanced language features
- Modifiers - Function and access modifiers
Language Features by Category
Core Language
- LET - Variable declaration (multiple syntax styles)
- CONST - Constant declaration
- ACTION/FUNCTION/LAMBDA/RETURN - Function definitions
- IF/ELIF/ELSE - Conditional execution
- WHILE/FOR/EACH/IN - Loops and iteration
- BREAK - Loop control - exit loops early
- PRINT/DEBUG - Output and debugging (includes multi-argument print)
- LOG - Output redirection and code generation
Error Handling
- Error Handling - TRY/CATCH/REQUIRE/REVERT
- THROW - Explicit error throwing with custom messages
Object-Oriented & Contracts
- THIS - Current instance reference for contracts and data classes
Module System
- MODULE_SYSTEM - USE, IMPORT, EXPORT, MODULE, PACKAGE
- Main Entry Point - run, execute, is_main patterns
Async & Concurrency
- ASYNC/AWAIT - Asynchronous programming
- ASYNC_CONCURRENCY - Channels, send, receive, atomic
Events & Reactive
- EVENTS_REACTIVE - Event system
- WATCH - Reactive state management
Security Features
- SECURITY - Security features overview
- RESTRICT - Input validation
- SANDBOX - Isolated execution
- AUDIT - Compliance logging
- TRAIL - Event tracking
Performance
- PERFORMANCE - Performance features
- NATIVE - C/C++ FFI
- INLINE - Function inlining
- GC - Garbage collection control
- BUFFER - Memory buffers
- SIMD - SIMD operations
Advanced Features
Blockchain & State
- BLOCKCHAIN_STATE - State management
Renderer/UI
- RENDERER_UI - UI and rendering system
Specific Features
- VM Integration - Virtual Machine details
- VM Quick Reference - VM API and usage
- Blockchain - Smart contracts and DApps
- Security - Security features guide
- Concurrency - Async/await and channels
- Module System - Import/export system
- Plugin System - Extending Zexus
- ZPM Guide - Package manager
- Performance - Optimization features
Command Documentation
Each advanced feature has detailed documentation:
- PROTECT - Security policies
- WATCH - Reactive state
- RESTRICT - Input validation
- SANDBOX - Isolated execution
- TRAIL - Audit logging
- DEFER - Deferred execution
- PATTERN - Pattern matching
- And many more in docs/keywords/
🤝 Contributing
We welcome contributions! Here's how:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature - Open a Pull Request
See CONTRIBUTING.md for detailed guidelines.
🧪 Testing
Run Test Suite
# Unit tests
pytest tests/unit/
# Integration tests
cd tests/integration
zx run test_builtins_simple.zx
zx run test_advanced_features_complete.zx
# VM integration tests
python test_vm_integration.py
💡 Best Practices
Code Organization
# Use modules for organization
module UserManagement {
export action createUser(name, email) { ... }
export action deleteUser(id) { ... }
private action hashPassword(password) { ... }
}
# Import only what you need
use {createUser, deleteUser} from "UserManagement"
Security First
# Always validate inputs
action processPayment(amount, recipient) {
# Validate amount
verify amount > 0, "Amount must be positive"
restrict(amount, {
type: "integer",
range: [1, 1000000]
})
# Validate recipient
verify is_email(recipient), "Invalid email"
# Sanitize inputs
let clean_recipient = sanitize(recipient, "email")
# Apply security policies
protect(processPayment, {
auth_required: true,
rate_limit: 10,
log_access: true
}, "strict")
}
Error Handling
# Use try-catch for error recovery
try {
let data = file_read_json("config.json")
process_config(data)
} catch (error) {
# Fallback to defaults
let data = get_default_config()
debug_log("Using default config", {error: error})
}
# Use defer for cleanup
action process_file(path) {
let handle = open_file(path)
defer {
close_file(handle) # Always executes
}
# Process file...
return result
}
Performance Optimization
# Use native for CPU-intensive tasks
native action calculate_hash(data: string) -> string {
source: "crypto.cpp"
function: "sha256_hash"
}
# Mark read-only functions as pure
action pure calculate_total(items) {
return reduce(items, lambda(sum, item) { sum + item.price }, 0)
}
# Use inline for small frequently-called functions
inline action square(x) {
return x * x
}
Async Patterns
# Use async/await for I/O operations
async action fetch_user_data(user_id) {
let profile = await http_get("/users/" + user_id)
let posts = await http_get("/users/" + user_id + "/posts")
return {profile: profile, posts: posts}
}
# Use channels for producer-consumer patterns
channel<Task> work_queue
action producer() {
for each task in pending_tasks {
send(work_queue, task)
}
close_channel(work_queue)
}
Testing with Dependency Injection
# Production code
register_dependency("database", ProductionDB())
action saveUser(user) {
inject database
database.insert("users", user)
}
# Test code
test_mode(true)
mock_dependency("database", MockDB())
# Now saveUser() uses mocks
Smart Contract Best Practices
# Use modifiers for reusable guards
contract Vault {
state owner
modifier onlyOwner {
require(TX.caller == owner, "Not authorized")
}
action payable withdraw(amount) modifier onlyOwner {
require(balance >= amount, "Insufficient balance")
transfer(TX.caller, amount)
emit Withdrawal(TX.caller, amount)
}
}
Code Style Guidelines
- Naming:
snake_casefor variables/functions,PascalCasefor types - Indentation: 4 spaces (not tabs)
- Comments: Use
#for single-line comments - Functions: Keep under 50 lines when possible
- Error Messages: Be descriptive and actionable
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Community Contributors - Thank you for your support!
- Open Source Libraries - Built with Python, Click, and Rich
- Inspiration - From modern languages like Rust, Python, Solidity, TypeScript, and Go
📞 Contact & Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Email: zaidux@example.com
🗺️ Roadmap
Completed ✅
- Core interpreter with hybrid execution
- VM-accelerated bytecode execution with JIT compilation
- 130+ language keywords fully implemented and tested
- Policy-as-code (PROTECT/VERIFY/RESTRICT)
- Enhanced VERIFY with validation builtins (email, URL, phone, patterns)
- Persistent memory management with leak detection
- Dependency injection system with auto-container creation
- Reactive state (WATCH) for automatic change reactions
- Blockchain primitives and smart contracts
- Blockchain modifiers (pure, view, payable, modifier, this, implements, emit)
- Module system (USE, EXPORT, MODULE, PACKAGE) with access control
- Package manager (ZPM) for dependency management
- 100+ built-in functions across all categories
- Advanced types (entities, contracts, protocols, enums, type_alias)
- Security features (sandbox, seal, trail, audit, capability, grant/revoke)
- Concurrency primitives (async/await with Promises, channels, send/receive, atomic)
- Main entry point system (run, execute, is_main, exit_program, on_start/on_exit)
- Enterprise features (middleware, auth, throttle, cache, inject)
- UI rendering system (screen, component, theme, canvas)
- Performance optimization (native, inline, gc, buffer, simd)
- Advanced features (defer, pattern, stream, exactly, embedded)
- Dual-mode DEBUG (function and statement modes)
- Multiple syntax styles (
:and=for assignments) - Tolerance blocks for enhanced REQUIRE
- Comprehensive test suite (1175+ tests)
- World-class error reporting system (v1.5.0)
- Generic types and advanced DATA features (v1.5.0)
- Pattern matching with exhaustiveness checking (v1.5.0)
- Stack trace formatter with source context (v1.5.0)
In Progress 🚧
- VS Code extension with full IntelliSense ✅
- Language Server Protocol (LSP) ✅
- Standard library expansion (fs, http, json, datetime, crypto, blockchain) ✅
- Performance profiling tools ✅
- Debugger integration (DAP) ✅
- Transaction mempool with gas-price ordering ✅ (v1.8.4)
- Gas price oracle (EIP-1559 dynamic base fee) ✅ (v1.8.4)
- Contract ABI encoding ✅ (v1.8.4)
-
selectstatement for channel multiplexing ✅ (v1.8.4) - Structured concurrency (TaskGroup) ✅ (v1.8.4)
- Backpressure (configurable overflow policy) ✅ (v1.8.4)
- Context propagation (tracing IDs/deadlines) ✅ (v1.8.4)
-
use "cache"— LRU + TTL caches ✅ (v1.8.4) -
use "queue"— Message queue abstraction ✅ (v1.8.4) -
use "template"— Server-side rendering ✅ (v1.8.4) -
use "testing"— Assert library + mocking ✅ (v1.8.4) -
use "fuzz"— Coverage-guided fuzzing ✅ (v1.8.4) -
use "secrets"— Vault integration, envelope encryption ✅ (v1.8.4) -
use "netsec"— Port scanner, TLS checker, DNS enum ✅ (v1.8.4) -
use "payloads"— XSS/SQLi/SSRF test vectors ✅ (v1.8.4) -
use "pentest"— Pen-testing framework ✅ (v1.8.4) -
zx auditCLI — SAST scanner with SARIF output ✅ (v1.8.4) - Contract security analyzer ✅ (v1.8.4)
Planned 🎯
- WASM compilation target
- JIT compilation for hot paths
- Official package registry
- CI/CD templates
- Docker images
- Production monitoring tools
Ecosystem Development 🌐
See Ecosystem Strategy for detailed roadmap.
Phase 1: Build WITH Zexus (Q1-Q2 2025)
- HTTP Server implementation
- PostgreSQL, MySQL, MongoDB drivers
- CLI Framework
- Testing Framework
Phase 2: Integrate INTO Zexus (Q3-Q4 2025)
- HTTP native keywords
- DATABASE native keywords
- AI/ML primitives
- Enhanced GUI keywords
Phase 3: Batteries Included (2026+)
- @zexus/web - Full-stack web framework
- @zexus/db - Database ORM and drivers
- @zexus/ai - Machine learning framework
- @zexus/gui - Cross-platform GUI framework
- Additional official packages
Future Enhancements 🚀
- GPU acceleration for SIMD operations
- Distributed computing primitives
- Native mobile app support
- WebAssembly interop
- Advanced static analysis
📊 Project Stats
- Language: Python 3.8+
- Version: 1.8.4 (Stable)
- Lines of Code: ~75,000+
- Keywords: 130+ language keywords
- Built-in Functions: 100+ built-in functions
- Stdlib Modules: 30+
- Test Cases: 2500+ comprehensive tests
- Features: 100+ language features
- Supported Platforms: Linux, macOS, Windows
❓ Getting Help & Troubleshooting
Common Issues
"Identifier not found" errors
- Check variable spelling and case sensitivity
- Ensure variable is declared in current or parent scope
- Remember: Zexus uses function-level scoping (not block-level)
- Variables declared in blocks persist in function scope
Import/Module errors
- Use
use {symbol} from "module"syntax for imports - Check that module file exists and has
.zxextension - Ensure exported symbols are marked with
exportkeyword - Use
zpm installto install package dependencies
Syntax errors
- Zexus supports multiple syntax styles:
let x = 5orlet x : 5 - Ensure proper braces
{}for blocks - Use
;for statement termination (optional in some contexts) - Check for unmatched parentheses, brackets, or braces
Performance issues
- Enable VM execution for compute-heavy code (default: auto)
- Use
--use-vmflag for explicit VM mode - Consider using
nativekeyword for C/C++ FFI - Profile with
memory_stats()to check for leaks
PyPI upload fails on Termux with: "unsupported platform tag 'linux_aarch64'"
- PyPI rejects wheels with generic
linux_*platform tags (common when building on Termux). - Fix: upload an sdist (source distribution) and/or a pure-Python wheel:
python -m pip install --upgrade build twinepython -m build# createsdist/*.tar.gzand (by default) apy3-none-any.whlpython -m twine upload dist/*.tar.gz dist/*-py3-none-any.whl
ZEXUS_BUILD_EXTENSIONS=1 python -m buildmeans: build the optional native extensions (Cython/C/C++) in addition to the Python code (it does not skip Python). This produces a platform-specific wheel.- If you want “everything compiled” locally, use:
ZEXUS_BUILD_EXTENSIONS=1 python -m build- or
ZEXUS_BUILD_EXTENSIONS=1 python -m pip install .
- For publishing native wheels to PyPI, build them in a manylinux environment (e.g. GitHub Actions + cibuildwheel). Wheels built on Termux are usually not PyPI-uploadable.
- This repo includes a workflow you can run:
.github/workflows/wheels.yml(builds manylinuxaarch64+x86_64, plus macOS/Windows wheels). - To publish from GitHub Actions without API tokens, use PyPI Trusted Publishing:
- PyPI → your project → Settings → Publishing → Trusted publishers → Add a new trusted publisher
- Provider: GitHub Actions
- Owner:
Zaidux(or your GitHub org/user) - Repository:
zexus-interpreter - Workflow:
.github/workflows/wheels.yml - Environment:
pypi(and optionally also add another trusted publisher entry fortestpypi) - Then either:
- Run Actions → “Build wheels (cibuildwheel)” → Run workflow and choose
testpypifirst, or - Push a release tag like
v1.7.3to auto-build + publish
- Run Actions → “Build wheels (cibuildwheel)” → Run workflow and choose
- This repo includes a workflow you can run:
Blockchain/Contract issues
- Remember
TXis a global context object (uppercase) - Use
persistent storagefor contract state - Mark value-receiving functions as
payable - Use
pureorviewfor read-only functions
Documentation Quick Links
- Beginner: Start with Quick Start Guide
- Keywords: See Keyword Master List
- Examples: Check examples/ directory
- API Reference: Browse docs/ for detailed docs
- Advanced: Read Advanced Features Guide
Debug Tools
# Enable detailed debugging
debug myVariable; # Logs with context
# Check execution context
print(is_main()) # Am I the main module?
print(get_module_name()) # Current module name
print(module_info()) # Module metadata
# Memory debugging
track_memory() # Enable tracking
print(memory_stats()) # Check for leaks
# AST/Token inspection
# Run: zx ast program.zx
# Run: zx tokens program.zx
Getting Support
- GitHub Issues: Report bugs or request features
- Discussions: Ask questions and share ideas
- Documentation: Browse complete docs
- Examples: See working code samples
Community & Ecosystem
Official Resources
- GitHub Repository: Zaidux/zexus-interpreter
- Documentation Site: docs/
- VS Code Extension: .vscode/extensions/zexus-language/
- Syntax Highlighting: syntaxes/
Standard Library Packages
- zexus-blockchain: Blockchain utilities and helpers
- zexus-network: HTTP, WebSocket, and networking
- zexus-math: Advanced mathematical operations
- zexus-stdlib: Standard library modules
Install packages with ZPM:
zpm install zexus-blockchain
zpm install zexus-network
zpm install zexus-math
Learning Resources
- Quick Start: docs/QUICK_START.md
- Examples Directory: examples/
- Test Suite: tests/ - 1175+ working examples
- Keyword Testing: docs/KEYWORD_TESTING_MASTER_LIST.md
- Feature Guides: docs/features/
Development Tools
- CLI:
zxfor running programs - Package Manager:
zpmfor dependencies - REPL: Interactive shell with
zx repl - AST Inspector:
zx ast program.zx - Token Viewer:
zx tokens program.zx - Validator:
zx validate program.zx
Made with ❤️ by the Zexus Team
⭐ Star us on GitHub | 📖 Read the Docs | 🐛 Report Bug | 💡 Request Feature
Metadata
Release files for zexus 2.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| zexus-2.0.0.tar.gz | 3.3 MB | Without provenance | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| zexus-2.0.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 4.3 MB
Release files / zexus-2.0.0.tar.gz
| Download URL | zexus-2.0.0.tar.gz |
|---|---|
| Size | 3.3 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
389ea6e46e41e2f70ffcebbef0ed126d2adf757d61bba5d75adb8ba966a865ad
|
|
BLAKE2b-256 checksum How to use checksums |
dfdb8dde2ceb300868ffc457827dc4782c2eae546926da01d67f3686027c5fcb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.3
|
Release files / zexus-2.0.0-py3-none-any.whl
| Download URL | zexus-2.0.0-py3-none-any.whl |
|---|---|
| Size | 1.0 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f002267417dbff6a215c82bde067fac596d880cc55bab253e0dfff428e5f5f32
|
|
BLAKE2b-256 checksum How to use checksums |
1d90312b00c7081317fdb8e263276e24c99aecdb7b6b556628baa3c56eb188eb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.3
|
Security for zexus 2.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.