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.
- package/LICENSE +0 -0
- package/README.md +2513 -0
- package/bin/zexus +2 -0
- package/bin/zpics +2 -0
- package/bin/zpm +2 -0
- package/bin/zx +2 -0
- package/bin/zx-deploy +2 -0
- package/bin/zx-dev +2 -0
- package/bin/zx-run +2 -0
- package/package.json +66 -0
- package/scripts/README.md +24 -0
- package/scripts/postinstall.js +44 -0
- package/shared_config.json +24 -0
- package/src/README.md +1525 -0
- package/src/tests/run_zexus_tests.py +117 -0
- package/src/tests/test_all_phases.zx +346 -0
- package/src/tests/test_blockchain_features.zx +306 -0
- package/src/tests/test_complexity_features.zx +321 -0
- package/src/tests/test_core_integration.py +185 -0
- package/src/tests/test_phase10_ecosystem.zx +177 -0
- package/src/tests/test_phase1_modifiers.zx +87 -0
- package/src/tests/test_phase2_plugins.zx +80 -0
- package/src/tests/test_phase3_security.zx +97 -0
- package/src/tests/test_phase4_vfs.zx +116 -0
- package/src/tests/test_phase5_types.zx +117 -0
- package/src/tests/test_phase6_metaprogramming.zx +125 -0
- package/src/tests/test_phase7_optimization.zx +132 -0
- package/src/tests/test_phase9_advanced_types.zx +157 -0
- package/src/tests/test_security_features.py +419 -0
- package/src/tests/test_security_features.zx +276 -0
- package/src/tests/test_simple_zx.zx +1 -0
- package/src/tests/test_verification_simple.zx +69 -0
- package/src/zexus/__init__.py +28 -0
- package/src/zexus/__main__.py +5 -0
- package/src/zexus/__pycache__/__init__.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/advanced_types.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/builtin_modules.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/capability_system.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/complexity_system.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/concurrency_system.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/config.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/dependency_injection.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/ecosystem.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/environment.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/error_reporter.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/hybrid_orchestrator.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/lexer.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/metaprogramming.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/module_cache.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/object.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/optimization.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/plugin_system.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/policy_engine.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/security.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/stdlib_integration.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/strategy_recovery.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/syntax_validator.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/type_system.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/virtual_filesystem.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/zexus_ast.cpython-312.pyc +0 -0
- package/src/zexus/__pycache__/zexus_token.cpython-312.pyc +0 -0
- package/src/zexus/advanced_types.py +401 -0
- package/src/zexus/blockchain/__init__.py +40 -0
- package/src/zexus/blockchain/__pycache__/__init__.cpython-312.pyc +0 -0
- package/src/zexus/blockchain/__pycache__/crypto.cpython-312.pyc +0 -0
- package/src/zexus/blockchain/__pycache__/ledger.cpython-312.pyc +0 -0
- package/src/zexus/blockchain/__pycache__/transaction.cpython-312.pyc +0 -0
- package/src/zexus/blockchain/crypto.py +463 -0
- package/src/zexus/blockchain/ledger.py +255 -0
- package/src/zexus/blockchain/transaction.py +267 -0
- package/src/zexus/builtin_modules.py +284 -0
- package/src/zexus/builtin_plugins.py +317 -0
- package/src/zexus/capability_system.py +372 -0
- package/src/zexus/cli/__init__.py +2 -0
- package/src/zexus/cli/__pycache__/__init__.cpython-312.pyc +0 -0
- package/src/zexus/cli/__pycache__/main.cpython-312.pyc +0 -0
- package/src/zexus/cli/main.py +707 -0
- package/src/zexus/cli/zpm.py +203 -0
- package/src/zexus/compare_interpreter_compiler.py +146 -0
- package/src/zexus/compiler/__init__.py +169 -0
- package/src/zexus/compiler/__pycache__/__init__.cpython-312.pyc +0 -0
- package/src/zexus/compiler/__pycache__/lexer.cpython-312.pyc +0 -0
- package/src/zexus/compiler/__pycache__/parser.cpython-312.pyc +0 -0
- package/src/zexus/compiler/__pycache__/zexus_ast.cpython-312.pyc +0 -0
- package/src/zexus/compiler/bytecode.py +266 -0
- package/src/zexus/compiler/compat_runtime.py +277 -0
- package/src/zexus/compiler/lexer.py +257 -0
- package/src/zexus/compiler/parser.py +779 -0
- package/src/zexus/compiler/semantic.py +118 -0
- package/src/zexus/compiler/zexus_ast.py +454 -0
- package/src/zexus/complexity_system.py +575 -0
- package/src/zexus/concurrency_system.py +493 -0
- package/src/zexus/config.py +201 -0
- package/src/zexus/crypto_bridge.py +19 -0
- package/src/zexus/dependency_injection.py +423 -0
- package/src/zexus/ecosystem.py +434 -0
- package/src/zexus/environment.py +101 -0
- package/src/zexus/environment_manager.py +119 -0
- package/src/zexus/error_reporter.py +314 -0
- package/src/zexus/evaluator/__init__.py +12 -0
- package/src/zexus/evaluator/__pycache__/__init__.cpython-312.pyc +0 -0
- package/src/zexus/evaluator/__pycache__/bytecode_compiler.cpython-312.pyc +0 -0
- package/src/zexus/evaluator/__pycache__/core.cpython-312.pyc +0 -0
- package/src/zexus/evaluator/__pycache__/expressions.cpython-312.pyc +0 -0
- package/src/zexus/evaluator/__pycache__/functions.cpython-312.pyc +0 -0
- package/src/zexus/evaluator/__pycache__/integration.cpython-312.pyc +0 -0
- package/src/zexus/evaluator/__pycache__/statements.cpython-312.pyc +0 -0
- package/src/zexus/evaluator/__pycache__/utils.cpython-312.pyc +0 -0
- package/src/zexus/evaluator/bytecode_compiler.py +700 -0
- package/src/zexus/evaluator/core.py +891 -0
- package/src/zexus/evaluator/expressions.py +827 -0
- package/src/zexus/evaluator/functions.py +3989 -0
- package/src/zexus/evaluator/integration.py +396 -0
- package/src/zexus/evaluator/statements.py +4303 -0
- package/src/zexus/evaluator/utils.py +126 -0
- package/src/zexus/evaluator_original.py +2041 -0
- package/src/zexus/external_bridge.py +16 -0
- package/src/zexus/find_affected_imports.sh +155 -0
- package/src/zexus/hybrid_orchestrator.py +152 -0
- package/src/zexus/input_validation.py +259 -0
- package/src/zexus/lexer.py +571 -0
- package/src/zexus/logging.py +89 -0
- package/src/zexus/lsp/__init__.py +9 -0
- package/src/zexus/lsp/completion_provider.py +207 -0
- package/src/zexus/lsp/definition_provider.py +22 -0
- package/src/zexus/lsp/hover_provider.py +71 -0
- package/src/zexus/lsp/server.py +269 -0
- package/src/zexus/lsp/symbol_provider.py +31 -0
- package/src/zexus/metaprogramming.py +321 -0
- package/src/zexus/module_cache.py +89 -0
- package/src/zexus/module_manager.py +107 -0
- package/src/zexus/object.py +973 -0
- package/src/zexus/optimization.py +424 -0
- package/src/zexus/parser/__init__.py +31 -0
- package/src/zexus/parser/__pycache__/__init__.cpython-312.pyc +0 -0
- package/src/zexus/parser/__pycache__/parser.cpython-312.pyc +0 -0
- package/src/zexus/parser/__pycache__/strategy_context.cpython-312.pyc +0 -0
- package/src/zexus/parser/__pycache__/strategy_structural.cpython-312.pyc +0 -0
- package/src/zexus/parser/integration.py +86 -0
- package/src/zexus/parser/parser.py +3977 -0
- package/src/zexus/parser/strategy_context.py +7254 -0
- package/src/zexus/parser/strategy_structural.py +1033 -0
- package/src/zexus/persistence.py +391 -0
- package/src/zexus/plugin_system.py +290 -0
- package/src/zexus/policy_engine.py +365 -0
- package/src/zexus/profiler/__init__.py +5 -0
- package/src/zexus/profiler/profiler.py +233 -0
- package/src/zexus/purity_system.py +398 -0
- package/src/zexus/runtime/__init__.py +20 -0
- package/src/zexus/runtime/async_runtime.py +324 -0
- package/src/zexus/search_old_imports.sh +65 -0
- package/src/zexus/security.py +1407 -0
- package/src/zexus/stack_trace.py +233 -0
- package/src/zexus/stdlib/__init__.py +27 -0
- package/src/zexus/stdlib/blockchain.py +341 -0
- package/src/zexus/stdlib/compression.py +167 -0
- package/src/zexus/stdlib/crypto.py +124 -0
- package/src/zexus/stdlib/datetime.py +163 -0
- package/src/zexus/stdlib/db_mongo.py +199 -0
- package/src/zexus/stdlib/db_mysql.py +162 -0
- package/src/zexus/stdlib/db_postgres.py +163 -0
- package/src/zexus/stdlib/db_sqlite.py +133 -0
- package/src/zexus/stdlib/encoding.py +230 -0
- package/src/zexus/stdlib/fs.py +195 -0
- package/src/zexus/stdlib/http.py +219 -0
- package/src/zexus/stdlib/http_server.py +248 -0
- package/src/zexus/stdlib/json_module.py +61 -0
- package/src/zexus/stdlib/math.py +360 -0
- package/src/zexus/stdlib/os_module.py +265 -0
- package/src/zexus/stdlib/regex.py +148 -0
- package/src/zexus/stdlib/sockets.py +253 -0
- package/src/zexus/stdlib/test_framework.zx +208 -0
- package/src/zexus/stdlib/test_runner.zx +119 -0
- package/src/zexus/stdlib_integration.py +341 -0
- package/src/zexus/strategy_recovery.py +256 -0
- package/src/zexus/syntax_validator.py +356 -0
- package/src/zexus/testing/zpics.py +407 -0
- package/src/zexus/testing/zpics_runtime.py +369 -0
- package/src/zexus/type_system.py +374 -0
- package/src/zexus/validation_system.py +569 -0
- package/src/zexus/virtual_filesystem.py +355 -0
- package/src/zexus/vm/__init__.py +8 -0
- package/src/zexus/vm/__pycache__/__init__.cpython-312.pyc +0 -0
- package/src/zexus/vm/__pycache__/async_optimizer.cpython-312.pyc +0 -0
- package/src/zexus/vm/__pycache__/bytecode.cpython-312.pyc +0 -0
- package/src/zexus/vm/__pycache__/cache.cpython-312.pyc +0 -0
- package/src/zexus/vm/__pycache__/jit.cpython-312.pyc +0 -0
- package/src/zexus/vm/__pycache__/memory_manager.cpython-312.pyc +0 -0
- package/src/zexus/vm/__pycache__/memory_pool.cpython-312.pyc +0 -0
- package/src/zexus/vm/__pycache__/optimizer.cpython-312.pyc +0 -0
- package/src/zexus/vm/__pycache__/parallel_vm.cpython-312.pyc +0 -0
- package/src/zexus/vm/__pycache__/peephole_optimizer.cpython-312.pyc +0 -0
- package/src/zexus/vm/__pycache__/profiler.cpython-312.pyc +0 -0
- package/src/zexus/vm/__pycache__/register_allocator.cpython-312.pyc +0 -0
- package/src/zexus/vm/__pycache__/register_vm.cpython-312.pyc +0 -0
- package/src/zexus/vm/__pycache__/ssa_converter.cpython-312.pyc +0 -0
- package/src/zexus/vm/__pycache__/vm.cpython-312.pyc +0 -0
- package/src/zexus/vm/async_optimizer.py +420 -0
- package/src/zexus/vm/bytecode.py +428 -0
- package/src/zexus/vm/bytecode_converter.py +297 -0
- package/src/zexus/vm/cache.py +532 -0
- package/src/zexus/vm/jit.py +720 -0
- package/src/zexus/vm/memory_manager.py +520 -0
- package/src/zexus/vm/memory_pool.py +511 -0
- package/src/zexus/vm/optimizer.py +478 -0
- package/src/zexus/vm/parallel_vm.py +899 -0
- package/src/zexus/vm/peephole_optimizer.py +452 -0
- package/src/zexus/vm/profiler.py +527 -0
- package/src/zexus/vm/register_allocator.py +462 -0
- package/src/zexus/vm/register_vm.py +520 -0
- package/src/zexus/vm/ssa_converter.py +757 -0
- package/src/zexus/vm/vm.py +1392 -0
- package/src/zexus/zexus_ast.py +1782 -0
- package/src/zexus/zexus_token.py +253 -0
- package/src/zexus/zpm/__init__.py +15 -0
- package/src/zexus/zpm/installer.py +116 -0
- package/src/zexus/zpm/package_manager.py +208 -0
- package/src/zexus/zpm/publisher.py +98 -0
- package/src/zexus/zpm/registry.py +110 -0
- package/src/zexus.egg-info/PKG-INFO +2235 -0
- package/src/zexus.egg-info/SOURCES.txt +876 -0
- package/src/zexus.egg-info/dependency_links.txt +1 -0
- package/src/zexus.egg-info/entry_points.txt +3 -0
- package/src/zexus.egg-info/not-zip-safe +1 -0
- package/src/zexus.egg-info/requires.txt +14 -0
- package/src/zexus.egg-info/top_level.txt +2 -0
- package/zexus.json +14 -0
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Internal optimization system for Zexus.
|
|
3
|
+
|
|
4
|
+
Provides constant folding, dead code elimination, inlining, and bytecode compilation.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any, Dict, List, Optional, Tuple, Set
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from enum import Enum
|
|
10
|
+
from abc import ABC, abstractmethod
|
|
11
|
+
import hashlib
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class OptimizationType(Enum):
|
|
15
|
+
"""Types of code optimizations."""
|
|
16
|
+
CONSTANT_FOLDING = "constant_folding"
|
|
17
|
+
DEAD_CODE_ELIMINATION = "dce"
|
|
18
|
+
INLINING = "inlining"
|
|
19
|
+
LOOP_OPTIMIZATION = "loop_opt"
|
|
20
|
+
COMMON_SUBEXPR_ELIM = "cse"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class BytecodeOp:
|
|
25
|
+
"""Single bytecode operation."""
|
|
26
|
+
opcode: str # Operation code (LOAD, STORE, ADD, CALL, etc.)
|
|
27
|
+
operands: List[Any] = field(default_factory=list)
|
|
28
|
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
29
|
+
|
|
30
|
+
def __repr__(self) -> str:
|
|
31
|
+
"""String representation."""
|
|
32
|
+
if self.operands:
|
|
33
|
+
ops_str = ", ".join(str(op) for op in self.operands)
|
|
34
|
+
return f"{self.opcode}({ops_str})"
|
|
35
|
+
return self.opcode
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class CompiledFunction:
|
|
40
|
+
"""Compiled function with bytecode."""
|
|
41
|
+
name: str
|
|
42
|
+
bytecode: List[BytecodeOp]
|
|
43
|
+
constants: Dict[str, Any] = field(default_factory=dict)
|
|
44
|
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
45
|
+
optimization_passes: List[str] = field(default_factory=list)
|
|
46
|
+
|
|
47
|
+
def get_bytecode_size(self) -> int:
|
|
48
|
+
"""Get size of bytecode in operations."""
|
|
49
|
+
return len(self.bytecode)
|
|
50
|
+
|
|
51
|
+
def add_pass(self, pass_name: str):
|
|
52
|
+
"""Record an optimization pass applied."""
|
|
53
|
+
if pass_name not in self.optimization_passes:
|
|
54
|
+
self.optimization_passes.append(pass_name)
|
|
55
|
+
|
|
56
|
+
def __repr__(self) -> str:
|
|
57
|
+
"""String representation."""
|
|
58
|
+
return f"CompiledFunction({self.name}, {len(self.bytecode)} ops)"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class OptimizationPass(ABC):
|
|
62
|
+
"""Base class for optimization passes."""
|
|
63
|
+
|
|
64
|
+
@abstractmethod
|
|
65
|
+
def optimize(self, bytecode: List[BytecodeOp]) -> List[BytecodeOp]:
|
|
66
|
+
"""Apply optimization pass to bytecode."""
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
@abstractmethod
|
|
70
|
+
def get_name(self) -> str:
|
|
71
|
+
"""Get name of optimization."""
|
|
72
|
+
pass
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ConstantFoldingPass(OptimizationPass):
|
|
76
|
+
"""Fold constant expressions at compile time."""
|
|
77
|
+
|
|
78
|
+
def optimize(self, bytecode: List[BytecodeOp]) -> List[BytecodeOp]:
|
|
79
|
+
"""Apply constant folding."""
|
|
80
|
+
result = []
|
|
81
|
+
i = 0
|
|
82
|
+
while i < len(bytecode):
|
|
83
|
+
# Pattern: LOAD_CONST, LOAD_CONST, BINOP -> LOAD_CONST
|
|
84
|
+
if i + 2 < len(bytecode):
|
|
85
|
+
op1 = bytecode[i]
|
|
86
|
+
op2 = bytecode[i + 1]
|
|
87
|
+
op3 = bytecode[i + 2]
|
|
88
|
+
|
|
89
|
+
if (op1.opcode == "LOAD_CONST" and
|
|
90
|
+
op2.opcode == "LOAD_CONST" and
|
|
91
|
+
op3.opcode in ("ADD", "SUB", "MUL", "DIV", "MOD")):
|
|
92
|
+
|
|
93
|
+
try:
|
|
94
|
+
val1 = op1.operands[0]
|
|
95
|
+
val2 = op2.operands[0]
|
|
96
|
+
|
|
97
|
+
# Compute constant expression
|
|
98
|
+
if op3.opcode == "ADD":
|
|
99
|
+
folded = val1 + val2
|
|
100
|
+
elif op3.opcode == "SUB":
|
|
101
|
+
folded = val1 - val2
|
|
102
|
+
elif op3.opcode == "MUL":
|
|
103
|
+
folded = val1 * val2
|
|
104
|
+
elif op3.opcode == "DIV":
|
|
105
|
+
folded = val1 / val2 if val2 != 0 else None
|
|
106
|
+
else: # MOD
|
|
107
|
+
folded = val1 % val2 if val2 != 0 else None
|
|
108
|
+
|
|
109
|
+
if folded is not None:
|
|
110
|
+
result.append(BytecodeOp("LOAD_CONST", [folded]))
|
|
111
|
+
i += 3
|
|
112
|
+
continue
|
|
113
|
+
except Exception:
|
|
114
|
+
pass
|
|
115
|
+
|
|
116
|
+
result.append(bytecode[i])
|
|
117
|
+
i += 1
|
|
118
|
+
|
|
119
|
+
return result
|
|
120
|
+
|
|
121
|
+
def get_name(self) -> str:
|
|
122
|
+
"""Get name."""
|
|
123
|
+
return "ConstantFolding"
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class DeadCodeEliminationPass(OptimizationPass):
|
|
127
|
+
"""Remove unreachable code after return/break."""
|
|
128
|
+
|
|
129
|
+
def optimize(self, bytecode: List[BytecodeOp]) -> List[BytecodeOp]:
|
|
130
|
+
"""Apply dead code elimination."""
|
|
131
|
+
result = []
|
|
132
|
+
|
|
133
|
+
for op in bytecode:
|
|
134
|
+
result.append(op)
|
|
135
|
+
|
|
136
|
+
# Stop adding operations after unconditional return/break
|
|
137
|
+
if op.opcode in ("RETURN", "BREAK", "BREAK_LOOP"):
|
|
138
|
+
break
|
|
139
|
+
|
|
140
|
+
return result
|
|
141
|
+
|
|
142
|
+
def get_name(self) -> str:
|
|
143
|
+
"""Get name."""
|
|
144
|
+
return "DeadCodeElimination"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class InliningPass(OptimizationPass):
|
|
148
|
+
"""Inline small function calls."""
|
|
149
|
+
|
|
150
|
+
def __init__(self, size_threshold: int = 5):
|
|
151
|
+
"""
|
|
152
|
+
Initialize inlining pass.
|
|
153
|
+
|
|
154
|
+
Args:
|
|
155
|
+
size_threshold: Max bytecode size to inline
|
|
156
|
+
"""
|
|
157
|
+
self.size_threshold = size_threshold
|
|
158
|
+
self.function_bytecode: Dict[str, List[BytecodeOp]] = {}
|
|
159
|
+
|
|
160
|
+
def register_function(self, name: str, bytecode: List[BytecodeOp]):
|
|
161
|
+
"""Register a function for potential inlining."""
|
|
162
|
+
self.function_bytecode[name] = bytecode
|
|
163
|
+
|
|
164
|
+
def optimize(self, bytecode: List[BytecodeOp]) -> List[BytecodeOp]:
|
|
165
|
+
"""Apply inlining."""
|
|
166
|
+
result = []
|
|
167
|
+
|
|
168
|
+
for op in bytecode:
|
|
169
|
+
# Inline small function calls
|
|
170
|
+
if op.opcode == "CALL" and len(op.operands) > 0:
|
|
171
|
+
func_name = op.operands[0]
|
|
172
|
+
|
|
173
|
+
if (func_name in self.function_bytecode and
|
|
174
|
+
len(self.function_bytecode[func_name]) <= self.size_threshold):
|
|
175
|
+
|
|
176
|
+
# Inline the function body
|
|
177
|
+
result.extend(self.function_bytecode[func_name])
|
|
178
|
+
continue
|
|
179
|
+
|
|
180
|
+
result.append(op)
|
|
181
|
+
|
|
182
|
+
return result
|
|
183
|
+
|
|
184
|
+
def get_name(self) -> str:
|
|
185
|
+
"""Get name."""
|
|
186
|
+
return "Inlining"
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class LoopOptimizationPass(OptimizationPass):
|
|
190
|
+
"""Optimize loop structures."""
|
|
191
|
+
|
|
192
|
+
def optimize(self, bytecode: List[BytecodeOp]) -> List[BytecodeOp]:
|
|
193
|
+
"""Apply loop optimizations."""
|
|
194
|
+
result = []
|
|
195
|
+
|
|
196
|
+
i = 0
|
|
197
|
+
while i < len(bytecode):
|
|
198
|
+
# Detect LOOP pattern
|
|
199
|
+
if bytecode[i].opcode == "LOOP":
|
|
200
|
+
loop_start = i
|
|
201
|
+
loop_size = 1
|
|
202
|
+
|
|
203
|
+
# Find loop end
|
|
204
|
+
i += 1
|
|
205
|
+
while i < len(bytecode) and bytecode[i].opcode != "LOOP_END":
|
|
206
|
+
loop_size += 1
|
|
207
|
+
i += 1
|
|
208
|
+
|
|
209
|
+
# Add loop with optimization metadata
|
|
210
|
+
loop_op = BytecodeOp("LOOP", bytecode[loop_start].operands)
|
|
211
|
+
loop_op.metadata["optimized"] = True
|
|
212
|
+
loop_op.metadata["size"] = loop_size
|
|
213
|
+
result.append(loop_op)
|
|
214
|
+
else:
|
|
215
|
+
result.append(bytecode[i])
|
|
216
|
+
i += 1
|
|
217
|
+
|
|
218
|
+
return result
|
|
219
|
+
|
|
220
|
+
def get_name(self) -> str:
|
|
221
|
+
"""Get name."""
|
|
222
|
+
return "LoopOptimization"
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class CommonSubexprEliminationPass(OptimizationPass):
|
|
226
|
+
"""Eliminate redundant subexpressions."""
|
|
227
|
+
|
|
228
|
+
def optimize(self, bytecode: List[BytecodeOp]) -> List[BytecodeOp]:
|
|
229
|
+
"""Apply common subexpression elimination."""
|
|
230
|
+
result = []
|
|
231
|
+
expr_map: Dict[str, str] = {} # Expression hash -> variable
|
|
232
|
+
|
|
233
|
+
for op in bytecode:
|
|
234
|
+
# For binary operations, check if already computed
|
|
235
|
+
if op.opcode in ("ADD", "SUB", "MUL", "DIV"):
|
|
236
|
+
expr_key = f"{op.opcode}:{op.operands}"
|
|
237
|
+
expr_hash = hashlib.md5(expr_key.encode()).hexdigest()[:8]
|
|
238
|
+
|
|
239
|
+
if expr_hash in expr_map:
|
|
240
|
+
# Use previously computed result
|
|
241
|
+
result.append(BytecodeOp("LOAD_VAR", [expr_map[expr_hash]]))
|
|
242
|
+
continue
|
|
243
|
+
else:
|
|
244
|
+
# First occurrence - store result
|
|
245
|
+
expr_map[expr_hash] = f"_cse_{expr_hash}"
|
|
246
|
+
result.append(op)
|
|
247
|
+
result.append(BytecodeOp("STORE_VAR", [f"_cse_{expr_hash}"]))
|
|
248
|
+
else:
|
|
249
|
+
result.append(op)
|
|
250
|
+
|
|
251
|
+
return result
|
|
252
|
+
|
|
253
|
+
def get_name(self) -> str:
|
|
254
|
+
"""Get name."""
|
|
255
|
+
return "CommonSubexprElimination"
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
class OptimizationPipeline:
|
|
259
|
+
"""Pipeline for running multiple optimization passes."""
|
|
260
|
+
|
|
261
|
+
def __init__(self):
|
|
262
|
+
"""Initialize optimization pipeline."""
|
|
263
|
+
self.passes: List[OptimizationPass] = []
|
|
264
|
+
self.enabled_passes: Set[OptimizationType] = set(OptimizationType)
|
|
265
|
+
|
|
266
|
+
def add_pass(self, pass_obj: OptimizationPass) -> 'OptimizationPipeline':
|
|
267
|
+
"""Add optimization pass."""
|
|
268
|
+
self.passes.append(pass_obj)
|
|
269
|
+
return self
|
|
270
|
+
|
|
271
|
+
def enable_pass(self, pass_type: OptimizationType) -> 'OptimizationPipeline':
|
|
272
|
+
"""Enable specific optimization type."""
|
|
273
|
+
self.enabled_passes.add(pass_type)
|
|
274
|
+
return self
|
|
275
|
+
|
|
276
|
+
def disable_pass(self, pass_type: OptimizationType) -> 'OptimizationPipeline':
|
|
277
|
+
"""Disable specific optimization type."""
|
|
278
|
+
self.enabled_passes.discard(pass_type)
|
|
279
|
+
return self
|
|
280
|
+
|
|
281
|
+
def optimize(self, bytecode: List[BytecodeOp]) -> List[BytecodeOp]:
|
|
282
|
+
"""Run all enabled optimization passes."""
|
|
283
|
+
result = bytecode
|
|
284
|
+
|
|
285
|
+
for pass_obj in self.passes:
|
|
286
|
+
result = pass_obj.optimize(result)
|
|
287
|
+
|
|
288
|
+
return result
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
class BytecodeCompiler:
|
|
292
|
+
"""Compile AST/functions to bytecode."""
|
|
293
|
+
|
|
294
|
+
def __init__(self):
|
|
295
|
+
"""Initialize bytecode compiler."""
|
|
296
|
+
self.compiled_functions: Dict[str, CompiledFunction] = {}
|
|
297
|
+
self.optimization_pipeline = OptimizationPipeline()
|
|
298
|
+
self._setup_default_passes()
|
|
299
|
+
|
|
300
|
+
def _setup_default_passes(self):
|
|
301
|
+
"""Setup default optimization passes."""
|
|
302
|
+
self.optimization_pipeline.add_pass(ConstantFoldingPass())
|
|
303
|
+
self.optimization_pipeline.add_pass(DeadCodeEliminationPass())
|
|
304
|
+
self.optimization_pipeline.add_pass(LoopOptimizationPass())
|
|
305
|
+
self.optimization_pipeline.add_pass(CommonSubexprEliminationPass())
|
|
306
|
+
|
|
307
|
+
def compile_function(self, name: str, bytecode: List[BytecodeOp],
|
|
308
|
+
optimize: bool = True) -> CompiledFunction:
|
|
309
|
+
"""Compile function with optional optimization."""
|
|
310
|
+
initial_size = len(bytecode)
|
|
311
|
+
|
|
312
|
+
if optimize:
|
|
313
|
+
optimized = self.optimization_pipeline.optimize(bytecode)
|
|
314
|
+
else:
|
|
315
|
+
optimized = bytecode
|
|
316
|
+
|
|
317
|
+
compiled = CompiledFunction(
|
|
318
|
+
name=name,
|
|
319
|
+
bytecode=optimized,
|
|
320
|
+
metadata={
|
|
321
|
+
"initial_size": initial_size,
|
|
322
|
+
"final_size": len(optimized),
|
|
323
|
+
"reduction": initial_size - len(optimized)
|
|
324
|
+
}
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
self.compiled_functions[name] = compiled
|
|
328
|
+
return compiled
|
|
329
|
+
|
|
330
|
+
def get_compiled_function(self, name: str) -> Optional[CompiledFunction]:
|
|
331
|
+
"""Get compiled function by name."""
|
|
332
|
+
return self.compiled_functions.get(name)
|
|
333
|
+
|
|
334
|
+
def get_optimization_stats(self) -> Dict[str, Any]:
|
|
335
|
+
"""Get optimization statistics."""
|
|
336
|
+
total_initial = 0
|
|
337
|
+
total_final = 0
|
|
338
|
+
|
|
339
|
+
for func in self.compiled_functions.values():
|
|
340
|
+
total_initial += func.metadata.get("initial_size", 0)
|
|
341
|
+
total_final += func.metadata.get("final_size", 0)
|
|
342
|
+
|
|
343
|
+
return {
|
|
344
|
+
"total_functions": len(self.compiled_functions),
|
|
345
|
+
"total_initial_size": total_initial,
|
|
346
|
+
"total_final_size": total_final,
|
|
347
|
+
"total_reduction": total_initial - total_final,
|
|
348
|
+
"reduction_percentage": (
|
|
349
|
+
(total_initial - total_final) / total_initial * 100
|
|
350
|
+
if total_initial > 0 else 0
|
|
351
|
+
)
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
class ExecutionProfile:
|
|
356
|
+
"""Profile for tracking function execution."""
|
|
357
|
+
|
|
358
|
+
def __init__(self, name: str):
|
|
359
|
+
"""Initialize execution profile."""
|
|
360
|
+
self.name = name
|
|
361
|
+
self.call_count = 0
|
|
362
|
+
self.total_time = 0.0
|
|
363
|
+
self.optimization_enabled = True
|
|
364
|
+
|
|
365
|
+
def record_call(self, execution_time: float):
|
|
366
|
+
"""Record a function call."""
|
|
367
|
+
self.call_count += 1
|
|
368
|
+
self.total_time += execution_time
|
|
369
|
+
|
|
370
|
+
def get_avg_time(self) -> float:
|
|
371
|
+
"""Get average execution time."""
|
|
372
|
+
return self.total_time / self.call_count if self.call_count > 0 else 0.0
|
|
373
|
+
|
|
374
|
+
def should_optimize(self) -> bool:
|
|
375
|
+
"""Determine if function should be optimized."""
|
|
376
|
+
# Optimize hot functions (called frequently or slow)
|
|
377
|
+
return self.call_count > 10 or self.total_time > 1.0
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
class OptimizationFramework:
|
|
381
|
+
"""Overall optimization framework."""
|
|
382
|
+
|
|
383
|
+
def __init__(self):
|
|
384
|
+
"""Initialize optimization framework."""
|
|
385
|
+
self.compiler = BytecodeCompiler()
|
|
386
|
+
self.profiles: Dict[str, ExecutionProfile] = {}
|
|
387
|
+
|
|
388
|
+
def create_profile(self, name: str) -> ExecutionProfile:
|
|
389
|
+
"""Create execution profile for function."""
|
|
390
|
+
profile = ExecutionProfile(name)
|
|
391
|
+
self.profiles[name] = profile
|
|
392
|
+
return profile
|
|
393
|
+
|
|
394
|
+
def get_profile(self, name: str) -> Optional[ExecutionProfile]:
|
|
395
|
+
"""Get execution profile."""
|
|
396
|
+
return self.profiles.get(name)
|
|
397
|
+
|
|
398
|
+
def get_hot_functions(self, threshold: int = 10) -> List[str]:
|
|
399
|
+
"""Get frequently called functions."""
|
|
400
|
+
return [
|
|
401
|
+
name for name, profile in self.profiles.items()
|
|
402
|
+
if profile.call_count >= threshold
|
|
403
|
+
]
|
|
404
|
+
|
|
405
|
+
def get_slow_functions(self, threshold: float = 1.0) -> List[str]:
|
|
406
|
+
"""Get slow functions."""
|
|
407
|
+
return [
|
|
408
|
+
name for name, profile in self.profiles.items()
|
|
409
|
+
if profile.total_time >= threshold
|
|
410
|
+
]
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
# Global optimization framework
|
|
414
|
+
_global_optimizer = OptimizationFramework()
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def get_optimizer() -> OptimizationFramework:
|
|
418
|
+
"""Get global optimizer instance."""
|
|
419
|
+
return _global_optimizer
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def compile_function(name: str, bytecode: List[BytecodeOp]) -> CompiledFunction:
|
|
423
|
+
"""Compile function with optimizations."""
|
|
424
|
+
return _global_optimizer.compiler.compile_function(name, bytecode)
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# src/zexus/parser/__init__.py
|
|
2
|
+
"""
|
|
3
|
+
Parser module for Zexus language.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
# Use absolute imports inside the package
|
|
7
|
+
try:
|
|
8
|
+
from .parser import Parser, UltimateParser
|
|
9
|
+
# Import the actual class names defined in the strategy files
|
|
10
|
+
from .strategy_context import ContextStackParser
|
|
11
|
+
from .strategy_structural import StructuralAnalyzer
|
|
12
|
+
except ImportError as e:
|
|
13
|
+
print(f"Warning: Could not import parser modules: {e}")
|
|
14
|
+
# Define placeholders
|
|
15
|
+
class Parser: pass
|
|
16
|
+
class UltimateParser: pass
|
|
17
|
+
class ContextStackParser: pass
|
|
18
|
+
class StructuralAnalyzer: pass
|
|
19
|
+
|
|
20
|
+
# Aliases for backward compatibility or external references
|
|
21
|
+
StrategyContext = ContextStackParser
|
|
22
|
+
StructuralStrategy = StructuralAnalyzer
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"Parser",
|
|
26
|
+
"UltimateParser",
|
|
27
|
+
"ContextStackParser",
|
|
28
|
+
"StructuralAnalyzer",
|
|
29
|
+
"StrategyContext",
|
|
30
|
+
"StructuralStrategy"
|
|
31
|
+
]
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Parser integration for Phase 1 (Modifiers) and Phase 6 (Metaprogramming).
|
|
3
|
+
|
|
4
|
+
Applies modifier parsing and macro expansion during AST construction.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any, List, Optional
|
|
8
|
+
from ..zexus_ast import FunctionLiteral, ActionLiteral
|
|
9
|
+
from ..evaluator.integration import get_integration
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ParserIntegration:
|
|
13
|
+
"""Integration hooks for parser with modifier and metaprogramming support."""
|
|
14
|
+
|
|
15
|
+
@staticmethod
|
|
16
|
+
def attach_modifiers(node: Any, modifiers: List[str]) -> Any:
|
|
17
|
+
"""Attach modifiers to AST node.
|
|
18
|
+
|
|
19
|
+
Phase 1: Modifier System
|
|
20
|
+
"""
|
|
21
|
+
if not hasattr(node, 'modifiers'):
|
|
22
|
+
node.modifiers = []
|
|
23
|
+
|
|
24
|
+
if isinstance(modifiers, list):
|
|
25
|
+
node.modifiers.extend(modifiers)
|
|
26
|
+
else:
|
|
27
|
+
node.modifiers.append(modifiers)
|
|
28
|
+
|
|
29
|
+
return node
|
|
30
|
+
|
|
31
|
+
@staticmethod
|
|
32
|
+
def parse_modifiers(tokens: List[str]) -> tuple:
|
|
33
|
+
"""Parse modifier tokens from token list.
|
|
34
|
+
|
|
35
|
+
Returns: (modifiers, remaining_tokens)
|
|
36
|
+
"""
|
|
37
|
+
modifier_tokens = {
|
|
38
|
+
'PUBLIC', 'PRIVATE', 'SEALED', 'ASYNC',
|
|
39
|
+
'NATIVE', 'INLINE', 'SECURE', 'PURE'
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
modifiers = []
|
|
43
|
+
remaining = []
|
|
44
|
+
|
|
45
|
+
for token in tokens:
|
|
46
|
+
if isinstance(token, str) and token.upper() in modifier_tokens:
|
|
47
|
+
modifiers.append(token.upper())
|
|
48
|
+
else:
|
|
49
|
+
remaining.append(token)
|
|
50
|
+
|
|
51
|
+
return modifiers, remaining
|
|
52
|
+
|
|
53
|
+
@staticmethod
|
|
54
|
+
def apply_macro_expansion(ast_node: Any) -> Any:
|
|
55
|
+
"""Apply metaprogramming macros to AST.
|
|
56
|
+
|
|
57
|
+
Phase 6: Metaprogramming
|
|
58
|
+
"""
|
|
59
|
+
try:
|
|
60
|
+
integration = get_integration()
|
|
61
|
+
return integration.meta_registry.apply_macros(ast_node)
|
|
62
|
+
except Exception:
|
|
63
|
+
# If metaprogramming fails, return original node
|
|
64
|
+
return ast_node
|
|
65
|
+
|
|
66
|
+
@staticmethod
|
|
67
|
+
def extract_function_signature(func_node: Any) -> Optional[dict]:
|
|
68
|
+
"""Extract function signature information.
|
|
69
|
+
|
|
70
|
+
Returns: {'name': str, 'params': List[str], 'modifiers': List[str]}
|
|
71
|
+
"""
|
|
72
|
+
if isinstance(func_node, (FunctionLiteral, ActionLiteral)):
|
|
73
|
+
params = []
|
|
74
|
+
if hasattr(func_node, 'parameters') and func_node.parameters:
|
|
75
|
+
params = [p.value if hasattr(p, 'value') else str(p) for p in func_node.parameters]
|
|
76
|
+
|
|
77
|
+
modifiers = getattr(func_node, 'modifiers', [])
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
'name': getattr(func_node, 'name', 'anonymous'),
|
|
81
|
+
'params': params,
|
|
82
|
+
'modifiers': modifiers,
|
|
83
|
+
'has_modifiers': len(modifiers) > 0
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return None
|