kinetik-embed 0.1.0-alpha.0

Rust-native scripting language runtime and CLI for game engines.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
//! Rust embedding API for Kinetik.

use std::any::Any;
use std::collections::BTreeMap;
use std::fmt;
use std::fs;
use std::io;
use std::path::Path;

use kinetik_diag::{Diagnostic, SourceFile, SourceId, Span};
use kinetik_parse::parse_module;
use kinetik_runtime::HostId;
pub use kinetik_runtime::{HostHandle, Value};
use kinetik_vm::{HostNativeResult, RuntimeError, Vm};

/// Convenient result type for Kinetik embedding operations.
pub type Result<T> = std::result::Result<T, Error>;

/// Result of a successful hot reload.
#[derive(Clone, Debug, PartialEq)]
pub struct ReloadReport {
    /// Value produced by evaluating the reloaded source.
    pub value: Value,
    /// Non-fatal reload diagnostics such as incompatible preserved values.
    pub diagnostics: Vec<Diagnostic>,
}

/// Error returned by the Kinetik embedding API.
#[derive(Debug)]
pub enum Error {
    /// A script file could not be read.
    Io(io::Error),
    /// Source text could not be parsed.
    Parse {
        /// Source file associated with the diagnostics.
        source: Box<SourceFile>,
        /// Diagnostics emitted by lexing or parsing.
        diagnostics: Vec<Diagnostic>,
    },
    /// Runtime evaluation failed.
    Runtime {
        /// Source file associated with the runtime span.
        source: Option<Box<SourceFile>>,
        /// Runtime error emitted by the VM.
        error: Box<RuntimeError>,
    },
    /// A requested function is not defined.
    MissingFunction(String),
    /// A value could not be converted to a requested Rust type.
    Conversion(String),
    /// A host handle no longer refers to a live host object.
    StaleHostHandle {
        /// Raw host handle id.
        id: u64,
    },
    /// A host handle was accessed as the wrong Rust type.
    HostTypeMismatch {
        /// Expected Rust type name.
        expected: &'static str,
    },
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(error) => write!(f, "failed to read script: {error}"),
            Self::Parse { diagnostics, .. } => {
                write!(
                    f,
                    "failed to parse script with {} diagnostic(s)",
                    diagnostics.len()
                )
            }
            Self::Runtime { error, .. } => write!(f, "runtime error: {}", error.message()),
            Self::MissingFunction(name) => write!(f, "function `{name}` is not defined"),
            Self::Conversion(message) => f.write_str(message),
            Self::StaleHostHandle { id } => write!(f, "stale host handle #{id}"),
            Self::HostTypeMismatch { expected } => {
                write!(f, "host handle does not contain `{expected}`")
            }
        }
    }
}

impl std::error::Error for Error {}

impl From<io::Error> for Error {
    fn from(error: io::Error) -> Self {
        Self::Io(error)
    }
}

/// Embedded Kinetik runtime.
#[derive(Debug)]
pub struct Kinetik {
    vm: Vm,
    sources: BTreeMap<SourceId, SourceFile>,
    hosts: HostRegistry,
    next_source_id: u32,
}

impl Default for Kinetik {
    fn default() -> Self {
        Self::new()
    }
}

impl Kinetik {
    /// Creates a new embedded runtime.
    #[must_use]
    pub fn new() -> Self {
        Self {
            vm: Vm::new(),
            sources: BTreeMap::new(),
            hosts: HostRegistry::default(),
            next_source_id: 1,
        }
    }

    /// Registers a host-native function in the root environment.
    pub fn register_native<F>(&mut self, name: impl Into<String>, function: F)
    where
        F: Fn(&[Value]) -> HostNativeResult + Send + Sync + 'static,
    {
        self.vm.define_host_native(name, function);
    }

    /// Stores a host-owned object and returns an opaque script value for it.
    pub fn insert_host<T>(&mut self, value: T) -> Value
    where
        T: Any + Send + Sync + 'static,
    {
        self.hosts.insert(value)
    }

    /// Removes a host-owned object, making existing handles stale.
    ///
    /// # Errors
    ///
    /// Returns a stale handle error when the value is not a live host handle.
    pub fn remove_host(&mut self, value: &Value) -> Result<()> {
        self.hosts.remove(value)
    }

    /// Accesses a host object through a closure without exposing raw references.
    ///
    /// # Errors
    ///
    /// Returns a stale handle or type mismatch error when the handle is invalid.
    pub fn with_host<T, R>(&self, value: &Value, read: impl FnOnce(&T) -> R) -> Result<R>
    where
        T: Any + Send + Sync + 'static,
    {
        self.hosts.with(value, read)
    }

