Skip to main content

vibe/eval/
program.rs

1use super::*;
2
3impl<'a, H: Host> Engine<'a, H> {
4    /// Evaluates a program.
5    pub fn eval_program(&mut self, program: &Program, env: &mut Env) -> Result<Value, Diagnostic> {
6        populate_import_aliases(env, &program.imports)?;
7        self.granted = program.requires.iter().map(|c| c.id.clone()).collect();
8        let mut last = Value::Null;
9        let has_cells = program.items.iter().any(|i| matches!(i, Item::Cell(_)));
10        let mut cell_graph = if has_cells {
11            Some(
12                crate::reactive_cell::ReactiveCellGraph::from_program(program)
13                    .map_err(|e| Diagnostic::new(DiagCode::E600, program.span, e.to_string()))?,
14            )
15        } else {
16            None
17        };
18        let mut cells_stepped = false;
19        for item in &program.items {
20            match item {
21                Item::Const(c) => {
22                    let v = self.eval_expr(&c.value, env)?;
23                    env.vars.insert(c.name.clone(), v);
24                }
25                Item::Statement(s) => match self.eval_stmt(s, env)? {
26                    Flow::Return(v) => return Ok(v),
27                    Flow::Next(v) => last = v,
28                },
29                Item::Function(_) | Item::Hook(_) => {}
30                Item::Enum(e) => {
31                    env.enums.insert(e.name.clone(), e.clone());
32                }
33                Item::Field(f) => {
34                    let mut rec = std::collections::BTreeMap::new();
35                    rec.insert("name".to_string(), Value::String(f.name.clone()));
36                    rec.insert("ty".to_string(), Value::String(f.ty.name.clone()));
37                    if let Some(u) = &f.unit {
38                        rec.insert("unit".to_string(), Value::String(u.clone()));
39                    }
40                    rec.insert(
41                        "support".to_string(),
42                        Value::String(format!("{:?}", f.support).to_lowercase()),
43                    );
44                    rec.insert(
45                        "representation".to_string(),
46                        Value::String(format!("{:?}", f.representation).to_lowercase()),
47                    );
48                    env.fields.insert(f.name.clone(), Value::Record(rec));
49                }
50                Item::Material(m) => {
51                    let mut rec = std::collections::BTreeMap::new();
52                    rec.insert("name".to_string(), Value::String(m.name.clone()));
53                    for prop in &m.properties {
54                        let v = self.eval_expr(&prop.value, env)?;
55                        rec.insert(prop.name.clone(), v);
56                    }
57                    // Words a cell uses: part, signature, facet. One physics stack.
58                    if rec.contains_key("part")
59                        || rec.contains_key("signature")
60                        || rec.contains_key("facet")
61                    {
62                        attach_part_signature(&mut rec, m.span)?;
63                    }
64                    env.materials.insert(m.name.clone(), Value::Record(rec));
65                }
66                Item::Present(p) => {
67                    let mut sheaf =
68                        crate::presentation::PresentationSheaf::new(Value::String(p.name.clone()));
69                    let mut css = std::collections::BTreeMap::new();
70                    for prop in &p.properties {
71                        let v = self.eval_expr(&prop.value, env)?;
72                        match prop.name.as_str() {
73                            "speech" | "announce" | "auditory" => {
74                                let text = match &v {
75                                    Value::String(s) => s.clone(),
76                                    other => format!("{other}"),
77                                };
78                                sheaf.add(crate::presentation::Presentation::speech(&text));
79                            }
80                            "braille" => {
81                                let cells: Vec<u8> = match &v {
82                                    Value::String(s) => s.bytes().map(|b| b & 0x3F).collect(),
83                                    Value::List(xs) => xs
84                                        .iter()
85                                        .filter_map(|x| x.as_i64().map(|n| n as u8))
86                                        .collect(),
87                                    _ => Vec::new(),
88                                };
89                                sheaf.add(crate::presentation::Presentation::braille_cells(cells));
90                            }
91                            "haptic" => {
92                                sheaf.add(crate::presentation::Presentation::haptic_pattern(vec![
93                                    (100, 0.5),
94                                ]));
95                            }
96                            "svg" => {
97                                let s = match &v {
98                                    Value::String(s) => s.clone(),
99                                    other => format!("{other}"),
100                                };
101                                sheaf.add(crate::presentation::Presentation::svg(&s));
102                            }
103                            _ => {
104                                css.insert(prop.name.clone(), v);
105                            }
106                        }
107                    }
108                    if !css.is_empty() {
109                        sheaf.add(crate::presentation::Presentation::css(css));
110                    }
111                    let rec = sheaf.to_value();
112                    env.vars.insert(p.name.clone(), rec.clone());
113                    last = rec;
114                }
115                Item::Cell(c) => {
116                    if let Some(g) = cell_graph.as_mut() {
117                        if !cells_stepped {
118                            let updated = g.step_with(self, env, 0.0).map_err(|e| {
119                                Diagnostic::new(DiagCode::E600, c.span, e.to_string())
120                            })?;
121                            cells_stepped = true;
122                            if let Some((_, v)) = updated.last() {
123                                last = v.clone();
124                            }
125                        } else if let Some(v) = g.get_value(&c.name) {
126                            last = v.clone();
127                        }
128                    }
129                }
130                Item::Bind(b) => {
131                    self.apply_bind(b, env)?;
132                }
133                Item::Law(l) => {
134                    let mut rec = std::collections::BTreeMap::new();
135                    rec.insert("name".to_string(), Value::String(l.name.clone()));
136                    rec.insert("has_condition".to_string(), Value::Bool(true));
137                    rec.insert("has_consequence".to_string(), Value::Bool(true));
138                    env.laws.insert(l.name.clone(), Value::Record(rec));
139                }
140            }
141        }
142        Ok(last)
143    }
144
145    fn apply_bind(&mut self, b: &BindDecl, env: &mut Env) -> Result<(), Diagnostic> {
146        let left_v = self.eval_expr(&b.left, env)?;
147        let right_v = self.eval_expr(&b.right, env)?;
148        let mut chosen = match b.resolve {
149            BindResolve::Left => left_v,
150            BindResolve::Right => right_v.clone(),
151            BindResolve::Latest => {
152                if !matches!(right_v, Value::Null) {
153                    right_v.clone()
154                } else {
155                    left_v
156                }
157            }
158        };
159        if let Some((lo, hi)) = &b.clamp {
160            let lo_v = self.eval_expr(lo, env)?;
161            let hi_v = self.eval_expr(hi, env)?;
162            if let (Some(x), Some(lo_n), Some(hi_n)) =
163                (chosen.as_f64(), lo_v.as_f64(), hi_v.as_f64())
164            {
165                let c = x.clamp(lo_n, hi_n);
166                chosen = match &chosen {
167                    Value::Quantity(q) => Value::Quantity(crate::value::Quantity {
168                        value: c,
169                        unit: q.unit.clone(),
170                    }),
171                    _ => Value::F64(c),
172                };
173            }
174        }
175        assign_path(env, &b.left, chosen.clone())?;
176        assign_path(env, &b.right, chosen)?;
177        Ok(())
178    }
179
180    /// Calls a function.
181    pub fn call_function(
182        &mut self,
183        program: &Program,
184        name: &str,
185        args: Vec<Value>,
186        env: &mut Env,
187    ) -> Result<Value, Diagnostic> {
188        let f = program.items.iter().find_map(|i| match i {
189            Item::Function(f) if f.name == name => Some(f),
190            _ => None,
191        });
192        let f = f.ok_or_else(|| {
193            Diagnostic::new(
194                DiagCode::E600,
195                Span::point(0),
196                format!("no function {name}"),
197            )
198        })?;
199        if let Some(steps) = budget_steps(&f.budget, env, self)? {
200            self.budget.steps_left = self.budget.steps_left.min(steps);
201        }
202        let mut local = Env::with_task_scope(env.task_scope.clone());
203        // Inherit import aliases, enum declarations, and field/material/law
204        // declarations from the calling env.
205        local.aliases = env.aliases.clone();
206        local.enums = env.enums.clone();
207        for item in &program.items {
208            if let Item::Enum(e) = item {
209                local.enums.entry(e.name.clone()).or_insert_with(|| e.clone());
210            }
211        }
212        local.fields = env.fields.clone();
213        local.materials = env.materials.clone();
214        local.laws = env.laws.clone();
215        for (p, a) in f.params.iter().zip(args.into_iter()) {
216            local.vars.insert(p.name.clone(), a);
217        }
218        // Attach the program so nested calls can resolve sibling functions.
219        let prev = self.program.take();
220        self.program = Some(std::sync::Arc::new(program.clone()));
221        let r = self.finish_block(&f.body, &mut local);
222        self.program = prev;
223        r
224    }
225
226    /// Dispatch a hook by event path (e.g. `["pulse", "message"]` or `["tick"]`).
227    ///
228    /// Finds the first `on <path>(…)` hook in the program whose path matches,
229    /// binds the supplied argument values to its parameters, and evaluates its
230    /// body. Returns `Ok(Value::Null)` if no matching hook exists (the host
231    /// may choose to ignore unhandled events silently).
232    pub fn call_hook(
233        &mut self,
234        program: &Program,
235        path: &[String],
236        args: Vec<Value>,
237        env: &mut Env,
238    ) -> Result<Value, Diagnostic> {
239        let h = program.items.iter().find_map(|i| match i {
240            Item::Hook(h) if h.path == path => Some(h),
241            _ => None,
242        });
243        let h = match h {
244            Some(h) => h,
245            None => return Ok(Value::Null),
246        };
247        if let Some(steps) = budget_steps(&h.budget, env, self)? {
248            self.budget.steps_left = self.budget.steps_left.min(steps);
249        }
250        let mut local = Env::with_task_scope(env.task_scope.clone());
251        local.aliases = env.aliases.clone();
252        local.enums = env.enums.clone();
253        for item in &program.items {
254            if let Item::Enum(e) = item {
255                local.enums.entry(e.name.clone()).or_insert_with(|| e.clone());
256            }
257        }
258        local.fields = env.fields.clone();
259        local.materials = env.materials.clone();
260        local.laws = env.laws.clone();
261        for (p, a) in h.params.iter().zip(args.into_iter()) {
262            local.vars.insert(p.name.clone(), a);
263        }
264        // Attach the program so the hook body can call sibling functions.
265        let prev = self.program.take();
266        self.program = Some(std::sync::Arc::new(program.clone()));
267        let r = self.finish_block(&h.body, &mut local);
268        self.program = prev;
269        r
270    }
271}
272
273fn assign_path(env: &mut Env, target: &Expr, value: Value) -> Result<(), Diagnostic> {
274    match &target.kind {
275        ExprKind::Ident(n) => {
276            env.vars.insert(n.clone(), value);
277            Ok(())
278        }
279        ExprKind::Member { recv, name } => {
280            if let ExprKind::Ident(root) = &recv.kind {
281                match env.vars.get_mut(root) {
282                    Some(Value::Record(map)) => {
283                        map.insert(name.clone(), value);
284                        Ok(())
285                    }
286                    Some(_) => Err(Diagnostic::new(
287                        DiagCode::E600,
288                        target.span,
289                        format!("cannot bind into non-record `{root}`"),
290                    )),
291                    None => {
292                        let mut map = std::collections::BTreeMap::new();
293                        map.insert(name.clone(), value);
294                        env.vars.insert(root.clone(), Value::Record(map));
295                        Ok(())
296                    }
297                }
298            } else {
299                Err(Diagnostic::new(
300                    DiagCode::E100,
301                    target.span,
302                    "bind target must be an identifier or record.field",
303                ))
304            }
305        }
306        _ => Err(Diagnostic::new(
307            DiagCode::E100,
308            target.span,
309            "bind target must be an identifier or record.field",
310        )),
311    }
312}
313
314/// Resolve `part` + `signature` plus a facet and/or a colour|sound reading.
315///
316/// Shared words for Poet and every Qualia app, not a town or game dialect.
317/// A part is its own continuant. Water conditions are not `liquid_water`.
318/// Flora, fauna, and funga are not sugar, water, or oil records. Colour and
319/// sound are two readings of one EMF spectrum axis. They do not write spatial
320/// coordinates or bake a frame.
321fn attach_part_signature(
322    rec: &mut std::collections::BTreeMap<String, Value>,
323    span: crate::span::Span,
324) -> Result<(), Diagnostic> {
325    use crate::physics::PartContinuant;
326
327    let part = match rec.get("part") {
328        Some(Value::String(s)) => s.clone(),
329        _ => {
330            return Err(Diagnostic::new(
331                DiagCode::E600,
332                span,
333                "part must name a continuant id",
334            ))
335        }
336    };
337    let signature = match rec.get("signature") {
338        Some(Value::String(s)) => s.clone(),
339        _ => {
340            return Err(Diagnostic::new(
341                DiagCode::E600,
342                span,
343                "signature must name a material signature on this physics stack",
344            ))
345        }
346    };
347    let facet = match rec.get("facet") {
348        Some(Value::String(s)) => Some(s.clone()),
349        Some(_) => {
350            return Err(Diagnostic::new(
351                DiagCode::E600,
352                span,
353                "facet must be mechanical, thermal, optical, acoustic, or chemical",
354            ))
355        }
356        None => None,
357    };
358    let reading = match rec.get("reading") {
359        Some(Value::String(s)) => Some(s.clone()),
360        Some(_) => {
361            return Err(Diagnostic::new(
362                DiagCode::E600,
363                span,
364                "reading must be colour or sound",
365            ))
366        }
367        None => None,
368    };
369    let bound = PartContinuant::bind_with(&part, &signature, facet.as_deref(), reading.as_deref())
370        .map_err(|e| Diagnostic::new(DiagCode::E600, span, e.message()))?;
371    if let Value::Record(extra) = bound.to_record() {
372        for (k, v) in extra {
373            rec.insert(k, v);
374        }
375    }
376    Ok(())
377}