zexus 1.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/LICENSE +0 -0
  2. package/README.md +2513 -0
  3. package/bin/zexus +2 -0
  4. package/bin/zpics +2 -0
  5. package/bin/zpm +2 -0
  6. package/bin/zx +2 -0
  7. package/bin/zx-deploy +2 -0
  8. package/bin/zx-dev +2 -0
  9. package/bin/zx-run +2 -0
  10. package/package.json +66 -0
  11. package/scripts/README.md +24 -0
  12. package/scripts/postinstall.js +44 -0
  13. package/shared_config.json +24 -0
  14. package/src/README.md +1525 -0
  15. package/src/tests/run_zexus_tests.py +117 -0
  16. package/src/tests/test_all_phases.zx +346 -0
  17. package/src/tests/test_blockchain_features.zx +306 -0
  18. package/src/tests/test_complexity_features.zx +321 -0
  19. package/src/tests/test_core_integration.py +185 -0
  20. package/src/tests/test_phase10_ecosystem.zx +177 -0
  21. package/src/tests/test_phase1_modifiers.zx +87 -0
  22. package/src/tests/test_phase2_plugins.zx +80 -0
  23. package/src/tests/test_phase3_security.zx +97 -0
  24. package/src/tests/test_phase4_vfs.zx +116 -0
  25. package/src/tests/test_phase5_types.zx +117 -0
  26. package/src/tests/test_phase6_metaprogramming.zx +125 -0
  27. package/src/tests/test_phase7_optimization.zx +132 -0
  28. package/src/tests/test_phase9_advanced_types.zx +157 -0
  29. package/src/tests/test_security_features.py +419 -0
  30. package/src/tests/test_security_features.zx +276 -0
  31. package/src/tests/test_simple_zx.zx +1 -0
  32. package/src/tests/test_verification_simple.zx +69 -0
  33. package/src/zexus/__init__.py +28 -0
  34. package/src/zexus/__main__.py +5 -0
  35. package/src/zexus/__pycache__/__init__.cpython-312.pyc +0 -0
  36. package/src/zexus/__pycache__/advanced_types.cpython-312.pyc +0 -0
  37. package/src/zexus/__pycache__/builtin_modules.cpython-312.pyc +0 -0
  38. package/src/zexus/__pycache__/capability_system.cpython-312.pyc +0 -0
  39. package/src/zexus/__pycache__/complexity_system.cpython-312.pyc +0 -0
  40. package/src/zexus/__pycache__/concurrency_system.cpython-312.pyc +0 -0
  41. package/src/zexus/__pycache__/config.cpython-312.pyc +0 -0
  42. package/src/zexus/__pycache__/dependency_injection.cpython-312.pyc +0 -0
  43. package/src/zexus/__pycache__/ecosystem.cpython-312.pyc +0 -0
  44. package/src/zexus/__pycache__/environment.cpython-312.pyc +0 -0
  45. package/src/zexus/__pycache__/error_reporter.cpython-312.pyc +0 -0
  46. package/src/zexus/__pycache__/hybrid_orchestrator.cpython-312.pyc +0 -0
  47. package/src/zexus/__pycache__/lexer.cpython-312.pyc +0 -0
  48. package/src/zexus/__pycache__/metaprogramming.cpython-312.pyc +0 -0
  49. package/src/zexus/__pycache__/module_cache.cpython-312.pyc +0 -0
  50. package/src/zexus/__pycache__/object.cpython-312.pyc +0 -0
  51. package/src/zexus/__pycache__/optimization.cpython-312.pyc +0 -0
  52. package/src/zexus/__pycache__/plugin_system.cpython-312.pyc +0 -0
  53. package/src/zexus/__pycache__/policy_engine.cpython-312.pyc +0 -0
  54. package/src/zexus/__pycache__/security.cpython-312.pyc +0 -0
  55. package/src/zexus/__pycache__/stdlib_integration.cpython-312.pyc +0 -0
  56. package/src/zexus/__pycache__/strategy_recovery.cpython-312.pyc +0 -0
  57. package/src/zexus/__pycache__/syntax_validator.cpython-312.pyc +0 -0
  58. package/src/zexus/__pycache__/type_system.cpython-312.pyc +0 -0
  59. package/src/zexus/__pycache__/virtual_filesystem.cpython-312.pyc +0 -0
  60. package/src/zexus/__pycache__/zexus_ast.cpython-312.pyc +0 -0
  61. package/src/zexus/__pycache__/zexus_token.cpython-312.pyc +0 -0
  62. package/src/zexus/advanced_types.py +401 -0
  63. package/src/zexus/blockchain/__init__.py +40 -0
  64. package/src/zexus/blockchain/__pycache__/__init__.cpython-312.pyc +0 -0
  65. package/src/zexus/blockchain/__pycache__/crypto.cpython-312.pyc +0 -0
  66. package/src/zexus/blockchain/__pycache__/ledger.cpython-312.pyc +0 -0
  67. package/src/zexus/blockchain/__pycache__/transaction.cpython-312.pyc +0 -0
  68. package/src/zexus/blockchain/crypto.py +463 -0
  69. package/src/zexus/blockchain/ledger.py +255 -0
  70. package/src/zexus/blockchain/transaction.py +267 -0
  71. package/src/zexus/builtin_modules.py +284 -0
  72. package/src/zexus/builtin_plugins.py +317 -0
  73. package/src/zexus/capability_system.py +372 -0
  74. package/src/zexus/cli/__init__.py +2 -0
  75. package/src/zexus/cli/__pycache__/__init__.cpython-312.pyc +0 -0
  76. package/src/zexus/cli/__pycache__/main.cpython-312.pyc +0 -0
  77. package/src/zexus/cli/main.py +707 -0
  78. package/src/zexus/cli/zpm.py +203 -0
  79. package/src/zexus/compare_interpreter_compiler.py +146 -0
  80. package/src/zexus/compiler/__init__.py +169 -0
  81. package/src/zexus/compiler/__pycache__/__init__.cpython-312.pyc +0 -0
  82. package/src/zexus/compiler/__pycache__/lexer.cpython-312.pyc +0 -0
  83. package/src/zexus/compiler/__pycache__/parser.cpython-312.pyc +0 -0
  84. package/src/zexus/compiler/__pycache__/zexus_ast.cpython-312.pyc +0 -0
  85. package/src/zexus/compiler/bytecode.py +266 -0
  86. package/src/zexus/compiler/compat_runtime.py +277 -0
  87. package/src/zexus/compiler/lexer.py +257 -0
  88. package/src/zexus/compiler/parser.py +779 -0
  89. package/src/zexus/compiler/semantic.py +118 -0
  90. package/src/zexus/compiler/zexus_ast.py +454 -0
  91. package/src/zexus/complexity_system.py +575 -0
  92. package/src/zexus/concurrency_system.py +493 -0
  93. package/src/zexus/config.py +201 -0
  94. package/src/zexus/crypto_bridge.py +19 -0
  95. package/src/zexus/dependency_injection.py +423 -0
  96. package/src/zexus/ecosystem.py +434 -0
  97. package/src/zexus/environment.py +101 -0
  98. package/src/zexus/environment_manager.py +119 -0
  99. package/src/zexus/error_reporter.py +314 -0
  100. package/src/zexus/evaluator/__init__.py +12 -0
  101. package/src/zexus/evaluator/__pycache__/__init__.cpython-312.pyc +0 -0
  102. package/src/zexus/evaluator/__pycache__/bytecode_compiler.cpython-312.pyc +0 -0
  103. package/src/zexus/evaluator/__pycache__/core.cpython-312.pyc +0 -0
  104. package/src/zexus/evaluator/__pycache__/expressions.cpython-312.pyc +0 -0
  105. package/src/zexus/evaluator/__pycache__/functions.cpython-312.pyc +0 -0
  106. package/src/zexus/evaluator/__pycache__/integration.cpython-312.pyc +0 -0
  107. package/src/zexus/evaluator/__pycache__/statements.cpython-312.pyc +0 -0
  108. package/src/zexus/evaluator/__pycache__/utils.cpython-312.pyc +0 -0
  109. package/src/zexus/evaluator/bytecode_compiler.py +700 -0
  110. package/src/zexus/evaluator/core.py +891 -0
  111. package/src/zexus/evaluator/expressions.py +827 -0
  112. package/src/zexus/evaluator/functions.py +3989 -0
  113. package/src/zexus/evaluator/integration.py +396 -0
  114. package/src/zexus/evaluator/statements.py +4303 -0
  115. package/src/zexus/evaluator/utils.py +126 -0
  116. package/src/zexus/evaluator_original.py +2041 -0
  117. package/src/zexus/external_bridge.py +16 -0
  118. package/src/zexus/find_affected_imports.sh +155 -0
  119. package/src/zexus/hybrid_orchestrator.py +152 -0
  120. package/src/zexus/input_validation.py +259 -0
  121. package/src/zexus/lexer.py +571 -0
  122. package/src/zexus/logging.py +89 -0
  123. package/src/zexus/lsp/__init__.py +9 -0
  124. package/src/zexus/lsp/completion_provider.py +207 -0
  125. package/src/zexus/lsp/definition_provider.py +22 -0
  126. package/src/zexus/lsp/hover_provider.py +71 -0
  127. package/src/zexus/lsp/server.py +269 -0
  128. package/src/zexus/lsp/symbol_provider.py +31 -0
  129. package/src/zexus/metaprogramming.py +321 -0
  130. package/src/zexus/module_cache.py +89 -0
  131. package/src/zexus/module_manager.py +107 -0
  132. package/src/zexus/object.py +973 -0
  133. package/src/zexus/optimization.py +424 -0
  134. package/src/zexus/parser/__init__.py +31 -0
  135. package/src/zexus/parser/__pycache__/__init__.cpython-312.pyc +0 -0
  136. package/src/zexus/parser/__pycache__/parser.cpython-312.pyc +0 -0
  137. package/src/zexus/parser/__pycache__/strategy_context.cpython-312.pyc +0 -0
  138. package/src/zexus/parser/__pycache__/strategy_structural.cpython-312.pyc +0 -0
  139. package/src/zexus/parser/integration.py +86 -0
  140. package/src/zexus/parser/parser.py +3977 -0
  141. package/src/zexus/parser/strategy_context.py +7254 -0
  142. package/src/zexus/parser/strategy_structural.py +1033 -0
  143. package/src/zexus/persistence.py +391 -0
  144. package/src/zexus/plugin_system.py +290 -0
  145. package/src/zexus/policy_engine.py +365 -0
  146. package/src/zexus/profiler/__init__.py +5 -0
  147. package/src/zexus/profiler/profiler.py +233 -0
  148. package/src/zexus/purity_system.py +398 -0
  149. package/src/zexus/runtime/__init__.py +20 -0
  150. package/src/zexus/runtime/async_runtime.py +324 -0
  151. package/src/zexus/search_old_imports.sh +65 -0
  152. package/src/zexus/security.py +1407 -0
  153. package/src/zexus/stack_trace.py +233 -0
  154. package/src/zexus/stdlib/__init__.py +27 -0
  155. package/src/zexus/stdlib/blockchain.py +341 -0
  156. package/src/zexus/stdlib/compression.py +167 -0
  157. package/src/zexus/stdlib/crypto.py +124 -0
  158. package/src/zexus/stdlib/datetime.py +163 -0
  159. package/src/zexus/stdlib/db_mongo.py +199 -0
  160. package/src/zexus/stdlib/db_mysql.py +162 -0
  161. package/src/zexus/stdlib/db_postgres.py +163 -0
  162. package/src/zexus/stdlib/db_sqlite.py +133 -0
  163. package/src/zexus/stdlib/encoding.py +230 -0
  164. package/src/zexus/stdlib/fs.py +195 -0
  165. package/src/zexus/stdlib/http.py +219 -0
  166. package/src/zexus/stdlib/http_server.py +248 -0
  167. package/src/zexus/stdlib/json_module.py +61 -0
  168. package/src/zexus/stdlib/math.py +360 -0
  169. package/src/zexus/stdlib/os_module.py +265 -0
  170. package/src/zexus/stdlib/regex.py +148 -0
  171. package/src/zexus/stdlib/sockets.py +253 -0
  172. package/src/zexus/stdlib/test_framework.zx +208 -0
  173. package/src/zexus/stdlib/test_runner.zx +119 -0
  174. package/src/zexus/stdlib_integration.py +341 -0
  175. package/src/zexus/strategy_recovery.py +256 -0
  176. package/src/zexus/syntax_validator.py +356 -0
  177. package/src/zexus/testing/zpics.py +407 -0
  178. package/src/zexus/testing/zpics_runtime.py +369 -0
  179. package/src/zexus/type_system.py +374 -0
  180. package/src/zexus/validation_system.py +569 -0
  181. package/src/zexus/virtual_filesystem.py +355 -0
  182. package/src/zexus/vm/__init__.py +8 -0
  183. package/src/zexus/vm/__pycache__/__init__.cpython-312.pyc +0 -0
  184. package/src/zexus/vm/__pycache__/async_optimizer.cpython-312.pyc +0 -0
  185. package/src/zexus/vm/__pycache__/bytecode.cpython-312.pyc +0 -0
  186. package/src/zexus/vm/__pycache__/cache.cpython-312.pyc +0 -0
  187. package/src/zexus/vm/__pycache__/jit.cpython-312.pyc +0 -0
  188. package/src/zexus/vm/__pycache__/memory_manager.cpython-312.pyc +0 -0
  189. package/src/zexus/vm/__pycache__/memory_pool.cpython-312.pyc +0 -0
  190. package/src/zexus/vm/__pycache__/optimizer.cpython-312.pyc +0 -0
  191. package/src/zexus/vm/__pycache__/parallel_vm.cpython-312.pyc +0 -0
  192. package/src/zexus/vm/__pycache__/peephole_optimizer.cpython-312.pyc +0 -0
  193. package/src/zexus/vm/__pycache__/profiler.cpython-312.pyc +0 -0
  194. package/src/zexus/vm/__pycache__/register_allocator.cpython-312.pyc +0 -0
  195. package/src/zexus/vm/__pycache__/register_vm.cpython-312.pyc +0 -0
  196. package/src/zexus/vm/__pycache__/ssa_converter.cpython-312.pyc +0 -0
  197. package/src/zexus/vm/__pycache__/vm.cpython-312.pyc +0 -0
  198. package/src/zexus/vm/async_optimizer.py +420 -0
  199. package/src/zexus/vm/bytecode.py +428 -0
  200. package/src/zexus/vm/bytecode_converter.py +297 -0
  201. package/src/zexus/vm/cache.py +532 -0
  202. package/src/zexus/vm/jit.py +720 -0
  203. package/src/zexus/vm/memory_manager.py +520 -0
  204. package/src/zexus/vm/memory_pool.py +511 -0
  205. package/src/zexus/vm/optimizer.py +478 -0
  206. package/src/zexus/vm/parallel_vm.py +899 -0
  207. package/src/zexus/vm/peephole_optimizer.py +452 -0
  208. package/src/zexus/vm/profiler.py +527 -0
  209. package/src/zexus/vm/register_allocator.py +462 -0
  210. package/src/zexus/vm/register_vm.py +520 -0
  211. package/src/zexus/vm/ssa_converter.py +757 -0
  212. package/src/zexus/vm/vm.py +1392 -0
  213. package/src/zexus/zexus_ast.py +1782 -0
  214. package/src/zexus/zexus_token.py +253 -0
  215. package/src/zexus/zpm/__init__.py +15 -0
  216. package/src/zexus/zpm/installer.py +116 -0
  217. package/src/zexus/zpm/package_manager.py +208 -0
  218. package/src/zexus/zpm/publisher.py +98 -0
  219. package/src/zexus/zpm/registry.py +110 -0
  220. package/src/zexus.egg-info/PKG-INFO +2235 -0
  221. package/src/zexus.egg-info/SOURCES.txt +876 -0
  222. package/src/zexus.egg-info/dependency_links.txt +1 -0
  223. package/src/zexus.egg-info/entry_points.txt +3 -0
  224. package/src/zexus.egg-info/not-zip-safe +1 -0
  225. package/src/zexus.egg-info/requires.txt +14 -0
  226. package/src/zexus.egg-info/top_level.txt +2 -0
  227. package/zexus.json +14 -0