    /// Mutates a host object through a closure without exposing raw references.
    ///
    /// # Errors
    ///
    /// Returns a stale handle or type mismatch error when the handle is invalid.
    pub fn with_host_mut<T, R>(
        &mut self,
        value: &Value,
        write: impl FnOnce(&mut T) -> R,
    ) -> Result<R>
    where
        T: Any + Send + Sync + 'static,
    {
        self.hosts.with_mut(value, write)
    }

    /// Defines a global script value.
    pub fn define_global(&mut self, name: impl Into<String>, value: Value) {
        self.vm.define_global(name, value);
    }

    /// Loads, parses, and evaluates a Kinetik source string.
    ///
    /// # Errors
    ///
    /// Returns parse diagnostics or a runtime error when script loading fails.
    pub fn load_source(
        &mut self,
        name: impl Into<String>,
        text: impl Into<String>,
    ) -> Result<Value> {
        self.eval_source(name, text)
    }

    /// Parses and reloads a Kinetik source string into the running runtime.
    ///
    /// Parse errors are reported before the current runtime is mutated, so the
    /// previously loaded script functions remain callable after a bad edit.
    ///
    /// # Errors
    ///
    /// Returns parse diagnostics or a runtime error when script reloading fails.
    pub fn reload_source(
        &mut self,
        name: impl Into<String>,
        text: impl Into<String>,
    ) -> Result<ReloadReport> {
        let source = self.source_file(name, text);
        let parsed = parse_module(&source);
        if parsed.has_errors() {
            return Err(Error::Parse {
                source: Box::new(source),
                diagnostics: parsed.diagnostics,
            });
        }

        let Some(module) = parsed.node else {
            return Err(Error::Conversion(String::from(
                "parser did not produce a module",
            )));
        };

        let previous = self.vm.globals();
        let stale_tasks = self.vm.cancel_stale_tasks();
        self.sources.insert(source.id(), source.clone());
        let value = self
            .vm
            .eval_module(&module)
            .map_err(|error| self.runtime_error(error))?;

        let mut diagnostics = preserve_compatible_globals(&mut self.vm, &previous, module.span);
        if stale_tasks > 0 {
            diagnostics.push(
                Diagnostic::warning(format!(
                    "cancelled {stale_tasks} stale task(s) during reload"
                ))
                .with_span(module.span),
            );
        }

        Ok(ReloadReport { value, diagnostics })
    }

    fn eval_source(&mut self, name: impl Into<String>, text: impl Into<String>) -> Result<Value> {
        let source = self.source_file(name, text);
        let parsed = parse_module(&source);
        if parsed.has_errors() {
            return Err(Error::Parse {
                source: Box::new(source),
                diagnostics: parsed.diagnostics,
            });
        }

        self.sources.insert(source.id(), source.clone());
        let Some(module) = parsed.node else {
            return Err(Error::Conversion(String::from(
                "parser did not produce a module",
            )));
        };
        let value = self
            .vm
            .eval_module(&module)
            .map_err(|error| self.runtime_error(error))?;
        Ok(value)
    }

    /// Loads, parses, and evaluates a Kinetik script file.
    ///
    /// # Errors
    ///
    /// Returns I/O, parse, or runtime errors when script loading fails.
    pub fn load_file(&mut self, path: impl AsRef<Path>) -> Result<Value> {
        let path = path.as_ref();
        let text = fs::read_to_string(path)?;
        self.load_source(path.display().to_string(), text)
    }

    /// Calls a named script or native function.
    ///
    /// # Errors
    ///
    /// Returns an error when the function is missing, not callable, or fails.
    pub fn call_function(&mut self, name: &str, args: &[Value]) -> Result<Vec<Value>> {
        let callee = self
            .vm
            .get(name)
            .ok_or_else(|| Error::MissingFunction(name.to_owned()))?;
        self.vm
            .call(&callee, args, Span::new(SourceId(0), 0, 0))
            .map_err(|error| self.runtime_error(error))
    }

    /// Reads a global value from the embedded runtime.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<Value> {
        self.vm.get(name)
    }

    /// Drains lines produced by the default standard-library `print` function.
    pub fn drain_output(&mut self) -> impl Iterator<Item = String> + '_ {
        self.vm.drain_output()
    }

    fn source_file(&mut self, name: impl Into<String>, text: impl Into<String>) -> SourceFile {
        let id = SourceId(self.next_source_id);
        self.next_source_id += 1;
        SourceFile::new(id, name, text)
    }

    fn runtime_error(&self, error: RuntimeError) -> Error {
        Error::Runtime {
            source: self
                .sources
                .get(&error.span().source)
                .cloned()
                .map(Box::new),
            error: Box::new(error),
        }
    }
}

