1use std::collections::BTreeMap;
8
9use super::{animation_preset, is_known};
10use crate::animation::presets::{evaluate_preset, AnimationSample};
11use crate::animation::AnimationFamily;
12use crate::error::{DiagCode, Diagnostic};
13use crate::span::Span;
14use crate::value::Value;
15
16pub fn invoke_local(id: &str, args: &Value, span: Span) -> Result<Value, Diagnostic> {
18 if let Some((family_name, preset)) = animation_preset(id) {
19 let t = f64_field(args, "t")
20 .or_else(|| scalar_arg(args))
21 .unwrap_or(0.0);
22 let family = AnimationFamily::from_name(family_name).ok_or_else(|| {
23 Diagnostic::new(
24 DiagCode::E100,
25 span,
26 format!("unknown animation family {family_name}"),
27 )
28 })?;
29 return Ok(sample_to_value(evaluate_preset(family, preset, t)));
30 }
31 if id == "Animation.evaluate_preset" {
32 let family_name = string_field(args, "family").unwrap_or("spatial_kinematics");
33 let preset = string_field(args, "preset").unwrap_or("orbit_spin");
34 let t = f64_field(args, "t").unwrap_or(0.0);
35 let family = AnimationFamily::from_name(family_name).ok_or_else(|| {
36 Diagnostic::new(
37 DiagCode::E100,
38 span,
39 format!("unknown animation family {family_name}"),
40 )
41 })?;
42 return Ok(sample_to_value(evaluate_preset(family, preset, t)));
43 }
44 if id == "Animation.spring_step" {
45 let current = f64_field(args, "current").unwrap_or(0.0);
46 let target = f64_field(args, "target").unwrap_or(1.0);
47 let velocity = f64_field(args, "velocity").unwrap_or(0.0);
48 let stiffness = f64_field(args, "stiffness").unwrap_or(300.0);
49 let damping = f64_field(args, "damping").unwrap_or(25.0);
50 let dt = f64_field(args, "dt").unwrap_or(0.016);
51 let cfg = crate::animation::SpringConfig::new(stiffness, damping);
52 let state = crate::animation::SpringState1D::new(current, velocity, target);
53 let (pos, vel, settled) = state.evaluate_at(&cfg, dt);
54 let mut rec = BTreeMap::new();
55 rec.insert("position".into(), Value::F64(pos));
56 rec.insert("velocity".into(), Value::F64(vel));
57 rec.insert("settled".into(), Value::Bool(settled));
58 return Ok(Value::Record(rec));
59 }
60 if id == "Animation.list_presets" {
61 let mut list = Vec::new();
62 for info in crate::animation::list_all_presets() {
63 let mut rec = BTreeMap::new();
64 rec.insert("family".into(), Value::String(info.family.into()));
65 rec.insert("preset".into(), Value::String(info.preset.into()));
66 list.push(Value::Record(rec));
67 }
68 return Ok(Value::List(list));
69 }
70 if id.starts_with("Cosmic.") {
71 return super::cosmic::invoke(id, args, span);
72 }
73 if let Some(result) = super::stdlib::try_invoke(id, args, span) {
74 return result;
75 }
76 if let Some(result) = super::logic::try_invoke(id, args, span) {
77 return result;
78 }
79 if let Some(result) = super::specialized::try_invoke(id, args, span) {
80 return result;
81 }
82 if id == "GraphDatabase.volume_open" {
83 if let Some(res) = try_local_volume_open(args, span) {
84 return res;
85 }
86 }
87 if id == "GraphDatabase.sparql" {
88 return eval_local_sparql(args, span);
89 }
90 if id.starts_with("HID.") {
91 return Err(Diagnostic::new(
92 DiagCode::E702,
93 span,
94 format!("capability `{id}` requires a bound HID hardware host"),
95 ));
96 }
97 if is_known(id) {
98 return Err(Diagnostic::new(
99 DiagCode::E702,
100 span,
101 format!("capability `{id}` has no in-process local kernel; bind a host provider"),
102 ));
103 }
104 Err(Diagnostic::new(DiagCode::E100, span, unknown_message(id)))
105}
106
107pub fn sample_to_value(s: AnimationSample) -> Value {
109 let mut rec = BTreeMap::new();
110 rec.insert("scalar".into(), Value::F64(s.scalar));
111 rec.insert(
112 "vector".into(),
113 Value::List(vec![
114 Value::F64(s.vector[0]),
115 Value::F64(s.vector[1]),
116 Value::F64(s.vector[2]),
117 ]),
118 );
119 rec.insert("secondary".into(), Value::F64(s.secondary));
120 rec.insert("settled".into(), Value::Bool(s.settled));
121 Value::Record(rec)
122}
123
124pub fn payload_from_args(pos: &[Value], named: &[(String, Value)]) -> Value {
126 if named.is_empty() && pos.len() == 1 {
127 match &pos[0] {
128 Value::Record(_) => return pos[0].clone(),
129 other => {
130 let mut rec = BTreeMap::new();
131 rec.insert("t".into(), other.clone());
132 rec.insert("value".into(), other.clone());
133 return Value::Record(rec);
134 }
135 }
136 }
137 let mut rec = BTreeMap::new();
138 if pos.len() == 1 {
139 rec.insert("t".into(), pos[0].clone());
140 rec.insert("value".into(), pos[0].clone());
141 } else {
142 for (i, a) in pos.iter().enumerate() {
143 rec.insert(format!("arg{i}"), a.clone());
144 }
145 }
146 for (k, v) in named {
147 rec.insert(k.clone(), v.clone());
148 }
149 Value::Record(rec)
150}
151
152fn unknown_message(id: &str) -> String {
153 match super::did_you_mean(id) {
154 Some(s) => format!("unknown capability `{id}`; did you mean `{s}`?"),
155 None => format!("unknown capability `{id}`"),
156 }
157}
158
159fn string_field<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
160 match args {
161 Value::Record(map) => match map.get(key) {
162 Some(Value::String(s)) => Some(s.as_str()),
163 _ => None,
164 },
165 _ => None,
166 }
167}
168
169fn f64_field(args: &Value, key: &str) -> Option<f64> {
170 match args {
171 Value::Record(map) => match map.get(key) {
172 Some(Value::F64(n)) => Some(*n),
173 Some(Value::I64(n)) => Some(*n as f64),
174 Some(Value::U64(n)) => Some(*n as f64),
175 Some(Value::Quantity(q)) => Some(q.value),
176 _ => None,
177 },
178 _ => None,
179 }
180}
181
182fn scalar_arg(args: &Value) -> Option<f64> {
183 match args {
184 Value::F64(n) => Some(*n),
185 Value::I64(n) => Some(*n as f64),
186 Value::Record(map) => match map.get("value") {
187 Some(Value::F64(n)) => Some(*n),
188 Some(Value::I64(n)) => Some(*n as f64),
189 _ => None,
190 },
191 _ => None,
192 }
193}
194
195#[derive(Clone, Copy, Debug)]
196struct LocalQuin {
197 subject: u64,
198 predicate: u64,
199 object: u64,
200 context: u64,
201 metadata: u64,
202 parity: u64,
203}
204
205impl LocalQuin {
206 fn from_le_bytes(chunk: &[u8]) -> Option<Self> {
207 if chunk.len() != 48 {
208 return None;
209 }
210 let subject = u64::from_le_bytes(chunk[0..8].try_into().ok()?);
211 let predicate = u64::from_le_bytes(chunk[8..16].try_into().ok()?);
212 let object = u64::from_le_bytes(chunk[16..24].try_into().ok()?);
213 let context = u64::from_le_bytes(chunk[24..32].try_into().ok()?);
214 let metadata = u64::from_le_bytes(chunk[32..40].try_into().ok()?);
215 let parity = u64::from_le_bytes(chunk[40..48].try_into().ok()?);
216 Some(Self {
217 subject,
218 predicate,
219 object,
220 context,
221 metadata,
222 parity,
223 })
224 }
225
226 fn to_record(self) -> Value {
227 let mut rec = BTreeMap::new();
228 rec.insert("subject".into(), Value::U64(self.subject));
229 rec.insert("predicate".into(), Value::U64(self.predicate));
230 rec.insert("object".into(), Value::U64(self.object));
231 rec.insert("context".into(), Value::U64(self.context));
232 rec.insert("metadata".into(), Value::U64(self.metadata));
233 rec.insert("parity".into(), Value::U64(self.parity));
234 Value::Record(rec)
235 }
236}
237
238std::thread_local! {
239 static LOCAL_ADMITTED_QUINS: std::cell::RefCell<Vec<LocalQuin>> = const { std::cell::RefCell::new(Vec::new()) };
240}
241
242fn extract_u8_slice(args: &Value, key: &str, span: Span) -> Result<Option<Vec<u8>>, Diagnostic> {
243 let Value::Record(map) = args else {
244 return Ok(None);
245 };
246 let Some(val) = map.get(key) else {
247 return Ok(None);
248 };
249 let Value::List(items) = val else {
250 return Err(Diagnostic::new(
251 DiagCode::E100,
252 span,
253 format!("`{key}` must be a list of u8 bytes"),
254 ));
255 };
256 let mut out = Vec::with_capacity(items.len());
257 for item in items {
258 match item {
259 Value::U64(n) if *n <= 255 => out.push(*n as u8),
260 Value::I64(n) if *n >= 0 && *n <= 255 => out.push(*n as u8),
261 _ => {
262 return Err(Diagnostic::new(
263 DiagCode::E100,
264 span,
265 format!("`{key}` byte element out of range [0..255]"),
266 ))
267 }
268 }
269 }
270 Ok(Some(out))
271}
272
273fn parse_quins_from_bytes(bytes: &[u8], span: Span) -> Result<Vec<LocalQuin>, Diagnostic> {
274 if bytes.is_empty() || bytes.len() % 48 != 0 {
275 return Err(Diagnostic::new(
276 DiagCode::E100,
277 span,
278 "local Q42 slice must be a non-empty multiple of 48-byte NQuin records",
279 ));
280 }
281 let mut quins = Vec::with_capacity(bytes.len() / 48);
282 for chunk in bytes.chunks_exact(48) {
283 if let Some(q) = LocalQuin::from_le_bytes(chunk) {
284 quins.push(q);
285 }
286 }
287 Ok(quins)
288}
289
290fn try_local_volume_open(args: &Value, span: Span) -> Option<Result<Value, Diagnostic>> {
291 let bytes = match extract_u8_slice(args, "bytes", span) {
292 Ok(Some(b)) => b,
293 Ok(None) => return None,
294 Err(e) => return Some(Err(e)),
295 };
296 let quins = match parse_quins_from_bytes(&bytes, span) {
297 Ok(q) => q,
298 Err(e) => return Some(Err(e)),
299 };
300 let count = quins.len() as u64;
301 let load = match args {
302 Value::Record(m) => match m.get("load") {
303 Some(Value::Bool(b)) => *b,
304 _ => true,
305 },
306 _ => true,
307 };
308 if load {
309 LOCAL_ADMITTED_QUINS.with(|cell| {
310 *cell.borrow_mut() = quins;
311 });
312 }
313 let key = string_field(args, "key")
314 .or_else(|| string_field(args, "path"))
315 .unwrap_or("entry.q42");
316 let mut rec = BTreeMap::new();
317 rec.insert("path".into(), Value::String(key.into()));
318 rec.insert("loaded".into(), Value::Bool(load));
319 rec.insert("created".into(), Value::Bool(false));
320 rec.insert("quin_count".into(), Value::U64(count));
321 rec.insert("block_count".into(), Value::U64(0));
322 rec.insert("version".into(), Value::U64(0));
323 Some(Ok(Value::Record(rec)))
324}
325
326fn u64_field(args: &Value, key: &str) -> Option<u64> {
327 match args {
328 Value::Record(map) => match map.get(key) {
329 Some(Value::U64(n)) => Some(*n),
330 Some(Value::I64(n)) if *n >= 0 => Some(*n as u64),
331 _ => None,
332 },
333 _ => None,
334 }
335}
336
337fn eval_local_sparql(args: &Value, span: Span) -> Result<Value, Diagnostic> {
338 let inline = extract_u8_slice(args, "bytes", span)?;
339 let quins = if let Some(raw) = inline {
340 parse_quins_from_bytes(&raw, span)?
341 } else {
342 LOCAL_ADMITTED_QUINS.with(|cell| cell.borrow().clone())
343 };
344 if quins.is_empty() {
345 return Ok(Value::List(Vec::new()));
346 }
347 let subj = u64_field(args, "subject");
348 let pred = u64_field(args, "predicate");
349 let obj = u64_field(args, "object");
350 let ctx = u64_field(args, "context");
351 let mut rows = Vec::new();
352 for q in quins {
353 if subj.is_some_and(|s| s != q.subject)
354 || pred.is_some_and(|p| p != q.predicate)
355 || obj.is_some_and(|o| o != q.object)
356 || ctx.is_some_and(|c| c != q.context)
357 {
358 continue;
359 }
360 rows.push(q.to_record());
361 }
362 Ok(Value::List(rows))
363}