@@ -0,0 +1,1782 @@
1
+ # src/zexus/zexus_ast.py
2
+
3
+ # Base classes
4
+ class Node:
5
+ def __repr__(self):
6
+ return f"{self.__class__.__name__}()"
7
+
8
+ def __str__(self):
9
+ return self.__repr__()
10
+
11
+ class Statement(Node): pass
12
+ class Expression(Node): pass
13
+
14
+ class Program(Node):
15
+ def __init__(self):
16
+ self.statements = []
17
+
18
+ def __repr__(self):
19
+ return f"Program(statements={len(self.statements)})"
20
+
21
+ # Statement Nodes
22
+ class LetStatement(Statement):
23
+ def __init__(self, name, value, type_annotation=None):
24
+ self.name = name
25
+ self.value = value
26
+ self.type_annotation = type_annotation
27
+
28
+ def __repr__(self):
29
+ type_str = f", type={self.type_annotation}" if self.type_annotation else ""
30
+ return f"LetStatement(name={self.name}, value={self.value}{type_str})"
31
+
32
+ class ConstStatement(Statement):
33
+ """Const statement - immutable variable declaration
34
+
35
+ const MAX_VALUE = 100;
36
+ """
37
+ def __init__(self, name, value):
38
+ self.name = name
39
+ self.value = value
40
+
41
+ def __repr__(self):
42
+ return f"ConstStatement(name={self.name}, value={self.value})"
43
+
44
+ class DataStatement(Statement):
45
+ """Data statement - dataclass definition
46
+
47
+ data User {
48
+ name: string,
49
+ email: string,
50
+ age: number
51
+ }
52
+
53
+ data Admin extends User {
54
+ permissions: array
55
+ }
56
+
57
+ @validated
58
+ data Email {
59
+ address: string
60
+ }
61
+
62
+ data Box<T> {
63
+ value: T
64
+ }
65
+
66
+ Creates a structured type with automatic methods:
67
+ - Constructor
68
+ - toString(), toJSON(), fromJSON()
69
+ - equals(), clone(), hash()
70
+ """
71
+ def __init__(self, name, fields, modifiers=None, parent=None, decorators=None, type_params=None):
72
+ self.name = name # Identifier: class name
73
+ self.fields = fields # List of DataField objects
74
+ self.modifiers = modifiers or [] # List of modifiers: ["immutable", "verified", etc.]
75
+ self.parent = parent # String: parent dataclass name (for inheritance)
76
+ self.decorators = decorators or [] # List of decorator names: ["validated", "logged", etc.]
77
+ self.type_params = type_params or [] # List of type parameter names: ["T", "U", "V"]
78
+
79
+ def __repr__(self):
80
+ mods = f", modifiers={self.modifiers}" if self.modifiers else ""
81
+ parent = f", extends={self.parent}" if self.parent else ""
82
+ decs = f", decorators={self.decorators}" if self.decorators else ""
83
+ tparams = f", type_params={self.type_params}" if self.type_params else ""
84
+ return f"DataStatement(name={self.name}, fields={self.fields}{mods}{parent}{decs}{tparams})"
85
+
86
+ class DataField:
87
+ """Field definition in a dataclass
88
+
89
+ name: string = "default" require len(name) > 0
90
+ method area() { return this.width * this.height; }
91
+ operator +(other) { return Point(this.x + other.x, this.y + other.y); }
92
+
93
+ @logged
94
+ method calculate() { ... }
95
+ """
96
+ def __init__(self, name, field_type=None, default_value=None, constraint=None, computed=None, method_body=None, method_params=None, operator=None, decorators=None):
97
+ self.name = name # Identifier: field name
98
+ self.field_type = field_type # String: type annotation (optional)
99
+ self.default_value = default_value # Expression: default value (optional)
100
+ self.constraint = constraint # Expression: validation constraint (optional)
101
+ self.computed = computed # Expression: computed property (optional)
102
+ self.method_body = method_body # BlockStatement: method body (optional)
103
+ self.method_params = method_params or [] # List of parameters for method
104
+ self.operator = operator # String: operator symbol (+, -, *, /, ==, etc.)
105
+ self.decorators = decorators or [] # List of decorator names for methods
106
+
107
+ def __repr__(self):
108
+ parts = [f"name={self.name}"]
109
+ if self.field_type:
110
+ parts.append(f"type={self.field_type}")
111
+ if self.default_value:
112
+ parts.append(f"default={self.default_value}")
113
+ if self.constraint:
114
+ parts.append(f"require={self.constraint}")
115
+ if self.computed:
116
+ parts.append(f"computed={self.computed}")
117
+ return f"DataField({', '.join(parts)})"
118
+
119
+ class ReturnStatement(Statement):
120
+ def __init__(self, return_value):
121
+ self.return_value = return_value
122
+
123
+ def __repr__(self):
124
+ return f"ReturnStatement(return_value={self.return_value})"
125
+
126
+ class ContinueStatement(Statement):
127
+ """Continue on error - allows program to continue execution even on errors."""
128
+ def __init__(self):
129
+ pass
130
+
131
+ def __repr__(self):
132
+ return "ContinueStatement()"
133
+
134
+ class BreakStatement(Statement):
135
+ """Break statement - exits the current loop."""
136
+ def __init__(self):
137
+ pass
138
+
139
+ def __repr__(self):
140
+ return "BreakStatement()"
141
+
142
+ class ThrowStatement(Statement):
143
+ """Throw statement - throws an error/exception."""
144
+ def __init__(self, message):
145
+ self.message = message
146
+
147
+ def __repr__(self):
148
+ return f"ThrowStatement(message={self.message})"
149
+
150
+ class ExpressionStatement(Statement):
151
+ def __init__(self, expression):
152
+ self.expression = expression
153
+
154
+ def __repr__(self):
155
+ return f"ExpressionStatement(expression={self.expression})"
156
+
157
+ class BlockStatement(Statement):
158
+ def __init__(self):
159
+ self.statements = []
160
+
161
+ def __repr__(self):
162
+ return f"BlockStatement(statements={len(self.statements)})"
163
+
164
+ class TxStatement(Statement):
165
+ """Transaction block statement - executes statements in transactional context
166
+
167
+ tx {
168
+ balance = balance - amount;
169
+ recipient_balance = recipient_balance + amount;
170
+ }
171
+ """
172
+ def __init__(self, body):
173
+ self.body = body # BlockStatement
174
+
175
+ def __repr__(self):
176
+ return f"TxStatement(body={self.body})"
177
+
178
+ class PrintStatement(Statement):
179
+ def __init__(self, value=None, values=None, condition=None):
180
+ # Support both single value (legacy) and multiple values
181
+ # condition: optional condition expression (for conditional printing)
182
+ self.value = value
183
+ self.values = values if values is not None else ([value] if value is not None else [])
184
+ self.condition = condition
185
+
186
+ def __repr__(self):
187
+ if self.condition:
188
+ return f"PrintStatement(condition={self.condition}, values={self.values})"
189
+ return f"PrintStatement(values={self.values})"
190
+
191
+ class ForEachStatement(Statement):
192
+ def __init__(self, item, iterable, body):
193
+ self.item = item; self.iterable = iterable; self.body = body
194
+
195
+ def __repr__(self):
196
+ return f"ForEachStatement(item={self.item}, iterable={self.iterable})"
197
+
198
+ class EmbeddedCodeStatement(Statement):
199
+ def __init__(self, name, language, code):
200
+ self.name = name
201
+ self.language = language
202
+ self.code = code
203
+
204
+ def __repr__(self):
205
+ return f"EmbeddedCodeStatement(name={self.name}, language={self.language})"
206
+
207
+ class UseStatement(Statement):
208
+ def __init__(self, file_path, alias=None, names=None, is_named_import=False):
209
+ self.file_path = file_path # StringLiteral or string path
210
+ self.alias = alias # Optional Identifier for alias
211
+ self.names = names or [] # List of Identifiers for named imports
212
+ self.is_named_import = is_named_import
213
+
214
+ def __repr__(self):
215
+ if self.is_named_import:
216
+ names_list = [str(n.value if hasattr(n, 'value') else n) for n in self.names]
217
+ return f"UseStatement(file='{self.file_path}', names={names_list})"
218
+ alias_str = f", alias={self.alias}" if self.alias else ""
219
+ return f"UseStatement(file_path={self.file_path}{alias_str})"
220
+
221
+ def __str__(self):
222
+ if self.is_named_import:
223
+ names_str = ", ".join([str(n.value if hasattr(n, 'value') else n) for n in self.names])
224
+ return f"use {{ {names_str} }} from '{self.file_path}'"
225
+ elif self.alias:
226
+ alias_val = self.alias.value if hasattr(self.alias, 'value') else self.alias
227
+ return f"use '{self.file_path}' as {alias_val}"
228
+ else:
229
+ return f"use '{self.file_path}'"
230
+
231
+ class FromStatement(Statement):
232
+ def __init__(self, file_path, imports=None):
233
+ self.file_path = file_path # StringLiteral for file path
234
+ self.imports = imports or [] # List of (Identifier, Optional Identifier) for name and alias
235
+
236
+ def __repr__(self):
237
+ return f"FromStatement(file_path={self.file_path}, imports={len(self.imports)})"
238
+
239
+ class IfStatement(Statement):
240
+ def __init__(self, condition, consequence, elif_parts=None, alternative=None):
241
+ self.condition = condition
242
+ self.consequence = consequence
243
+ self.elif_parts = elif_parts or [] # List of (condition, consequence) tuples for elif chains
244
+ self.alternative = alternative
245
+
246
+ def __repr__(self):
247
+ return f"IfStatement(condition={self.condition}, elif_parts={len(self.elif_parts)})"
248
+
249
+ class WhileStatement(Statement):
250
+ def __init__(self, condition, body):
251
+ self.condition = condition
252
+ self.body = body
253
+
254
+ def __repr__(self):
255
+ return f"WhileStatement(condition={self.condition})"
256
+
257
+ class ScreenStatement(Statement):
258
+ def __init__(self, name, body):
259
+ self.name = name
260
+ self.body = body
261
+
262
+ def __repr__(self):
263
+ return f"ScreenStatement(name={self.name})"
264
+
265
+ # NEW: Component and Theme AST nodes for interpreter
266
+ class ComponentStatement(Statement):
267
+ def __init__(self, name, properties):
268
+ self.name = name
269
+ self.properties = properties # expected to be MapLiteral or BlockStatement
270
+
271
+ def __repr__(self):
272
+ return f"ComponentStatement(name={self.name}, properties={self.properties})"
273
+
274
+ class ThemeStatement(Statement):
275
+ def __init__(self, name, properties):
276
+ self.name = name
277
+ self.properties = properties # expected to be MapLiteral or BlockStatement
278
+
279
+ def __repr__(self):
280
+ return f"ThemeStatement(name={self.name}, properties={self.properties})"
281
+
282
+ class ActionStatement(Statement):
283
+ def __init__(self, name, parameters, body, is_async=False, return_type=None):
284
+ self.name = name
285
+ self.parameters = parameters
286
+ self.body = body
287
+ self.is_async = is_async
288
+ self.return_type = return_type
289
+
290
+ def __repr__(self):
291
+ async_str = "async " if self.is_async else ""
292
+ return_type_str = f" -> {self.return_type}" if self.return_type else ""
293
+ return f"ActionStatement({async_str}name={self.name}, parameters={len(self.parameters)}{return_type_str})"
294
+
295
+ class FunctionStatement(Statement):
296
+ def __init__(self, name, parameters, body, return_type=None):
297
+ self.name = name
298
+ self.parameters = parameters
299
+ self.body = body
300
+ self.return_type = return_type
301
+
302
+ def __repr__(self):
303
+ return_type_str = f" -> {self.return_type}" if self.return_type else ""
304
+ return f"FunctionStatement(name={self.name}, parameters={len(self.parameters)}{return_type_str})"
305
+
306
+ class ExactlyStatement(Statement):
307
+ def __init__(self, name, body):
308
+ self.name = name
309
+ self.body = body
310
+
311
+ def __repr__(self):
312
+ return f"ExactlyStatement(name={self.name})"
313
+
314
+ # Export statement
315
+ class ExportStatement(Statement):
316
+ def __init__(self, name=None, names=None, allowed_files=None, permission=None):
317
+ # `names` is a list of Identifier nodes; `name` kept for backward compatibility (first item)
318
+ self.names = names or ([] if names is not None else ([name] if name is not None else []))
319
+ self.name = self.names[0] if self.names else name
320
+ self.allowed_files = allowed_files or []
321
+ self.permission = permission or "read_only"
322
+
323
+ def __repr__(self):
324
+ names = [n.value if hasattr(n, 'value') else str(n) for n in self.names]
325
+ return f"ExportStatement(names={names}, files={len(self.allowed_files)}, permission='{self.permission}')"
326
+
327
+ # NEW: Debug statement
328
+ class DebugStatement(Statement):
329
+ def __init__(self, value, condition=None):
330
+ # value: expression to debug print
331
+ # condition: optional condition expression (for conditional debugging)
332
+ self.value = value
333
+ self.condition = condition
334
+
335
+ def __repr__(self):
336
+ if self.condition:
337
+ return f"DebugStatement(condition={self.condition}, value={self.value})"
338
+ return f"DebugStatement(value={self.value})"
339
+
340
+ # NEW: Try-catch statement
341
+ class TryCatchStatement(Statement):
342
+ def __init__(self, try_block, error_variable, catch_block):
343
+ self.try_block = try_block
344
+ self.error_variable = error_variable
345
+ self.catch_block = catch_block
346
+
347
+ def __repr__(self):
348
+ return f"TryCatchStatement(error_var={self.error_variable})"
349
+
350
+ # NEW: External function declaration
351
+ class ExternalDeclaration(Statement):
352
+ def __init__(self, name, parameters, module_path):
353
+ self.name = name
354
+ self.parameters = parameters
355
+ self.module_path = module_path
356
+
357
+ def __repr__(self):
358
+ return f"ExternalDeclaration(name={self.name}, module={self.module_path})"
359
+
360
+ class AuditStatement(Statement):
361
+ """Audit statement - Log data access for compliance
362
+
363
+ audit user_data, "access", timestamp;
364
+ audit CONFIG, "modification", current_time;
365
+ """
366
+ def __init__(self, data_name, action_type, timestamp=None):
367
+ self.data_name = data_name # Variable/identifier to audit
368
+ self.action_type = action_type # String: "access", "modification", "deletion", etc.
369
+ self.timestamp = timestamp # Optional timestamp expression
370
+
371
+ def __repr__(self):
372
+ return f"AuditStatement(data={self.data_name}, action={self.action_type}, timestamp={self.timestamp})"
373
+
374
+ class RestrictStatement(Statement):
375
+ """Restrict statement - Field-level access control
376
+
377
+ restrict obj.field = "read-only";
378
+ restrict user.password = "deny";
379
+ restrict config.api_key = "admin-only";
380
+ """
381
+ def __init__(self, target, restriction_type):
382
+ self.target = target # PropertyAccessExpression for obj.field
383
+ self.restriction_type = restriction_type # String: "read-only", "deny", "admin-only", etc.
384
+
385
+ def __repr__(self):
386
+ return f"RestrictStatement(target={self.target}, restriction={self.restriction_type})"
387
+
388
+ class SandboxStatement(Statement):
389
+ """Sandbox statement - Isolated execution environment
390
+
391
+ sandbox {
392
+ // code runs in isolated context
393
+ let x = unsafe_operation();
394
+ }
395
+ """
396
+ def __init__(self, body, policy=None):
397
+ self.body = body # BlockStatement containing sandboxed code
398
+ self.policy = policy # Optional policy name (string)
399
+
400
+ def __repr__(self):
401
+ return f"SandboxStatement(body={self.body}, policy={self.policy})"
402
+
403
+ class TrailStatement(Statement):
404
+ """Trail statement - Real-time audit/debug/print tracking
405
+
406
+ trail audit; // follow all audit events
407
+ trail print; // follow all print statements
408
+ trail debug; // follow all debug output
409
+ trail *, "resource_access"; // trail all events for resource_access
410
+ """
411
+ def __init__(self, trail_type, filter_key=None):
412
+ self.trail_type = trail_type # String: "audit", "print", "debug", "*"
413
+ self.filter_key = filter_key # Optional filter/pattern
414
+
415
+ def __repr__(self):
416
+ return f"TrailStatement(type={self.trail_type}, filter={self.filter_key})"
417
+
418
+ # Expression Nodes
419
+ class Identifier(Expression):
420
+ def __init__(self, value):
421
+ self.value = value
422
+
423
+ def __repr__(self):
424
+ return f"Identifier('{self.value}')"
425
+
426
+ def __str__(self):
427
+ return self.value
428
+
429
+ class IntegerLiteral(Expression):
430
+ def __init__(self, value):
431
+ self.value = value
432
+
433
+ def __repr__(self):
434
+ return f"IntegerLiteral({self.value})"
435
+
436
+ class FloatLiteral(Expression):
437
+ def __init__(self, value):
438
+ self.value = value
439
+
440
+ def __repr__(self):
441
+ return f"FloatLiteral({self.value})"
442
+
443
+ class StringLiteral(Expression):
444
+ def __init__(self, value):
445
+ self.value = value
446
+
447
+ def __repr__(self):
448
+ return f"StringLiteral('{self.value}')"
449
+
450
+ def __str__(self):
451
+ return self.value
452
+
453
+ class Boolean(Expression):
454
+ def __init__(self, value):
455
+ self.value = value
456
+
457
+ def __repr__(self):
458
+ return f"Boolean({self.value})"
459
+
460
+ class NullLiteral(Expression):
461
+ def __repr__(self):
462
+ return "NullLiteral()"
463
+
464
+
465
+ class ThisExpression(Expression):
466
+ """This expression - reference to current contract instance
467
+
468
+ this.balances[account]
469
+ this.owner = TX.caller
470
+ """
471
+ def __repr__(self):
472
+ return "ThisExpression()"
473
+
474
+
475
+ class ListLiteral(Expression):
476
+ def __init__(self, elements):
477
+ self.elements = elements
478
+
479
+ def __repr__(self):
480
+ return f"ListLiteral(elements={len(self.elements)})"
481
+
482
+ class MapLiteral(Expression):
483
+ def __init__(self, pairs):
484
+ self.pairs = pairs
485
+
486
+ def __repr__(self):
487
+ return f"MapLiteral(pairs={len(self.pairs)})"
488
+
489
+ class ActionLiteral(Expression):
490
+ def __init__(self, parameters, body):
491
+ self.parameters = parameters
492
+ self.body = body
493
+
494
+ def __repr__(self):
495
+ return f"ActionLiteral(parameters={len(self.parameters)})"
496
+
497
+ # Lambda expression
498
+ class LambdaExpression(Expression):
499
+ def __init__(self, parameters, body):
500
+ self.parameters = parameters
501
+ self.body = body
502
+
503
+ def __repr__(self):
504
+ return f"LambdaExpression(parameters={len(self.parameters)})"
505
+
506
+ class CallExpression(Expression):
507
+ def __init__(self, function, arguments, type_args=None):
508
+ self.function = function
509
+ self.arguments = arguments
510
+ self.type_args = type_args or [] # List of type arguments for generic instantiation: Box<number>
511
+
512
+ def __repr__(self):
513
+ targs = f", type_args={self.type_args}" if self.type_args else ""
514
+ return f"CallExpression(function={self.function}, arguments={len(self.arguments)}{targs})"
515
+
516
+ class AsyncExpression(Expression):
517
+ """Async expression: async <expression>
518
+
519
+ Executes the expression asynchronously in a background thread.
520
+ Example: async producer()
521
+ """
522
+ def __init__(self, expression):
523
+ self.expression = expression # The expression to execute asynchronously
524
+
525
+ def __repr__(self):
526
+ return f"AsyncExpression(expression={self.expression})"
527
+
528
+ class MethodCallExpression(Expression):
529
+ def __init__(self, object, method, arguments):
530
+ self.object = object
531
+ self.method = method
532
+ self.arguments = arguments
533
+
534
+ def __repr__(self):
535
+ return f"MethodCallExpression(object={self.object}, method={self.method})"
536
+
537
+ class MatchExpression(Expression):
538
+ """Match expression for pattern matching
539
+
540
+ match value {
541
+ Point(x, y) => x + y,
542
+ User(name, _) => name,
543
+ 42 => "the answer",
544
+ _ => "default"
545
+ }
546
+ """
547
+ def __init__(self, value, cases):
548
+ self.value = value # Expression: value to match against
549
+ self.cases = cases # List[MatchCase]: pattern cases
550
+
551
+ def __repr__(self):
552
+ return f"MatchExpression(value={self.value}, cases={len(self.cases)})"
553
+
554
+ class MatchCase:
555
+ """A single match case with pattern and result expression"""
556
+ def __init__(self, pattern, result):
557
+ self.pattern = pattern # Pattern: pattern to match
558
+ self.result = result # Expression: result if matched
559
+
560
+ def __repr__(self):
561
+ return f"MatchCase(pattern={self.pattern}, result={self.result})"
562
+
563
+ # Pattern nodes for destructuring
564
+ class ConstructorPattern:
565
+ """Constructor pattern: Point(x, y)"""
566
+ def __init__(self, constructor_name, bindings):
567
+ self.constructor_name = constructor_name # String: type name
568
+ self.bindings = bindings # List[Pattern]: nested patterns or variable names
569
+
570
+ def __repr__(self):
571
+ return f"ConstructorPattern({self.constructor_name}, bindings={self.bindings})"
572
+
573
+ class VariablePattern:
574
+ """Variable binding pattern: x, name, value"""
575
+ def __init__(self, name):
576
+ self.name = name # String: variable name to bind
577
+
578
+ def __repr__(self):
579
+ return f"VariablePattern({self.name})"
580
+
581
+ class WildcardPattern:
582
+ """Wildcard pattern: _ (matches anything, no binding)"""
583
+ def __repr__(self):
584
+ return "WildcardPattern(_)"
585
+
586
+ class LiteralPattern:
587
+ """Literal pattern: 42, "hello", true"""
588
+ def __init__(self, value):
589
+ self.value = value # Literal value (IntegerLiteral, StringLiteral, etc.)
590
+
591
+ def __repr__(self):
592
+ return f"LiteralPattern({self.value})"
593
+
594
+ class PropertyAccessExpression(Expression):
595
+ def __init__(self, object, property):
596
+ self.object = object
597
+ self.property = property
598
+
599
+ def __repr__(self):
600
+ return f"PropertyAccessExpression(object={self.object}, property={self.property})"
601
+
602
+ class AssignmentExpression(Expression):
603
+ def __init__(self, name, value):
604
+ self.name = name
605
+ self.value = value
606
+
607
+ def __repr__(self):
608
+ return f"AssignmentExpression(name={self.name}, value={self.value})"
609
+
610
+ class AwaitExpression(Expression):
611
+ def __init__(self, expression):
612
+ self.expression = expression
613
+
614
+ def token_literal(self):
615
+ return "await"
616
+
617
+ def string(self):
618
+ return f"await {self.expression}"
619
+
620
+ def __repr__(self):
621
+ return f"AwaitExpression(expression={self.expression})"
622
+
623
+ class FileImportExpression(Expression):
624
+ """File import expression for << operator
625
+
626
+ let code << "filename.ext"
627
+
628
+ Reads the file contents and returns as a string.
629
+ Supports any file extension.
630
+ """
631
+ def __init__(self, filepath):
632
+ self.filepath = filepath # Expression: path to file
633
+
634
+ def __repr__(self):
635
+ return f"FileImportExpression(<< {self.filepath})"
636
+
637
+ class EmbeddedLiteral(Expression):
638
+ def __init__(self, language, code):
639
+ self.language = language
640
+ self.code = code
641
+
642
+ def __repr__(self):
643
+ return f"EmbeddedLiteral(language={self.language})"
644
+
645
+ class PrefixExpression(Expression):
646
+ def __init__(self, operator, right):
647
+ self.operator = operator; self.right = right
648
+
649
+ def __repr__(self):
650
+ return f"PrefixExpression(operator='{self.operator}', right={self.right})"
651
+
652
+ class InfixExpression(Expression):
653
+ def __init__(self, left, operator, right):
654
+ self.left = left; self.operator = operator; self.right = right
655
+
656
+ def __repr__(self):
657
+ return f"InfixExpression(left={self.left}, operator='{self.operator}', right={self.right})"
658
+
659
+ class IfExpression(Expression):
660
+ def __init__(self, condition, consequence, elif_parts=None, alternative=None):
661
+ self.condition = condition
662
+ self.consequence = consequence
663
+ self.elif_parts = elif_parts or [] # List of (condition, consequence) tuples for elif chains
664
+ self.alternative = alternative
665
+
666
+ def __repr__(self):
667
+ return f"IfExpression(condition={self.condition}, elif_parts={len(self.elif_parts)})"
668
+
669
+ class TernaryExpression(Expression):
670
+ """Represents: condition ? true_value : false_value"""
671
+ def __init__(self, condition, true_value, false_value):
672
+ self.condition = condition
673
+ self.true_value = true_value
674
+ self.false_value = false_value
675
+
676
+ def __repr__(self):
677
+ return f"TernaryExpression(condition={self.condition}, true={self.true_value}, false={self.false_value})"
678
+
679
+ class NullishExpression(Expression):
680
+ """Represents: value ?? default (returns default if value is null/undefined)"""
681
+ def __init__(self, left, right):
682
+ self.left = left
683
+ self.right = right
684
+
685
+ def __repr__(self):
686
+ return f"NullishExpression(left={self.left}, default={self.right})"
687
+
688
+
689
+ # =====================================================
690
+ # NEW: ENTITY, VERIFY, CONTRACT, PROTECT STATEMENTS
691
+ # =====================================================
692
+
693
+ class EntityStatement(Statement):
694
+ """Entity declaration - advanced OOP with inheritance from let
695
+
696
+ entity User {
697
+ name: string,
698
+ email: string,
699
+ role: string = "user"
700
+ }
701
+ """
702
+ def __init__(self, name, properties, parent=None, methods=None):
703
+ self.name = name # Identifier
704
+ self.properties = properties # List of dicts: {name, type, default_value}
705
+ self.parent = parent # Optional parent entity (inheritance)
706
+ self.methods = methods or [] # List of ActionStatement
707
+
708
+ def __repr__(self):
709
+ return f"EntityStatement(name={self.name}, properties={len(self.properties)})"
710
+
711
+ def __str__(self):
712
+ name_str = self.name.value if hasattr(self.name, 'value') else str(self.name)
713
+ props_str = ",\n ".join([f"{prop['name']}: {prop['type']}" for prop in self.properties])
714
+ return f"entity {name_str} {{\n {props_str}\n}}"
715
+
716
+
717
+ class VerifyStatement(Statement):
718
+ r"""Verify security checks - supports multiple forms:
719
+
720
+ Simple assertion:
721
+ verify condition, "error message"
722
+
723
+ Complex verification wrapper:
724
+ verify(transfer_funds, [
725
+ check_authenticated(),
726
+ check_balance(amount),
727
+ check_whitelist(recipient)
728
+ ])
729
+
730
+ Data/format verification:
731
+ verify:data input matches email_pattern, "Invalid email"
732
+ verify:data input is_type "string", "Must be string"
733
+
734
+ Access control (blocks on failure):
735
+ verify:access user.role == "admin" {
736
+ log_unauthorized_access(user);
737
+ block_request();
738
+ }
739
+
740
+ Database verification:
741
+ verify:db user_id exists_in "users", "User not found"
742
+ verify:db email unique_in "users", "Email already exists"
743
+
744
+ Environment variable verification:
745
+ verify:env "API_KEY" is_set, "API_KEY not configured"
746
+ verify:env "DEBUG_MODE" equals "false", "Debug mode must be disabled"
747
+
748
+ Custom logic block:
749
+ verify condition {
750
+ // Custom actions on failure
751
+ log_error("Verification failed");
752
+ send_alert(admin);
753
+ return false;
754
+ }
755
+
756
+ Pattern matching:
757
+ verify:pattern email matches r"/^[a-z]+@[a-z]+\.[a-z]+$/", "Invalid format"
758
+ """
759
+ def __init__(self, condition=None, message=None, target=None, conditions=None,
760
+ error_handler=None, mode=None, pattern=None, db_table=None,
761
+ db_query=None, env_var=None, expected_value=None,
762
+ logic_block=None, action_block=None, verify_type=None):
763
+ # Simple assertion form
764
+ self.condition = condition # Boolean condition to check
765
+ self.message = message # Error message if condition fails
766
+
767
+ # Complex wrapper form
768
+ self.target = target # Function/action to verify
769
+ self.conditions = conditions # List of verification conditions
770
+ self.error_handler = error_handler # Optional error handling action
771
+
772
+ # Extended forms
773
+ self.mode = mode # Verification mode: 'data', 'access', 'db', 'env', 'pattern'
774
+ self.pattern = pattern # Pattern for pattern matching
775
+ self.db_table = db_table # Database table name
776
+ self.db_query = db_query # Database query/condition
777
+ self.env_var = env_var # Environment variable name
778
+ self.expected_value = expected_value # Expected value for comparisons
779
+ self.logic_block = logic_block # Custom logic block (BlockStatement)
780
+ self.action_block = action_block # Action block on failure
781
+ self.verify_type = verify_type # Type check: 'email', 'number', 'string', etc.
782
+
783
+ def __repr__(self):
784
+ if self.mode:
785
+ return f"VerifyStatement(mode={self.mode}, condition={self.condition})"
786
+ return f"VerifyStatement(target={self.target}, conditions={len(self.conditions) if self.conditions else 0})"
787
+
788
+
789
+ class ProtectStatement(Statement):
790
+ """Protection guardrails - security rules against unauthorized access
791
+
792
+ protect(app, {
793
+ rate_limit: 100, // 100 requests per minute
794
+ auth_required: true, // Must be authenticated
795
+ allowed_ips: ["10.0.0.0/8"],
796
+ blocked_ips: ["192.168.1.1"],
797
+ require_https: true,
798
+ min_password_strength: "strong",
799
+ session_timeout: 3600
800
+ })
801
+ """
802
+ def __init__(self, target, rules, enforcement_level="strict"):
803
+ self.target = target # Function/app to protect
804
+ self.rules = rules # Protection rules (Map or dict)
805
+ self.enforcement_level = enforcement_level # "strict", "warn", or "audit"
806
+
807
+ def __repr__(self):
808
+ return f"ProtectStatement(target={self.target}, enforcement={self.enforcement_level})"
809
+
810
+
811
+ # Additional advanced statements for completeness
812
+ class MiddlewareStatement(Statement):
813
+ """Middleware registration - request/response processing
814
+
815
+ middleware(authenticate, (request, response) -> {
816
+ let token = request.headers["Authorization"]
817
+ if (!verify_token(token)) {
818
+ response.status = 401
819
+ return false
820
+ }
821
+ return true
822
+ })
823
+ """
824
+ def __init__(self, name, handler):
825
+ self.name = name # Identifier
826
+ self.handler = handler # ActionLiteral with (req, res) parameters
827
+
828
+ def __repr__(self):
829
+ return f"MiddlewareStatement(name={self.name})"
830
+
831
+
832
+ class AuthStatement(Statement):
833
+ """Authentication configuration
834
+
835
+ auth {
836
+ provider: "oauth2",
837
+ scopes: ["read", "write", "delete"],
838
+ token_expiry: 3600
839
+ }
840
+ """
841
+ def __init__(self, config):
842
+ self.config = config # Map or dict with auth config
843
+
844
+ def __repr__(self):
845
+ return f"AuthStatement(config_keys={len(self.config.items()) if hasattr(self.config, 'items') else 0})"
846
+
847
+
848
+ class ThrottleStatement(Statement):
849
+ """Rate limiting/throttling
850
+
851
+ throttle(api_endpoint, {
852
+ requests_per_minute: 100,
853
+ burst_size: 10,
854
+ per_user: true
855
+ })
856
+ """
857
+ def __init__(self, target, limits):
858
+ self.target = target # Function to throttle
859
+ self.limits = limits # Throttle limits (Map or dict)
860
+
861
+ def __repr__(self):
862
+ return f"ThrottleStatement(target={self.target})"
863
+
864
+
865
+ class CacheStatement(Statement):
866
+ """Caching directive
867
+
868
+ cache(expensive_query, {
869
+ ttl: 3600, // Time to live: 1 hour
870
+ key: "query_result",
871
+ invalidate_on: ["data_changed"]
872
+ })
873
+ """
874
+ def __init__(self, target, policy):
875
+ self.target = target # Function to cache
876
+ self.policy = policy # Cache policy (Map or dict)
877
+
878
+ def __repr__(self):
879
+ return f"CacheStatement(target={self.target})"
880
+
881
+
882
+ class SealStatement(Statement):
883
+ """Seal statement - make a variable/object immutable at runtime
884
+
885
+ seal myObj
886
+ """
887
+ def __init__(self, target):
888
+ # target is expected to be an Identifier or PropertyAccessExpression
889
+ self.target = target
890
+
891
+ def __repr__(self):
892
+ return f"SealStatement(target={self.target})"
893
+
894
+
895
+ # PERFORMANCE OPTIMIZATION STATEMENT NODES
896
+
897
+ class NativeStatement(Statement):
898
+ """Native statement - Call C/C++ code directly
899
+
900
+ native "libmath.so", "add_numbers"(x, y);
901
+ native "libcrypto.so", "sha256"(data) as hash;
902
+ """
903
+ def __init__(self, library_name, function_name, args=None, alias=None):
904
+ self.library_name = library_name # String: path to .so/.dll file
905
+ self.function_name = function_name # String: function name in library
906
+ self.args = args or [] # List[Expression]: arguments to function
907
+ self.alias = alias # Optional: variable name to store result
908
+
909
+ def __repr__(self):
910
+ return f"NativeStatement(lib={self.library_name}, func={self.function_name}, args={self.args}, alias={self.alias})"
911
+
912
+
913
+ class GCStatement(Statement):
914
+ """Garbage Collection statement - Control garbage collection behavior
915
+
916
+ gc "collect"; // Force garbage collection
917
+ gc "pause"; // Pause garbage collection
918
+ gc "resume"; // Resume garbage collection
919
+ gc "enable_debug"; // Enable GC debug output
920
+ """
921
+ def __init__(self, action):
922
+ self.action = action # String: "collect", "pause", "resume", "enable_debug", "disable_debug"
923
+
924
+ def __repr__(self):
925
+ return f"GCStatement(action={self.action})"
926
+
927
+
928
+ class InlineStatement(Statement):
929
+ """Inline statement - Mark function for inlining optimization
930
+
931
+ inline my_function;
932
+ inline critical_path_func;
933
+ """
934
+ def __init__(self, function_name):
935
+ self.function_name = function_name # String or Identifier: function to inline
936
+
937
+ def __repr__(self):
938
+ return f"InlineStatement(func={self.function_name})"
939
+
940
+
941
+ class BufferStatement(Statement):
942
+ """Buffer statement - Direct memory access and manipulation
943
+
944
+ buffer my_mem = allocate(1024);
945
+ buffer my_mem.write(0, [1, 2, 3, 4]);
946
+ buffer my_mem.read(0, 4);
947
+ """
948
+ def __init__(self, buffer_name, operation=None, arguments=None):
949
+ self.buffer_name = buffer_name # String: buffer name
950
+ self.operation = operation # String: "allocate", "write", "read", "free"
951
+ self.arguments = arguments or [] # List[Expression]: operation arguments
952
+
953
+ def __repr__(self):
954
+ return f"BufferStatement(name={self.buffer_name}, op={self.operation}, args={self.arguments})"
955
+
956
+
957
+ class SIMDStatement(Statement):
958
+ """SIMD statement - Vector operations using SIMD instructions
959
+
960
+ simd vector1 + vector2;
961
+ simd matrix_mul(A, B);
962
+ simd dot_product([1,2,3], [4,5,6]);
963
+ """
964
+ def __init__(self, operation, operands=None):
965
+ self.operation = operation # Expression: SIMD operation (binary op or function call)
966
+ self.operands = operands or [] # List[Expression]: operands for SIMD
967
+
968
+ def __repr__(self):
969
+ return f"SIMDStatement(op={self.operation}, operands={self.operands})"
970
+
971
+
972
+ # CONVENIENCE FEATURE STATEMENT NODES
973
+
974
+ class DeferStatement(Statement):
975
+ """Defer statement - Cleanup code execution (LIFO order)
976
+
977
+ defer file.close();
978
+ defer cleanup();
979
+ defer release_lock();
980
+ """
981
+ def __init__(self, code_block):
982
+ self.code_block = code_block # Expression or BlockStatement: code to execute on defer
983
+
984
+ def __repr__(self):
985
+ return f"DeferStatement(code={self.code_block})"
986
+
987
+
988
+ class PatternStatement(Statement):
989
+ """Pattern matching statement - Match expression against patterns
990
+
991
+ pattern value {
992
+ case 1 => print "one";
993
+ case 2 => print "two";
994
+ default => print "other";
995
+ }
996
+ """
997
+ def __init__(self, expression, cases):
998
+ self.expression = expression # Expression: value to match
999
+ self.cases = cases # List[PatternCase]: pattern cases
1000
+
1001
+ def __repr__(self):
1002
+ return f"PatternStatement(expr={self.expression}, cases={len(self.cases)} patterns)"
1003
+
1004
+
1005
+ class PatternCase:
1006
+ """A single pattern case
1007
+
1008
+ case pattern => action;
1009
+ """
1010
+ def __init__(self, pattern, action):
1011
+ self.pattern = pattern # String or Expression: pattern to match
1012
+ self.action = action # Expression or BlockStatement: action if matched
1013
+
1014
+ def __repr__(self):
1015
+ return f"PatternCase(pattern={self.pattern}, action={self.action})"
1016
+
1017
+
1018
+ # ADVANCED FEATURE STATEMENT NODES
1019
+
1020
+ class EnumStatement(Statement):
1021
+ """Enum statement - Type-safe enumerations
1022
+
1023
+ enum Color {
1024
+ Red,
1025
+ Green,
1026
+ Blue
1027
+ }
1028
+
1029
+ enum Status {
1030
+ Active = 1,
1031
+ Inactive = 2,
1032
+ Pending = 3
1033
+ }
1034
+ """
1035
+ def __init__(self, name, members):
1036
+ self.name = name # String: enum name
1037
+ self.members = members # List[EnumMember]: enum values
1038
+
1039
+ def __repr__(self):
1040
+ return f"EnumStatement(name={self.name}, members={len(self.members)})"
1041
+
1042
+
1043
+ class EnumMember:
1044
+ """A single enum member"""
1045
+ def __init__(self, name, value=None):
1046
+ self.name = name # String: member name
1047
+ self.value = value # Optional value (integer or string)
1048
+
1049
+ def __repr__(self):
1050
+ return f"EnumMember({self.name}={self.value})"
1051
+
1052
+
1053
+ class StreamStatement(Statement):
1054
+ """Stream statement - Event streaming and handling
1055
+
1056
+ stream clicks as event => {
1057
+ print "Clicked: " + event.x + ", " + event.y;
1058
+ }
1059
+
1060
+ stream api_responses as response => {
1061
+ handle_response(response);
1062
+ }
1063
+ """
1064
+ def __init__(self, stream_name, event_var, handler):
1065
+ self.stream_name = stream_name # String: stream name
1066
+ self.event_var = event_var # Identifier: event variable name
1067
+ self.handler = handler # BlockStatement: event handler code
1068
+
1069
+ def __repr__(self):
1070
+ return f"StreamStatement(stream={self.stream_name}, var={self.event_var})"
1071
+
1072
+
1073
+ class WatchStatement(Statement):
1074
+ """Watch statement - Reactive state management
1075
+
1076
+ watch {
1077
+ print("x changed to " + x);
1078
+ }
1079
+
1080
+ watch user_name => {
1081
+ update_ui();
1082
+ }
1083
+ """
1084
+ def __init__(self, reaction, watched_expr=None):
1085
+ self.reaction = reaction # BlockStatement: code to execute
1086
+ self.watched_expr = watched_expr # Optional Expression: explicit dependency
1087
+
1088
+ def __repr__(self):
1089
+ return f"WatchStatement(expr={self.watched_expr}, reaction={self.reaction})"
1090
+
1091
+ def __repr__(self):
1092
+ return f"WatchStatement(watch={self.watched_expr})"
1093
+
1094
+
1095
+ class LogStatement(Statement):
1096
+ """Log statement - Redirect output to file
1097
+
1098
+ log > output.txt # Write mode (overwrites on first write in scope)
1099
+ log >> output.txt # Append mode (always appends)
1100
+
1101
+ Supports any file extension: .txt, .py, .zx, .cpp, .rs, etc.
1102
+ Redirects subsequent print output to the specified file.
1103
+ """
1104
+ def __init__(self, filepath, append_mode=True):
1105
+ self.filepath = filepath # Expression: path to log file
1106
+ self.append_mode = append_mode # True for >>, False for >
1107
+
1108
+ def __repr__(self):
1109
+ mode = ">>" if self.append_mode else ">"
1110
+ return f"LogStatement({mode} {self.filepath})"
1111
+
1112
+
1113
+ class ImportLogStatement(Statement):
1114
+ """Import/Execute code from file (Hidden Layer)
1115
+
1116
+ log << "helpers.zx" # Import and execute Zexus code from file
1117
+
1118
+ Creates a hidden layer where generated code is automatically loaded
1119
+ and executed in the current scope. Combines code generation with
1120
+ immediate execution without explicit eval_file() calls.
1121
+
1122
+ Example:
1123
+ action generateHelpers {
1124
+ log >> "helpers.zx";
1125
+ print("action add(a, b) { return a + b; }");
1126
+ }
1127
+ generateHelpers();
1128
+
1129
+ log << "helpers.zx"; // Auto-imports and executes
1130
+ let result = add(5, 10); // Can use imported functions
1131
+ """
1132
+ def __init__(self, filepath):
1133
+ self.filepath = filepath # Expression: path to file to import
1134
+
1135
+ def __repr__(self):
1136
+ return f"ImportLogStatement(<< {self.filepath})"
1137
+
1138
+
1139
+ # NEW: Capability-based security statements
1140
+
1141
+ class CapabilityStatement(Statement):
1142
+ """Capability definition statement - Define what entities can do
1143
+
1144
+ capability read_file = {
1145
+ description: "Read file system",
1146
+ scope: "io",
1147
+ level: "restricted"
1148
+ };
1149
+
1150
+ capability write_network = {
1151
+ description: "Write to network",
1152
+ scope: "io.network",
1153
+ level: "privileged"
1154
+ };
1155
+ """
1156
+ def __init__(self, name, definition=None):
1157
+ self.name = name # Identifier: capability name
1158
+ self.definition = definition # Dict with description, scope, level, etc.
1159
+
1160
+ def __repr__(self):
1161
+ return f"CapabilityStatement(name={self.name})"
1162
+
1163
+
1164
+ class GrantStatement(Statement):
1165
+ """Grant capabilities to an entity
1166
+
1167
+ grant user1 {
1168
+ read_file,
1169
+ read_network
1170
+ };
1171
+
1172
+ grant plugin_trusted capability(read_file);
1173
+ """
1174
+ def __init__(self, entity_name, capabilities):
1175
+ self.entity_name = entity_name # Identifier: entity to grant to
1176
+ self.capabilities = capabilities # List of capability names or FunctionCall nodes
1177
+
1178
+ def __repr__(self):
1179
+ return f"GrantStatement(entity={self.entity_name}, capabilities={len(self.capabilities)})"
1180
+
1181
+
1182
+ class RevokeStatement(Statement):
1183
+ """Revoke capabilities from an entity
1184
+
1185
+ revoke user1 {
1186
+ write_file,
1187
+ write_network
1188
+ };
1189
+
1190
+ revoke plugin_untrusted capability(read_file);
1191
+ """
1192
+ def __init__(self, entity_name, capabilities):
1193
+ self.entity_name = entity_name # Identifier: entity to revoke from
1194
+ self.capabilities = capabilities # List of capability names or FunctionCall nodes
1195
+
1196
+ def __repr__(self):
1197
+ return f"RevokeStatement(entity={self.entity_name}, capabilities={len(self.capabilities)})"
1198
+
1199
+
1200
+ # NEW: Pure function declarations
1201
+
1202
+ class PureFunctionStatement(Statement):
1203
+ """Declare a function as pure (referentially transparent)
1204
+
1205
+ pure function add(a, b) {
1206
+ return a + b;
1207
+ }
1208
+
1209
+ function multiply(x, y) {
1210
+ pure {
1211
+ return x * y;
1212
+ }
1213
+ }
1214
+ """
1215
+ def __init__(self, function_decl):
1216
+ self.function_decl = function_decl # FunctionExpression or FunctionStatement
1217
+
1218
+ def __repr__(self):
1219
+ return f"PureFunctionStatement(function={self.function_decl})"
1220
+
1221
+
1222
+ class ImmutableStatement(Statement):
1223
+ """Declare a variable or parameter as immutable
1224
+
1225
+ immutable const user = { name: "Alice", age: 30 };
1226
+ immutable let config = load_config();
1227
+
1228
+ function process(immutable data) {
1229
+ // data cannot be modified
1230
+ print data.name;
1231
+ }
1232
+ """
1233
+ def __init__(self, target, value=None):
1234
+ self.target = target # Identifier: variable to make immutable
1235
+ self.value = value # Optional Expression: value to assign
1236
+
1237
+ def __repr__(self):
1238
+ return f"ImmutableStatement(target={self.target})"
1239
+
1240
+
1241
+ # NEW: Data validation and sanitization
1242
+
1243
+ class ValidateStatement(Statement):
1244
+ """Validate data against a schema
1245
+
1246
+ validate user_input, {
1247
+ name: string,
1248
+ email: email,
1249
+ age: number(18, 120)
1250
+ };
1251
+
1252
+ validate(request.body, schema_user);
1253
+ """
1254
+ def __init__(self, data, schema, options=None):
1255
+ self.data = data # Expression: value to validate
1256
+ self.schema = schema # Dict or Identifier: validation schema
1257
+ self.options = options # Optional: validation options
1258
+
1259
+ def __repr__(self):
1260
+ return f"ValidateStatement(data={self.data})"
1261
+
1262
+
1263
+ class SanitizeStatement(Statement):
1264
+ """Sanitize untrusted input
1265
+
1266
+ sanitize user_input, {
1267
+ encoding: "html",
1268
+ rules: ["remove_scripts", "remove_events"]
1269
+ };
1270
+
1271
+ let clean_data = sanitize(request.body, encoding="url");
1272
+ """
1273
+ def __init__(self, data, rules=None, encoding=None):
1274
+ self.data = data # Expression: value to sanitize
1275
+ self.rules = rules # Optional: list of sanitization rules
1276
+ self.encoding = encoding # Optional: encoding type (html, sql, url, javascript)
1277
+
1278
+ def __repr__(self):
1279
+ return f"SanitizeStatement(data={self.data})"
1280
+
1281
+
1282
+ class InjectStatement(Statement):
1283
+ """Dependency injection statement
1284
+
1285
+ inject DatabaseAPI;
1286
+ inject max_retries;
1287
+
1288
+ Used for dependency injection pattern where external
1289
+ dependencies are injected at runtime.
1290
+ """
1291
+ def __init__(self, dependency):
1292
+ self.dependency = dependency # Identifier: dependency name
1293
+
1294
+ def __repr__(self):
1295
+ return f"InjectStatement(dependency={self.dependency})"
1296
+
1297
+
1298
+ # NEW: Complexity & Large Project Management
1299
+
1300
+ class InterfaceStatement(Statement):
1301
+ """Formal interface/type class definition
1302
+
1303
+ interface Drawable {
1304
+ draw(canvas);
1305
+ get_bounds();
1306
+ };
1307
+
1308
+ interface Serializable {
1309
+ to_string();
1310
+ from_string(str);
1311
+ };
1312
+ """
1313
+ def __init__(self, name, methods=None, properties=None, extends=None):
1314
+ self.name = name # Identifier: interface name
1315
+ self.methods = methods or [] # List of method declarations
1316
+ self.properties = properties or {} # Dict of property names -> types
1317
+ self.extends = extends or [] # List of interface names this extends
1318
+
1319
+ def __repr__(self):
1320
+ return f"InterfaceStatement(name={self.name}, methods={len(self.methods)})"
1321
+
1322
+
1323
+ class TypeAliasStatement(Statement):
1324
+ """Type alias definition for complex types
1325
+
1326
+ type_alias UserID = integer;
1327
+ type_alias Point = { x: float, y: float };
1328
+ type_alias Handler = function(request) -> response;
1329
+ """
1330
+ def __init__(self, name, base_type):
1331
+ self.name = name # Identifier: alias name
1332
+ self.base_type = base_type # Expression or type name
1333
+
1334
+ def __repr__(self):
1335
+ return f"TypeAliasStatement(name={self.name}, base_type={self.base_type})"
1336
+
1337
+
1338
+ class ModuleStatement(Statement):
1339
+ """Module definition for code organization
1340
+
1341
+ module database {
1342
+ internal function connect_db(path) { ... }
1343
+ public function query(sql) { ... }
1344
+ }
1345
+
1346
+ module users {
1347
+ public function get_user(id) { ... }
1348
+ internal function validate_user(user) { ... }
1349
+ }
1350
+ """
1351
+ def __init__(self, name, body=None, parent=None):
1352
+ self.name = name # Identifier: module name
1353
+ self.body = body # BlockStatement: module body
1354
+ self.parent = parent # Parent module (if nested)
1355
+
1356
+ def __repr__(self):
1357
+ return f"ModuleStatement(name={self.name})"
1358
+
1359
+
1360
+ class PackageStatement(Statement):
1361
+ """Package definition for high-level organization
1362
+
1363
+ package myapp.database {
1364
+ module connection { ... }
1365
+ module query { ... }
1366
+ }
1367
+ """
1368
+ def __init__(self, name, body=None):
1369
+ self.name = name # Identifier or dotted name: package name
1370
+ self.body = body # BlockStatement: package body
1371
+
1372
+ def __repr__(self):
1373
+ return f"PackageStatement(name={self.name})"
1374
+
1375
+
1376
+ class UsingStatement(Statement):
1377
+ """Resource management with automatic cleanup (RAII pattern)
1378
+
1379
+ using(file = open("/path/to/file.txt")) {
1380
+ content = file.read();
1381
+ process(content);
1382
+ // file is automatically closed
1383
+ }
1384
+
1385
+ using(connection = db.connect()) {
1386
+ result = connection.query("SELECT * FROM users");
1387
+ // connection is automatically closed
1388
+ }
1389
+ """
1390
+ def __init__(self, resource_name, resource_expr, body):
1391
+ self.resource_name = resource_name # Identifier: name for the resource
1392
+ self.resource_expr = resource_expr # Expression: acquires the resource
1393
+ self.body = body # BlockStatement: code using the resource
1394
+
1395
+ def __repr__(self):
1396
+ return f"UsingStatement(resource={self.resource_name})"
1397
+
1398
+
1399
+ class VisibilityModifier(Statement):
1400
+ """Visibility modifier for module members
1401
+
1402
+ public function get_data() { ... }
1403
+ internal function helper() { ... }
1404
+ protected function submodule_only() { ... }
1405
+ """
1406
+ def __init__(self, visibility, statement):
1407
+ self.visibility = visibility # String: "public", "internal", "protected"
1408
+ self.statement = statement # The statement being modified
1409
+
1410
+ def __repr__(self):
1411
+ return f"VisibilityModifier({self.visibility}, {self.statement})"
1412
+
1413
+
1414
+ class ChannelStatement(Statement):
1415
+ """Channel declaration for message passing between concurrent tasks
1416
+
1417
+ channel<integer> numbers;
1418
+ channel<string> messages;
1419
+ channel<{"id": integer, "name": string}> user_updates;
1420
+ """
1421
+ def __init__(self, name, element_type=None, capacity=None):
1422
+ self.name = name # Identifier: channel name
1423
+ self.element_type = element_type # Expression: type of elements
1424
+ self.capacity = capacity # Optional: buffer capacity (None = unbuffered)
1425
+
1426
+ def __repr__(self):
1427
+ return f"ChannelStatement({self.name}, type={self.element_type})"
1428
+
1429
+
1430
+ class SendStatement(Statement):
1431
+ """Send value to a channel
1432
+
1433
+ send(channel, value);
1434
+ send(data_channel, {"id": 1, "name": "Alice"});
1435
+ """
1436
+ def __init__(self, channel_expr, value_expr):
1437
+ self.channel_expr = channel_expr # Expression: channel to send to
1438
+ self.value_expr = value_expr # Expression: value to send
1439
+
1440
+ def __repr__(self):
1441
+ return f"SendStatement(channel={self.channel_expr}, value={self.value_expr})"
1442
+
1443
+
1444
+ class ReceiveStatement(Statement):
1445
+ """Receive value from a channel (blocking)
1446
+
1447
+ value = receive(channel);
1448
+ user = receive(user_updates);
1449
+ """
1450
+ def __init__(self, channel_expr, target=None):
1451
+ self.channel_expr = channel_expr # Expression: channel to receive from
1452
+ self.target = target # Optional Identifier: variable to bind received value
1453
+
1454
+ def __repr__(self):
1455
+ return f"ReceiveStatement(channel={self.channel_expr})"
1456
+
1457
+
1458
+ class AtomicStatement(Statement):
1459
+ """Atomic operation - indivisible unit of concurrent code
1460
+
1461
+ atomic(counter = counter + 1);
1462
+ atomic {
1463
+ x = x + 1;
1464
+ y = y + 1;
1465
+ };
1466
+ """
1467
+ def __init__(self, body=None, expr=None):
1468
+ self.body = body # BlockStatement: atomic block
1469
+ self.expr = expr # Expression: atomic expression (single operation)
1470
+ # Note: exactly one of body or expr should be non-None
1471
+
1472
+ def __repr__(self):
1473
+ return f"AtomicStatement(body={self.body}, expr={self.expr})"
1474
+
1475
+
1476
+ # ============================================================================
1477
+ # BLOCKCHAIN & SMART CONTRACT AST NODES
1478
+ # ============================================================================
1479
+
1480
+ class LedgerStatement(Statement):
1481
+ """Ledger statement - Immutable, versioned state storage
1482
+
1483
+ ledger balances;
1484
+ ledger accounts = {};
1485
+ ledger state_root;
1486
+ """
1487
+ def __init__(self, name, initial_value=None):
1488
+ self.name = name # Identifier: ledger variable name
1489
+ self.initial_value = initial_value # Optional Expression: initial value
1490
+
1491
+ def __repr__(self):
1492
+ return f"LedgerStatement(name={self.name}, initial={self.initial_value})"
1493
+
1494
+
1495
+ class StateStatement(Statement):
1496
+ """State statement - Mutable state within contracts
1497
+
1498
+ state counter = 0;
1499
+ state owner = TX.caller;
1500
+ state locked = false;
1501
+ """
1502
+ def __init__(self, name, initial_value=None):
1503
+ self.name = name # Identifier: state variable name
1504
+ self.initial_value = initial_value # Optional Expression: initial value
1505
+
1506
+ def __repr__(self):
1507
+ return f"StateStatement(name={self.name}, initial={self.initial_value})"
1508
+
1509
+
1510
+ class ContractStatement(Statement):
1511
+ """Contract statement - Smart contract definition
1512
+
1513
+ contract Token {
1514
+ state balances = {};
1515
+ state total_supply = 0;
1516
+
1517
+ action mint(recipient, amount) limit 5000 {
1518
+ require(TX.caller == owner, "Only owner can mint");
1519
+ balances[recipient] = balances[recipient] + amount;
1520
+ total_supply = total_supply + amount;
1521
+ }
1522
+ }
1523
+
1524
+ contract QuantumCrypto implements QuantumResistantCrypto { ... }
1525
+ """
1526
+ def __init__(self, name, body, modifiers=None, implements=None):
1527
+ self.name = name # Identifier: contract name
1528
+ self.body = body # BlockStatement: contract body (state vars and actions)
1529
+ self.modifiers = modifiers or [] # List of modifiers
1530
+ self.implements = implements # Optional protocol name that contract implements
1531
+
1532
+ def __repr__(self):
1533
+ impl_str = f", implements={self.implements}" if self.implements else ""
1534
+ return f"ContractStatement(name={self.name}, modifiers={self.modifiers}{impl_str})"
1535
+
1536
+
1537
+ class RevertStatement(Statement):
1538
+ """Revert statement - Rollback transaction
1539
+
1540
+ revert();
1541
+ revert("Insufficient balance");
1542
+ revert("Unauthorized: " + TX.caller);
1543
+ """
1544
+ def __init__(self, reason=None):
1545
+ self.reason = reason # Optional Expression: revert reason message
1546
+
1547
+ def __repr__(self):
1548
+ return f"RevertStatement(reason={self.reason})"
1549
+
1550
+
1551
+ class RequireStatement(Statement):
1552
+ """Require statement - Prerequisites, dependencies, and resource requirements
1553
+
1554
+ Basic requirement:
1555
+ require(balance >= amount);
1556
+ require(TX.caller == owner, "Only owner");
1557
+ require(balance >= amount, "Insufficient funds");
1558
+
1559
+ With conditional tolerance logic:
1560
+ require balance >= 0.1 {
1561
+ // Tolerance logic - allow exceptions
1562
+ if (user.isVIP) {
1563
+ print "VIP user - waiving requirement";
1564
+ } else {
1565
+ return false;
1566
+ }
1567
+ }
1568
+
1569
+ File/module dependencies:
1570
+ require "math_plus.zx" imported, "Math module required";
1571
+ require module "database" available, "Database unavailable";
1572
+
1573
+ Resource requirements:
1574
+ require:balance amount >= minimum, "Insufficient funds";
1575
+ require:gas available >= needed, "Insufficient gas";
1576
+
1577
+ Multiple conditions with fallback:
1578
+ require amount >= 100 || (user.subscribed && amount >= 10), "Minimum not met";
1579
+
1580
+ Prerequisite checking:
1581
+ require:prereq user.authenticated, "Login required";
1582
+ require:prereq file.exists("config.json"), "Config file missing";
1583
+ """
1584
+ def __init__(self, condition, message=None, tolerance_block=None, requirement_type=None,
1585
+ resource_name=None, minimum_value=None, file_path=None, module_name=None,
1586
+ fallback_condition=None, prereq_list=None):
1587
+ # Basic form
1588
+ self.condition = condition # Expression: condition that must be true
1589
+ self.message = message # Optional Expression: error message if false
1590
+
1591
+ # Conditional tolerance
1592
+ self.tolerance_block = tolerance_block # BlockStatement: tolerance/fallback logic
1593
+
1594
+ # Requirement types
1595
+ self.requirement_type = requirement_type # 'balance', 'gas', 'prereq', 'file', 'module'
1596
+
1597
+ # Resource requirements
1598
+ self.resource_name = resource_name # Resource identifier (balance, gas, etc.)
1599
+ self.minimum_value = minimum_value # Minimum required value
1600
+
1601
+ # File/module dependencies
1602
+ self.file_path = file_path # Required file path
1603
+ self.module_name = module_name # Required module name
1604
+
1605
+ # Fallback/alternative conditions
1606
+ self.fallback_condition = fallback_condition # Alternative condition if primary fails
1607
+
1608
+ # Prerequisites list
1609
+ self.prereq_list = prereq_list or [] # List of prerequisites
1610
+
1611
+ def __repr__(self):
1612
+ if self.requirement_type:
1613
+ return f"RequireStatement(type={self.requirement_type}, condition={self.condition})"
1614
+ return f"RequireStatement(condition={self.condition}, msg={self.message})"
1615
+
1616
+
1617
+ class LimitStatement(Statement):
1618
+ """Limit statement - Gas/resource limit for actions
1619
+
1620
+ action transfer() limit 1000 { ... }
1621
+ limit 5000; // Set limit for next operation
1622
+ """
1623
+ def __init__(self, amount):
1624
+ self.amount = amount # IntegerLiteral or Expression: gas limit amount
1625
+
1626
+ def __repr__(self):
1627
+ return f"LimitStatement(amount={self.amount})"
1628
+
1629
+
1630
+ # BLOCKCHAIN EXPRESSION NODES
1631
+
1632
+ class TXExpression(Expression):
1633
+ """TX expression - Transaction context access
1634
+
1635
+ TX.caller
1636
+ TX.timestamp
1637
+ TX.block_hash
1638
+ TX.gas_remaining
1639
+ """
1640
+ def __init__(self, property_name):
1641
+ self.property_name = property_name # String: property being accessed
1642
+
1643
+ def __repr__(self):
1644
+ return f"TXExpression(property={self.property_name})"
1645
+
1646
+
1647
+ class HashExpression(Expression):
1648
+ """Hash expression - Cryptographic hashing
1649
+
1650
+ hash(data, "SHA256")
1651
+ hash(message, "KECCAK256")
1652
+ hash(password, "SHA512")
1653
+ """
1654
+ def __init__(self, data, algorithm):
1655
+ self.data = data # Expression: data to hash
1656
+ self.algorithm = algorithm # Expression: hash algorithm name
1657
+
1658
+ def __repr__(self):
1659
+ return f"HashExpression(data={self.data}, algorithm={self.algorithm})"
1660
+
1661
+
1662
+ class SignatureExpression(Expression):
1663
+ """Signature expression - Digital signature creation
1664
+
1665
+ signature(message, private_key)
1666
+ signature(data, key, "ECDSA")
1667
+ """
1668
+ def __init__(self, data, private_key, algorithm=None):
1669
+ self.data = data # Expression: data to sign
1670
+ self.private_key = private_key # Expression: private key
1671
+ self.algorithm = algorithm # Optional Expression: signature algorithm
1672
+
1673
+ def __repr__(self):
1674
+ return f"SignatureExpression(data={self.data}, algorithm={self.algorithm})"
1675
+
1676
+
1677
+ class VerifySignatureExpression(Expression):
1678
+ """Verify signature expression - Signature verification
1679
+
1680
+ verify_sig(data, signature, public_key)
1681
+ verify_sig(message, sig, pub_key, "ECDSA")
1682
+ """
1683
+ def __init__(self, data, signature, public_key, algorithm=None):
1684
+ self.data = data # Expression: original data
1685
+ self.signature = signature # Expression: signature to verify
1686
+ self.public_key = public_key # Expression: public key
1687
+ self.algorithm = algorithm # Optional Expression: signature algorithm
1688
+
1689
+ def __repr__(self):
1690
+ return f"VerifySignatureExpression(data={self.data}, algorithm={self.algorithm})"
1691
+
1692
+
1693
+ class GasExpression(Expression):
1694
+ """Gas expression - Access gas tracking information
1695
+
1696
+ gas // Current gas tracker object
1697
+ gas.used // Gas consumed so far
1698
+ gas.remaining // Gas still available
1699
+ gas.limit // Total gas limit
1700
+ """
1701
+ def __init__(self, property_name=None):
1702
+ self.property_name = property_name # Optional String: property being accessed
1703
+
1704
+ def __repr__(self):
1705
+ return f"GasExpression(property={self.property_name})"
1706
+
1707
+
1708
+ def attach_modifiers(node, modifiers):
1709
+ """Attach modifiers to an AST node (best-effort).
1710
+
1711
+ Many AST constructors do not accept modifiers; this helper sets
1712
+ a `modifiers` attribute on the node for downstream passes.
1713
+ """
1714
+ try:
1715
+ if modifiers:
1716
+ setattr(node, 'modifiers', list(modifiers))
1717
+ else:
1718
+ setattr(node, 'modifiers', [])
1719
+ except Exception:
1720
+ pass
1721
+ return node
1722
+ class ProtocolStatement(Statement):
1723
+ """Protocol declaration - interface/trait definition
1724
+
1725
+ protocol Transferable {
1726
+ action transfer(to, amount)
1727
+ action balance() -> int
1728
+ }
1729
+ """
1730
+ def __init__(self, name, methods):
1731
+ self.name = name # Identifier
1732
+ self.methods = methods # List of method signatures
1733
+
1734
+ def __repr__(self):
1735
+ return f"ProtocolStatement(name={self.name}, methods={len(self.methods)})"
1736
+
1737
+
1738
+ class PersistentStatement(Statement):
1739
+ """Persistent storage declaration within contracts
1740
+
1741
+ persistent storage balances: map
1742
+ persistent storage owner: string
1743
+ """
1744
+ def __init__(self, name, type_annotation=None, initial_value=None):
1745
+ self.name = name # Identifier
1746
+ self.type_annotation = type_annotation # Optional type
1747
+ self.initial_value = initial_value # Optional initial value
1748
+
1749
+ def __repr__(self):
1750
+ return f"PersistentStatement(name={self.name})"
1751
+
1752
+
1753
+ class EmitStatement(Statement):
1754
+ """Emit event statement
1755
+
1756
+ emit Transfer(from, to, amount);
1757
+ emit StateChange("balance_updated", new_balance);
1758
+ """
1759
+ def __init__(self, event_name, arguments=None):
1760
+ self.event_name = event_name # Event name (Identifier or string)
1761
+ self.arguments = arguments or [] # List of arguments
1762
+
1763
+ def __repr__(self):
1764
+ return f"EmitStatement(event={self.event_name}, args={len(self.arguments)})"
1765
+
1766
+
1767
+ class ModifierDeclaration(Statement):
1768
+ """Modifier declaration - reusable function modifier
1769
+
1770
+ modifier onlyOwner {
1771
+ require(TX.caller == owner, "Not owner");
1772
+ }
1773
+
1774
+ action withdraw() modifier onlyOwner { ... }
1775
+ """
1776
+ def __init__(self, name, parameters, body):
1777
+ self.name = name # Modifier name (Identifier)
1778
+ self.parameters = parameters or [] # List of parameters
1779
+ self.body = body # BlockStatement
1780
+
1781
+ def __repr__(self):
1782
+ return f"ModifierDeclaration(name={self.name}, params={len(self.parameters)})"