fn preserve_compatible_globals(
    vm: &mut Vm,
    previous: &BTreeMap<String, Value>,
    span: Span,
) -> Vec<Diagnostic> {
    let current = vm.globals();
    let mut diagnostics = Vec::new();

    for (name, old_value) in previous {
        let Some(new_value) = current.get(name) else {
            continue;
        };
        if matches!(new_value, Value::Function(_)) {
            continue;
        }
        if old_value.type_name() == new_value.type_name() {
            vm.define_global(name.clone(), old_value.clone());
        } else {
            diagnostics.push(
                Diagnostic::warning(format!(
                    "reload recreated `{name}` because its type changed from {} to {}",
                    old_value.type_name(),
                    new_value.type_name()
                ))
                .with_span(span),
            );
        }
    }

    vm.refresh_function_globals();
    diagnostics
}

/// Converts Rust values into Kinetik runtime values.
pub trait IntoValue {
    /// Converts this value into a Kinetik value.
    fn into_value(self) -> Value;
}

impl IntoValue for Value {
    fn into_value(self) -> Value {
        self
    }
}

impl IntoValue for () {
    fn into_value(self) -> Value {
        Value::Nil
    }
}

impl IntoValue for bool {
    fn into_value(self) -> Value {
        Value::bool(self)
    }
}

impl IntoValue for f64 {
    fn into_value(self) -> Value {
        Value::number(self)
    }
}

impl IntoValue for String {
    fn into_value(self) -> Value {
        Value::string(self)
    }
}

impl IntoValue for &str {
    fn into_value(self) -> Value {
        Value::string(self)
    }
}

impl<T: IntoValue> IntoValue for Vec<T> {
    fn into_value(self) -> Value {
        Value::array(
            self.into_iter()
                .map(IntoValue::into_value)
                .collect::<Vec<_>>(),
        )
    }
}

impl<T: IntoValue> IntoValue for BTreeMap<String, T> {
    fn into_value(self) -> Value {
        Value::object(
            self.into_iter()
                .map(|(key, value)| (key, value.into_value())),
        )
    }
}

/// Converts Kinetik runtime values into Rust values.
pub trait FromValue: Sized {
    /// Converts a Kinetik value into this Rust type.
    ///
    /// # Errors
    ///
    /// Returns a conversion error when the runtime value has the wrong type.
    fn from_value(value: Value) -> Result<Self>;
}

impl FromValue for Value {
    fn from_value(value: Value) -> Result<Self> {
        Ok(value)
    }
}

impl FromValue for bool {
    fn from_value(value: Value) -> Result<Self> {
        match value {
            Value::Bool(value) => Ok(value),
            other => Err(type_error("bool", &other)),
        }
    }
}

impl FromValue for f64 {
    fn from_value(value: Value) -> Result<Self> {
        match value {
            Value::Number(value) => Ok(value),
            other => Err(type_error("number", &other)),
        }
    }
}

impl FromValue for String {
    fn from_value(value: Value) -> Result<Self> {
        match value {
            Value::String(value) => Ok(value),
            other => Err(type_error("string", &other)),
        }
    }
}

impl<T: FromValue> FromValue for Vec<T> {
    fn from_value(value: Value) -> Result<Self> {
        match value {
            Value::Array(array) => array
                .elements()
                .iter()
                .cloned()
                .map(T::from_value)
                .collect::<Result<Vec<_>>>(),
            other => Err(type_error("array", &other)),
        }
    }
}

impl<T: FromValue> FromValue for BTreeMap<String, T> {
    fn from_value(value: Value) -> Result<Self> {
        match value {
            Value::Object(object) => object
                .fields()
                .iter()
                .map(|(key, value)| T::from_value(value.clone()).map(|value| (key.clone(), value)))
                .collect::<Result<BTreeMap<_, _>>>(),
            other => Err(type_error("object", &other)),
        }
    }
}

fn type_error(expected: &str, value: &Value) -> Error {
    Error::Conversion(format!("expected {expected}, got {}", value.type_name()))
}

#[derive(Default)]
struct HostRegistry {
    entries: BTreeMap<HostId, HostEntry>,
    next_id: u64,
}

