1use crate::ast::*;
4use crate::bind::Host;
5use crate::budget::Budget;
6use crate::error::{DiagCode, Diagnostic};
7use crate::extension_registry::{
8 is_extension_namespace, CallExecutionContext, DispatchOutcome, ExtensionRegistry,
9 PreparedCallCache,
10};
11use crate::span::Span;
12use crate::value::Value;
13use std::collections::{HashMap, HashSet};
14use vibescript_abi::{q_hash_str, ExecutionMode, SentinelPolicyGate};
15
16mod budget;
17use budget::budget_steps;
18mod call;
19mod expr;
20mod ops;
21pub(crate) use ops::lit;
22use ops::{binop, collect_pat_idents, match_pat};
23mod program;
24mod stack;
25mod stmt;
26mod task_runtime;
27#[cfg(test)]
28mod tests;
29
30#[derive(Clone)]
31pub struct Env {
32 pub task_scope: crate::task_scheduler::TaskScope,
35 pub vars: HashMap<String, Value>,
36 pub mutables: HashSet<String>,
38 pub aliases: HashMap<String, String>,
41 pub enums: HashMap<String, EnumDecl>,
43 pub fields: HashMap<String, Value>,
45 pub materials: HashMap<String, Value>,
47 pub laws: HashMap<String, Value>,
49}
50
51impl Default for Env {
52 fn default() -> Self {
53 Self::with_task_scope(crate::task_scheduler::TaskScope::default())
54 }
55}
56
57impl Env {
58 fn with_task_scope(task_scope: crate::task_scheduler::TaskScope) -> Self {
60 Self {
61 task_scope,
62 vars: HashMap::new(),
63 mutables: HashSet::new(),
64 aliases: HashMap::new(),
65 enums: HashMap::new(),
66 fields: HashMap::new(),
67 materials: HashMap::new(),
68 laws: HashMap::new(),
69 }
70 }
71}
72
73pub const VIBE_0_1_NAMESPACES: &[&str] = &[
75 "math",
76 "rdf",
77 "quin",
78 "graph",
79 "aura",
80 "pulse",
81 "capability",
82 "time",
83 "conservation",
84 "causal",
85 "dag",
86 "deontic",
87 "hid",
88 "cue",
89 "crypto",
90 "zk",
91 "web",
92 "ui",
93 "form",
94 "input",
95 "validate",
96 "selection",
97 "layout",
98 "cbor_ld",
99 "reflect",
100 "record",
101 "uri",
102 "error",
103 "num",
104 "decimal",
105 "autodiff",
106 "str",
107 "regex",
108 "list",
109 "deque",
110 "pqueue",
111 "set",
112 "simplex",
113 "hypergraph",
114 "sheaf",
115 "topology",
116 "homotopy",
117 "context",
118 "manifold",
119 "inference",
120 "ast",
121 "diagnostic",
122 "effect",
123 "code",
124 "task",
125 "supervisor",
126 "contract",
127 "state",
128 "value",
129 "runtime",
130 "continuation",
131 "memory",
132 "simd",
133 "channel",
134];
135
136pub fn populate_import_aliases(env: &mut Env, imports: &[ImportDecl]) -> Result<(), Diagnostic> {
140 let mut seen = HashSet::new();
141 for imp in imports {
142 let ns = imp
143 .path
144 .strip_prefix("vibe:0.1/")
145 .or_else(|| imp.path.strip_prefix("vibe:0.3/"))
146 .unwrap_or(&imp.path);
147 if !VIBE_0_1_NAMESPACES.contains(&ns) && !is_extension_namespace(ns) {
148 return Err(Diagnostic::new(
149 DiagCode::E100,
150 imp.span,
151 format!(
152 "unknown namespace '{}'; valid: {}",
153 ns,
154 VIBE_0_1_NAMESPACES.join(", ")
155 ),
156 ));
157 }
158 let default_alias = ns.rsplit('/').next().unwrap_or(ns);
159 let alias = imp.alias.as_deref().unwrap_or(default_alias);
160 if !seen.insert(alias) {
161 return Err(Diagnostic::new(
162 DiagCode::E100,
163 imp.span,
164 format!("duplicate import alias '{alias}'"),
165 ));
166 }
167 env.aliases.insert(alias.to_string(), ns.to_string());
168 }
169 Ok(())
170}
171
172fn default_call_context() -> CallExecutionContext {
173 CallExecutionContext {
174 actor_did_hash: q_hash_str("did:q42:local_engine"),
175 context_world_hash: 1,
176 lamport_timestamp: 1,
177 mode: ExecutionMode::StandaloneDeveloper,
178 }
179}
180
181pub struct Engine<'a, H: Host> {
182 pub(crate) active_tasks: Vec<(crate::task_scheduler::TaskScope, u64)>,
183 host: &'a mut H,
184 budget: Budget,
185 depth: u32,
186 call_depth_limit: u32,
187 expression_depth: u32,
188 expression_depth_limit: u32,
189 evaluating_budget: bool,
191 program: Option<std::sync::Arc<Program>>,
193 phase_leaser: Option<&'a mut crate::deontic_interrupt::PhaseLeaser>,
195 granted: Vec<String>,
197 pub(crate) extension_registry: ExtensionRegistry<'a>,
199 pub(crate) prepared_cache: PreparedCallCache,
201 pub(crate) call_context: CallExecutionContext,
203 pub(crate) sentinel_gate: Option<&'a mut dyn SentinelPolicyGate>,
205 pub(crate) last_extension_outcome: Option<DispatchOutcome>,
207}
208
209pub(super) enum Flow {
210 Next(Value),
211 Return(Value),
212}
213
214impl<'a, H: Host> Engine<'a, H> {
215 pub(crate) fn set_session_stack_limits(&mut self, depth: u32, expression_depth: u32) {
217 self.call_depth_limit = depth.clamp(1, 8);
218 self.expression_depth_limit = expression_depth.clamp(1, 64);
219 }
220
221 pub fn workspace_left(&self) -> u64 {
223 self.budget.workspace_left
224 }
225
226 pub fn new(host: &'a mut H, budget: Budget) -> Self {
228 Self {
229 active_tasks: Vec::new(),
230 host,
231 budget,
232 depth: 0,
233 call_depth_limit: 64,
234 expression_depth: 0,
235 expression_depth_limit: u32::MAX,
236 evaluating_budget: false,
237 program: None,
238 phase_leaser: None,
239 granted: Vec::new(),
240 extension_registry: ExtensionRegistry::with_builtin_providers(),
241 prepared_cache: PreparedCallCache::new(),
242 call_context: default_call_context(),
243 sentinel_gate: None,
244 last_extension_outcome: None,
245 }
246 }
247
248 pub fn with_program(host: &'a mut H, budget: Budget, program: &Program) -> Self {
250 let mut engine = Self::new(host, budget);
251 engine.program = Some(std::sync::Arc::new(program.clone()));
252 engine.granted = program.requires.iter().map(|c| c.id.clone()).collect();
253 engine
254 }
255
256 pub fn with_phase_leaser(
258 host: &'a mut H,
259 budget: Budget,
260 leaser: &'a mut crate::deontic_interrupt::PhaseLeaser,
261 ) -> Self {
262 let mut engine = Self::new(host, budget);
263 engine.phase_leaser = Some(leaser);
264 engine
265 }
266
267 pub fn with_extension_governance(
269 host: &'a mut H,
270 budget: Budget,
271 registry: ExtensionRegistry<'a>,
272 call_context: CallExecutionContext,
273 gate: Option<&'a mut dyn SentinelPolicyGate>,
274 ) -> Self {
275 let mut engine = Self::new(host, budget);
276 engine.extension_registry = registry;
277 engine.call_context = call_context;
278 engine.sentinel_gate = gate;
279 engine
280 }
281
282 #[inline]
284 pub fn extension_registry(&self) -> &ExtensionRegistry<'a> {
285 &self.extension_registry
286 }
287
288 #[inline]
290 pub fn extension_registry_mut(&mut self) -> &mut ExtensionRegistry<'a> {
291 &mut self.extension_registry
292 }
293
294 #[inline]
296 pub fn set_extension_governance(
297 &mut self,
298 call_context: CallExecutionContext,
299 gate: Option<&'a mut dyn SentinelPolicyGate>,
300 ) {
301 self.call_context = call_context;
302 self.sentinel_gate = gate;
303 }
304
305 #[inline]
307 pub fn last_extension_outcome(&self) -> Option<&DispatchOutcome> {
308 self.last_extension_outcome.as_ref()
309 }
310
311 #[inline]
313 pub fn active_policy_generation(&self) -> Result<u64, vibescript_abi::VibeTrap> {
314 if self.call_context.mode.requires_sentinel_gate() {
315 let gate = self
316 .sentinel_gate
317 .as_ref()
318 .ok_or(vibescript_abi::VibeTrap::SentinelUnavailable)?;
319 if !gate.is_controller_alive() {
320 return Err(vibescript_abi::VibeTrap::SentinelUnavailable);
321 }
322 Ok(gate.current_policy_generation())
323 } else {
324 Ok(0)
325 }
326 }
327
328 pub(crate) fn granted_refs(&self) -> Vec<&str> {
330 self.granted.iter().map(|s| s.as_str()).collect()
331 }
332
333 pub(crate) fn check_phase_capability(&self, path: &str, span: Span) -> Result<(), Diagnostic> {
335 let Some(leaser) = &self.phase_leaser else {
336 return Ok(());
337 };
338 let cap = path.split('.').next().unwrap_or(path);
339 if leaser.is_interrupted() {
340 return Err(Diagnostic::new(
341 DiagCode::E700,
342 span,
343 format!(
344 "deontic interrupt: agent is halted, capability '{}' denied",
345 cap
346 ),
347 ));
348 }
349 if !leaser.is_leased(cap) {
350 return Err(Diagnostic::new(
351 DiagCode::E700,
352 span,
353 format!(
354 "deontic phase violation: capability '{}' is not leased in the current phase",
355 cap
356 ),
357 ));
358 }
359 Ok(())
360 }
361}