impl fmt::Debug for HostRegistry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HostRegistry")
            .field("entry_count", &self.entries.len())
            .field("next_id", &self.next_id)
            .finish()
    }
}

impl HostRegistry {
    fn insert<T>(&mut self, value: T) -> Value
    where
        T: Any + Send + Sync + 'static,
    {
        self.next_id += 1;
        let id = HostId::new(self.next_id);
        let generation = 1;
        self.entries.insert(
            id,
            HostEntry {
                generation,
                value: Box::new(value),
            },
        );
        Value::host(id, generation)
    }

    fn remove(&mut self, value: &Value) -> Result<()> {
        let handle = host_handle(value)?;
        let entry = self
            .entries
            .get(&handle.id())
            .ok_or_else(|| stale_handle(handle))?;
        if entry.generation != handle.generation() {
            return Err(stale_handle(handle));
        }
        self.entries.remove(&handle.id());
        Ok(())
    }

    fn with<T, R>(&self, value: &Value, read: impl FnOnce(&T) -> R) -> Result<R>
    where
        T: Any + Send + Sync + 'static,
    {
        let entry = self.entry(value)?;
        let Some(value) = entry.value.downcast_ref::<T>() else {
            return Err(Error::HostTypeMismatch {
                expected: std::any::type_name::<T>(),
            });
        };
        Ok(read(value))
    }

    fn with_mut<T, R>(&mut self, value: &Value, write: impl FnOnce(&mut T) -> R) -> Result<R>
    where
        T: Any + Send + Sync + 'static,
    {
        let entry = self.entry_mut(value)?;
        let Some(value) = entry.value.downcast_mut::<T>() else {
            return Err(Error::HostTypeMismatch {
                expected: std::any::type_name::<T>(),
            });
        };
        Ok(write(value))
    }

    fn entry(&self, value: &Value) -> Result<&HostEntry> {
        let handle = host_handle(value)?;
        let entry = self
            .entries
            .get(&handle.id())
            .ok_or_else(|| stale_handle(handle))?;
        if entry.generation == handle.generation() {
            Ok(entry)
        } else {
            Err(stale_handle(handle))
        }
    }

    fn entry_mut(&mut self, value: &Value) -> Result<&mut HostEntry> {
        let handle = host_handle(value)?;
        let entry = self
            .entries
            .get_mut(&handle.id())
            .ok_or_else(|| stale_handle(handle))?;
        if entry.generation == handle.generation() {
            Ok(entry)
        } else {
            Err(stale_handle(handle))
        }
    }
}

struct HostEntry {
    generation: u64,
    value: Box<dyn Any + Send + Sync>,
}

fn host_handle(value: &Value) -> Result<HostHandle> {
    match value {
        Value::Host(handle) => Ok(*handle),
        other => Err(type_error("native host handle", other)),
    }
}

fn stale_handle(handle: HostHandle) -> Error {
    Error::StaleHostHandle {
        id: handle.id().get(),
    }
}

#[cfg(test)]
mod tests {
    use super::{Error, FromValue, IntoValue, Kinetik, Value};

    #[test]
    fn converts_core_values() {
        assert_eq!(true.into_value(), Value::bool(true));
        assert_eq!(String::from("hi").into_value(), Value::string("hi"));

        let value = vec![1.0, 2.0].into_value();
        assert_eq!(
            Vec::<f64>::from_value(value).expect("array"),
            vec![1.0, 2.0]
        );
    }

    #[test]
    fn creates_runtime() {
        let mut runtime = Kinetik::new();
        runtime
            .load_source("test.kn", "let x = 2\n")
            .expect("loads source");

        assert_eq!(runtime.get("x"), Some(Value::number(2.0)));
    }

    #[test]
    fn stores_and_invalidates_host_handles() {
        let mut runtime = Kinetik::new();
        let handle = runtime.insert_host(String::from("player"));

        let name = runtime
            .with_host::<String, _>(&handle, Clone::clone)
            .expect("host value");
        assert_eq!(name, "player");

        runtime
            .with_host_mut::<String, _>(&handle, |name| name.push_str("-1"))
            .expect("host value mut");
        assert_eq!(
            runtime
                .with_host::<String, _>(&handle, Clone::clone)
                .expect("host value"),
            "player-1"
        );

        runtime.remove_host(&handle).expect("removes host value");
        assert!(matches!(
            runtime.with_host::<String, _>(&handle, Clone::clone),
            Err(Error::StaleHostHandle { .. })
        ));
    }
}