From bf2ce364330d0416359abb2cfcfdc56e5ba0ed07 Mon Sep 17 00:00:00 2001 From: Ian Hobson Date: Wed, 11 Oct 2023 10:24:43 +0200 Subject: [PATCH 01/13] Rename ValueMap -> KMap and DataMap -> ValueMap --- core/koto/src/koto.rs | 4 +- core/runtime/src/core_lib/io.rs | 8 +- core/runtime/src/core_lib/iterator.rs | 70 +++++------ .../runtime/src/core_lib/iterator/peekable.rs | 4 +- core/runtime/src/core_lib/koto.rs | 26 ++-- core/runtime/src/core_lib/list.rs | 112 +++++++++--------- core/runtime/src/core_lib/map.rs | 107 ++++++++--------- core/runtime/src/core_lib/mod.rs | 28 ++--- core/runtime/src/core_lib/number.rs | 54 ++++----- core/runtime/src/core_lib/os.rs | 12 +- core/runtime/src/core_lib/range.rs | 32 ++--- core/runtime/src/core_lib/string.rs | 54 +++++---- core/runtime/src/core_lib/string/format.rs | 6 +- core/runtime/src/core_lib/test.rs | 26 ++-- core/runtime/src/core_lib/tuple.rs | 32 +++-- core/runtime/src/lib.rs | 4 +- core/runtime/src/prelude.rs | 10 +- core/runtime/src/types/meta_map.rs | 8 +- core/runtime/src/types/mod.rs | 2 +- core/runtime/src/types/object.rs | 18 ++- core/runtime/src/types/value.rs | 26 ++-- core/runtime/src/types/value_iterator.rs | 6 +- core/runtime/src/types/value_key.rs | 2 +- core/runtime/src/types/value_map.rs | 80 ++++++------- core/runtime/src/vm.rs | 24 ++-- core/runtime/tests/object_tests.rs | 4 +- core/runtime/tests/vm_tests.rs | 68 +++++------ examples/poetry/src/koto_bindings.rs | 4 +- libs/color/src/color.rs | 4 +- libs/color/src/lib.rs | 7 +- libs/geometry/src/lib.rs | 6 +- libs/geometry/src/rect.rs | 4 +- libs/geometry/src/vec2.rs | 4 +- libs/geometry/src/vec3.rs | 4 +- libs/json/src/lib.rs | 10 +- libs/random/src/lib.rs | 8 +- libs/tempfile/src/lib.rs | 6 +- libs/toml/src/lib.rs | 10 +- libs/yaml/src/lib.rs | 10 +- 39 files changed, 448 insertions(+), 456 deletions(-) diff --git a/core/koto/src/koto.rs b/core/koto/src/koto.rs index aa894aafd..4694508c1 100644 --- a/core/koto/src/koto.rs +++ b/core/koto/src/koto.rs @@ -64,12 +64,12 @@ impl Koto { } /// Returns a reference to the runtime's prelude - pub fn prelude(&self) -> &ValueMap { + pub fn prelude(&self) -> &KMap { self.runtime.prelude() } /// Returns a reference to the runtime's exports - pub fn exports(&self) -> &ValueMap { + pub fn exports(&self) -> &KMap { self.runtime.exports() } diff --git a/core/runtime/src/core_lib/io.rs b/core/runtime/src/core_lib/io.rs index e68067726..5493412bf 100644 --- a/core/runtime/src/core_lib/io.rs +++ b/core/runtime/src/core_lib/io.rs @@ -12,10 +12,10 @@ use std::{ }; /// The initializer for the io module -pub fn make_module() -> ValueMap { +pub fn make_module() -> KMap { use Value::{Bool, Null, Str}; - let result = ValueMap::with_type("core.io"); + let result = KMap::with_type("core.io"); result.add_fn("create", { move |ctx| match ctx.args() { @@ -217,7 +217,7 @@ impl From for Value { } } -fn file_entries() -> DataMap { +fn file_entries() -> ValueMap { use Value::*; ObjectEntryBuilder::::new() @@ -277,7 +277,7 @@ fn file_entries() -> DataMap { thread_local! { static FILE_TYPE_STRING: ValueString = File::TYPE.into(); - static FILE_ENTRIES: DataMap = file_entries(); + static FILE_ENTRIES: ValueMap = file_entries(); } struct BufferedSystemFile diff --git a/core/runtime/src/core_lib/iterator.rs b/core/runtime/src/core_lib/iterator.rs index 2eb76de00..b63529b4f 100644 --- a/core/runtime/src/core_lib/iterator.rs +++ b/core/runtime/src/core_lib/iterator.rs @@ -7,10 +7,8 @@ pub mod peekable; use crate::{prelude::*, Result, ValueIteratorOutput as Output}; /// Initializes the `iterator` core library module -pub fn make_module() -> ValueMap { - use Value::*; - - let result = ValueMap::with_type("core.iterator"); +pub fn make_module() -> KMap { + let result = KMap::with_type("core.iterator"); result.add_fn("all", |ctx| { let expected_error = "an iterable and predicate function"; @@ -32,7 +30,7 @@ pub fn make_module() -> ValueMap { }; match predicate_result { - Ok(Bool(result)) => { + Ok(Value::Bool(result)) => { if !result { return Ok(false.into()); } @@ -73,7 +71,7 @@ pub fn make_module() -> ValueMap { }; match predicate_result { - Ok(Bool(result)) => { + Ok(Value::Bool(result)) => { if result { return Ok(true.into()); } @@ -105,7 +103,7 @@ pub fn make_module() -> ValueMap { ctx.vm.make_iterator(iterable_b)?, )); - Ok(Iterator(result)) + Ok(Value::Iterator(result)) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -115,7 +113,7 @@ pub fn make_module() -> ValueMap { let expected_error = "an iterable and a chunk size greater than zero"; match ctx.instance_and_args(Value::is_iterable, expected_error)? { - (iterable, [Number(n)]) => { + (iterable, [Value::Number(n)]) => { let iterable = iterable.clone(); let n = *n; match adaptors::Chunks::new(ctx.vm.make_iterator(iterable)?, n.into()) { @@ -138,7 +136,7 @@ pub fn make_module() -> ValueMap { return Err(error); } } - Ok(Null) + Ok(Value::Null) } (iterable, [f]) if f.is_callable() => { let iterable = iterable.clone(); @@ -154,7 +152,7 @@ pub fn make_module() -> ValueMap { Output::Error(error) => return Err(error), } } - Ok(Null) + Ok(Value::Null) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -173,7 +171,7 @@ pub fn make_module() -> ValueMap { } result += 1; } - Ok(Number(result.into())) + Ok(Value::Number(result.into())) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -240,7 +238,7 @@ pub fn make_module() -> ValueMap { .vm .run_function(predicate.clone(), CallArgs::Single(value.clone())) { - Ok(Bool(result)) => { + Ok(Value::Bool(result)) => { if result { return Ok(value); } @@ -259,7 +257,7 @@ pub fn make_module() -> ValueMap { } } - Ok(Null) + Ok(Value::Null) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -330,7 +328,7 @@ pub fn make_module() -> ValueMap { let result = generators::Generate::new(f.clone(), ctx.vm.spawn_shared_vm()); Ok(ValueIterator::new(result).into()) } - [Number(n), f] if f.is_callable() => { + [Value::Number(n), f] if f.is_callable() => { let result = generators::GenerateN::new(n.into(), f.clone(), ctx.vm.spawn_shared_vm()); Ok(ValueIterator::new(result).into()) } @@ -369,7 +367,7 @@ pub fn make_module() -> ValueMap { match ctx.instance_and_args(Value::is_iterable, expected_error)? { (iterable, []) => { let iterable = iterable.clone(); - Ok(Iterator(ctx.vm.make_iterator(iterable)?)) + Ok(Value::Iterator(ctx.vm.make_iterator(iterable)?)) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -399,7 +397,7 @@ pub fn make_module() -> ValueMap { match ctx.instance_and_args(Value::is_iterable, expected_error)? { (iterable, []) => { let iterable = iterable.clone(); - let mut result = Null; + let mut result = Value::Null; let mut iter = ctx.vm.make_iterator(iterable)?.map(collect_pair); for output in &mut iter { @@ -474,7 +472,9 @@ pub fn make_module() -> ValueMap { } } - Ok(result.map_or(Null, |(min, max)| Tuple(vec![min, max].into()))) + Ok(result.map_or(Value::Null, |(min, max)| { + Value::Tuple(vec![min, max].into()) + })) } (iterable, [key_fn]) if key_fn.is_callable() => { let iterable = iterable.clone(); @@ -512,7 +512,9 @@ pub fn make_module() -> ValueMap { } } - Ok(result.map_or(Null, |((min, _), (max, _))| Tuple(vec![min, max].into()))) + Ok(result.map_or(Value::Null, |((min, _), (max, _))| { + Value::Tuple(vec![min, max].into()) + })) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -521,7 +523,7 @@ pub fn make_module() -> ValueMap { result.add_fn("next", |ctx| { let mut iter = match (ctx.instance(), ctx.args()) { // No need to call make_iterator when the argument is already an Iterator - (Some(Iterator(i)), []) => i.clone(), + (Some(Value::Iterator(i)), []) => i.clone(), (Some(iterable), []) | (None, [iterable]) if iterable.is_iterable() => { ctx.vm.make_iterator(iterable.clone())? } @@ -533,7 +535,7 @@ pub fn make_module() -> ValueMap { result.add_fn("next_back", |ctx| { let mut iter = match (ctx.instance(), ctx.args()) { - (Some(Iterator(i)), []) => i.clone(), + (Some(Value::Iterator(i)), []) => i.clone(), (Some(iterable), []) | (None, [iterable]) if iterable.is_iterable() => { ctx.vm.make_iterator(iterable.clone())? } @@ -577,7 +579,7 @@ pub fn make_module() -> ValueMap { }; match predicate_result { - Ok(Bool(result)) => { + Ok(Value::Bool(result)) => { if result { return Ok(i.into()); } @@ -592,7 +594,7 @@ pub fn make_module() -> ValueMap { } } - Ok(Null) + Ok(Value::Null) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -617,7 +619,7 @@ pub fn make_module() -> ValueMap { let result = generators::Repeat::new(value.clone()); Ok(ValueIterator::new(result).into()) } - [value, Number(n)] => { + [value, Value::Number(n)] => { let result = generators::RepeatN::new(value.clone(), n.into()); Ok(ValueIterator::new(result).into()) } @@ -643,7 +645,7 @@ pub fn make_module() -> ValueMap { let expected_error = "an iterable and non-negative number"; match ctx.instance_and_args(Value::is_iterable, expected_error)? { - (iterable, [Number(n)]) if *n >= 0.0 => { + (iterable, [Value::Number(n)]) if *n >= 0.0 => { let iterable = iterable.clone(); let n = *n; let mut iter = ctx.vm.make_iterator(iterable)?; @@ -654,7 +656,7 @@ pub fn make_module() -> ValueMap { } } - Ok(Iterator(iter)) + Ok(Value::Iterator(iter)) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -678,7 +680,7 @@ pub fn make_module() -> ValueMap { let expected_error = "an iterable and non-negative number"; match ctx.instance_and_args(Value::is_iterable, expected_error)? { - (iterable, [Number(n)]) if *n >= 0.0 => { + (iterable, [Value::Number(n)]) if *n >= 0.0 => { let iterable = iterable.clone(); let n = *n; let result = adaptors::Take::new(ctx.vm.make_iterator(iterable)?, n.into()); @@ -706,7 +708,7 @@ pub fn make_module() -> ValueMap { } } - Ok(List(ValueList::with_data(result))) + Ok(Value::List(ValueList::with_data(result))) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -720,24 +722,24 @@ pub fn make_module() -> ValueMap { let iterable = iterable.clone(); let iterator = ctx.vm.make_iterator(iterable)?; let (size_hint, _) = iterator.size_hint(); - let mut result = DataMap::with_capacity(size_hint); + let mut result = ValueMap::with_capacity(size_hint); for output in iterator { let (key, value) = match output { Output::ValuePair(key, value) => (key, value), - Output::Value(Tuple(t)) if t.len() == 2 => { + Output::Value(Value::Tuple(t)) if t.len() == 2 => { let key = t[0].clone(); let value = t[1].clone(); (key, value) } - Output::Value(value) => (value, Null), + Output::Value(value) => (value, Value::Null), Output::Error(error) => return Err(error), }; result.insert(ValueKey::try_from(key)?, value); } - Ok(Map(ValueMap::with_data(result))) + Ok(Value::Map(KMap::with_data(result))) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -754,7 +756,7 @@ pub fn make_module() -> ValueMap { let mut display_context = DisplayContext::with_vm_and_capacity(ctx.vm, size_hint); for output in iterator.map(collect_pair) { match output { - Output::Value(Str(s)) => display_context.append(s), + Output::Value(Value::Str(s)) => display_context.append(s), Output::Value(value) => value.display(&mut display_context)?, Output::Error(error) => return Err(error), _ => unreachable!(), @@ -785,7 +787,7 @@ pub fn make_module() -> ValueMap { } } - Ok(Tuple(result.into())) + Ok(Value::Tuple(result.into())) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -795,7 +797,7 @@ pub fn make_module() -> ValueMap { let expected_error = "an iterable and a chunnk size greater than zero"; match ctx.instance_and_args(Value::is_iterable, expected_error)? { - (iterable, [Number(n)]) => { + (iterable, [Value::Number(n)]) => { let iterable = iterable.clone(); let n = *n; match adaptors::Windows::new(ctx.vm.make_iterator(iterable)?, n.into()) { diff --git a/core/runtime/src/core_lib/iterator/peekable.rs b/core/runtime/src/core_lib/iterator/peekable.rs index 8eadef872..b4e67bf36 100644 --- a/core/runtime/src/core_lib/iterator/peekable.rs +++ b/core/runtime/src/core_lib/iterator/peekable.rs @@ -111,7 +111,7 @@ impl KotoObject for Peekable { } } -fn peekable_entries() -> DataMap { +fn peekable_entries() -> ValueMap { ObjectEntryBuilder::::new() .method("peek", |context| context.instance_mut()?.peek()) .method("peek_back", |context| context.instance_mut()?.peek_back()) @@ -120,7 +120,7 @@ fn peekable_entries() -> DataMap { thread_local! { static PEEKABLE_TYPE_STRING: ValueString = Peekable::TYPE.into(); - static PEEKABLE_ENTRIES: DataMap = peekable_entries(); + static PEEKABLE_ENTRIES: ValueMap = peekable_entries(); } // For tests, see runtime/tests/iterator_tests.rs diff --git a/core/runtime/src/core_lib/koto.rs b/core/runtime/src/core_lib/koto.rs index 735ebe59c..4677ef662 100644 --- a/core/runtime/src/core_lib/koto.rs +++ b/core/runtime/src/core_lib/koto.rs @@ -4,24 +4,22 @@ use crate::prelude::*; use std::hash::{Hash, Hasher}; /// Initializes the `koto` core library module -pub fn make_module() -> ValueMap { - use Value::*; +pub fn make_module() -> KMap { + let result = KMap::with_type("core.koto"); - let result = ValueMap::with_type("core.koto"); - - result.add_value("args", Tuple(ValueTuple::default())); + result.add_value("args", Value::Tuple(ValueTuple::default())); result.add_fn("copy", |ctx| match ctx.args() { - [Iterator(iter)] => Ok(iter.make_copy()?.into()), - [List(l)] => Ok(ValueList::with_data(l.data().clone()).into()), - [Map(m)] => { - let result = ValueMap::with_contents( + [Value::Iterator(iter)] => Ok(iter.make_copy()?.into()), + [Value::List(l)] => Ok(ValueList::with_data(l.data().clone()).into()), + [Value::Map(m)] => { + let result = KMap::with_contents( m.data().clone(), m.meta_map().map(|meta| meta.borrow().clone()), ); Ok(result.into()) } - [Object(o)] => o.try_borrow().map(|o| o.copy().into()), + [Value::Object(o)] => o.try_borrow().map(|o| o.copy().into()), [other] => Ok(other.clone()), unexpected => type_error_with_slice("a single argument", unexpected), }); @@ -31,7 +29,7 @@ pub fn make_module() -> ValueMap { unexpected => type_error_with_slice("a single argument", unexpected), }); - result.add_fn("exports", |ctx| Ok(Map(ctx.vm.exports().clone()))); + result.add_fn("exports", |ctx| Ok(Value::Map(ctx.vm.exports().clone()))); result.add_fn("hash", |ctx| match ctx.args() { [value] => match ValueKey::try_from(value.clone()) { @@ -40,13 +38,13 @@ pub fn make_module() -> ValueMap { key.hash(&mut hasher); Ok(hasher.finish().into()) } - Err(_) => Ok(Null), + Err(_) => Ok(Value::Null), }, unexpected => type_error_with_slice("a single argument", unexpected), }); - result.add_value("script_dir", Null); - result.add_value("script_path", Null); + result.add_value("script_dir", Value::Null); + result.add_value("script_path", Value::Null); result.add_fn("type", |ctx| match ctx.args() { [value] => Ok(value.type_as_string().into()), diff --git a/core/runtime/src/core_lib/list.rs b/core/runtime/src/core_lib/list.rs index 1160f14d5..a8b5d9e35 100644 --- a/core/runtime/src/core_lib/list.rs +++ b/core/runtime/src/core_lib/list.rs @@ -8,18 +8,16 @@ use crate::prelude::*; use std::{cmp::Ordering, ops::DerefMut}; /// Initializes the `list` core library module -pub fn make_module() -> ValueMap { - use Value::*; - - let result = ValueMap::with_type("core.list"); +pub fn make_module() -> KMap { + let result = KMap::with_type("core.list"); result.add_fn("clear", |ctx| { let expected_error = "a List"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), []) => { + (Value::List(l), []) => { l.data_mut().clear(); - Ok(List(l.clone())) + Ok(Value::List(l.clone())) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -29,7 +27,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a List and a Value"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), [value]) => { + (Value::List(l), [value]) => { let l = l.clone(); let value = value.clone(); for candidate in l.data().iter() { @@ -37,8 +35,8 @@ pub fn make_module() -> ValueMap { .vm .run_binary_op(BinaryOp::Equal, value.clone(), candidate.clone()) { - Ok(Bool(false)) => {} - Ok(Bool(true)) => return Ok(true.into()), + Ok(Value::Bool(false)) => {} + Ok(Value::Bool(true)) => return Ok(true.into()), Ok(unexpected) => { return runtime_error!( "list.contains: Expected Bool from comparison, found '{}'", @@ -58,15 +56,15 @@ pub fn make_module() -> ValueMap { let expected_error = "a List and iterable"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), [List(other)]) => { + (Value::List(l), [Value::List(other)]) => { l.data_mut().extend(other.data().iter().cloned()); - Ok(List(l.clone())) + Ok(Value::List(l.clone())) } - (List(l), [Tuple(other)]) => { + (Value::List(l), [Value::Tuple(other)]) => { l.data_mut().extend(other.iter().cloned()); - Ok(List(l.clone())) + Ok(Value::List(l.clone())) } - (List(l), [iterable]) if iterable.is_iterable() => { + (Value::List(l), [iterable]) if iterable.is_iterable() => { let l = l.clone(); let iterable = iterable.clone(); let iterator = ctx.vm.make_iterator(iterable)?; @@ -85,7 +83,7 @@ pub fn make_module() -> ValueMap { } } - Ok(List(l)) + Ok(Value::List(l)) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -95,11 +93,11 @@ pub fn make_module() -> ValueMap { let expected_error = "a List and a Value"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), [value]) => { + (Value::List(l), [value]) => { for v in l.data_mut().iter_mut() { *v = value.clone(); } - Ok(List(l.clone())) + Ok(Value::List(l.clone())) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -109,9 +107,9 @@ pub fn make_module() -> ValueMap { let expected_error = "a List"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), []) => match l.data().first() { + (Value::List(l), []) => match l.data().first() { Some(value) => Ok(value.clone()), - None => Ok(Null), + None => Ok(Value::Null), }, (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -122,8 +120,8 @@ pub fn make_module() -> ValueMap { let expected_error = "a List and a Number (with optional default value)"; match ctx.instance_and_args(is_list, expected_error)? { - (List(list), [Number(n)]) => (list, n, &Null), - (List(list), [Number(n), default]) => (list, n, default), + (Value::List(list), [Value::Number(n)]) => (list, n, &Value::Null), + (Value::List(list), [Value::Number(n), default]) => (list, n, default), (_, unexpected) => return type_error_with_slice(expected_error, unexpected), } }; @@ -138,14 +136,14 @@ pub fn make_module() -> ValueMap { let expected_error = "a List, a non-negative Number, and a Value"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), [Number(n), value]) if *n >= 0.0 => { + (Value::List(l), [Value::Number(n), value]) if *n >= 0.0 => { let index: usize = n.into(); if index > l.data().len() { return runtime_error!("list.insert: Index out of bounds"); } l.data_mut().insert(index, value.clone()); - Ok(List(l.clone())) + Ok(Value::List(l.clone())) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -155,7 +153,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a List"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), []) => Ok(l.data().is_empty().into()), + (Value::List(l), []) => Ok(l.data().is_empty().into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -164,9 +162,9 @@ pub fn make_module() -> ValueMap { let expected_error = "a List"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), []) => match l.data().last() { + (Value::List(l), []) => match l.data().last() { Some(value) => Ok(value.clone()), - None => Ok(Null), + None => Ok(Value::Null), }, (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -176,9 +174,9 @@ pub fn make_module() -> ValueMap { let expected_error = "a List"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), []) => match l.data_mut().pop() { + (Value::List(l), []) => match l.data_mut().pop() { Some(value) => Ok(value), - None => Ok(Null), + None => Ok(Value::Null), }, (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -188,9 +186,9 @@ pub fn make_module() -> ValueMap { let expected_error = "a List"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), [value]) => { + (Value::List(l), [value]) => { l.data_mut().push(value.clone()); - Ok(List(l.clone())) + Ok(Value::List(l.clone())) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -200,7 +198,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a List"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), [Number(n)]) if *n >= 0.0 => { + (Value::List(l), [Value::Number(n)]) if *n >= 0.0 => { let index: usize = n.into(); if index >= l.data().len() { return runtime_error!( @@ -220,13 +218,13 @@ pub fn make_module() -> ValueMap { let expected_error = "a List, a non-negative Number, and an optional Value"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), [Number(n)]) if *n >= 0.0 => { - l.data_mut().resize(n.into(), Null); - Ok(List(l.clone())) + (Value::List(l), [Value::Number(n)]) if *n >= 0.0 => { + l.data_mut().resize(n.into(), Value::Null); + Ok(Value::List(l.clone())) } - (List(l), [Number(n), value]) if *n >= 0.0 => { + (Value::List(l), [Value::Number(n), value]) if *n >= 0.0 => { l.data_mut().resize(n.into(), value.clone()); - Ok(List(l.clone())) + Ok(Value::List(l.clone())) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -236,7 +234,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a List, a non-negative Number, and a function"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), [Number(n), f]) if *n >= 0.0 && f.is_callable() => { + (Value::List(l), [Value::Number(n), f]) if *n >= 0.0 && f.is_callable() => { let new_size = usize::from(n); let len = l.len(); let l = l.clone(); @@ -254,7 +252,7 @@ pub fn make_module() -> ValueMap { Ordering::Equal => {} } - Ok(List(l)) + Ok(Value::List(l)) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -265,7 +263,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a List, and either a predicate function or matching Value"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), [f]) if f.is_callable() => { + (Value::List(l), [f]) if f.is_callable() => { let l = l.clone(); let f = f.clone(); @@ -276,7 +274,7 @@ pub fn make_module() -> ValueMap { .vm .run_function(f.clone(), CallArgs::Single(value.clone())) { - Ok(Bool(result)) => { + Ok(Value::Bool(result)) => { if result { l.data_mut()[write_index] = value; write_index += 1; @@ -291,10 +289,10 @@ pub fn make_module() -> ValueMap { Err(error) => return Err(error), } } - l.data_mut().resize(write_index, Null); + l.data_mut().resize(write_index, Value::Null); l } - (List(l), [value]) => { + (Value::List(l), [value]) => { let l = l.clone(); let value = value.clone(); @@ -307,8 +305,8 @@ pub fn make_module() -> ValueMap { .vm .run_binary_op(BinaryOp::Equal, x.clone(), value.clone()) { - Ok(Bool(true)) => true, - Ok(Bool(false)) => false, + Ok(Value::Bool(true)) => true, + Ok(Value::Bool(false)) => false, Ok(unexpected) => { error = Some(type_error_with_slice( "a Bool from the equality comparison", @@ -331,16 +329,16 @@ pub fn make_module() -> ValueMap { } }; - Ok(List(result)) + Ok(Value::List(result)) }); result.add_fn("reverse", |ctx| { let expected_error = "a List"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), []) => { + (Value::List(l), []) => { l.data_mut().reverse(); - Ok(List(l.clone())) + Ok(Value::List(l.clone())) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -350,7 +348,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a List"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), []) => Ok(Number(l.len().into())), + (Value::List(l), []) => Ok(Value::Number(l.len().into())), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -359,13 +357,13 @@ pub fn make_module() -> ValueMap { let expected_error = "a List, and an optional key function"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), []) => { + (Value::List(l), []) => { let l = l.clone(); let mut data = l.data_mut(); sort_values(ctx.vm, &mut data)?; - Ok(List(l.clone())) + Ok(Value::List(l.clone())) } - (List(l), [f]) if f.is_callable() => { + (Value::List(l), [f]) if f.is_callable() => { let l = l.clone(); let f = f.clone(); @@ -411,7 +409,7 @@ pub fn make_module() -> ValueMap { .map(|(_key, value)| value.clone()) .collect::<_>(); - Ok(List(l)) + Ok(Value::List(l)) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -421,9 +419,9 @@ pub fn make_module() -> ValueMap { let expected_error = "two Lists"; match ctx.instance_and_args(is_list, expected_error)? { - (List(a), [List(b)]) => { + (Value::List(a), [Value::List(b)]) => { std::mem::swap(a.data_mut().deref_mut(), b.data_mut().deref_mut()); - Ok(Null) + Ok(Value::Null) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -433,7 +431,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a List"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), []) => Ok(Value::Tuple(l.data().as_slice().into())), + (Value::List(l), []) => Ok(Value::Tuple(l.data().as_slice().into())), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -442,7 +440,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a List and a function"; match ctx.instance_and_args(is_list, expected_error)? { - (List(l), [f]) if f.is_callable() => { + (Value::List(l), [f]) if f.is_callable() => { let l = l.clone(); let f = f.clone(); @@ -456,7 +454,7 @@ pub fn make_module() -> ValueMap { } } - Ok(List(l)) + Ok(Value::List(l)) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } diff --git a/core/runtime/src/core_lib/map.rs b/core/runtime/src/core_lib/map.rs index d4179352d..04e87774c 100644 --- a/core/runtime/src/core_lib/map.rs +++ b/core/runtime/src/core_lib/map.rs @@ -5,18 +5,16 @@ use crate::{prelude::*, Result}; use std::cmp::Ordering; /// Initializes the `map` core library module -pub fn make_module() -> ValueMap { - use Value::*; - - let result = ValueMap::with_type("core.map"); +pub fn make_module() -> KMap { + let result = KMap::with_type("core.map"); result.add_fn("clear", |ctx| { let expected_error = "a Map"; match map_instance_and_args(ctx, expected_error)? { - (Map(m), []) => { + (Value::Map(m), []) => { m.data_mut().clear(); - Ok(Map(m.clone())) + Ok(Value::Map(m.clone())) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -26,7 +24,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Map and key"; match map_instance_and_args(ctx, expected_error)? { - (Map(m), [key]) => { + (Value::Map(m), [key]) => { let result = m.data().contains_key(&ValueKey::try_from(key.clone())?); Ok(result.into()) } @@ -38,16 +36,16 @@ pub fn make_module() -> ValueMap { let expected_error = "a Map and an iterable"; match map_instance_and_args(ctx, expected_error)? { - (Map(m), [Map(other)]) => { + (Value::Map(m), [Value::Map(other)]) => { m.data_mut().extend( other .data() .iter() .map(|(key, value)| (key.clone(), value.clone())), ); - Ok(Map(m.clone())) + Ok(Value::Map(m.clone())) } - (Map(m), [iterable]) if iterable.is_iterable() => { + (Value::Map(m), [iterable]) if iterable.is_iterable() => { let m = m.clone(); let iterable = iterable.clone(); let iterator = ctx.vm.make_iterator(iterable)?; @@ -61,12 +59,12 @@ pub fn make_module() -> ValueMap { use ValueIteratorOutput as Output; let (key, value) = match output { Output::ValuePair(key, value) => (key, value), - Output::Value(Tuple(t)) if t.len() == 2 => { + Output::Value(Value::Tuple(t)) if t.len() == 2 => { let key = t[0].clone(); let value = t[1].clone(); (key, value) } - Output::Value(value) => (value, Null), + Output::Value(value) => (value, Value::Null), Output::Error(error) => return Err(error), }; @@ -74,7 +72,7 @@ pub fn make_module() -> ValueMap { } } - Ok(Map(m)) + Ok(Value::Map(m)) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -85,8 +83,8 @@ pub fn make_module() -> ValueMap { let expected_error = "a Map and a key, with an optional default value"; match map_instance_and_args(ctx, expected_error)? { - (Map(map), [key]) => (map, key, &Null), - (Map(map), [key, default]) => (map, key, default), + (Value::Map(map), [key]) => (map, key, &Value::Null), + (Value::Map(map), [key, default]) => (map, key, default), (_, unexpected) => return type_error_with_slice(expected_error, unexpected), } }; @@ -102,14 +100,16 @@ pub fn make_module() -> ValueMap { let expected_error = "a Map and a non-negative number"; match map_instance_and_args(ctx, expected_error)? { - (Map(map), [Number(n)]) => (map, n, &Null), - (Map(map), [Number(n), default]) => (map, n, default), + (Value::Map(map), [Value::Number(n)]) => (map, n, &Value::Null), + (Value::Map(map), [Value::Number(n), default]) => (map, n, default), (_, unexpected) => return type_error_with_slice(expected_error, unexpected), } }; match map.data().get_index(index.into()) { - Some((key, value)) => Ok(Tuple(vec![key.value().clone(), value.clone()].into())), + Some((key, value)) => Ok(Value::Tuple( + vec![key.value().clone(), value.clone()].into(), + )), None => Ok(default.clone()), } }); @@ -118,14 +118,14 @@ pub fn make_module() -> ValueMap { let expected_error = "a Map"; match map_instance_and_args(ctx, expected_error)? { - (Map(map), []) => { + (Value::Map(map), []) => { if map.meta_map().is_some() { - Ok(Map(ValueMap::from_data_and_meta_maps( - &ValueMap::default(), + Ok(Value::Map(KMap::from_data_and_meta_maps( + &KMap::default(), map, ))) } else { - Ok(Null) + Ok(Value::Null) } } (_, unexpected) => type_error_with_slice(expected_error, unexpected), @@ -136,17 +136,20 @@ pub fn make_module() -> ValueMap { let expected_error = "a Map and key (with optional Value to insert)"; match map_instance_and_args(ctx, expected_error)? { - (Map(m), [key]) => match m.data_mut().insert(ValueKey::try_from(key.clone())?, Null) { + (Value::Map(m), [key]) => match m + .data_mut() + .insert(ValueKey::try_from(key.clone())?, Value::Null) + { Some(old_value) => Ok(old_value), - None => Ok(Null), + None => Ok(Value::Null), }, - (Map(m), [key, value]) => { + (Value::Map(m), [key, value]) => { match m .data_mut() .insert(ValueKey::try_from(key.clone())?, value.clone()) { Some(old_value) => Ok(old_value), - None => Ok(Null), + None => Ok(Value::Null), } } (_, unexpected) => type_error_with_slice(expected_error, unexpected), @@ -157,7 +160,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Map"; match map_instance_and_args(ctx, expected_error)? { - (Map(m), []) => Ok(m.is_empty().into()), + (Value::Map(m), []) => Ok(m.is_empty().into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -166,7 +169,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Map"; match map_instance_and_args(ctx, expected_error)? { - (Map(m), []) => { + (Value::Map(m), []) => { let result = adaptors::PairFirst::new(ValueIterator::with_map(m.clone())); Ok(ValueIterator::new(result).into()) } @@ -178,10 +181,12 @@ pub fn make_module() -> ValueMap { let expected_error = "a Map and key"; match map_instance_and_args(ctx, expected_error)? { - (Map(m), [key]) => match m.data_mut().shift_remove(&ValueKey::try_from(key.clone())?) { - Some(old_value) => Ok(old_value), - None => Ok(Null), - }, + (Value::Map(m), [key]) => { + match m.data_mut().shift_remove(&ValueKey::try_from(key.clone())?) { + Some(old_value) => Ok(old_value), + None => Ok(Value::Null), + } + } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -190,7 +195,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Map"; match map_instance_and_args(ctx, expected_error)? { - (Map(m), []) => Ok(Number(m.len().into())), + (Value::Map(m), []) => Ok(Value::Number(m.len().into())), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -199,7 +204,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Map and optional sort key function"; match map_instance_and_args(ctx, expected_error)? { - (Map(m), []) => { + (Value::Map(m), []) => { let mut error = None; m.data_mut().sort_by(|key_a, _, key_b, _| { if error.is_some() { @@ -219,16 +224,16 @@ pub fn make_module() -> ValueMap { if let Some(error) = error { error } else { - Ok(Map(m.clone())) + Ok(Value::Map(m.clone())) } } - (Map(m), [f]) if f.is_callable() => { + (Value::Map(m), [f]) if f.is_callable() => { let m = m.clone(); let f = f.clone(); let mut error = None; let get_sort_key = |vm: &mut Vm, - cache: &mut DataMap, + cache: &mut ValueMap, key: &ValueKey, value: &Value| -> Result { @@ -240,7 +245,7 @@ pub fn make_module() -> ValueMap { Ok(value) }; - let mut cache = DataMap::with_capacity(m.len()); + let mut cache = ValueMap::with_capacity(m.len()); m.data_mut().sort_by(|key_a, value_a, key_b, value_b| { if error.is_some() { return Ordering::Equal; @@ -252,7 +257,7 @@ pub fn make_module() -> ValueMap { Ok(val) => val, Err(e) => { error.get_or_insert(Err(e)); - Null + Value::Null } }, }; @@ -262,7 +267,7 @@ pub fn make_module() -> ValueMap { Ok(val) => val, Err(e) => { error.get_or_insert(Err(e)); - Null + Value::Null } }, }; @@ -279,7 +284,7 @@ pub fn make_module() -> ValueMap { if let Some(error) = error { error } else { - Ok(Map(m)) + Ok(Value::Map(m)) } } (_, unexpected) => type_error_with_slice("a Map ", unexpected), @@ -290,14 +295,14 @@ pub fn make_module() -> ValueMap { let expected_error = "a Map, key, optional default Value, and update function"; match map_instance_and_args(ctx, expected_error)? { - (Map(m), [key, f]) if f.is_callable() => do_map_update( + (Value::Map(m), [key, f]) if f.is_callable() => do_map_update( m.clone(), ValueKey::try_from(key.clone())?, - Null, + Value::Null, f.clone(), ctx.vm, ), - (Map(m), [key, default, f]) if f.is_callable() => do_map_update( + (Value::Map(m), [key, default, f]) if f.is_callable() => do_map_update( m.clone(), ValueKey::try_from(key.clone())?, default.clone(), @@ -312,7 +317,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Map"; match map_instance_and_args(ctx, expected_error)? { - (Map(m), []) => { + (Value::Map(m), []) => { let result = adaptors::PairSecond::new(ValueIterator::with_map(m.clone())); Ok(ValueIterator::new(result).into()) } @@ -324,7 +329,9 @@ pub fn make_module() -> ValueMap { let expected_error = "two Maps"; match map_instance_and_args(ctx, expected_error)? { - (Map(data), [Map(meta)]) => Ok(Map(ValueMap::from_data_and_meta_maps(data, meta))), + (Value::Map(data), [Value::Map(meta)]) => { + Ok(Value::Map(KMap::from_data_and_meta_maps(data, meta))) + } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -332,13 +339,7 @@ pub fn make_module() -> ValueMap { result } -fn do_map_update( - map: ValueMap, - key: ValueKey, - default: Value, - f: Value, - vm: &mut Vm, -) -> Result { +fn do_map_update(map: KMap, key: ValueKey, default: Value, f: Value, vm: &mut Vm) -> Result { if !map.data().contains_key(&key) { map.data_mut().insert(key.clone(), default); } diff --git a/core/runtime/src/core_lib/mod.rs b/core/runtime/src/core_lib/mod.rs index 60b069921..4675c3b8c 100644 --- a/core/runtime/src/core_lib/mod.rs +++ b/core/runtime/src/core_lib/mod.rs @@ -13,28 +13,28 @@ pub mod test; pub mod tuple; mod value_sort; -use crate::ValueMap; +use crate::KMap; #[derive(Clone)] #[allow(missing_docs)] pub struct CoreLib { - pub io: ValueMap, - pub iterator: ValueMap, - pub koto: ValueMap, - pub list: ValueMap, - pub map: ValueMap, - pub os: ValueMap, - pub number: ValueMap, - pub range: ValueMap, - pub string: ValueMap, - pub test: ValueMap, - pub tuple: ValueMap, + pub io: KMap, + pub iterator: KMap, + pub koto: KMap, + pub list: KMap, + pub map: KMap, + pub os: KMap, + pub number: KMap, + pub range: KMap, + pub string: KMap, + pub test: KMap, + pub tuple: KMap, } impl CoreLib { /// The core lib items made available in each Koto script - pub fn prelude(&self) -> ValueMap { - let result = ValueMap::default(); + pub fn prelude(&self) -> KMap { + let result = KMap::default(); result.add_map("io", self.io.clone()); result.add_map("iterator", self.iterator.clone()); result.add_map("koto", self.koto.clone()); diff --git a/core/runtime/src/core_lib/number.rs b/core/runtime/src/core_lib/number.rs index cc6c18a30..0af6eb89d 100644 --- a/core/runtime/src/core_lib/number.rs +++ b/core/runtime/src/core_lib/number.rs @@ -3,10 +3,8 @@ use crate::prelude::*; /// Initializes the `number` core library module -pub fn make_module() -> ValueMap { - use Value::*; - - let result = ValueMap::with_type("core.number"); +pub fn make_module() -> KMap { + let result = KMap::with_type("core.number"); macro_rules! number_fn { ($fn:ident) => { @@ -17,7 +15,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Number"; match ctx.instance_and_args(is_number, expected_error)? { - (Number(n), []) => Ok(Number(n.$fn())), + (Value::Number(n), []) => Ok(Value::Number(n.$fn())), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -33,7 +31,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Number"; match ctx.instance_and_args(is_number, expected_error)? { - (Number(n), []) => Ok(Number(f64::from(n).$fn().into())), + (Value::Number(n), []) => Ok(Value::Number(f64::from(n).$fn().into())), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -47,7 +45,7 @@ pub fn make_module() -> ValueMap { let expected_error = "two Integers"; match ctx.instance_and_args(is_integer, expected_error)? { - (Number(I64(a)), [Number(I64(b))]) => Ok(Number((a $op b).into())), + (Value::Number(I64(a)), [Value::Number(I64(b))]) => Ok((a $op b).into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }) @@ -62,7 +60,7 @@ pub fn make_module() -> ValueMap { let expected_error = "two Integers (with non-negative second Integer)"; match ctx.instance_and_args(is_integer, expected_error)? { - (Number(I64(a)), [Number(I64(b))]) if *b >= 0 => Ok(Number((a $op b).into())), + (Value::Number(I64(a)), [Value::Number(I64(b))]) if *b >= 0 => Ok((a $op b).into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }) @@ -82,9 +80,9 @@ pub fn make_module() -> ValueMap { let expected_error = "two Numbers"; match ctx.instance_and_args(is_number, expected_error)? { - (Number(y), [Number(x)]) => { + (Value::Number(y), [Value::Number(x)]) => { let result = f64::from(y).atan2(f64::from(x)); - Ok(Number(result.into())) + Ok(Value::Number(result.into())) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -96,7 +94,9 @@ pub fn make_module() -> ValueMap { let expected_error = "three Numbers"; match ctx.instance_and_args(is_number, expected_error)? { - (Number(x), [Number(a), Number(b)]) => Ok(Number(*a.max(b.min(x)))), + (Value::Number(x), [Value::Number(a), Value::Number(b)]) => { + Ok(Value::Number(*a.max(b.min(x)))) + } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -105,7 +105,7 @@ pub fn make_module() -> ValueMap { number_f64_fn!(cosh); number_f64_fn!("degrees", to_degrees); - result.add_value("e", Number(std::f64::consts::E.into())); + result.add_value("e", std::f64::consts::E.into()); number_f64_fn!(exp); number_f64_fn!(exp2); @@ -114,20 +114,20 @@ pub fn make_module() -> ValueMap { let expected_error = "an Integer"; match ctx.instance_and_args(is_integer, expected_error)? { - (Number(ValueNumber::I64(n)), []) => Ok(Number((!n).into())), + (Value::Number(ValueNumber::I64(n)), []) => Ok((!n).into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); number_fn!(floor); - result.add_value("infinity", Number(std::f64::INFINITY.into())); + result.add_value("infinity", Value::Number(std::f64::INFINITY.into())); result.add_fn("is_nan", |ctx| { let expected_error = "a Number"; match ctx.instance_and_args(is_number, expected_error)? { - (Number(n), []) => Ok(n.is_nan().into()), + (Value::Number(n), []) => Ok(n.is_nan().into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -136,7 +136,7 @@ pub fn make_module() -> ValueMap { let expected_error = "three Numbers"; match ctx.instance_and_args(is_number, expected_error)? { - (Number(a), [Number(b), Number(t)]) => { + (Value::Number(a), [Value::Number(b), Value::Number(t)]) => { let result = *a + (b - a) * *t; Ok(result.into()) } @@ -152,7 +152,7 @@ pub fn make_module() -> ValueMap { let expected_error = "two Numbers"; match ctx.instance_and_args(is_number, expected_error)? { - (Number(a), [Number(b)]) => Ok(Number(*a.max(b))), + (Value::Number(a), [Value::Number(b)]) => Ok(Value::Number(*a.max(b))), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -161,25 +161,25 @@ pub fn make_module() -> ValueMap { let expected_error = "two Numbers"; match ctx.instance_and_args(is_number, expected_error)? { - (Number(a), [Number(b)]) => Ok(Number(*a.min(b))), + (Value::Number(a), [Value::Number(b)]) => Ok(Value::Number(*a.min(b))), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); - result.add_value("nan", Number(std::f64::NAN.into())); - result.add_value("negative_infinity", Number(std::f64::NEG_INFINITY.into())); + result.add_value("nan", std::f64::NAN.into()); + result.add_value("negative_infinity", std::f64::NEG_INFINITY.into()); bitwise_fn!(or, |); - result.add_value("pi", Number(std::f64::consts::PI.into())); - result.add_value("pi_2", Number(std::f64::consts::FRAC_PI_2.into())); - result.add_value("pi_4", Number(std::f64::consts::FRAC_PI_4.into())); + result.add_value("pi", Value::Number(std::f64::consts::PI.into())); + result.add_value("pi_2", Value::Number(std::f64::consts::FRAC_PI_2.into())); + result.add_value("pi_4", Value::Number(std::f64::consts::FRAC_PI_4.into())); result.add_fn("pow", |ctx| { let expected_error = "two Numbers"; match ctx.instance_and_args(is_number, expected_error)? { - (Number(a), [Number(b)]) => Ok(Number(a.pow(*b))), + (Value::Number(a), [Value::Number(b)]) => Ok(Value::Number(a.pow(*b))), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -197,13 +197,13 @@ pub fn make_module() -> ValueMap { number_f64_fn!(tan); number_f64_fn!(tanh); - result.add_value("tau", Number(std::f64::consts::TAU.into())); + result.add_value("tau", std::f64::consts::TAU.into()); result.add_fn("to_float", |ctx| { let expected_error = "a Number"; match ctx.instance_and_args(is_number, expected_error)? { - (Number(n), []) => Ok(Number(f64::from(n).into())), + (Value::Number(n), []) => Ok(f64::from(n).into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -212,7 +212,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Number"; match ctx.instance_and_args(is_number, expected_error)? { - (Number(n), []) => Ok(Number(i64::from(n).into())), + (Value::Number(n), []) => Ok(i64::from(n).into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); diff --git a/core/runtime/src/core_lib/os.rs b/core/runtime/src/core_lib/os.rs index 9563f297f..47162a2d3 100644 --- a/core/runtime/src/core_lib/os.rs +++ b/core/runtime/src/core_lib/os.rs @@ -6,10 +6,10 @@ use instant::Instant; use std::ops::Deref; /// Initializes the `os` core library module -pub fn make_module() -> ValueMap { +pub fn make_module() -> KMap { use Value::Number; - let result = ValueMap::with_type("core.os"); + let result = KMap::with_type("core.os"); result.add_fn("name", |_| Ok(std::env::consts::OS.into())); @@ -93,7 +93,7 @@ impl KotoObject for DateTime { } } -fn datetime_entries() -> DataMap { +fn datetime_entries() -> ValueMap { ObjectEntryBuilder::::new() .method("day", |ctx| Ok(ctx.instance()?.day().into())) .method("hour", |ctx| Ok(ctx.instance()?.hour().into())) @@ -118,7 +118,7 @@ fn datetime_entries() -> DataMap { thread_local! { static DATETIME_TYPE_STRING: ValueString = DateTime::TYPE.into(); - static DATETIME_ENTRIES: DataMap = datetime_entries(); + static DATETIME_ENTRIES: ValueMap = datetime_entries(); } /// The underlying data type returned by `os.start_timer()` @@ -184,7 +184,7 @@ impl KotoObject for Timer { } } -fn named_timer_entries() -> DataMap { +fn named_timer_entries() -> ValueMap { ObjectEntryBuilder::::new() .method("elapsed", |ctx| { Ok(ctx.instance()?.elapsed_seconds().into()) @@ -194,5 +194,5 @@ fn named_timer_entries() -> DataMap { thread_local! { static TIMER_TYPE_STRING: ValueString = Timer::TYPE.into(); - static TIMER_ENTRIES: DataMap = named_timer_entries(); + static TIMER_ENTRIES: ValueMap = named_timer_entries(); } diff --git a/core/runtime/src/core_lib/range.rs b/core/runtime/src/core_lib/range.rs index d276d40a3..dbc2c3ce5 100644 --- a/core/runtime/src/core_lib/range.rs +++ b/core/runtime/src/core_lib/range.rs @@ -3,17 +3,15 @@ use crate::prelude::*; /// Initializes the `range` core library module -pub fn make_module() -> ValueMap { - use Value::*; - - let result = ValueMap::with_type("core.range"); +pub fn make_module() -> KMap { + let result = KMap::with_type("core.range"); result.add_fn("contains", |ctx| { let expected_error = "a Range, and a Number or another Range"; match ctx.instance_and_args(is_range, expected_error)? { - (Range(r), [Number(n)]) => Ok(r.contains(*n).into()), - (Range(a), [Range(b)]) => { + (Value::Range(r), [Value::Number(n)]) => Ok(r.contains(*n).into()), + (Value::Range(a), [Value::Range(b)]) => { let r_a = a.as_sorted_range(); let r_b = b.as_sorted_range(); let result = r_b.start >= r_a.start && r_b.end <= r_a.end; @@ -27,7 +25,9 @@ pub fn make_module() -> ValueMap { let expected_error = "a Range"; match ctx.instance_and_args(is_range, expected_error)? { - (Range(r), []) => Ok(r.end().map_or(Null, |(end, _inclusive)| end.into())), + (Value::Range(r), []) => { + Ok(r.end().map_or(Value::Null, |(end, _inclusive)| end.into())) + } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -36,7 +36,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Range and Number"; match ctx.instance_and_args(is_range, expected_error)? { - (Range(r), [Number(n)]) => match (r.start(), r.end()) { + (Value::Range(r), [Value::Number(n)]) => match (r.start(), r.end()) { (Some(start), Some((end, inclusive))) => { let n = i64::from(n); let result = if r.is_ascending() { @@ -56,7 +56,9 @@ pub fn make_module() -> ValueMap { let expected_error = "two Ranges"; match ctx.instance_and_args(is_range, expected_error)? { - (Range(a), [Range(b)]) => Ok(a.intersection(b).map_or(Null, |result| result.into())), + (Value::Range(a), [Value::Range(b)]) => Ok(a + .intersection(b) + .map_or(Value::Null, |result| result.into())), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -65,7 +67,9 @@ pub fn make_module() -> ValueMap { let expected_error = "a Range"; match ctx.instance_and_args(is_range, expected_error)? { - (Range(r), []) => Ok(r.end().map_or(false, |(_end, inclusive)| inclusive).into()), + (Value::Range(r), []) => { + Ok(r.end().map_or(false, |(_end, inclusive)| inclusive).into()) + } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -74,7 +78,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Range"; match ctx.instance_and_args(is_range, expected_error)? { - (Range(r), []) => match r.size() { + (Value::Range(r), []) => match r.size() { Some(size) => Ok(size.into()), None => runtime_error!("range.size can't be used with '{r}'"), }, @@ -86,7 +90,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Range"; match ctx.instance_and_args(is_range, expected_error)? { - (Range(r), []) => Ok(r.start().map_or(Null, Value::from)), + (Value::Range(r), []) => Ok(r.start().map_or(Value::Null, Value::from)), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -95,7 +99,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Range, and a Number or another Range"; match ctx.instance_and_args(is_range, expected_error)? { - (Range(r), [Number(n)]) => { + (Value::Range(r), [Value::Number(n)]) => { let n = i64::from(n); match (r.start(), r.end()) { (Some(start), Some((end, inclusive))) => { @@ -109,7 +113,7 @@ pub fn make_module() -> ValueMap { _ => runtime_error!("range.union can't be used with '{r}'"), } } - (Range(a), [Range(b)]) => match (a.start(), a.end()) { + (Value::Range(a), [Value::Range(b)]) => match (a.start(), a.end()) { (Some(start), Some((end, inclusive))) => { let r_b = b.as_sorted_range(); let result = if start <= end { diff --git a/core/runtime/src/core_lib/string.rs b/core/runtime/src/core_lib/string.rs index 36cddb487..48b3c87fe 100644 --- a/core/runtime/src/core_lib/string.rs +++ b/core/runtime/src/core_lib/string.rs @@ -9,16 +9,14 @@ use std::convert::TryFrom; use unicode_segmentation::UnicodeSegmentation; /// Initializes the `string` core library module -pub fn make_module() -> ValueMap { - use Value::*; - - let result = ValueMap::with_type("core.string"); +pub fn make_module() -> KMap { + let result = KMap::with_type("core.string"); result.add_fn("bytes", |ctx| { let expected_error = "a String"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(s), []) => { + (Value::Str(s), []) => { let result = iterators::Bytes::new(s.clone()); Ok(ValueIterator::new(result).into()) } @@ -30,7 +28,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a String"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(s), []) => Ok(Iterator(ValueIterator::with_string(s.clone()))), + (Value::Str(s), []) => Ok(Value::Iterator(ValueIterator::with_string(s.clone()))), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -39,7 +37,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a String"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(s1), [Str(s2)]) => Ok(s1.contains(s2.as_str()).into()), + (Value::Str(s1), [Value::Str(s2)]) => Ok(s1.contains(s2.as_str()).into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -48,7 +46,9 @@ pub fn make_module() -> ValueMap { let expected_error = "a String"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(s), [Str(pattern)]) => Ok(s.as_str().ends_with(pattern.as_str()).into()), + (Value::Str(s), [Value::Str(pattern)]) => { + Ok(s.as_str().ends_with(pattern.as_str()).into()) + } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -57,7 +57,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a String"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(s), []) => Ok(s.escape_default().to_string().into()), + (Value::Str(s), []) => Ok(s.escape_default().to_string().into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -66,8 +66,8 @@ pub fn make_module() -> ValueMap { let expected_error = "a String optionally followed by additional values"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(s), []) => Ok(Str(s.clone())), - (Str(format), format_args) => { + (Value::Str(s), []) => Ok(Value::Str(s.clone())), + (Value::Str(format), format_args) => { let format = format.clone(); let format_args = format_args.to_vec(); match format::format_string(ctx.vm, &format, &format_args) { @@ -89,7 +89,7 @@ pub fn make_module() -> ValueMap { for output in iterator.map(collect_pair) { use ValueIteratorOutput as Output; match output { - Output::Value(Number(n)) => match u8::try_from(n.as_i64()) { + Output::Value(Value::Number(n)) => match u8::try_from(n.as_i64()) { Ok(byte) => bytes.push(byte), Err(_) => return runtime_error!("'{n}' is out of the valid byte range"), }, @@ -111,7 +111,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a String"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(s), []) => Ok(s.is_empty().into()), + (Value::Str(s), []) => Ok(s.is_empty().into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -120,7 +120,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a String"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(s), []) => { + (Value::Str(s), []) => { let result = iterators::Lines::new(s.clone()); Ok(ValueIterator::new(result).into()) } @@ -132,7 +132,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a String, followed by pattern and replacement Strings"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(input), [Str(pattern), Str(replace)]) => { + (Value::Str(input), [Value::Str(pattern), Value::Str(replace)]) => { Ok(input.replace(pattern.as_str(), replace).into()) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), @@ -143,7 +143,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a String"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(s), []) => Ok(s.graphemes(true).count().into()), + (Value::Str(s), []) => Ok(s.graphemes(true).count().into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -153,11 +153,11 @@ pub fn make_module() -> ValueMap { let expected_error = "a String, and either a String or a predicate function"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(input), [Str(pattern)]) => { + (Value::Str(input), [Value::Str(pattern)]) => { let result = iterators::Split::new(input.clone(), pattern.clone()); ValueIterator::new(result) } - (Str(input), [predicate]) if predicate.is_callable() => { + (Value::Str(input), [predicate]) if predicate.is_callable() => { let result = iterators::SplitWith::new( input.clone(), predicate.clone(), @@ -169,14 +169,16 @@ pub fn make_module() -> ValueMap { } }; - Ok(Iterator(iterator)) + Ok(Value::Iterator(iterator)) }); result.add_fn("starts_with", |ctx| { let expected_error = "two Strings"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(s), [Str(pattern)]) => Ok(s.as_str().starts_with(pattern.as_str()).into()), + (Value::Str(s), [Value::Str(pattern)]) => { + Ok(s.as_str().starts_with(pattern.as_str()).into()) + } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -185,7 +187,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a String"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(s), []) => { + (Value::Str(s), []) => { let result = s.chars().flat_map(|c| c.to_lowercase()).collect::(); Ok(result.into()) } @@ -197,10 +199,10 @@ pub fn make_module() -> ValueMap { let expected_error = "a String"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(s), []) => match s.parse::() { - Ok(n) => Ok(Number(n.into())), + (Value::Str(s), []) => match s.parse::() { + Ok(n) => Ok(n.into()), Err(_) => match s.parse::() { - Ok(n) => Ok(Number(n.into())), + Ok(n) => Ok(n.into()), Err(_) => { runtime_error!("string.to_number: Failed to convert '{s}'") } @@ -214,7 +216,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a String"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(s), []) => { + (Value::Str(s), []) => { let result = s.chars().flat_map(|c| c.to_uppercase()).collect::(); Ok(result.into()) } @@ -226,7 +228,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a String"; match ctx.instance_and_args(is_string, expected_error)? { - (Str(s), []) => { + (Value::Str(s), []) => { let result = match s.find(|c: char| !c.is_whitespace()) { Some(start) => { let end = s.rfind(|c: char| !c.is_whitespace()).unwrap(); diff --git a/core/runtime/src/core_lib/string/format.rs b/core/runtime/src/core_lib/string/format.rs index 251d5d4d5..cbf285f3b 100644 --- a/core/runtime/src/core_lib/string/format.rs +++ b/core/runtime/src/core_lib/string/format.rs @@ -415,7 +415,7 @@ fn value_to_string( #[cfg(test)] mod tests { use super::*; - use crate::{DataMap, ValueMap}; + use crate::{KMap, ValueMap}; fn spec_with_precision(precision: u32) -> FormatSpec { FormatSpec { @@ -575,10 +575,10 @@ mod tests { #[test] fn identifier_placeholders() { - let mut map_data = DataMap::default(); + let mut map_data = ValueMap::default(); map_data.insert("x".into(), Value::Number(42.into())); map_data.insert("y".into(), Value::Number(i64::from(-1).into())); - let map = Value::Map(ValueMap::with_data(map_data)); + let map = Value::Map(KMap::with_data(map_data)); check_format_output("{x} - {y}", &[map.clone()], "42 - -1"); check_format_output("{x:.2} - {y:.1}", &[map], "42.00 - -1.0"); diff --git a/core/runtime/src/core_lib/test.rs b/core/runtime/src/core_lib/test.rs index 54ce5350c..5e000aee0 100644 --- a/core/runtime/src/core_lib/test.rs +++ b/core/runtime/src/core_lib/test.rs @@ -3,15 +3,13 @@ use crate::{prelude::*, Result}; /// Initializes the `test` core library module -pub fn make_module() -> ValueMap { - use Value::*; - - let result = ValueMap::with_type("core.test"); +pub fn make_module() -> KMap { + let result = KMap::with_type("core.test"); result.add_fn("assert", |ctx| { for value in ctx.args().iter() { match value { - Bool(b) => { + Value::Bool(b) => { if !b { return runtime_error!("Assertion failed"); } @@ -19,7 +17,7 @@ pub fn make_module() -> ValueMap { unexpected => return type_error("Bool as argument", unexpected), } } - Ok(Null) + Ok(Value::Null) }); result.add_fn("assert_eq", |ctx| match ctx.args() { @@ -28,8 +26,8 @@ pub fn make_module() -> ValueMap { let b = b.clone(); let result = ctx.vm.run_binary_op(BinaryOp::Equal, a.clone(), b.clone()); match result { - Ok(Bool(true)) => Ok(Null), - Ok(Bool(false)) => { + Ok(Value::Bool(true)) => Ok(Value::Null), + Ok(Value::Bool(false)) => { runtime_error!( "Assertion failed, '{}' is not equal to '{}'", ctx.vm.value_to_string(&a)?, @@ -51,8 +49,8 @@ pub fn make_module() -> ValueMap { .vm .run_binary_op(BinaryOp::NotEqual, a.clone(), b.clone()); match result { - Ok(Bool(true)) => Ok(Null), - Ok(Bool(false)) => { + Ok(Value::Bool(true)) => Ok(Value::Null), + Ok(Value::Bool(false)) => { runtime_error!( "Assertion failed, '{}' should not be equal to '{}'", ctx.vm.value_to_string(&a)?, @@ -67,8 +65,10 @@ pub fn make_module() -> ValueMap { }); result.add_fn("assert_near", |ctx| match ctx.args() { - [Number(a), Number(b)] => number_near(*a, *b, 1.0e-12), - [Number(a), Number(b), Number(allowed_diff)] => number_near(*a, *b, allowed_diff.into()), + [Value::Number(a), Value::Number(b)] => number_near(*a, *b, 1.0e-12), + [Value::Number(a), Value::Number(b), Value::Number(allowed_diff)] => { + number_near(*a, *b, allowed_diff.into()) + } unexpected => type_error_with_slice( "two Numbers as arguments, \ followed by an optional Number that specifies the allowed difference", @@ -77,7 +77,7 @@ pub fn make_module() -> ValueMap { }); result.add_fn("run_tests", |ctx| match ctx.args() { - [Map(tests)] => { + [Value::Map(tests)] => { let tests = tests.clone(); ctx.vm.run_tests(tests) } diff --git a/core/runtime/src/core_lib/tuple.rs b/core/runtime/src/core_lib/tuple.rs index c8d5b496b..4b1665a6f 100644 --- a/core/runtime/src/core_lib/tuple.rs +++ b/core/runtime/src/core_lib/tuple.rs @@ -4,16 +4,14 @@ use super::value_sort::sort_values; use crate::prelude::*; /// Initializes the `tuple` core library module -pub fn make_module() -> ValueMap { - use Value::*; - - let result = ValueMap::with_type("core.tuple"); +pub fn make_module() -> KMap { + let result = KMap::with_type("core.tuple"); result.add_fn("contains", |ctx| { let expected_error = "a Tuple and a Value"; match ctx.instance_and_args(is_tuple, expected_error)? { - (Tuple(t), [value]) => { + (Value::Tuple(t), [value]) => { let t = t.clone(); let value = value.clone(); for candidate in t.iter() { @@ -21,8 +19,8 @@ pub fn make_module() -> ValueMap { .vm .run_binary_op(BinaryOp::Equal, value.clone(), candidate.clone()) { - Ok(Bool(false)) => {} - Ok(Bool(true)) => return Ok(true.into()), + Ok(Value::Bool(false)) => {} + Ok(Value::Bool(true)) => return Ok(true.into()), Ok(unexpected) => { return type_error_with_slice( "a Bool from the equality comparison", @@ -42,9 +40,9 @@ pub fn make_module() -> ValueMap { let expected_error = "a Tuple"; match ctx.instance_and_args(is_tuple, expected_error)? { - (Tuple(t), []) => match t.first() { + (Value::Tuple(t), []) => match t.first() { Some(value) => Ok(value.clone()), - None => Ok(Null), + None => Ok(Value::Null), }, (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -55,8 +53,8 @@ pub fn make_module() -> ValueMap { let expected_error = "a Tuple and Number (with optional default Value)"; match ctx.instance_and_args(is_tuple, expected_error)? { - (Tuple(tuple), [Number(n)]) => (tuple, n, &Null), - (Tuple(tuple), [Number(n), default]) => (tuple, n, default), + (Value::Tuple(tuple), [Value::Number(n)]) => (tuple, n, &Value::Null), + (Value::Tuple(tuple), [Value::Number(n), default]) => (tuple, n, default), (_, unexpected) => return type_error_with_slice(expected_error, unexpected), } }; @@ -71,9 +69,9 @@ pub fn make_module() -> ValueMap { let expected_error = "a Tuple"; match ctx.instance_and_args(is_tuple, expected_error)? { - (Tuple(t), []) => match t.last() { + (Value::Tuple(t), []) => match t.last() { Some(value) => Ok(value.clone()), - None => Ok(Null), + None => Ok(Value::Null), }, (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -83,7 +81,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Tuple"; match ctx.instance_and_args(is_tuple, expected_error)? { - (Tuple(t), []) => Ok(Number(t.len().into())), + (Value::Tuple(t), []) => Ok(Value::Number(t.len().into())), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -92,12 +90,12 @@ pub fn make_module() -> ValueMap { let expected_error = "a Tuple"; match ctx.instance_and_args(is_tuple, expected_error)? { - (Tuple(t), []) => { + (Value::Tuple(t), []) => { let mut result = t.to_vec(); sort_values(ctx.vm, &mut result)?; - Ok(Tuple(result.into())) + Ok(Value::Tuple(result.into())) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -107,7 +105,7 @@ pub fn make_module() -> ValueMap { let expected_error = "a Tuple"; match ctx.instance_and_args(is_tuple, expected_error)? { - (Tuple(t), []) => Ok(List(ValueList::from_slice(t))), + (Value::Tuple(t), []) => Ok(Value::List(ValueList::from_slice(t))), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); diff --git a/core/runtime/src/lib.rs b/core/runtime/src/lib.rs index a3e60064e..4c11453e5 100644 --- a/core/runtime/src/lib.rs +++ b/core/runtime/src/lib.rs @@ -16,8 +16,8 @@ pub use crate::{ error::{type_error, type_error_with_slice, Result, RuntimeError}, io::{BufferedFile, DefaultStderr, DefaultStdin, DefaultStdout, KotoFile, KotoRead, KotoWrite}, types::{ - BinaryOp, CallContext, CaptureFunctionInfo, DataMap, ExternalFunction, FunctionInfo, - IntRange, IsIterable, KotoHasher, KotoIterator, KotoObject, KotoType, MetaKey, MetaMap, + BinaryOp, CallContext, CaptureFunctionInfo, ExternalFunction, FunctionInfo, IntRange, + IsIterable, KMap, KotoHasher, KotoIterator, KotoObject, KotoType, MetaKey, MetaMap, MethodContext, Object, ObjectEntryBuilder, UnaryOp, Value, ValueIterator, ValueIteratorOutput, ValueKey, ValueList, ValueMap, ValueNumber, ValueString, ValueTuple, ValueVec, diff --git a/core/runtime/src/prelude.rs b/core/runtime/src/prelude.rs index 5270bed04..351450058 100644 --- a/core/runtime/src/prelude.rs +++ b/core/runtime/src/prelude.rs @@ -3,9 +3,9 @@ #[doc(inline)] pub use crate::{ make_runtime_error, runtime_error, type_error, type_error_with_slice, BinaryOp, Borrow, - BorrowMut, CallArgs, CallContext, DataMap, DisplayContext, ExternalFunction, IntRange, - IsIterable, KotoFile, KotoHasher, KotoIterator, KotoObject, KotoRead, KotoType, KotoWrite, - MetaKey, MetaMap, Object, ObjectEntryBuilder, Ptr, PtrMut, RuntimeError, UnaryOp, Value, - ValueIterator, ValueIteratorOutput, ValueKey, ValueList, ValueMap, ValueNumber, ValueString, - ValueTuple, ValueVec, Vm, VmSettings, + BorrowMut, CallArgs, CallContext, DisplayContext, ExternalFunction, IntRange, IsIterable, KMap, + KotoFile, KotoHasher, KotoIterator, KotoObject, KotoRead, KotoType, KotoWrite, MetaKey, + MetaMap, Object, ObjectEntryBuilder, Ptr, PtrMut, RuntimeError, UnaryOp, Value, ValueIterator, + ValueIteratorOutput, ValueKey, ValueList, ValueMap, ValueNumber, ValueString, ValueTuple, + ValueVec, Vm, VmSettings, }; diff --git a/core/runtime/src/types/meta_map.rs b/core/runtime/src/types/meta_map.rs index a250cf112..3692e7aa6 100644 --- a/core/runtime/src/types/meta_map.rs +++ b/core/runtime/src/types/meta_map.rs @@ -9,9 +9,9 @@ use std::{ type MetaMapType = IndexMap>; -/// The meta map used by [ValueMap](crate::ValueMap) +/// The meta map used by [KMap](crate::KMap) /// -/// Each ValueMap contains a metamap, which allows for customized value behaviour by implementing +/// Each KMap contains a metamap, which allows for customized value behaviour by implementing /// [MetaKeys](crate::MetaKey). #[derive(Clone, Default)] pub struct MetaMap(MetaMapType); @@ -66,7 +66,7 @@ pub enum MetaKey { /// /// e.g. `@meta my_named_key` /// - /// Named entries are used in [ValueMaps][crate::ValueMap], so that shared named items can be + /// Named entries are used in [KMaps][crate::KMap], so that shared named items can be /// made available without them being inserted into the map's contents. Named(ValueString), /// A test function @@ -75,7 +75,7 @@ pub enum MetaKey { Test(ValueString), /// `@tests` /// - /// Tests are defined together in a [ValueMap](crate::ValueMap). + /// Tests are defined together in a [KMap](crate::KMap). Tests, /// `@pre_test` /// diff --git a/core/runtime/src/types/mod.rs b/core/runtime/src/types/mod.rs index 5a377ceb1..18ee65719 100644 --- a/core/runtime/src/types/mod.rs +++ b/core/runtime/src/types/mod.rs @@ -22,7 +22,7 @@ pub use self::{ value_iterator::{KotoIterator, ValueIterator, ValueIteratorOutput}, value_key::ValueKey, value_list::{ValueList, ValueVec}, - value_map::{DataMap, KotoHasher, ValueMap}, + value_map::{KMap, KotoHasher, ValueMap}, value_number::ValueNumber, value_string::ValueString, value_tuple::ValueTuple, diff --git a/core/runtime/src/types/object.rs b/core/runtime/src/types/object.rs index 894b66c0a..f43a8dbb1 100644 --- a/core/runtime/src/types/object.rs +++ b/core/runtime/src/types/object.rs @@ -75,7 +75,7 @@ pub trait KotoObject: Downcast { /// does not match any entry within the object, `None` should be returned. /// /// The recommended pattern for complex objects is to use an [ObjectEntryBuilder] to create a - /// cached [DataMap], which helps to avoid the cost of recreating values for each lookup. + /// cached [ValueMap], which helps to avoid the cost of recreating values for each lookup. /// /// See the [ObjectEntryBuilder] docs for an example. fn lookup(&self, _key: &ValueKey) -> Option { @@ -312,18 +312,16 @@ pub trait KotoType { /// } /// } /// -/// fn make_foo_entries() -> DataMap { -/// use Value::*; -/// +/// fn make_foo_entries() -> ValueMap { /// ObjectEntryBuilder::::new() /// .method_aliased(&["data", "get_data"], |ctx| Ok(ctx.instance()?.data.into())) /// .method("set_data", |ctx| { /// let new_data = match ctx.args { -/// [Object(o)] if o.is_a::() => { +/// [Value::Object(o)] if o.is_a::() => { /// // .unwrap() is safe here, the is_a guard guarantees a successful cast /// o.cast::().unwrap().data /// } -/// [Number(n)] => n.into(), +/// [Value::Number(n)] => n.into(), /// unexpected => return type_error_with_slice("a Number", unexpected), /// }; /// @@ -337,12 +335,12 @@ pub trait KotoType { /// /// thread_local! { /// static FOO_TYPE_STRING: ValueString = Foo::TYPE.into(); -/// static FOO_ENTRIES: DataMap = make_foo_entries(); +/// static FOO_ENTRIES: ValueMap = make_foo_entries(); /// } /// ``` pub struct ObjectEntryBuilder { // The map that's being built - map: DataMap, + map: ValueMap, // We want to have T available through the implementation _phantom: PhantomData, } @@ -350,7 +348,7 @@ pub struct ObjectEntryBuilder { impl Default for ObjectEntryBuilder { fn default() -> Self { Self { - map: DataMap::default(), + map: ValueMap::default(), _phantom: PhantomData, } } @@ -363,7 +361,7 @@ impl ObjectEntryBuilder { } /// Returns the resulting DataMap, consuming the builder - pub fn build(self) -> DataMap { + pub fn build(self) -> ValueMap { self.map } diff --git a/core/runtime/src/types/value.rs b/core/runtime/src/types/value.rs index 1f3d105dd..758483b4a 100644 --- a/core/runtime/src/types/value.rs +++ b/core/runtime/src/types/value.rs @@ -1,6 +1,6 @@ //! The core value type used in the Koto runtime -use crate::{prelude::*, ExternalFunction, Result}; +use crate::{prelude::*, ExternalFunction, KMap, Result}; use koto_bytecode::Chunk; use std::fmt::Write; @@ -27,7 +27,7 @@ pub enum Value { Tuple(ValueTuple), /// The hash map type used in Koto - Map(ValueMap), + Map(KMap), /// The string type used in Koto Str(ValueString), @@ -61,35 +61,33 @@ impl Value { /// /// This is used by koto.deep_copy. pub fn deep_copy(&self) -> Result { - use Value::*; - let result = match &self { - List(l) => { + Value::List(l) => { let result = l .data() .iter() .map(|v| v.deep_copy()) .collect::>()?; - List(ValueList::with_data(result)) + Value::List(ValueList::with_data(result)) } - Tuple(t) => { + Value::Tuple(t) => { let result = t .iter() .map(|v| v.deep_copy()) .collect::>>()?; - Tuple(result.into()) + Value::Tuple(result.into()) } - Map(m) => { + Value::Map(m) => { let data = m .data() .iter() .map(|(k, v)| v.deep_copy().map(|v| (k.clone(), v))) .collect::>()?; let meta = m.meta_map().map(|meta| meta.borrow().clone()); - Map(ValueMap::with_contents(data, meta)) + Value::Map(KMap::with_contents(data, meta)) } - Iterator(i) => Iterator(i.make_copy()?), - Object(o) => Object(o.try_borrow()?.copy()), + Value::Iterator(i) => Value::Iterator(i.make_copy()?), + Value::Object(o) => Value::Object(o.try_borrow()?.copy()), _ => self.clone(), }; @@ -314,8 +312,8 @@ impl From for Value { } } -impl From for Value { - fn from(value: ValueMap) -> Self { +impl From for Value { + fn from(value: KMap) -> Self { Self::Map(value) } } diff --git a/core/runtime/src/types/value_iterator.rs b/core/runtime/src/types/value_iterator.rs index e47e569f3..9efaf536c 100644 --- a/core/runtime/src/types/value_iterator.rs +++ b/core/runtime/src/types/value_iterator.rs @@ -108,7 +108,7 @@ impl ValueIterator { } /// Creates a new ValueIterator from a Map - pub fn with_map(map: ValueMap) -> Self { + pub fn with_map(map: KMap) -> Self { Self::new(MapIterator::new(map)) } @@ -335,13 +335,13 @@ impl Iterator for TupleIterator { #[derive(Clone)] struct MapIterator { - data: ValueMap, + data: KMap, index: usize, end: usize, } impl MapIterator { - fn new(data: ValueMap) -> Self { + fn new(data: KMap) -> Self { let end = data.len(); Self { data, diff --git a/core/runtime/src/types/value_key.rs b/core/runtime/src/types/value_key.rs index 1e226acde..f9b40c581 100644 --- a/core/runtime/src/types/value_key.rs +++ b/core/runtime/src/types/value_key.rs @@ -6,7 +6,7 @@ use std::{ hash::{Hash, Hasher}, }; -/// The key type used by [DataMap](crate::DataMap) +/// The key type used by [ValueMap](crate::ValueMap) /// /// Only hashable values can be used as keys, see [Value::is_hashable] #[derive(Clone)] diff --git a/core/runtime/src/types/value_map.rs b/core/runtime/src/types/value_map.rs index abd42d237..8502890ac 100644 --- a/core/runtime/src/types/value_map.rs +++ b/core/runtime/src/types/value_map.rs @@ -10,83 +10,83 @@ use std::{ /// The hasher used throughout the Koto runtime pub type KotoHasher = FxHasher; -type DataMapType = IndexMap>; +type ValueMapType = IndexMap>; /// The (ValueKey -> Value) 'data' hashmap used by the Koto runtime /// -/// See also: [ValueMap] +/// See also: [KMap] #[derive(Clone, Default)] -pub struct DataMap(DataMapType); +pub struct ValueMap(ValueMapType); -impl DataMap { +impl ValueMap { /// Creates a new DataMap with the given capacity pub fn with_capacity(capacity: usize) -> Self { - Self(DataMapType::with_capacity_and_hasher( + Self(ValueMapType::with_capacity_and_hasher( capacity, Default::default(), )) } } -impl Deref for DataMap { - type Target = DataMapType; +impl Deref for ValueMap { + type Target = ValueMapType; fn deref(&self) -> &Self::Target { &self.0 } } -impl DerefMut for DataMap { +impl DerefMut for ValueMap { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } -impl FromIterator<(ValueKey, Value)> for DataMap { - fn from_iter>(iter: T) -> DataMap { - Self(DataMapType::from_iter(iter)) +impl FromIterator<(ValueKey, Value)> for ValueMap { + fn from_iter>(iter: T) -> ValueMap { + Self(ValueMapType::from_iter(iter)) } } -/// The Map value type used in Koto +/// The core hashmap value type used in Koto, containing a [ValueMap] and a [MetaMap] #[derive(Clone, Default)] -pub struct ValueMap { - data: PtrMut, +pub struct KMap { + data: PtrMut, meta: Option>, } -impl ValueMap { - /// Creates an empty ValueMap +impl KMap { + /// Creates an empty KMap pub fn new() -> Self { Self::default() } - /// Creates an empty ValueMap, with a MetaMap containing the given @type string + /// Creates an empty KMap, with a MetaMap containing the given @type string pub fn with_type(type_name: &str) -> Self { let mut meta = MetaMap::default(); meta.insert(MetaKey::Type, type_name.into()); - Self::with_contents(DataMap::default(), Some(meta)) + Self::with_contents(ValueMap::default(), Some(meta)) } - /// Creates an empty ValueMap with the given capacity + /// Creates an empty KMap with the given capacity pub fn with_capacity(capacity: usize) -> Self { - Self::with_contents(DataMap::with_capacity(capacity), None) + Self::with_contents(ValueMap::with_capacity(capacity), None) } - /// Creates a ValueMap initialized with the provided data - pub fn with_data(data: DataMap) -> Self { + /// Creates a KMap initialized with the provided data + pub fn with_data(data: ValueMap) -> Self { Self::with_contents(data, None) } - /// Creates a ValueMap initialized with the provided data and meta map - pub fn with_contents(data: DataMap, meta: Option) -> Self { + /// Creates a KMap initialized with the provided data and meta map + pub fn with_contents(data: ValueMap, meta: Option) -> Self { Self { data: data.into(), meta: meta.map(PtrMut::from), } } - /// Makes a ValueMap taking the data map from the first arg, and the meta map from the second + /// Makes a KMap taking the data map from the first arg, and the meta map from the second pub fn from_data_and_meta_maps(data: &Self, meta: &Self) -> Self { Self { data: data.data.clone(), @@ -94,24 +94,24 @@ impl ValueMap { } } - /// Provides a reference to the ValueMaps' data - pub fn data(&self) -> Borrow { + /// Provides a reference to the data map + pub fn data(&self) -> Borrow { self.data.borrow() } - /// Provides a mutable reference to the ValueMaps' data - pub fn data_mut(&self) -> BorrowMut { + /// Provides a mutable reference to the data map + pub fn data_mut(&self) -> BorrowMut { self.data.borrow_mut() } - /// Provides a reference to the ValueMap's meta map + /// Provides a reference to the KMap's meta map /// /// This is returned as a reference to the meta map's Rc to allow for cloning. pub fn meta_map(&self) -> Option<&PtrMut> { self.meta.as_ref() } - /// Sets the ValueMap's meta map + /// Sets the KMap's meta map pub fn set_meta_map(&mut self, meta: Option) { self.meta = meta.map(PtrMut::from) } @@ -130,7 +130,7 @@ impl ValueMap { .and_then(|meta| meta.borrow().get(key).cloned()) } - /// Insert an entry into the ValueMap's data + /// Insert an entry into the KMap's data pub fn insert(&self, key: ValueKey, value: Value) { self.data_mut().insert(key, value); } @@ -143,36 +143,36 @@ impl ValueMap { .insert(key, value); } - /// Adds a function to the ValueMap's data map + /// Adds a function to the KMap's data map pub fn add_fn(&self, id: &str, f: impl Fn(&mut CallContext) -> Result + 'static) { self.add_value(id, Value::ExternalFunction(ExternalFunction::new(f))); } - /// Adds a map to the ValueMap's data map - pub fn add_map(&self, id: &str, map: ValueMap) { + /// Adds a map to the KMap's data map + pub fn add_map(&self, id: &str, map: KMap) { self.add_value(id, Value::Map(map)); } - /// Adds a [Value](crate::Value) to the ValueMap's data map + /// Adds a [Value](crate::Value) to the KMap's data map pub fn add_value(&self, id: &str, value: Value) { self.insert(id.into(), value); } - /// Returns the number of entries in the ValueMap's data map + /// Returns the number of entries in the KMap's data map /// /// Note that this doesn't include entries in the meta map. pub fn len(&self) -> usize { self.data().len() } - /// Returns true if the ValueMap's data map contains no entries + /// Returns true if the KMap's data map contains no entries /// /// Note that this doesn't take entries in the meta map into account. pub fn is_empty(&self) -> bool { self.data().is_empty() } - /// Returns true if the provided ValueMap occupies the same memory address + /// Returns true if the provided KMap occupies the same memory address pub fn is_same_instance(&self, other: &Self) -> bool { PtrMut::ptr_eq(&self.data, &other.data) } @@ -229,7 +229,7 @@ mod tests { #[test] fn get_and_remove_with_string() { - let m = ValueMap::default(); + let m = KMap::default(); assert!(m.data().get("test").is_none()); m.add_value("test", Value::Null); diff --git a/core/runtime/src/vm.rs b/core/runtime/src/vm.rs index c5d526e98..455ae36d2 100644 --- a/core/runtime/src/vm.rs +++ b/core/runtime/src/vm.rs @@ -50,7 +50,7 @@ struct VmContext { // The settings that were used to initialize the runtime settings: VmSettings, // The runtime's prelude - prelude: ValueMap, + prelude: KMap, // The runtime's core library core_lib: CoreLib, // The module loader used to compile imported modules @@ -118,7 +118,7 @@ impl Default for VmSettings { #[derive(Clone)] pub struct Vm { // The exports map for the current module - exports: ValueMap, + exports: KMap, // Context shared by all VMs in the runtime context: Rc, // The VM's instruction reader, containing a pointer to the bytecode chunk that's being executed @@ -145,7 +145,7 @@ impl Vm { /// Initializes a Koto VM with the provided settings pub fn with_settings(settings: VmSettings) -> Self { Self { - exports: ValueMap::default(), + exports: KMap::default(), context: Rc::new(VmContext::with_settings(settings)), reader: InstructionReader::default(), registers: Vec::with_capacity(32), @@ -182,7 +182,7 @@ impl Vm { } /// The prelude, containing items that can be imported within all modules - pub fn prelude(&self) -> &ValueMap { + pub fn prelude(&self) -> &KMap { &self.context.prelude } @@ -190,7 +190,7 @@ impl Vm { /// /// Note that this is the exports map of the active module, so during execution the returned /// map will be of the module that's currently being executed. - pub fn exports(&self) -> &ValueMap { + pub fn exports(&self) -> &KMap { &self.exports } @@ -550,7 +550,7 @@ impl Vm { /// Runs any tests that are contained in the map's @tests meta entry /// /// Any test failure will be returned as an error. - pub fn run_tests(&mut self, tests: ValueMap) -> Result { + pub fn run_tests(&mut self, tests: KMap) -> Result { use Value::{Map, Null}; // It's important throughout this function to make sure we don't hang on to any references @@ -723,7 +723,7 @@ impl Vm { MakeMap { register, size_hint, - } => self.set_register(register, ValueMap::with_capacity(size_hint as usize).into()), + } => self.set_register(register, KMap::with_capacity(size_hint as usize).into()), SequenceStart { size_hint } => self .sequence_builders .push(Vec::with_capacity(size_hint as usize)), @@ -1847,7 +1847,7 @@ impl Vm { } // Called from run_equal / run_not_equal to compare the contents of maps - fn compare_value_maps(&mut self, map_a: ValueMap, map_b: ValueMap) -> Result { + fn compare_value_maps(&mut self, map_a: KMap, map_b: KMap) -> Result { if map_a.len() != map_b.len() { return Ok(false); } @@ -2023,7 +2023,7 @@ impl Vm { // Cache the current exports map and prepare an empty exports map for the module // that's being imported. let importer_exports = self.exports.clone(); - self.exports = ValueMap::default(); + self.exports = KMap::default(); // Execute the following steps in a closure to ensure that cleanup is performed afterwards let import_result = { @@ -2397,7 +2397,7 @@ impl Vm { fn get_core_op( &self, key: &ValueKey, - module: &ValueMap, + module: &KMap, iterator_fallback: bool, module_name: &str, ) -> Result { @@ -2987,8 +2987,8 @@ pub enum CallArgs<'a> { // A cache of the export maps of imported modules // -// The ValueMap is optional to prevent recursive imports (see Vm::run_import). -type ModuleCache = HashMap, BuildHasherDefault>; +// The Map is optional to prevent recursive imports (see Vm::run_import). +type ModuleCache = HashMap, BuildHasherDefault>; // A frame in the VM's call stack #[derive(Clone, Debug)] diff --git a/core/runtime/tests/object_tests.rs b/core/runtime/tests/object_tests.rs index 7f60e05aa..3c2365658 100644 --- a/core/runtime/tests/object_tests.rs +++ b/core/runtime/tests/object_tests.rs @@ -192,7 +192,7 @@ mod objects { } } - fn test_object_entries() -> DataMap { + fn test_object_entries() -> ValueMap { use Value::*; ObjectEntryBuilder::::new() @@ -224,7 +224,7 @@ mod objects { thread_local! { static TEST_OBJECT_TYPE_STRING: ValueString = TestObject::TYPE.into(); - static TEST_OBJECT_ENTRIES: DataMap = test_object_entries(); + static TEST_OBJECT_ENTRIES: ValueMap = test_object_entries(); } #[derive(Clone, Copy, Debug)] diff --git a/core/runtime/tests/vm_tests.rs b/core/runtime/tests/vm_tests.rs index e7a3dbcd4..3d38bebf1 100644 --- a/core/runtime/tests/vm_tests.rs +++ b/core/runtime/tests/vm_tests.rs @@ -4,15 +4,15 @@ mod vm { use crate::runtime_test_utils::{ number, number_list, number_tuple, run_script_with_vm, string, test_script, value_tuple, }; - use koto_runtime::{prelude::*, Value::*}; + use koto_runtime::prelude::*; mod literals { use super::*; #[test] fn null() { - test_script("null", Null); - test_script("()", Null); + test_script("null", Value::Null); + test_script("()", Value::Null); } #[test] @@ -64,7 +64,7 @@ a = 99 #[test] fn remainder_negative() { - test_script("assert_near 10 % -1.2, 0.4", Null); + test_script("assert_near 10 % -1.2, 0.4", Value::Null); } #[test] @@ -187,16 +187,16 @@ a %= 5 #[test] fn range() { - test_script("0..10", Range(IntRange::bounded(0, 10, false))); - test_script("0..-10", Range(IntRange::bounded(0, -10, false))); - test_script("1 + 1..2 + 2", Range(IntRange::bounded(2, 4, false))); + test_script("0..10", Value::Range(IntRange::bounded(0, 10, false))); + test_script("0..-10", Value::Range(IntRange::bounded(0, -10, false))); + test_script("1 + 1..2 + 2", Value::Range(IntRange::bounded(2, 4, false))); } #[test] fn range_inclusive() { - test_script("10..=20", Range(IntRange::bounded(10, 20, true))); - test_script("4..=0", Range(IntRange::bounded(4, 0, true))); - test_script("2 * 2..=3 * 3", Range(IntRange::bounded(4, 9, true))); + test_script("10..=20", Value::Range(IntRange::bounded(10, 20, true))); + test_script("4..=0", Value::Range(IntRange::bounded(4, 0, true))); + test_script("2 * 2..=3 * 3", Value::Range(IntRange::bounded(4, 9, true))); } } @@ -205,7 +205,7 @@ a %= 5 #[test] fn empty() { - test_script("(,)", Tuple(ValueTuple::default())); + test_script("(,)", Value::Tuple(ValueTuple::default())); } #[test] @@ -252,7 +252,7 @@ a %= 5 #[test] fn empty() { - test_script("[]", List(ValueList::default())); + test_script("[]", Value::List(ValueList::default())); } #[test] @@ -428,7 +428,7 @@ x[0], x[1] = -1, 42"; #[test] fn unpack_list() { let script = "a, b, c = [7, 8]"; - test_script(script, value_tuple(&[7.into(), 8.into(), Null])); + test_script(script, value_tuple(&[7.into(), 8.into(), Value::Null])); } #[test] @@ -436,14 +436,14 @@ x[0], x[1] = -1, 42"; let script = "a, b, c = [1, 2], [3, 4]"; test_script( script, - value_tuple(&[number_list(&[1, 2]), number_list(&[3, 4]), Null]), + value_tuple(&[number_list(&[1, 2]), number_list(&[3, 4]), Value::Null]), ); } #[test] fn iterator() { let script = "a, b, c = (1, 2).each |x| x * 10"; - test_script(script, value_tuple(&[10.into(), 20.into(), Null])); + test_script(script, value_tuple(&[10.into(), 20.into(), Value::Null])); } #[test] @@ -489,7 +489,7 @@ a, b, c = 1..=3 a, b, c = 1..=2 c "; - test_script(script, Null); + test_script(script, Value::Null); } } @@ -541,7 +541,7 @@ x"; if 5 < 4 42 "; - test_script(script, Null); + test_script(script, Value::Null); } #[test] @@ -554,7 +554,7 @@ else if 2 == 3 else if false 99 "; - test_script(script, Null); + test_script(script, Value::Null); } #[test] @@ -841,7 +841,7 @@ x = match a, b 3, 4 then 3, 4 x "#; - test_script(script, Null); + test_script(script, Value::Null); } #[test] @@ -894,7 +894,7 @@ x = switch 3 == 4 then 3, 4 x "#; - test_script(script, Null); + test_script(script, Value::Null); } #[test] @@ -921,7 +921,7 @@ x prelude.add_fn("assert", |ctx| { for value in ctx.args().iter() { match value { - Bool(b) => { + Value::Bool(b) => { if !b { return runtime_error!("Assertion failed"); } @@ -934,7 +934,7 @@ x } } } - Ok(Null) + Ok(Value::Null) }); if let Err(e) = run_script_with_vm(vm, script, expected_output) { @@ -951,13 +951,13 @@ x #[test] fn function() { let script = "assert 1 + 1 == 2"; - test_script_with_prelude(script, Null); + test_script_with_prelude(script, Value::Null); } #[test] fn function_two_args() { let script = "assert 1 + 1 == 2, 2 < 3"; - test_script_with_prelude(script, Null); + test_script_with_prelude(script, Value::Null); } } @@ -1004,7 +1004,7 @@ add(5, 6)"; foo = |a, b| b foo 42 "; - test_script(script, Null); + test_script(script, Value::Null); } #[test] @@ -1186,7 +1186,7 @@ f (f 5, 10, 20, 30), 40, 50"; let script = " f = |a, b...| b f()"; - test_script(script, Null); + test_script(script, Value::Null); } #[test] @@ -1263,7 +1263,7 @@ f = |x| return x f -42"; - test_script(script, Null); + test_script(script, Value::Null); } #[test] @@ -1577,7 +1577,7 @@ for i in 1..10 if i == 5 break "; - test_script(script, Null); + test_script(script, Value::Null); } #[test] @@ -1631,7 +1631,7 @@ for i in (1, 2) else i "; - test_script(script, Null); + test_script(script, Value::Null); } #[test] @@ -1730,7 +1730,7 @@ while (i += 1) < 5 else i "; - test_script(script, Null); + test_script(script, Value::Null); } #[test] @@ -1859,16 +1859,16 @@ result"; #[test] fn empty() { - test_script("{}", Map(ValueMap::new())); + test_script("{}", Value::Map(KMap::new())); } #[test] fn from_literals() { - let expected = ValueMap::default(); + let expected = KMap::default(); expected.add_value("foo", 42.into()); expected.add_value("bar", "baz".into()); - test_script("{foo: 42, bar: 'baz'}", Map(expected)); + test_script("{foo: 42, bar: 'baz'}", Value::Map(expected)); } #[test] @@ -3060,7 +3060,7 @@ x = a, b, c = x a, b, c "; - test_script(script, value_tuple(&[10.into(), 20.into(), Null])); + test_script(script, value_tuple(&[10.into(), 20.into(), Value::Null])); } } diff --git a/examples/poetry/src/koto_bindings.rs b/examples/poetry/src/koto_bindings.rs index 82c5cbd49..4a6cf60b7 100644 --- a/examples/poetry/src/koto_bindings.rs +++ b/examples/poetry/src/koto_bindings.rs @@ -1,8 +1,8 @@ use crate::Poetry; use koto::prelude::*; -pub fn make_module() -> ValueMap { - let result = ValueMap::with_type("poetry"); +pub fn make_module() -> KMap { + let result = KMap::with_type("poetry"); result.add_fn("new", { |ctx| match ctx.args() { diff --git a/libs/color/src/color.rs b/libs/color/src/color.rs index eb145bddb..411db8a8b 100644 --- a/libs/color/src/color.rs +++ b/libs/color/src/color.rs @@ -258,7 +258,7 @@ impl KotoObject for Color { } } -fn make_color_entries() -> DataMap { +fn make_color_entries() -> ValueMap { use Value::{Number, Object}; ObjectEntryBuilder::::new() @@ -315,7 +315,7 @@ fn make_color_entries() -> DataMap { thread_local! { static COLOR_TYPE_STRING: ValueString = Color::TYPE.into(); - static COLOR_ENTRIES: DataMap = make_color_entries(); + static COLOR_ENTRIES: ValueMap = make_color_entries(); } impl Deref for Color { diff --git a/libs/color/src/lib.rs b/libs/color/src/lib.rs index 79cf3dd3b..1b8ba1ae9 100644 --- a/libs/color/src/lib.rs +++ b/libs/color/src/lib.rs @@ -7,10 +7,9 @@ pub use color::Color; use koto_runtime::{prelude::*, Result}; use palette::{Hsl, Hsv}; -pub fn make_module() -> ValueMap { - use Value::*; - - let mut result = ValueMap::default(); +pub fn make_module() -> KMap { + use Value::{Number, Str}; + let mut result = KMap::default(); result.add_fn("hsl", |ctx| match ctx.args() { [Number(h), Number(s), Number(l)] => { diff --git a/libs/geometry/src/lib.rs b/libs/geometry/src/lib.rs index fa186f759..5918692cb 100644 --- a/libs/geometry/src/lib.rs +++ b/libs/geometry/src/lib.rs @@ -12,10 +12,10 @@ pub use vec3::Vec3; use koto_runtime::prelude::*; -pub fn make_module() -> ValueMap { - use Value::*; +pub fn make_module() -> KMap { + use Value::{Number, Object}; - let result = ValueMap::with_type("geometry"); + let result = KMap::with_type("geometry"); result.add_fn("rect", |ctx| { let (x, y, width, height) = match ctx.args() { diff --git a/libs/geometry/src/rect.rs b/libs/geometry/src/rect.rs index f50961aeb..fd32e708d 100644 --- a/libs/geometry/src/rect.rs +++ b/libs/geometry/src/rect.rs @@ -65,7 +65,7 @@ impl KotoObject for Rect { } } -fn make_rect_entries() -> DataMap { +fn make_rect_entries() -> ValueMap { use Value::*; ObjectEntryBuilder::::new() @@ -104,7 +104,7 @@ fn make_rect_entries() -> DataMap { thread_local! { static RECT_TYPE_STRING: ValueString = Rect::TYPE.into(); - static RECT_ENTRIES: DataMap = make_rect_entries(); + static RECT_ENTRIES: ValueMap = make_rect_entries(); } impl Deref for Rect { diff --git a/libs/geometry/src/vec2.rs b/libs/geometry/src/vec2.rs index bc6943e4b..ebaf701b3 100644 --- a/libs/geometry/src/vec2.rs +++ b/libs/geometry/src/vec2.rs @@ -116,7 +116,7 @@ impl KotoObject for Vec2 { } } -fn make_vec2_entries() -> DataMap { +fn make_vec2_entries() -> ValueMap { ObjectEntryBuilder::::new() .method("angle", |ctx| { Ok(Inner::X.angle_between(**ctx.instance()?).into()) @@ -129,7 +129,7 @@ fn make_vec2_entries() -> DataMap { thread_local! { static VEC2_TYPE_STRING: ValueString = Vec2::TYPE.into(); - static VEC2_ENTRIES: DataMap = make_vec2_entries(); + static VEC2_ENTRIES: ValueMap = make_vec2_entries(); } impl Deref for Vec2 { diff --git a/libs/geometry/src/vec3.rs b/libs/geometry/src/vec3.rs index c9529304e..d3c8b50d8 100644 --- a/libs/geometry/src/vec3.rs +++ b/libs/geometry/src/vec3.rs @@ -113,7 +113,7 @@ impl KotoObject for Vec3 { } } -fn make_vec3_entries() -> DataMap { +fn make_vec3_entries() -> ValueMap { ObjectEntryBuilder::::new() .method("sum", |ctx| { let v = ctx.instance()?; @@ -127,7 +127,7 @@ fn make_vec3_entries() -> DataMap { thread_local! { static VEC3_TYPE_STRING: ValueString = Vec3::TYPE.into(); - static VEC3_ENTRIES: DataMap = make_vec3_entries(); + static VEC3_ENTRIES: ValueMap = make_vec3_entries(); } impl Deref for Vec3 { diff --git a/libs/json/src/lib.rs b/libs/json/src/lib.rs index 10b187121..26816ec73 100644 --- a/libs/json/src/lib.rs +++ b/libs/json/src/lib.rs @@ -27,7 +27,7 @@ pub fn json_value_to_koto_value(value: &serde_json::Value) -> Result { - let map = ValueMap::with_capacity(o.len()); + let map = KMap::with_capacity(o.len()); for (key, value) in o.iter() { map.add_value(key, json_value_to_koto_value(value)?); } @@ -38,13 +38,11 @@ pub fn json_value_to_koto_value(value: &serde_json::Value) -> Result ValueMap { - use Value::*; - - let result = ValueMap::with_type("json"); +pub fn make_module() -> KMap { + let result = KMap::with_type("json"); result.add_fn("from_string", |ctx| match ctx.args() { - [Str(s)] => match serde_json::from_str(s) { + [Value::Str(s)] => match serde_json::from_str(s) { Ok(value) => match json_value_to_koto_value(&value) { Ok(result) => Ok(result), Err(e) => runtime_error!("json.from_string: Error while parsing input: {e}"), diff --git a/libs/random/src/lib.rs b/libs/random/src/lib.rs index 2b7b0324c..285e6a291 100644 --- a/libs/random/src/lib.rs +++ b/libs/random/src/lib.rs @@ -5,8 +5,8 @@ use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; use std::cell::RefCell; -pub fn make_module() -> ValueMap { - let result = ValueMap::with_type("random"); +pub fn make_module() -> KMap { + let result = KMap::with_type("random"); result.add_fn("bool", |_| { THREAD_RNG.with(|rng| rng.borrow_mut().gen_bool()) @@ -117,7 +117,7 @@ impl KotoObject for ChaChaRng { } } -fn rng_entries() -> DataMap { +fn rng_entries() -> ValueMap { ObjectEntryBuilder::::new() .method("bool", |ctx| ctx.instance_mut()?.gen_bool()) .method("number", |ctx| ctx.instance_mut()?.gen_number()) @@ -129,5 +129,5 @@ fn rng_entries() -> DataMap { thread_local! { static THREAD_RNG: RefCell = RefCell::new(ChaChaRng(ChaCha8Rng::from_entropy())); static RNG_TYPE_STRING: ValueString = ChaChaRng::TYPE.into(); - static RNG_ENTRIES: DataMap = rng_entries(); + static RNG_ENTRIES: ValueMap = rng_entries(); } diff --git a/libs/tempfile/src/lib.rs b/libs/tempfile/src/lib.rs index 482b9a183..0fd43fad7 100644 --- a/libs/tempfile/src/lib.rs +++ b/libs/tempfile/src/lib.rs @@ -2,12 +2,12 @@ use koto_runtime::{ core_lib::io::{map_io_err, File}, - ValueMap, + KMap, }; use tempfile::NamedTempFile; -pub fn make_module() -> ValueMap { - let result = ValueMap::with_type("temp_file"); +pub fn make_module() -> KMap { + let result = KMap::with_type("temp_file"); result.add_fn("temp_file", { |_| match NamedTempFile::new().map_err(map_io_err) { diff --git a/libs/toml/src/lib.rs b/libs/toml/src/lib.rs index 846fb65b8..815467f70 100644 --- a/libs/toml/src/lib.rs +++ b/libs/toml/src/lib.rs @@ -21,7 +21,7 @@ pub fn toml_to_koto_value(value: &Toml) -> Result { } } Toml::Table(o) => { - let map = ValueMap::with_capacity(o.len()); + let map = KMap::with_capacity(o.len()); for (key, value) in o.iter() { map.add_value(key, toml_to_koto_value(value)?); } @@ -33,13 +33,11 @@ pub fn toml_to_koto_value(value: &Toml) -> Result { Ok(result) } -pub fn make_module() -> ValueMap { - use Value::*; - - let result = ValueMap::with_type("toml"); +pub fn make_module() -> KMap { + let result = KMap::with_type("toml"); result.add_fn("from_string", |ctx| match ctx.args() { - [Str(s)] => match toml::from_str(s) { + [Value::Str(s)] => match toml::from_str(s) { Ok(toml) => match toml_to_koto_value(&toml) { Ok(result) => Ok(result), Err(e) => runtime_error!("Error while parsing input: {e}"), diff --git a/libs/yaml/src/lib.rs b/libs/yaml/src/lib.rs index 3fceee566..96a57f873 100644 --- a/libs/yaml/src/lib.rs +++ b/libs/yaml/src/lib.rs @@ -27,7 +27,7 @@ pub fn yaml_value_to_koto_value(value: &serde_yaml::Value) -> Result { - let map = ValueMap::with_capacity(mapping.len()); + let map = KMap::with_capacity(mapping.len()); for (key, value) in mapping.iter() { let key_as_koto_value = yaml_value_to_koto_value(key)?; map.insert( @@ -42,13 +42,11 @@ pub fn yaml_value_to_koto_value(value: &serde_yaml::Value) -> Result ValueMap { - use Value::*; - - let result = ValueMap::with_type("yaml"); +pub fn make_module() -> KMap { + let result = KMap::with_type("yaml"); result.add_fn("from_string", |ctx| match ctx.args() { - [Str(s)] => match serde_yaml::from_str(s) { + [Value::Str(s)] => match serde_yaml::from_str(s) { Ok(value) => match yaml_value_to_koto_value(&value) { Ok(result) => Ok(result), Err(e) => runtime_error!("Error while parsing input: {}", e), From 59812e314caadfdff5c11bf8fb3b00e4c119dfb6 Mon Sep 17 00:00:00 2001 From: Ian Hobson Date: Wed, 11 Oct 2023 10:47:35 +0200 Subject: [PATCH 02/13] Rename ValueIterator -> KIterator and ValueIteratorOutput -> KIteratorOutput --- core/runtime/src/core_lib/iterator.rs | 36 ++-- .../runtime/src/core_lib/iterator/adaptors.rs | 130 +++++++-------- .../src/core_lib/iterator/generators.rs | 20 +-- .../runtime/src/core_lib/iterator/peekable.rs | 8 +- core/runtime/src/core_lib/list.rs | 4 +- core/runtime/src/core_lib/map.rs | 10 +- core/runtime/src/core_lib/string.rs | 12 +- core/runtime/src/core_lib/string/iterators.rs | 20 +-- core/runtime/src/lib.rs | 7 +- core/runtime/src/prelude.rs | 10 +- core/runtime/src/types/mod.rs | 2 +- core/runtime/src/types/object.rs | 16 +- core/runtime/src/types/value.rs | 8 +- core/runtime/src/types/value_iterator.rs | 156 +++++++++--------- core/runtime/src/vm.rs | 40 ++--- core/runtime/tests/object_tests.rs | 8 +- examples/poetry/src/koto_bindings.rs | 4 +- libs/color/src/color.rs | 6 +- libs/geometry/src/rect.rs | 6 +- libs/geometry/src/vec2.rs | 6 +- libs/geometry/src/vec3.rs | 6 +- 21 files changed, 254 insertions(+), 261 deletions(-) diff --git a/core/runtime/src/core_lib/iterator.rs b/core/runtime/src/core_lib/iterator.rs index b63529b4f..663093325 100644 --- a/core/runtime/src/core_lib/iterator.rs +++ b/core/runtime/src/core_lib/iterator.rs @@ -4,7 +4,7 @@ pub mod adaptors; pub mod generators; pub mod peekable; -use crate::{prelude::*, Result, ValueIteratorOutput as Output}; +use crate::{prelude::*, KIteratorOutput as Output, Result}; /// Initializes the `iterator` core library module pub fn make_module() -> KMap { @@ -98,7 +98,7 @@ pub fn make_module() -> KMap { (iterable_a, [iterable_b]) if iterable_b.is_iterable() => { let iterable_a = iterable_a.clone(); let iterable_b = iterable_b.clone(); - let result = ValueIterator::new(adaptors::Chain::new( + let result = KIterator::new(adaptors::Chain::new( ctx.vm.make_iterator(iterable_a)?, ctx.vm.make_iterator(iterable_b)?, )); @@ -117,7 +117,7 @@ pub fn make_module() -> KMap { let iterable = iterable.clone(); let n = *n; match adaptors::Chunks::new(ctx.vm.make_iterator(iterable)?, n.into()) { - Ok(result) => Ok(ValueIterator::new(result).into()), + Ok(result) => Ok(KIterator::new(result).into()), Err(e) => runtime_error!("iterator.chunks: {}", e), } } @@ -190,7 +190,7 @@ pub fn make_module() -> KMap { ctx.vm.spawn_shared_vm(), ); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -204,7 +204,7 @@ pub fn make_module() -> KMap { let iterable = iterable.clone(); let result = adaptors::Cycle::new(ctx.vm.make_iterator(iterable)?); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -217,7 +217,7 @@ pub fn make_module() -> KMap { (iterable, []) => { let iterable = iterable.clone(); let result = adaptors::Enumerate::new(ctx.vm.make_iterator(iterable)?); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -274,7 +274,7 @@ pub fn make_module() -> KMap { ctx.vm.spawn_shared_vm(), ); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -326,11 +326,11 @@ pub fn make_module() -> KMap { result.add_fn("generate", |ctx| match ctx.args() { [f] if f.is_callable() => { let result = generators::Generate::new(f.clone(), ctx.vm.spawn_shared_vm()); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } [Value::Number(n), f] if f.is_callable() => { let result = generators::GenerateN::new(n.into(), f.clone(), ctx.vm.spawn_shared_vm()); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } unexpected => type_error_with_slice("(Function), or (Number, Function)", unexpected), }); @@ -348,14 +348,14 @@ pub fn make_module() -> KMap { ctx.vm.spawn_shared_vm(), ); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } (iterable, [separator]) => { let iterable = iterable.clone(); let separator = separator.clone(); let result = adaptors::Intersperse::new(ctx.vm.make_iterator(iterable)?, separator); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -385,7 +385,7 @@ pub fn make_module() -> KMap { predicate, ctx.vm.spawn_shared_vm(), ); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -617,11 +617,11 @@ pub fn make_module() -> KMap { result.add_fn("repeat", |ctx| match ctx.args() { [value] => { let result = generators::Repeat::new(value.clone()); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } [value, Value::Number(n)] => { let result = generators::RepeatN::new(value.clone(), n.into()); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } unexpected => type_error_with_slice("(Value), or (Number, Value)", unexpected), }); @@ -633,7 +633,7 @@ pub fn make_module() -> KMap { (iterable, []) => { let iterable = iterable.clone(); match adaptors::Reversed::new(ctx.vm.make_iterator(iterable)?) { - Ok(result) => Ok(ValueIterator::new(result).into()), + Ok(result) => Ok(KIterator::new(result).into()), Err(e) => runtime_error!("iterator.reversed: {}", e), } } @@ -684,7 +684,7 @@ pub fn make_module() -> KMap { let iterable = iterable.clone(); let n = *n; let result = adaptors::Take::new(ctx.vm.make_iterator(iterable)?, n.into()); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -801,7 +801,7 @@ pub fn make_module() -> KMap { let iterable = iterable.clone(); let n = *n; match adaptors::Windows::new(ctx.vm.make_iterator(iterable)?, n.into()) { - Ok(result) => Ok(ValueIterator::new(result).into()), + Ok(result) => Ok(KIterator::new(result).into()), Err(e) => runtime_error!("iterator.windows: {}", e), } } @@ -820,7 +820,7 @@ pub fn make_module() -> KMap { ctx.vm.make_iterator(iterable_a)?, ctx.vm.make_iterator(iterable_b)?, ); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } diff --git a/core/runtime/src/core_lib/iterator/adaptors.rs b/core/runtime/src/core_lib/iterator/adaptors.rs index c947d5d0b..519632963 100644 --- a/core/runtime/src/core_lib/iterator/adaptors.rs +++ b/core/runtime/src/core_lib/iterator/adaptors.rs @@ -1,19 +1,19 @@ //! Adapators used by the `iterator` core library module use super::collect_pair; -use crate::{prelude::*, Result, ValueIteratorOutput as Output}; +use crate::{prelude::*, KIteratorOutput as Output, Result}; use std::{collections::VecDeque, error, fmt, result::Result as StdResult}; use thiserror::Error; /// An iterator that links the output of two iterators together in a chained sequence pub struct Chain { - iter_a: Option, - iter_b: ValueIterator, + iter_a: Option, + iter_b: KIterator, } impl Chain { /// Creates a [Chain] adapator from two iterators - pub fn new(iter_a: ValueIterator, iter_b: ValueIterator) -> Self { + pub fn new(iter_a: KIterator, iter_b: KIterator) -> Self { Self { iter_a: Some(iter_a), iter_b, @@ -22,7 +22,7 @@ impl Chain { } impl KotoIterator for Chain { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { iter_a: match &self.iter_a { Some(iter) => Some(iter.make_copy()?), @@ -30,7 +30,7 @@ impl KotoIterator for Chain { }, iter_b: self.iter_b.make_copy()?, }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -71,13 +71,13 @@ impl Iterator for Chain { /// An iterator that splits the incoming iterator into iterators of size N pub struct Chunks { - iter: ValueIterator, + iter: KIterator, chunk_size: usize, } impl Chunks { /// Creates a [Chunks] adapator - pub fn new(iter: ValueIterator, chunk_size: usize) -> StdResult { + pub fn new(iter: KIterator, chunk_size: usize) -> StdResult { if chunk_size < 1 { Err(ChunksError::ChunkSizeMustBeAtLeastOne) } else { @@ -87,12 +87,12 @@ impl Chunks { } impl KotoIterator for Chunks { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { iter: self.iter.make_copy()?, chunk_size: self.chunk_size, }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -163,14 +163,14 @@ impl error::Error for ChunksError {} /// An iterator that cycles through the adapted iterator infinitely pub struct Cycle { - iter: ValueIterator, + iter: KIterator, cache: Vec, cycle_index: usize, } impl Cycle { /// Creates a new [Cycle] adaptor - pub fn new(iter: ValueIterator) -> Self { + pub fn new(iter: KIterator) -> Self { let (lower_bound, _) = iter.size_hint(); let size_hint = if lower_bound < usize::MAX { lower_bound @@ -187,13 +187,13 @@ impl Cycle { } impl KotoIterator for Cycle { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { iter: self.iter.make_copy()?, cache: self.cache.clone(), cycle_index: self.cycle_index, }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -238,14 +238,14 @@ impl Iterator for Cycle { /// An iterator that runs a function on each output value from the adapted iterator pub struct Each { - iter: ValueIterator, + iter: KIterator, function: Value, vm: Vm, } impl Each { /// Creates a new [Each] adaptor - pub fn new(iter: ValueIterator, function: Value, vm: Vm) -> Self { + pub fn new(iter: KIterator, function: Value, vm: Vm) -> Self { Self { iter, function, vm } } @@ -264,13 +264,13 @@ impl Each { } impl KotoIterator for Each { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { iter: self.iter.make_copy()?, function: self.function.clone(), vm: self.vm.spawn_shared_vm(), }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } fn is_bidirectional(&self) -> bool { @@ -296,24 +296,24 @@ impl Iterator for Each { /// An iterator that attaches an enumerated iteration position to each value pub struct Enumerate { - iter: ValueIterator, + iter: KIterator, index: usize, } impl Enumerate { /// Creates a new [Enumerate] adaptor - pub fn new(iter: ValueIterator) -> Self { + pub fn new(iter: KIterator) -> Self { Self { iter, index: 0 } } } impl KotoIterator for Enumerate { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { iter: self.iter.make_copy()?, index: self.index, }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -342,13 +342,13 @@ impl Iterator for Enumerate { /// An iterator that flattens the output of nested iterators pub struct Flatten { vm: Vm, - iter: ValueIterator, - nested: Option, + iter: KIterator, + nested: Option, } impl Flatten { /// Creates a new [Flatten] adaptor - pub fn new(iter: ValueIterator, vm: Vm) -> Self { + pub fn new(iter: KIterator, vm: Vm) -> Self { Self { vm, iter, @@ -358,7 +358,7 @@ impl Flatten { } impl KotoIterator for Flatten { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { vm: self.vm.spawn_shared_vm(), iter: self.iter.make_copy()?, @@ -367,7 +367,7 @@ impl KotoIterator for Flatten { None => None, }, }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -400,7 +400,7 @@ impl Iterator for Flatten { /// An iterator that inserts a separator value between each output value from the adapted iterator pub struct Intersperse { - iter: ValueIterator, + iter: KIterator, peeked: Option, next_is_separator: bool, separator: Value, @@ -408,7 +408,7 @@ pub struct Intersperse { impl Intersperse { /// Creates a new [Intersperse] adaptor - pub fn new(iter: ValueIterator, separator: Value) -> Self { + pub fn new(iter: KIterator, separator: Value) -> Self { Self { iter, peeked: None, @@ -419,14 +419,14 @@ impl Intersperse { } impl KotoIterator for Intersperse { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { iter: self.iter.make_copy()?, peeked: self.peeked.clone(), next_is_separator: self.next_is_separator, separator: self.separator.clone(), }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -460,7 +460,7 @@ impl Iterator for Intersperse { /// /// The separator value is the result of calling a provided separator function. pub struct IntersperseWith { - iter: ValueIterator, + iter: KIterator, peeked: Option, next_is_separator: bool, separator_function: Value, @@ -469,7 +469,7 @@ pub struct IntersperseWith { impl IntersperseWith { /// Creates a new [IntersperseWith] adaptor - pub fn new(iter: ValueIterator, separator_function: Value, vm: Vm) -> Self { + pub fn new(iter: KIterator, separator_function: Value, vm: Vm) -> Self { Self { iter, peeked: None, @@ -481,7 +481,7 @@ impl IntersperseWith { } impl KotoIterator for IntersperseWith { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { iter: self.iter.make_copy()?, peeked: self.peeked.clone(), @@ -489,7 +489,7 @@ impl KotoIterator for IntersperseWith { separator_function: self.separator_function.clone(), vm: self.vm.spawn_shared_vm(), }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -527,7 +527,7 @@ impl Iterator for IntersperseWith { } } -fn intersperse_size_hint(iter: &ValueIterator, next_is_separator: bool) -> (usize, Option) { +fn intersperse_size_hint(iter: &KIterator, next_is_separator: bool) -> (usize, Option) { let (lower, upper) = iter.size_hint(); let offset = !next_is_separator as usize; @@ -539,14 +539,14 @@ fn intersperse_size_hint(iter: &ValueIterator, next_is_separator: bool) -> (usiz /// An iterator that skips over values that fail a predicate, and keeps those that pass pub struct Keep { - iter: ValueIterator, + iter: KIterator, predicate: Value, vm: Vm, } impl Keep { /// Creates a new [Keep] adaptor - pub fn new(iter: ValueIterator, predicate: Value, vm: Vm) -> Self { + pub fn new(iter: KIterator, predicate: Value, vm: Vm) -> Self { Self { iter, predicate, @@ -556,13 +556,13 @@ impl Keep { } impl KotoIterator for Keep { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { iter: self.iter.make_copy()?, predicate: self.predicate.clone(), vm: self.vm.spawn_shared_vm(), }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -606,22 +606,22 @@ impl Iterator for Keep { /// An iterator that outputs the first element from any ValuePairs pub struct PairFirst { - iter: ValueIterator, + iter: KIterator, } impl PairFirst { /// Creates a new [PairFirst] adaptor - pub fn new(iter: ValueIterator) -> Self { + pub fn new(iter: KIterator) -> Self { Self { iter } } } impl KotoIterator for PairFirst { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { iter: self.iter.make_copy()?, }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -642,22 +642,22 @@ impl Iterator for PairFirst { /// An iterator that outputs the second element from any ValuePairs pub struct PairSecond { - iter: ValueIterator, + iter: KIterator, } impl PairSecond { /// Creates a new [PairSecond] adaptor - pub fn new(iter: ValueIterator) -> Self { + pub fn new(iter: KIterator) -> Self { Self { iter } } } impl KotoIterator for PairSecond { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { iter: self.iter.make_copy()?, }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -678,12 +678,12 @@ impl Iterator for PairSecond { /// An iterator adaptor that reverses the output of the input iterator pub struct Reversed { - iter: ValueIterator, + iter: KIterator, } impl Reversed { /// Creates a new [Reversed] adaptor - pub fn new(iter: ValueIterator) -> StdResult { + pub fn new(iter: KIterator) -> StdResult { if iter.is_bidirectional() { Ok(Self { iter: iter.make_copy().map_err(ReversedError::CopyError)?, @@ -695,11 +695,11 @@ impl Reversed { } impl KotoIterator for Reversed { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { iter: self.iter.make_copy()?, }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } fn is_bidirectional(&self) -> bool { @@ -735,13 +735,13 @@ pub enum ReversedError { /// An iterator that takes up to N values from the adapted iterator, and then stops pub struct Take { - iter: ValueIterator, + iter: KIterator, remaining: usize, } impl Take { /// Creates a new [Take] adaptor - pub fn new(iter: ValueIterator, count: usize) -> Self { + pub fn new(iter: KIterator, count: usize) -> Self { Self { iter, remaining: count, @@ -750,12 +750,12 @@ impl Take { } impl KotoIterator for Take { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { iter: self.iter.make_copy()?, remaining: self.remaining, }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -782,14 +782,14 @@ impl Iterator for Take { /// An iterator that splits the incoming iterator into overlapping iterators of size N pub struct Windows { - iter: ValueIterator, + iter: KIterator, cache: VecDeque, window_size: usize, } impl Windows { /// Creates a new [Windows] adaptor - pub fn new(iter: ValueIterator, window_size: usize) -> StdResult { + pub fn new(iter: KIterator, window_size: usize) -> StdResult { if window_size < 1 { Err(WindowsError::WindowSizeMustBeAtLeastOne) } else { @@ -803,13 +803,13 @@ impl Windows { } impl KotoIterator for Windows { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { iter: self.iter.make_copy()?, cache: self.cache.clone(), window_size: self.window_size, }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -872,24 +872,24 @@ impl error::Error for WindowsError {} /// An iterator that combines the output of two iterators, 'zipping' output pairs together pub struct Zip { - iter_a: ValueIterator, - iter_b: ValueIterator, + iter_a: KIterator, + iter_b: KIterator, } impl Zip { /// Creates a new [Zip] adaptor - pub fn new(iter_a: ValueIterator, iter_b: ValueIterator) -> Self { + pub fn new(iter_a: KIterator, iter_b: KIterator) -> Self { Self { iter_a, iter_b } } } impl KotoIterator for Zip { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { iter_a: self.iter_a.make_copy()?, iter_b: self.iter_b.make_copy()?, }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } diff --git a/core/runtime/src/core_lib/iterator/generators.rs b/core/runtime/src/core_lib/iterator/generators.rs index 6e02ea099..e20be2994 100644 --- a/core/runtime/src/core_lib/iterator/generators.rs +++ b/core/runtime/src/core_lib/iterator/generators.rs @@ -1,8 +1,6 @@ //! Generators used by the `iterator` core library module -use crate::{ - CallArgs, KotoIterator, Result, Value, ValueIterator, ValueIteratorOutput as Output, Vm, -}; +use crate::{CallArgs, KIterator, KIteratorOutput as Output, KotoIterator, Result, Value, Vm}; /// An iterator that repeatedly yields the same value pub struct Repeat { @@ -17,11 +15,11 @@ impl Repeat { } impl KotoIterator for Repeat { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { value: self.value.clone(), }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -50,12 +48,12 @@ impl RepeatN { } impl KotoIterator for RepeatN { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { remaining: self.remaining, value: self.value.clone(), }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -90,12 +88,12 @@ impl Generate { } impl KotoIterator for Generate { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { function: self.function.clone(), vm: self.vm.spawn_shared_vm(), }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } @@ -131,13 +129,13 @@ impl GenerateN { } impl KotoIterator for GenerateN { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { remaining: self.remaining, function: self.function.clone(), vm: self.vm.spawn_shared_vm(), }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } diff --git a/core/runtime/src/core_lib/iterator/peekable.rs b/core/runtime/src/core_lib/iterator/peekable.rs index b4e67bf36..15130b33b 100644 --- a/core/runtime/src/core_lib/iterator/peekable.rs +++ b/core/runtime/src/core_lib/iterator/peekable.rs @@ -1,19 +1,19 @@ //! A double-ended peekable iterator for Koto use super::iter_output_to_result; -use crate::{prelude::*, Result, ValueIteratorOutput as Output}; +use crate::{prelude::*, KIteratorOutput as Output, Result}; /// A double-ended peekable iterator for Koto #[derive(Clone)] pub struct Peekable { - iter: ValueIterator, + iter: KIterator, peeked_front: Option, peeked_back: Option, } impl Peekable { /// Initializes a Peekable that wraps the given iterator - pub fn new(iter: ValueIterator) -> Self { + pub fn new(iter: KIterator) -> Self { Self { iter, peeked_front: None, @@ -22,7 +22,7 @@ impl Peekable { } /// Makes an instance of Peekable along with a meta map that allows it be used as a Koto Value - pub fn make_value(iter: ValueIterator) -> Value { + pub fn make_value(iter: KIterator) -> Value { Object::from(Self::new(iter)).into() } diff --git a/core/runtime/src/core_lib/list.rs b/core/runtime/src/core_lib/list.rs index a8b5d9e35..fb64d2c0d 100644 --- a/core/runtime/src/core_lib/list.rs +++ b/core/runtime/src/core_lib/list.rs @@ -76,8 +76,8 @@ pub fn make_module() -> KMap { for value in iterator.map(collect_pair) { match value { - ValueIteratorOutput::Value(value) => list_data.push(value.clone()), - ValueIteratorOutput::Error(error) => return Err(error), + KIteratorOutput::Value(value) => list_data.push(value.clone()), + KIteratorOutput::Error(error) => return Err(error), _ => unreachable!(), } } diff --git a/core/runtime/src/core_lib/map.rs b/core/runtime/src/core_lib/map.rs index 04e87774c..760defd5a 100644 --- a/core/runtime/src/core_lib/map.rs +++ b/core/runtime/src/core_lib/map.rs @@ -56,7 +56,7 @@ pub fn make_module() -> KMap { map_data.reserve(size_hint); for output in iterator { - use ValueIteratorOutput as Output; + use KIteratorOutput as Output; let (key, value) = match output { Output::ValuePair(key, value) => (key, value), Output::Value(Value::Tuple(t)) if t.len() == 2 => { @@ -170,8 +170,8 @@ pub fn make_module() -> KMap { match map_instance_and_args(ctx, expected_error)? { (Value::Map(m), []) => { - let result = adaptors::PairFirst::new(ValueIterator::with_map(m.clone())); - Ok(ValueIterator::new(result).into()) + let result = adaptors::PairFirst::new(KIterator::with_map(m.clone())); + Ok(KIterator::new(result).into()) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -318,8 +318,8 @@ pub fn make_module() -> KMap { match map_instance_and_args(ctx, expected_error)? { (Value::Map(m), []) => { - let result = adaptors::PairSecond::new(ValueIterator::with_map(m.clone())); - Ok(ValueIterator::new(result).into()) + let result = adaptors::PairSecond::new(KIterator::with_map(m.clone())); + Ok(KIterator::new(result).into()) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } diff --git a/core/runtime/src/core_lib/string.rs b/core/runtime/src/core_lib/string.rs index 48b3c87fe..90cb18ac8 100644 --- a/core/runtime/src/core_lib/string.rs +++ b/core/runtime/src/core_lib/string.rs @@ -18,7 +18,7 @@ pub fn make_module() -> KMap { match ctx.instance_and_args(is_string, expected_error)? { (Value::Str(s), []) => { let result = iterators::Bytes::new(s.clone()); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -28,7 +28,7 @@ pub fn make_module() -> KMap { let expected_error = "a String"; match ctx.instance_and_args(is_string, expected_error)? { - (Value::Str(s), []) => Ok(Value::Iterator(ValueIterator::with_string(s.clone()))), + (Value::Str(s), []) => Ok(Value::Iterator(KIterator::with_string(s.clone()))), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -87,7 +87,7 @@ pub fn make_module() -> KMap { let mut bytes = Vec::::with_capacity(size_hint); for output in iterator.map(collect_pair) { - use ValueIteratorOutput as Output; + use KIteratorOutput as Output; match output { Output::Value(Value::Number(n)) => match u8::try_from(n.as_i64()) { Ok(byte) => bytes.push(byte), @@ -122,7 +122,7 @@ pub fn make_module() -> KMap { match ctx.instance_and_args(is_string, expected_error)? { (Value::Str(s), []) => { let result = iterators::Lines::new(s.clone()); - Ok(ValueIterator::new(result).into()) + Ok(KIterator::new(result).into()) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } @@ -155,7 +155,7 @@ pub fn make_module() -> KMap { match ctx.instance_and_args(is_string, expected_error)? { (Value::Str(input), [Value::Str(pattern)]) => { let result = iterators::Split::new(input.clone(), pattern.clone()); - ValueIterator::new(result) + KIterator::new(result) } (Value::Str(input), [predicate]) if predicate.is_callable() => { let result = iterators::SplitWith::new( @@ -163,7 +163,7 @@ pub fn make_module() -> KMap { predicate.clone(), ctx.vm.spawn_shared_vm(), ); - ValueIterator::new(result) + KIterator::new(result) } (_, unexpected) => return type_error_with_slice(expected_error, unexpected), } diff --git a/core/runtime/src/core_lib/string/iterators.rs b/core/runtime/src/core_lib/string/iterators.rs index 01fc50bd1..5289ca72c 100644 --- a/core/runtime/src/core_lib/string/iterators.rs +++ b/core/runtime/src/core_lib/string/iterators.rs @@ -1,8 +1,8 @@ //! A collection of string iterators use crate::{ - make_runtime_error, CallArgs, KotoIterator, Result, Value, ValueIterator, - ValueIteratorOutput as Output, ValueString, Vm, + make_runtime_error, CallArgs, KIterator, KIteratorOutput as Output, KotoIterator, Result, + Value, ValueString, Vm, }; use unicode_segmentation::UnicodeSegmentation; @@ -21,8 +21,8 @@ impl Bytes { } impl KotoIterator for Bytes { - fn make_copy(&self) -> Result { - Ok(ValueIterator::new(self.clone())) + fn make_copy(&self) -> Result { + Ok(KIterator::new(self.clone())) } } @@ -64,8 +64,8 @@ impl Lines { } impl KotoIterator for Lines { - fn make_copy(&self) -> Result { - Ok(ValueIterator::new(self.clone())) + fn make_copy(&self) -> Result { + Ok(KIterator::new(self.clone())) } } @@ -124,8 +124,8 @@ impl Split { } impl KotoIterator for Split { - fn make_copy(&self) -> Result { - Ok(ValueIterator::new(self.clone())) + fn make_copy(&self) -> Result { + Ok(KIterator::new(self.clone())) } } @@ -175,14 +175,14 @@ impl SplitWith { } impl KotoIterator for SplitWith { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let result = Self { input: self.input.clone(), predicate: self.predicate.clone(), vm: self.vm.spawn_shared_vm(), start: self.start, }; - Ok(ValueIterator::new(result)) + Ok(KIterator::new(result)) } } diff --git a/core/runtime/src/lib.rs b/core/runtime/src/lib.rs index 4c11453e5..2ddc76de5 100644 --- a/core/runtime/src/lib.rs +++ b/core/runtime/src/lib.rs @@ -17,10 +17,9 @@ pub use crate::{ io::{BufferedFile, DefaultStderr, DefaultStdin, DefaultStdout, KotoFile, KotoRead, KotoWrite}, types::{ BinaryOp, CallContext, CaptureFunctionInfo, ExternalFunction, FunctionInfo, IntRange, - IsIterable, KMap, KotoHasher, KotoIterator, KotoObject, KotoType, MetaKey, MetaMap, - MethodContext, Object, ObjectEntryBuilder, UnaryOp, Value, ValueIterator, - ValueIteratorOutput, ValueKey, ValueList, ValueMap, ValueNumber, ValueString, ValueTuple, - ValueVec, + IsIterable, KIterator, KIteratorOutput, KMap, KotoHasher, KotoIterator, KotoObject, + KotoType, MetaKey, MetaMap, MethodContext, Object, ObjectEntryBuilder, UnaryOp, Value, + ValueKey, ValueList, ValueMap, ValueNumber, ValueString, ValueTuple, ValueVec, }, vm::{CallArgs, ModuleImportedCallback, Vm, VmSettings}, }; diff --git a/core/runtime/src/prelude.rs b/core/runtime/src/prelude.rs index 351450058..a7207b377 100644 --- a/core/runtime/src/prelude.rs +++ b/core/runtime/src/prelude.rs @@ -3,9 +3,9 @@ #[doc(inline)] pub use crate::{ make_runtime_error, runtime_error, type_error, type_error_with_slice, BinaryOp, Borrow, - BorrowMut, CallArgs, CallContext, DisplayContext, ExternalFunction, IntRange, IsIterable, KMap, - KotoFile, KotoHasher, KotoIterator, KotoObject, KotoRead, KotoType, KotoWrite, MetaKey, - MetaMap, Object, ObjectEntryBuilder, Ptr, PtrMut, RuntimeError, UnaryOp, Value, ValueIterator, - ValueIteratorOutput, ValueKey, ValueList, ValueMap, ValueNumber, ValueString, ValueTuple, - ValueVec, Vm, VmSettings, + BorrowMut, CallArgs, CallContext, DisplayContext, ExternalFunction, IntRange, IsIterable, + KIterator, KIteratorOutput, KMap, KotoFile, KotoHasher, KotoIterator, KotoObject, KotoRead, + KotoType, KotoWrite, MetaKey, MetaMap, Object, ObjectEntryBuilder, Ptr, PtrMut, RuntimeError, + UnaryOp, Value, ValueKey, ValueList, ValueMap, ValueNumber, ValueString, ValueTuple, ValueVec, + Vm, VmSettings, }; diff --git a/core/runtime/src/types/mod.rs b/core/runtime/src/types/mod.rs index 18ee65719..e56883832 100644 --- a/core/runtime/src/types/mod.rs +++ b/core/runtime/src/types/mod.rs @@ -19,7 +19,7 @@ pub use self::{ meta_map::{meta_id_to_key, BinaryOp, MetaKey, MetaMap, UnaryOp}, object::{IsIterable, KotoObject, KotoType, MethodContext, Object, ObjectEntryBuilder}, value::{CaptureFunctionInfo, FunctionInfo, Value}, - value_iterator::{KotoIterator, ValueIterator, ValueIteratorOutput}, + value_iterator::{KIterator, KIteratorOutput, KotoIterator}, value_key::ValueKey, value_list::{ValueList, ValueVec}, value_map::{KMap, KotoHasher, ValueMap}, diff --git a/core/runtime/src/types/object.rs b/core/runtime/src/types/object.rs index f43a8dbb1..ffa247991 100644 --- a/core/runtime/src/types/object.rs +++ b/core/runtime/src/types/object.rs @@ -186,8 +186,8 @@ pub trait KotoObject: Downcast { /// /// If [IsIterable::Iterable] is returned from [is_iterable](Self::is_iterable), /// then the runtime will call this function when the object is used in iterable contexts, - /// expecting a [ValueIterator] to be returned. - fn make_iterator(&self, _vm: &mut Vm) -> Result { + /// expecting a [KIterator] to be returned. + fn make_iterator(&self, _vm: &mut Vm) -> Result { unimplemented_error("@iterator", self.object_type()) } @@ -195,20 +195,20 @@ pub trait KotoObject: Downcast { /// /// If either [ForwardIterator][IsIterable::ForwardIterator] or /// [BidirectionalIterator][IsIterable::BidirectionalIterator] is returned from - /// [is_iterable](Self::is_iterable), then the object will be wrapped in a [ValueIterator] + /// [is_iterable](Self::is_iterable), then the object will be wrapped in a [KIterator] /// whenever it's used in an iterable context. This function will then be called each time - /// [ValueIterator::next] is invoked. - fn iterator_next(&mut self, _vm: &mut Vm) -> Option { + /// [KIterator::next] is invoked. + fn iterator_next(&mut self, _vm: &mut Vm) -> Option { None } /// Gets the object's next value from the end of an iteration /// /// If [BidirectionalIterator][IsIterable::BidirectionalIterator] is returned from - /// [is_iterable](Self::is_iterable), then the object will be wrapped in a [ValueIterator] + /// [is_iterable](Self::is_iterable), then the object will be wrapped in a [KIterator] /// whenever it's used in an iterable context. This function will then be called each time - /// [ValueIterator::next_back] is invoked. - fn iterator_next_back(&mut self, _vm: &mut Vm) -> Option { + /// [KIterator::next_back] is invoked. + fn iterator_next_back(&mut self, _vm: &mut Vm) -> Option { None } } diff --git a/core/runtime/src/types/value.rs b/core/runtime/src/types/value.rs index 758483b4a..fbcaeb70c 100644 --- a/core/runtime/src/types/value.rs +++ b/core/runtime/src/types/value.rs @@ -42,7 +42,7 @@ pub enum Value { ExternalFunction(ExternalFunction), /// The iterator type used in Koto - Iterator(ValueIterator), + Iterator(KIterator), /// An object with behaviour defined via the [KotoObject] trait Object(Object), @@ -128,7 +128,7 @@ impl Value { } } - /// Returns true if a `ValueIterator` can be made from the value + /// Returns true if a [KIterator] can be made from the value pub fn is_iterable(&self) -> bool { use Value::*; match self { @@ -324,8 +324,8 @@ impl From for Value { } } -impl From for Value { - fn from(value: ValueIterator) -> Self { +impl From for Value { + fn from(value: KIterator) -> Self { Self::Iterator(value) } } diff --git a/core/runtime/src/types/value_iterator.rs b/core/runtime/src/types/value_iterator.rs index 9efaf536c..ecdbf4a3b 100644 --- a/core/runtime/src/types/value_iterator.rs +++ b/core/runtime/src/types/value_iterator.rs @@ -3,10 +3,10 @@ use std::{cell::RefCell, fmt, ops::DerefMut, rc::Rc, result::Result as StdResult /// The trait used to implement iterators in Koto /// -/// See `ValueIterator`. -pub trait KotoIterator: Iterator { +/// See [KIterator]. +pub trait KotoIterator: Iterator { /// Returns a copy of the iterator that (when possible), will produce the same output - fn make_copy(&self) -> Result; + fn make_copy(&self) -> Result; /// Returns true if the iterator supports reversed iteration via `next_back` fn is_bidirectional(&self) -> bool { @@ -16,14 +16,14 @@ pub trait KotoIterator: Iterator { /// Returns the next item produced by iterating backwards /// /// Returns `None` when no more items are available in reverse order. - fn next_back(&mut self) -> Option { + fn next_back(&mut self) -> Option { None } } /// The output type for iterators in Koto #[derive(Clone)] -pub enum ValueIteratorOutput { +pub enum KIteratorOutput { /// A single value Value(Value), /// A pair of values @@ -37,7 +37,7 @@ pub enum ValueIteratorOutput { Error(RuntimeError), } -impl From for ValueIteratorOutput +impl From for KIteratorOutput where Value: From, { @@ -46,33 +46,33 @@ where } } -impl TryFrom for Value { +impl TryFrom for Value { type Error = RuntimeError; - fn try_from(iterator_output: ValueIteratorOutput) -> StdResult { + fn try_from(iterator_output: KIteratorOutput) -> StdResult { match iterator_output { - ValueIteratorOutput::Value(value) => Ok(value), - ValueIteratorOutput::ValuePair(first, second) => { + KIteratorOutput::Value(value) => Ok(value), + KIteratorOutput::ValuePair(first, second) => { Ok(Value::Tuple(vec![first, second].into())) } - ValueIteratorOutput::Error(error) => Err(error), + KIteratorOutput::Error(error) => Err(error), } } } /// The iterator value type used in Koto #[derive(Clone)] -pub struct ValueIterator(PtrMut); +pub struct KIterator(PtrMut); -impl ValueIterator { - /// Creates a new ValueIterator from any value that implements [KotoIterator] +impl KIterator { + /// Creates a new KIterator from any value that implements [KotoIterator] pub fn new(external: impl KotoIterator + 'static) -> Self { Self(PtrMut::from( Rc::new(RefCell::new(external)) as Rc> )) } - /// Creates a new ValueIterator from any iterator that implements DoubleEndedIterator + /// Creates a new KIterator from any iterator that implements DoubleEndedIterator /// /// This should only be used for iterators without side-effects. pub fn with_std_iter(iter: T) -> Self @@ -82,7 +82,7 @@ impl ValueIterator { Self::new(StdDoubleEndedIterator:: { iter }) } - /// Creates a new ValueIterator from any iterator that implements Iterator + /// Creates a new KIterator from any iterator that implements Iterator /// /// This should only be used for iterators without side-effects. pub fn with_std_forward_iter(iter: T) -> Self @@ -92,42 +92,42 @@ impl ValueIterator { Self::new(StdForwardIterator:: { iter }) } - /// Creates a new ValueIterator from a Range + /// Creates a new KIterator from a Range pub fn with_range(range: IntRange) -> Result { Ok(Self::new(RangeIterator::new(range)?)) } - /// Creates a new ValueIterator from a List + /// Creates a new KIterator from a List pub fn with_list(list: ValueList) -> Self { Self::new(ListIterator::new(list)) } - /// Creates a new ValueIterator from a Tuple + /// Creates a new KIterator from a Tuple pub fn with_tuple(tuple: ValueTuple) -> Self { Self::new(TupleIterator::new(tuple)) } - /// Creates a new ValueIterator from a Map + /// Creates a new KIterator from a Map pub fn with_map(map: KMap) -> Self { Self::new(MapIterator::new(map)) } - /// Creates a new ValueIterator from a String + /// Creates a new KIterator from a String pub fn with_string(s: ValueString) -> Self { Self::new(StringIterator::new(s)) } - /// Creates a new ValueIterator from a Vm, used to implement generators + /// Creates a new KIterator from a Vm, used to implement generators pub fn with_vm(vm: Vm) -> Self { Self::new(GeneratorIterator::new(vm)) } - /// Creates a new ValueIterator from a Value that has an implementation of `@next` + /// Creates a new KIterator from a Value that has an implementation of `@next` pub fn with_meta_next(vm: Vm, iterator: Value) -> Result { Ok(Self::new(MetaIterator::new(vm, iterator)?)) } - /// Creates a new ValueIterator from an Object that implements [KotoIterator] + /// Creates a new KIterator from an Object that implements [KotoIterator] pub fn with_object(vm: Vm, o: Object) -> Result { Ok(Self::new(ObjectIterator::new(vm, o)?)) } @@ -149,21 +149,21 @@ impl ValueIterator { /// Returns the next item produced by iterating backwards /// /// See [KotoIterator::next_back] - pub fn next_back(&mut self) -> Option { + pub fn next_back(&mut self) -> Option { self.0.borrow_mut().next_back() } /// Mutably borrows the underlying iterator, allowing repeated iterations with a single borrow pub fn borrow_internals( &mut self, - mut f: impl FnMut(&mut dyn KotoIterator) -> Option, - ) -> Option { + mut f: impl FnMut(&mut dyn KotoIterator) -> Option, + ) -> Option { f(self.0.borrow_mut().deref_mut()) } } -impl Iterator for ValueIterator { - type Item = ValueIteratorOutput; +impl Iterator for KIterator { + type Item = KIteratorOutput; fn next(&mut self) -> Option { self.0.borrow_mut().next() @@ -174,14 +174,14 @@ impl Iterator for ValueIterator { } } -impl fmt::Debug for ValueIterator { +impl fmt::Debug for KIterator { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "ValueIterator") + write!(f, "KIterator") } } // Convenience type alias for the rest of this module -type Output = ValueIteratorOutput; +type Output = KIteratorOutput; #[derive(Clone)] struct RangeIterator { @@ -199,19 +199,19 @@ impl RangeIterator { } impl KotoIterator for RangeIterator { - fn make_copy(&self) -> Result { - Ok(ValueIterator::new(self.clone())) + fn make_copy(&self) -> Result { + Ok(KIterator::new(self.clone())) } fn is_bidirectional(&self) -> bool { true } - fn next_back(&mut self) -> Option { + fn next_back(&mut self) -> Option { match self.range.pop_back() { - Ok(Some(output)) => Some(ValueIteratorOutput::Value(output.into())), + Ok(Some(output)) => Some(KIteratorOutput::Value(output.into())), Ok(None) => None, - Err(e) => Some(ValueIteratorOutput::Error(e)), + Err(e) => Some(KIteratorOutput::Error(e)), } } } @@ -221,9 +221,9 @@ impl Iterator for RangeIterator { fn next(&mut self) -> Option { match self.range.pop_front() { - Ok(Some(output)) => Some(ValueIteratorOutput::Value(output.into())), + Ok(Some(output)) => Some(KIteratorOutput::Value(output.into())), Ok(None) => None, - Err(e) => Some(ValueIteratorOutput::Error(e)), + Err(e) => Some(KIteratorOutput::Error(e)), } } @@ -251,24 +251,24 @@ impl ListIterator { } } - fn get_output(&self, index: usize) -> Option { + fn get_output(&self, index: usize) -> Option { self.data .data() .get(index) - .map(|data| ValueIteratorOutput::Value(data.clone())) + .map(|data| KIteratorOutput::Value(data.clone())) } } impl KotoIterator for ListIterator { - fn make_copy(&self) -> Result { - Ok(ValueIterator::new(self.clone())) + fn make_copy(&self) -> Result { + Ok(KIterator::new(self.clone())) } fn is_bidirectional(&self) -> bool { true } - fn next_back(&mut self) -> Option { + fn next_back(&mut self) -> Option { if self.end > self.index { self.end -= 1; self.get_output(self.end) @@ -307,16 +307,16 @@ impl TupleIterator { } impl KotoIterator for TupleIterator { - fn make_copy(&self) -> Result { - Ok(ValueIterator::new(self.clone())) + fn make_copy(&self) -> Result { + Ok(KIterator::new(self.clone())) } fn is_bidirectional(&self) -> bool { true } - fn next_back(&mut self) -> Option { - self.0.pop_back().map(ValueIteratorOutput::Value) + fn next_back(&mut self) -> Option { + self.0.pop_back().map(KIteratorOutput::Value) } } @@ -324,7 +324,7 @@ impl Iterator for TupleIterator { type Item = Output; fn next(&mut self) -> Option { - self.0.pop_front().map(ValueIteratorOutput::Value) + self.0.pop_front().map(KIteratorOutput::Value) } fn size_hint(&self) -> (usize, Option) { @@ -350,24 +350,24 @@ impl MapIterator { } } - fn get_output(&self, index: usize) -> Option { + fn get_output(&self, index: usize) -> Option { self.data .data() .get_index(index) - .map(|(key, value)| ValueIteratorOutput::ValuePair(key.value().clone(), value.clone())) + .map(|(key, value)| KIteratorOutput::ValuePair(key.value().clone(), value.clone())) } } impl KotoIterator for MapIterator { - fn make_copy(&self) -> Result { - Ok(ValueIterator::new(self.clone())) + fn make_copy(&self) -> Result { + Ok(KIterator::new(self.clone())) } fn is_bidirectional(&self) -> bool { true } - fn next_back(&mut self) -> Option { + fn next_back(&mut self) -> Option { if self.end > self.index { self.end -= 1; self.get_output(self.end) @@ -426,15 +426,15 @@ impl MetaIterator { } impl KotoIterator for MetaIterator { - fn make_copy(&self) -> Result { - Ok(ValueIterator::new(self.clone())) + fn make_copy(&self) -> Result { + Ok(KIterator::new(self.clone())) } fn is_bidirectional(&self) -> bool { self.is_bidirectional } - fn next_back(&mut self) -> Option { + fn next_back(&mut self) -> Option { match self .vm .run_unary_op(UnaryOp::NextBack, self.iterator.clone()) @@ -480,12 +480,12 @@ impl ObjectIterator { } impl KotoIterator for ObjectIterator { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let copy = Self { vm: self.vm.spawn_shared_vm(), object: self.object.try_borrow()?.copy(), }; - Ok(ValueIterator::new(copy)) + Ok(KIterator::new(copy)) } fn is_bidirectional(&self) -> bool { @@ -494,10 +494,10 @@ impl KotoIterator for ObjectIterator { }) } - fn next_back(&mut self) -> Option { + fn next_back(&mut self) -> Option { match self.object.try_borrow_mut() { Ok(mut o) => o.iterator_next_back(&mut self.vm), - Err(e) => Some(ValueIteratorOutput::Error(e)), + Err(e) => Some(KIteratorOutput::Error(e)), } } } @@ -508,7 +508,7 @@ impl Iterator for ObjectIterator { fn next(&mut self) -> Option { match self.object.try_borrow_mut() { Ok(mut o) => o.iterator_next(&mut self.vm), - Err(e) => Some(ValueIteratorOutput::Error(e)), + Err(e) => Some(KIteratorOutput::Error(e)), } } } @@ -524,18 +524,16 @@ impl StringIterator { } impl KotoIterator for StringIterator { - fn make_copy(&self) -> Result { - Ok(ValueIterator::new(self.clone())) + fn make_copy(&self) -> Result { + Ok(KIterator::new(self.clone())) } fn is_bidirectional(&self) -> bool { true } - fn next_back(&mut self) -> Option { - self.0 - .pop_back() - .map(|s| ValueIteratorOutput::Value(s.into())) + fn next_back(&mut self) -> Option { + self.0.pop_back().map(|s| KIteratorOutput::Value(s.into())) } } @@ -543,9 +541,7 @@ impl Iterator for StringIterator { type Item = Output; fn next(&mut self) -> Option { - self.0 - .pop_front() - .map(|s| ValueIteratorOutput::Value(s.into())) + self.0.pop_front().map(|s| KIteratorOutput::Value(s.into())) } fn size_hint(&self) -> (usize, Option) { @@ -567,9 +563,9 @@ impl GeneratorIterator { } impl KotoIterator for GeneratorIterator { - fn make_copy(&self) -> Result { + fn make_copy(&self) -> Result { let new_vm = crate::vm::clone_generator_vm(&self.vm)?; - Ok(ValueIterator::with_vm(new_vm)) + Ok(KIterator::with_vm(new_vm)) } } @@ -582,8 +578,8 @@ impl Iterator for GeneratorIterator { Ok(Value::TemporaryTuple(_)) => { unreachable!("Yield shouldn't produce temporary tuples") } - Ok(result) => Some(ValueIteratorOutput::Value(result)), - Err(error) => Some(ValueIteratorOutput::Error(error)), + Ok(result) => Some(KIteratorOutput::Value(result)), + Err(error) => Some(KIteratorOutput::Error(error)), } } } @@ -600,8 +596,8 @@ impl KotoIterator for StdForwardIterator where T: Iterator + Clone + 'static, { - fn make_copy(&self) -> Result { - Ok(ValueIterator::new(self.clone())) + fn make_copy(&self) -> Result { + Ok(KIterator::new(self.clone())) } } @@ -628,15 +624,15 @@ impl KotoIterator for StdDoubleEndedIterator where T: DoubleEndedIterator + Clone + 'static, { - fn make_copy(&self) -> Result { - Ok(ValueIterator::new(self.clone())) + fn make_copy(&self) -> Result { + Ok(KIterator::new(self.clone())) } fn is_bidirectional(&self) -> bool { true } - fn next_back(&mut self) -> Option { + fn next_back(&mut self) -> Option { self.iter.next_back() } } diff --git a/core/runtime/src/vm.rs b/core/runtime/src/vm.rs index 455ae36d2..2cc928296 100644 --- a/core/runtime/src/vm.rs +++ b/core/runtime/src/vm.rs @@ -506,13 +506,13 @@ impl Vm { result } - /// Makes a ValueIterator that iterates over the provided value's contents - pub fn make_iterator(&mut self, value: Value) -> Result { + /// Makes a KIterator that iterates over the provided value's contents + pub fn make_iterator(&mut self, value: Value) -> Result { use Value::*; match value { _ if value.contains_meta_key(&UnaryOp::Next.into()) => { - ValueIterator::with_meta_next(self.spawn_shared_vm(), value) + KIterator::with_meta_next(self.spawn_shared_vm(), value) } _ if value.contains_meta_key(&UnaryOp::Iterator.into()) => { // If the value implements @iterator, @@ -521,11 +521,11 @@ impl Vm { self.make_iterator(iterator_call_result) } Iterator(i) => Ok(i), - Range(r) => ValueIterator::with_range(r), - List(l) => Ok(ValueIterator::with_list(l)), - Tuple(t) => Ok(ValueIterator::with_tuple(t)), - Str(s) => Ok(ValueIterator::with_string(s)), - Map(m) => Ok(ValueIterator::with_map(m)), + Range(r) => KIterator::with_range(r), + List(l) => Ok(KIterator::with_list(l)), + Tuple(t) => Ok(KIterator::with_tuple(t)), + Str(s) => Ok(KIterator::with_string(s)), + Map(m) => Ok(KIterator::with_map(m)), Object(o) => { use IsIterable::*; @@ -534,7 +534,7 @@ impl Vm { NotIterable => runtime_error!("{} is not iterable", o_inner.object_type()), Iterable => o_inner.make_iterator(self), ForwardIterator | BidirectionalIterator => { - ValueIterator::with_object(self.spawn_shared_vm(), o.clone()) + KIterator::with_object(self.spawn_shared_vm(), o.clone()) } } } @@ -1022,7 +1022,7 @@ impl Vm { let iterator = match iterable { _ if iterable.contains_meta_key(&UnaryOp::Next.into()) => { - ValueIterator::with_meta_next(self.spawn_shared_vm(), iterable)?.into() + KIterator::with_meta_next(self.spawn_shared_vm(), iterable)?.into() } _ if iterable.contains_meta_key(&UnaryOp::Iterator.into()) => { if let Some(op) = iterable.get_meta_value(&UnaryOp::Iterator.into()) { @@ -1042,11 +1042,11 @@ impl Vm { // situations like argument unpacking. iterable } - Range(range) => ValueIterator::with_range(range)?.into(), - List(list) => ValueIterator::with_list(list).into(), - Tuple(tuple) => ValueIterator::with_tuple(tuple).into(), - Str(s) => ValueIterator::with_string(s).into(), - Map(map) => ValueIterator::with_map(map).into(), + Range(range) => KIterator::with_range(range)?.into(), + List(list) => KIterator::with_list(list).into(), + Tuple(tuple) => KIterator::with_tuple(tuple).into(), + Str(s) => KIterator::with_string(s).into(), + Map(map) => KIterator::with_map(map).into(), Object(o) => { use IsIterable::*; let o_inner = o.try_borrow()?; @@ -1056,7 +1056,7 @@ impl Vm { } Iterable => o_inner.make_iterator(self)?.into(), ForwardIterator | BidirectionalIterator => { - ValueIterator::with_object(self.spawn_shared_vm(), o.clone())?.into() + KIterator::with_object(self.spawn_shared_vm(), o.clone())?.into() } } } @@ -1081,8 +1081,8 @@ impl Vm { let output = match self.clone_register(iterable_register) { Iterator(mut iterator) => { match iterator.next() { - Some(ValueIteratorOutput::Value(value)) => Some(value), - Some(ValueIteratorOutput::ValuePair(first, second)) => { + Some(KIteratorOutput::Value(value)) => Some(value), + Some(KIteratorOutput::ValuePair(first, second)) => { if let Some(result) = result_register { if output_is_temporary { self.set_register(result + 1, first); @@ -1100,7 +1100,7 @@ impl Vm { Some(Null) } } - Some(ValueIteratorOutput::Error(error)) => { + Some(KIteratorOutput::Error(error)) => { return runtime_error!(error.to_string()); } None => None, @@ -2524,7 +2524,7 @@ impl Vm { // Wrap the generator vm in an iterator and place it in the result register self.set_register( call_info.result_register, - ValueIterator::with_vm(generator_vm).into(), + KIterator::with_vm(generator_vm).into(), ); Ok(()) diff --git a/core/runtime/tests/object_tests.rs b/core/runtime/tests/object_tests.rs index 3c2365658..c1264e9a9 100644 --- a/core/runtime/tests/object_tests.rs +++ b/core/runtime/tests/object_tests.rs @@ -187,8 +187,8 @@ mod objects { IsIterable::Iterable } - fn make_iterator(&self, vm: &mut Vm) -> Result { - ValueIterator::with_object(vm.spawn_shared_vm(), TestIterator::make_object(self.x)) + fn make_iterator(&self, vm: &mut Vm) -> Result { + KIterator::with_object(vm.spawn_shared_vm(), TestIterator::make_object(self.x)) } } @@ -255,12 +255,12 @@ mod objects { IsIterable::BidirectionalIterator } - fn iterator_next(&mut self, _vm: &mut Vm) -> Option { + fn iterator_next(&mut self, _vm: &mut Vm) -> Option { self.x += 1; Some(self.x.into()) } - fn iterator_next_back(&mut self, _vm: &mut Vm) -> Option { + fn iterator_next_back(&mut self, _vm: &mut Vm) -> Option { self.x -= 1; Some(self.x.into()) } diff --git a/examples/poetry/src/koto_bindings.rs b/examples/poetry/src/koto_bindings.rs index 4a6cf60b7..18ea60157 100644 --- a/examples/poetry/src/koto_bindings.rs +++ b/examples/poetry/src/koto_bindings.rs @@ -35,9 +35,9 @@ impl KotoObject for Poetry { IsIterable::ForwardIterator } - fn iterator_next(&mut self, _vm: &mut Vm) -> Option { + fn iterator_next(&mut self, _vm: &mut Vm) -> Option { self.next_word() - .map(|word| ValueIteratorOutput::Value(word.as_ref().into())) + .map(|word| KIteratorOutput::Value(word.as_ref().into())) } } diff --git a/libs/color/src/color.rs b/libs/color/src/color.rs index 411db8a8b..6f6cc122a 100644 --- a/libs/color/src/color.rs +++ b/libs/color/src/color.rs @@ -240,7 +240,7 @@ impl KotoObject for Color { IsIterable::Iterable } - fn make_iterator(&self, _vm: &mut Vm) -> Result { + fn make_iterator(&self, _vm: &mut Vm) -> Result { let c = *self; let iter = (0..=3).map(move |i| { @@ -251,10 +251,10 @@ impl KotoObject for Color { 3 => c.alpha(), _ => unreachable!(), }; - ValueIteratorOutput::Value(result.into()) + KIteratorOutput::Value(result.into()) }); - Ok(ValueIterator::with_std_iter(iter)) + Ok(KIterator::with_std_iter(iter)) } } diff --git a/libs/geometry/src/rect.rs b/libs/geometry/src/rect.rs index fd32e708d..ce074e518 100644 --- a/libs/geometry/src/rect.rs +++ b/libs/geometry/src/rect.rs @@ -47,7 +47,7 @@ impl KotoObject for Rect { IsIterable::Iterable } - fn make_iterator(&self, _vm: &mut Vm) -> Result { + fn make_iterator(&self, _vm: &mut Vm) -> Result { let r = *self; let iter = (0..=3).map(move |i| { @@ -58,10 +58,10 @@ impl KotoObject for Rect { 3 => r.h(), _ => unreachable!(), }; - ValueIteratorOutput::Value(result.into()) + KIteratorOutput::Value(result.into()) }); - Ok(ValueIterator::with_std_iter(iter)) + Ok(KIterator::with_std_iter(iter)) } } diff --git a/libs/geometry/src/vec2.rs b/libs/geometry/src/vec2.rs index ebaf701b3..0912edec2 100644 --- a/libs/geometry/src/vec2.rs +++ b/libs/geometry/src/vec2.rs @@ -100,7 +100,7 @@ impl KotoObject for Vec2 { IsIterable::Iterable } - fn make_iterator(&self, _vm: &mut Vm) -> Result { + fn make_iterator(&self, _vm: &mut Vm) -> Result { let v = *self; let iter = (0..=1).map(move |i| { @@ -109,10 +109,10 @@ impl KotoObject for Vec2 { 1 => v.y, _ => unreachable!(), }; - ValueIteratorOutput::Value(result.into()) + KIteratorOutput::Value(result.into()) }); - Ok(ValueIterator::with_std_iter(iter)) + Ok(KIterator::with_std_iter(iter)) } } diff --git a/libs/geometry/src/vec3.rs b/libs/geometry/src/vec3.rs index d3c8b50d8..abfc4e50a 100644 --- a/libs/geometry/src/vec3.rs +++ b/libs/geometry/src/vec3.rs @@ -96,7 +96,7 @@ impl KotoObject for Vec3 { IsIterable::Iterable } - fn make_iterator(&self, _vm: &mut Vm) -> Result { + fn make_iterator(&self, _vm: &mut Vm) -> Result { let v = *self; let iter = (0..=2).map(move |i| { @@ -106,10 +106,10 @@ impl KotoObject for Vec3 { 2 => v.z, _ => unreachable!(), }; - ValueIteratorOutput::Value(result.into()) + KIteratorOutput::Value(result.into()) }); - Ok(ValueIterator::with_std_iter(iter)) + Ok(KIterator::with_std_iter(iter)) } } From 61db1c71e76f3be31cd7c2821c6bb3286e0fcf24 Mon Sep 17 00:00:00 2001 From: Ian Hobson Date: Wed, 11 Oct 2023 11:10:58 +0200 Subject: [PATCH 03/13] Rename ValueList -> KList --- core/runtime/src/core_lib/iterator.rs | 2 +- core/runtime/src/core_lib/koto.rs | 2 +- core/runtime/src/core_lib/tuple.rs | 2 +- core/runtime/src/lib.rs | 4 ++-- core/runtime/src/prelude.rs | 8 ++++---- core/runtime/src/types/mod.rs | 2 +- core/runtime/src/types/value.rs | 20 ++++++++++---------- core/runtime/src/types/value_iterator.rs | 6 +++--- core/runtime/src/types/value_list.rs | 6 +++--- core/runtime/src/vm.rs | 14 +++++++------- core/runtime/tests/runtime_test_utils.rs | 2 +- core/runtime/tests/vm_tests.rs | 2 +- libs/json/src/lib.rs | 2 +- libs/toml/src/lib.rs | 2 +- libs/yaml/src/lib.rs | 2 +- 15 files changed, 38 insertions(+), 38 deletions(-) diff --git a/core/runtime/src/core_lib/iterator.rs b/core/runtime/src/core_lib/iterator.rs index 663093325..9fb377661 100644 --- a/core/runtime/src/core_lib/iterator.rs +++ b/core/runtime/src/core_lib/iterator.rs @@ -708,7 +708,7 @@ pub fn make_module() -> KMap { } } - Ok(Value::List(ValueList::with_data(result))) + Ok(Value::List(KList::with_data(result))) } (_, unexpected) => type_error_with_slice(expected_error, unexpected), } diff --git a/core/runtime/src/core_lib/koto.rs b/core/runtime/src/core_lib/koto.rs index 4677ef662..167e967ea 100644 --- a/core/runtime/src/core_lib/koto.rs +++ b/core/runtime/src/core_lib/koto.rs @@ -11,7 +11,7 @@ pub fn make_module() -> KMap { result.add_fn("copy", |ctx| match ctx.args() { [Value::Iterator(iter)] => Ok(iter.make_copy()?.into()), - [Value::List(l)] => Ok(ValueList::with_data(l.data().clone()).into()), + [Value::List(l)] => Ok(KList::with_data(l.data().clone()).into()), [Value::Map(m)] => { let result = KMap::with_contents( m.data().clone(), diff --git a/core/runtime/src/core_lib/tuple.rs b/core/runtime/src/core_lib/tuple.rs index 4b1665a6f..1b7480992 100644 --- a/core/runtime/src/core_lib/tuple.rs +++ b/core/runtime/src/core_lib/tuple.rs @@ -105,7 +105,7 @@ pub fn make_module() -> KMap { let expected_error = "a Tuple"; match ctx.instance_and_args(is_tuple, expected_error)? { - (Value::Tuple(t), []) => Ok(Value::List(ValueList::from_slice(t))), + (Value::Tuple(t), []) => Ok(Value::List(KList::from_slice(t))), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); diff --git a/core/runtime/src/lib.rs b/core/runtime/src/lib.rs index 2ddc76de5..802d05a52 100644 --- a/core/runtime/src/lib.rs +++ b/core/runtime/src/lib.rs @@ -17,9 +17,9 @@ pub use crate::{ io::{BufferedFile, DefaultStderr, DefaultStdin, DefaultStdout, KotoFile, KotoRead, KotoWrite}, types::{ BinaryOp, CallContext, CaptureFunctionInfo, ExternalFunction, FunctionInfo, IntRange, - IsIterable, KIterator, KIteratorOutput, KMap, KotoHasher, KotoIterator, KotoObject, + IsIterable, KIterator, KIteratorOutput, KList, KMap, KotoHasher, KotoIterator, KotoObject, KotoType, MetaKey, MetaMap, MethodContext, Object, ObjectEntryBuilder, UnaryOp, Value, - ValueKey, ValueList, ValueMap, ValueNumber, ValueString, ValueTuple, ValueVec, + ValueKey, ValueMap, ValueNumber, ValueString, ValueTuple, ValueVec, }, vm::{CallArgs, ModuleImportedCallback, Vm, VmSettings}, }; diff --git a/core/runtime/src/prelude.rs b/core/runtime/src/prelude.rs index a7207b377..25065d55d 100644 --- a/core/runtime/src/prelude.rs +++ b/core/runtime/src/prelude.rs @@ -4,8 +4,8 @@ pub use crate::{ make_runtime_error, runtime_error, type_error, type_error_with_slice, BinaryOp, Borrow, BorrowMut, CallArgs, CallContext, DisplayContext, ExternalFunction, IntRange, IsIterable, - KIterator, KIteratorOutput, KMap, KotoFile, KotoHasher, KotoIterator, KotoObject, KotoRead, - KotoType, KotoWrite, MetaKey, MetaMap, Object, ObjectEntryBuilder, Ptr, PtrMut, RuntimeError, - UnaryOp, Value, ValueKey, ValueList, ValueMap, ValueNumber, ValueString, ValueTuple, ValueVec, - Vm, VmSettings, + KIterator, KIteratorOutput, KList, KMap, KotoFile, KotoHasher, KotoIterator, KotoObject, + KotoRead, KotoType, KotoWrite, MetaKey, MetaMap, Object, ObjectEntryBuilder, Ptr, PtrMut, + RuntimeError, UnaryOp, Value, ValueKey, ValueMap, ValueNumber, ValueString, ValueTuple, + ValueVec, Vm, VmSettings, }; diff --git a/core/runtime/src/types/mod.rs b/core/runtime/src/types/mod.rs index e56883832..71763ee7c 100644 --- a/core/runtime/src/types/mod.rs +++ b/core/runtime/src/types/mod.rs @@ -21,7 +21,7 @@ pub use self::{ value::{CaptureFunctionInfo, FunctionInfo, Value}, value_iterator::{KIterator, KIteratorOutput, KotoIterator}, value_key::ValueKey, - value_list::{ValueList, ValueVec}, + value_list::{KList, ValueVec}, value_map::{KMap, KotoHasher, ValueMap}, value_number::ValueNumber, value_string::ValueString, diff --git a/core/runtime/src/types/value.rs b/core/runtime/src/types/value.rs index fbcaeb70c..d0ebf89cb 100644 --- a/core/runtime/src/types/value.rs +++ b/core/runtime/src/types/value.rs @@ -21,7 +21,7 @@ pub enum Value { Range(IntRange), /// The list type used in Koto - List(ValueList), + List(KList), /// The tuple type used in Koto Tuple(ValueTuple), @@ -68,7 +68,7 @@ impl Value { .iter() .map(|v| v.deep_copy()) .collect::>()?; - Value::List(ValueList::with_data(result)) + Value::List(KList::with_data(result)) } Value::Tuple(t) => { let result = t @@ -300,8 +300,8 @@ impl From for Value { } } -impl From for Value { - fn from(value: ValueList) -> Self { +impl From for Value { + fn from(value: KList) -> Self { Self::List(value) } } @@ -368,18 +368,18 @@ pub struct CaptureFunctionInfo { pub info: FunctionInfo, /// The optional list of captures that should be copied into scope when the function is called. // - // Q. Why use a ValueList? + // Q. Why use a KList? // A. Because capturing values currently works by assigning by index, after the function // itself has been created. // Q. Why not use a SequenceBuilder? // A. Recursive functions need to capture themselves into the list, and the captured function // and the assigned function need to share the same captures list. Currently the only way // for this to work is to allow mutation of the shared list after the creation of the - // function, so a ValueList is a reasonable choice. - // Q. What about using Ptr<[Value]> for non-recursive functions, or Option for - // non-recursive functions with a single capture? - // A. These could be worth investigating, but for now the ValueList will do. - pub captures: ValueList, + // function, so a KList is a reasonable choice. + // Q. After capturing is complete, what about using Ptr<[Value]> for non-recursive functions, + // or Option for non-recursive functions with a single capture? + // A. These could be worth investigating, but for now the KList will do. + pub captures: KList, } /// A slice of a VM's registers diff --git a/core/runtime/src/types/value_iterator.rs b/core/runtime/src/types/value_iterator.rs index ecdbf4a3b..3dc556285 100644 --- a/core/runtime/src/types/value_iterator.rs +++ b/core/runtime/src/types/value_iterator.rs @@ -98,7 +98,7 @@ impl KIterator { } /// Creates a new KIterator from a List - pub fn with_list(list: ValueList) -> Self { + pub fn with_list(list: KList) -> Self { Self::new(ListIterator::new(list)) } @@ -236,13 +236,13 @@ impl Iterator for RangeIterator { #[derive(Clone)] struct ListIterator { - data: ValueList, + data: KList, index: usize, end: usize, } impl ListIterator { - fn new(data: ValueList) -> Self { + fn new(data: KList) -> Self { let end = data.len(); Self { data, diff --git a/core/runtime/src/types/value_list.rs b/core/runtime/src/types/value_list.rs index 6be2b8c2c..ab406a65d 100644 --- a/core/runtime/src/types/value_list.rs +++ b/core/runtime/src/types/value_list.rs @@ -1,13 +1,13 @@ use crate::{prelude::*, Result}; -/// The underlying Vec type used by [ValueList] +/// The underlying Vec type used by [KList] pub type ValueVec = smallvec::SmallVec<[Value; 4]>; /// The Koto runtime's List type #[derive(Clone, Default)] -pub struct ValueList(PtrMut); +pub struct KList(PtrMut); -impl ValueList { +impl KList { /// Creates an empty list with the given capacity pub fn with_capacity(capacity: usize) -> Self { Self(ValueVec::with_capacity(capacity).into()) diff --git a/core/runtime/src/vm.rs b/core/runtime/src/vm.rs index 2cc928296..86f794b64 100644 --- a/core/runtime/src/vm.rs +++ b/core/runtime/src/vm.rs @@ -1231,11 +1231,11 @@ impl Vm { if is_slice_to { list.data() .get(..index) - .map_or(Null, |entries| List(ValueList::from_slice(entries))) + .map_or(Null, |entries| List(KList::from_slice(entries))) } else { list.data() .get(index..) - .map_or(Null, |entries| List(ValueList::from_slice(entries))) + .map_or(Null, |entries| List(KList::from_slice(entries))) } } Tuple(tuple) => { @@ -1282,7 +1282,7 @@ impl Vm { captures.resize(capture_count as usize, Null); CaptureFunction(Ptr::new(CaptureFunctionInfo { info, - captures: ValueList::with_data(captures), + captures: KList::with_data(captures), })) } else { Function(info) @@ -2157,7 +2157,7 @@ impl Vm { } (List(l), Range(range)) => self.set_register( result_register, - List(ValueList::from_slice(&l.data()[range.indices(l.len())])), + List(KList::from_slice(&l.data()[range.indices(l.len())])), ), (Tuple(t), Number(n)) => { let index = self.validate_index(n, Some(t.len()))?; @@ -2443,7 +2443,7 @@ impl Vm { &mut self, call_info: &CallInfo, f: &FunctionInfo, - captures: Option<&ValueList>, + captures: Option<&KList>, temp_tuple_values: Option<&[Value]>, ) -> Result<()> { // Spawn a VM for the generator @@ -2534,7 +2534,7 @@ impl Vm { &mut self, call_info: &CallInfo, f: &FunctionInfo, - captures: Option<&ValueList>, + captures: Option<&KList>, temp_tuple_values: Option<&[Value]>, ) -> Result<()> { if f.generator { @@ -2718,7 +2718,7 @@ impl Vm { fn run_sequence_to_list(&mut self, register: u8) -> Result<()> { if let Some(result) = self.sequence_builders.pop() { - let list = ValueList::with_data(ValueVec::from_vec(result)); + let list = KList::with_data(ValueVec::from_vec(result)); self.set_register(register, list.into()); Ok(()) } else { diff --git a/core/runtime/tests/runtime_test_utils.rs b/core/runtime/tests/runtime_test_utils.rs index a3939fb55..167ebf39c 100644 --- a/core/runtime/tests/runtime_test_utils.rs +++ b/core/runtime/tests/runtime_test_utils.rs @@ -112,7 +112,7 @@ where } pub fn value_list(values: &[Value]) -> Value { - List(ValueList::from_slice(values)) + List(KList::from_slice(values)) } pub fn value_tuple(values: &[Value]) -> Value { diff --git a/core/runtime/tests/vm_tests.rs b/core/runtime/tests/vm_tests.rs index 3d38bebf1..ace2bcf33 100644 --- a/core/runtime/tests/vm_tests.rs +++ b/core/runtime/tests/vm_tests.rs @@ -252,7 +252,7 @@ a %= 5 #[test] fn empty() { - test_script("[]", Value::List(ValueList::default())); + test_script("[]", Value::List(KList::default())); } #[test] diff --git a/libs/json/src/lib.rs b/libs/json/src/lib.rs index 26816ec73..211f608e6 100644 --- a/libs/json/src/lib.rs +++ b/libs/json/src/lib.rs @@ -22,7 +22,7 @@ pub fn json_value_to_koto_value(value: &serde_json::Value) -> Result>() { - Ok(result) => Value::List(ValueList::with_data(result)), + Ok(result) => Value::List(KList::with_data(result)), Err(e) => return Err(e), } } diff --git a/libs/toml/src/lib.rs b/libs/toml/src/lib.rs index 815467f70..6c72c5016 100644 --- a/libs/toml/src/lib.rs +++ b/libs/toml/src/lib.rs @@ -16,7 +16,7 @@ pub fn toml_to_koto_value(value: &Toml) -> Result { .map(toml_to_koto_value) .collect::>() { - Ok(result) => Value::List(ValueList::with_data(result)), + Ok(result) => Value::List(KList::with_data(result)), Err(e) => return Err(e), } } diff --git a/libs/yaml/src/lib.rs b/libs/yaml/src/lib.rs index 96a57f873..4d6f0e54d 100644 --- a/libs/yaml/src/lib.rs +++ b/libs/yaml/src/lib.rs @@ -22,7 +22,7 @@ pub fn yaml_value_to_koto_value(value: &serde_yaml::Value) -> Result>() { - Ok(result) => Value::List(ValueList::with_data(result)), + Ok(result) => Value::List(KList::with_data(result)), Err(e) => return Err(e), } } From 63edfbf4ef300bb49e353833037f4c2e395e85d1 Mon Sep 17 00:00:00 2001 From: Ian Hobson Date: Wed, 11 Oct 2023 11:15:21 +0200 Subject: [PATCH 04/13] Rename ValueNumber -> KNumber --- core/runtime/src/core_lib/number.rs | 49 ++++----- core/runtime/src/core_lib/test.rs | 2 +- core/runtime/src/lib.rs | 6 +- core/runtime/src/prelude.rs | 8 +- core/runtime/src/types/int_range.rs | 2 +- core/runtime/src/types/mod.rs | 2 +- core/runtime/src/types/value.rs | 10 +- core/runtime/src/types/value_number.rs | 144 ++++++++++++------------- core/runtime/src/vm.rs | 4 +- libs/color/src/lib.rs | 4 +- 10 files changed, 114 insertions(+), 117 deletions(-) diff --git a/core/runtime/src/core_lib/number.rs b/core/runtime/src/core_lib/number.rs index 0af6eb89d..66bca02a8 100644 --- a/core/runtime/src/core_lib/number.rs +++ b/core/runtime/src/core_lib/number.rs @@ -4,6 +4,8 @@ use crate::prelude::*; /// Initializes the `number` core library module pub fn make_module() -> KMap { + use Value::Number; + let result = KMap::with_type("core.number"); macro_rules! number_fn { @@ -15,7 +17,7 @@ pub fn make_module() -> KMap { let expected_error = "a Number"; match ctx.instance_and_args(is_number, expected_error)? { - (Value::Number(n), []) => Ok(Value::Number(n.$fn())), + (Number(n), []) => Ok(Number(n.$fn())), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -31,7 +33,7 @@ pub fn make_module() -> KMap { let expected_error = "a Number"; match ctx.instance_and_args(is_number, expected_error)? { - (Value::Number(n), []) => Ok(Value::Number(f64::from(n).$fn().into())), + (Number(n), []) => Ok(Number(f64::from(n).$fn().into())), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -41,11 +43,11 @@ pub fn make_module() -> KMap { macro_rules! bitwise_fn { ($name:ident, $op:tt) => { result.add_fn(stringify!($name), |ctx| { - use ValueNumber::I64; + use KNumber::I64; let expected_error = "two Integers"; match ctx.instance_and_args(is_integer, expected_error)? { - (Value::Number(I64(a)), [Value::Number(I64(b))]) => Ok((a $op b).into()), + (Number(I64(a)), [Number(I64(b))]) => Ok((a $op b).into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }) @@ -55,12 +57,12 @@ pub fn make_module() -> KMap { macro_rules! bitwise_fn_positive_arg { ($name:ident, $op:tt) => { result.add_fn(stringify!($name), |ctx| { - use ValueNumber::I64; + use KNumber::I64; let expected_error = "two Integers (with non-negative second Integer)"; match ctx.instance_and_args(is_integer, expected_error)? { - (Value::Number(I64(a)), [Value::Number(I64(b))]) if *b >= 0 => Ok((a $op b).into()), + (Number(I64(a)), [Number(I64(b))]) if *b >= 0 => Ok((a $op b).into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }) @@ -80,10 +82,7 @@ pub fn make_module() -> KMap { let expected_error = "two Numbers"; match ctx.instance_and_args(is_number, expected_error)? { - (Value::Number(y), [Value::Number(x)]) => { - let result = f64::from(y).atan2(f64::from(x)); - Ok(Value::Number(result.into())) - } + (Number(y), [Number(x)]) => Ok(f64::from(y).atan2(f64::from(x)).into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -94,9 +93,7 @@ pub fn make_module() -> KMap { let expected_error = "three Numbers"; match ctx.instance_and_args(is_number, expected_error)? { - (Value::Number(x), [Value::Number(a), Value::Number(b)]) => { - Ok(Value::Number(*a.max(b.min(x)))) - } + (Number(x), [Number(a), Number(b)]) => Ok(Number(*a.max(b.min(x)))), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -114,20 +111,20 @@ pub fn make_module() -> KMap { let expected_error = "an Integer"; match ctx.instance_and_args(is_integer, expected_error)? { - (Value::Number(ValueNumber::I64(n)), []) => Ok((!n).into()), + (Number(KNumber::I64(n)), []) => Ok((!n).into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); number_fn!(floor); - result.add_value("infinity", Value::Number(std::f64::INFINITY.into())); + result.add_value("infinity", Number(std::f64::INFINITY.into())); result.add_fn("is_nan", |ctx| { let expected_error = "a Number"; match ctx.instance_and_args(is_number, expected_error)? { - (Value::Number(n), []) => Ok(n.is_nan().into()), + (Number(n), []) => Ok(n.is_nan().into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -136,7 +133,7 @@ pub fn make_module() -> KMap { let expected_error = "three Numbers"; match ctx.instance_and_args(is_number, expected_error)? { - (Value::Number(a), [Value::Number(b), Value::Number(t)]) => { + (Number(a), [Number(b), Number(t)]) => { let result = *a + (b - a) * *t; Ok(result.into()) } @@ -152,7 +149,7 @@ pub fn make_module() -> KMap { let expected_error = "two Numbers"; match ctx.instance_and_args(is_number, expected_error)? { - (Value::Number(a), [Value::Number(b)]) => Ok(Value::Number(*a.max(b))), + (Number(a), [Number(b)]) => Ok(Number(*a.max(b))), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -161,7 +158,7 @@ pub fn make_module() -> KMap { let expected_error = "two Numbers"; match ctx.instance_and_args(is_number, expected_error)? { - (Value::Number(a), [Value::Number(b)]) => Ok(Value::Number(*a.min(b))), + (Number(a), [Number(b)]) => Ok(Number(*a.min(b))), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -171,15 +168,15 @@ pub fn make_module() -> KMap { bitwise_fn!(or, |); - result.add_value("pi", Value::Number(std::f64::consts::PI.into())); - result.add_value("pi_2", Value::Number(std::f64::consts::FRAC_PI_2.into())); - result.add_value("pi_4", Value::Number(std::f64::consts::FRAC_PI_4.into())); + result.add_value("pi", std::f64::consts::PI.into()); + result.add_value("pi_2", std::f64::consts::FRAC_PI_2.into()); + result.add_value("pi_4", std::f64::consts::FRAC_PI_4.into()); result.add_fn("pow", |ctx| { let expected_error = "two Numbers"; match ctx.instance_and_args(is_number, expected_error)? { - (Value::Number(a), [Value::Number(b)]) => Ok(Value::Number(a.pow(*b))), + (Number(a), [Number(b)]) => Ok(Number(a.pow(*b))), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -203,7 +200,7 @@ pub fn make_module() -> KMap { let expected_error = "a Number"; match ctx.instance_and_args(is_number, expected_error)? { - (Value::Number(n), []) => Ok(f64::from(n).into()), + (Number(n), []) => Ok(f64::from(n).into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -212,7 +209,7 @@ pub fn make_module() -> KMap { let expected_error = "a Number"; match ctx.instance_and_args(is_number, expected_error)? { - (Value::Number(n), []) => Ok(i64::from(n).into()), + (Number(n), []) => Ok(i64::from(n).into()), (_, unexpected) => type_error_with_slice(expected_error, unexpected), } }); @@ -227,5 +224,5 @@ fn is_number(value: &Value) -> bool { } fn is_integer(value: &Value) -> bool { - matches!(value, Value::Number(ValueNumber::I64(_))) + matches!(value, Value::Number(KNumber::I64(_))) } diff --git a/core/runtime/src/core_lib/test.rs b/core/runtime/src/core_lib/test.rs index 5e000aee0..465472478 100644 --- a/core/runtime/src/core_lib/test.rs +++ b/core/runtime/src/core_lib/test.rs @@ -91,7 +91,7 @@ fn f64_near(a: f64, b: f64, allowed_diff: f64) -> bool { (a - b).abs() <= allowed_diff } -fn number_near(a: ValueNumber, b: ValueNumber, allowed_diff: f64) -> Result { +fn number_near(a: KNumber, b: KNumber, allowed_diff: f64) -> Result { if f64_near(a.into(), b.into(), allowed_diff) { Ok(Value::Null) } else { diff --git a/core/runtime/src/lib.rs b/core/runtime/src/lib.rs index 802d05a52..c488793b3 100644 --- a/core/runtime/src/lib.rs +++ b/core/runtime/src/lib.rs @@ -17,9 +17,9 @@ pub use crate::{ io::{BufferedFile, DefaultStderr, DefaultStdin, DefaultStdout, KotoFile, KotoRead, KotoWrite}, types::{ BinaryOp, CallContext, CaptureFunctionInfo, ExternalFunction, FunctionInfo, IntRange, - IsIterable, KIterator, KIteratorOutput, KList, KMap, KotoHasher, KotoIterator, KotoObject, - KotoType, MetaKey, MetaMap, MethodContext, Object, ObjectEntryBuilder, UnaryOp, Value, - ValueKey, ValueMap, ValueNumber, ValueString, ValueTuple, ValueVec, + IsIterable, KIterator, KIteratorOutput, KList, KMap, KNumber, KotoHasher, KotoIterator, + KotoObject, KotoType, MetaKey, MetaMap, MethodContext, Object, ObjectEntryBuilder, UnaryOp, + Value, ValueKey, ValueMap, ValueString, ValueTuple, ValueVec, }, vm::{CallArgs, ModuleImportedCallback, Vm, VmSettings}, }; diff --git a/core/runtime/src/prelude.rs b/core/runtime/src/prelude.rs index 25065d55d..d31258746 100644 --- a/core/runtime/src/prelude.rs +++ b/core/runtime/src/prelude.rs @@ -4,8 +4,8 @@ pub use crate::{ make_runtime_error, runtime_error, type_error, type_error_with_slice, BinaryOp, Borrow, BorrowMut, CallArgs, CallContext, DisplayContext, ExternalFunction, IntRange, IsIterable, - KIterator, KIteratorOutput, KList, KMap, KotoFile, KotoHasher, KotoIterator, KotoObject, - KotoRead, KotoType, KotoWrite, MetaKey, MetaMap, Object, ObjectEntryBuilder, Ptr, PtrMut, - RuntimeError, UnaryOp, Value, ValueKey, ValueMap, ValueNumber, ValueString, ValueTuple, - ValueVec, Vm, VmSettings, + KIterator, KIteratorOutput, KList, KMap, KNumber, KotoFile, KotoHasher, KotoIterator, + KotoObject, KotoRead, KotoType, KotoWrite, MetaKey, MetaMap, Object, ObjectEntryBuilder, Ptr, + PtrMut, RuntimeError, UnaryOp, Value, ValueKey, ValueMap, ValueString, ValueTuple, ValueVec, + Vm, VmSettings, }; diff --git a/core/runtime/src/types/int_range.rs b/core/runtime/src/types/int_range.rs index 646759124..ae7b309b8 100644 --- a/core/runtime/src/types/int_range.rs +++ b/core/runtime/src/types/int_range.rs @@ -132,7 +132,7 @@ impl IntRange { } /// Returns true if the provided number is within the range - pub fn contains(&self, n: ValueNumber) -> bool { + pub fn contains(&self, n: KNumber) -> bool { let n: i64 = if n < 0.0 { n.floor() } else { n.ceil() }.into(); self.as_sorted_range().contains(&n) } diff --git a/core/runtime/src/types/mod.rs b/core/runtime/src/types/mod.rs index 71763ee7c..7d337736e 100644 --- a/core/runtime/src/types/mod.rs +++ b/core/runtime/src/types/mod.rs @@ -23,7 +23,7 @@ pub use self::{ value_key::ValueKey, value_list::{KList, ValueVec}, value_map::{KMap, KotoHasher, ValueMap}, - value_number::ValueNumber, + value_number::KNumber, value_string::ValueString, value_tuple::ValueTuple, }; diff --git a/core/runtime/src/types/value.rs b/core/runtime/src/types/value.rs index d0ebf89cb..e683e6bb2 100644 --- a/core/runtime/src/types/value.rs +++ b/core/runtime/src/types/value.rs @@ -15,7 +15,7 @@ pub enum Value { Bool(bool), /// A number, represented as either a signed 64 bit integer or float - Number(ValueNumber), + Number(KNumber), /// A range with start/end boundaries Range(IntRange), @@ -169,8 +169,8 @@ impl Value { match &self { Null => TYPE_NULL.with(|x| x.clone()), Bool(_) => TYPE_BOOL.with(|x| x.clone()), - Number(ValueNumber::F64(_)) => TYPE_FLOAT.with(|x| x.clone()), - Number(ValueNumber::I64(_)) => TYPE_INT.with(|x| x.clone()), + Number(KNumber::F64(_)) => TYPE_FLOAT.with(|x| x.clone()), + Number(KNumber::I64(_)) => TYPE_INT.with(|x| x.clone()), List(_) => TYPE_LIST.with(|x| x.clone()), Range { .. } => TYPE_RANGE.with(|x| x.clone()), Map(m) if m.meta_map().is_some() => match m.get_meta_value(&MetaKey::Type) { @@ -270,8 +270,8 @@ impl From for Value { } } -impl From for Value { - fn from(value: ValueNumber) -> Self { +impl From for Value { + fn from(value: KNumber) -> Self { Self::Number(value) } } diff --git a/core/runtime/src/types/value_number.rs b/core/runtime/src/types/value_number.rs index 864bab024..de52119f4 100644 --- a/core/runtime/src/types/value_number.rs +++ b/core/runtime/src/types/value_number.rs @@ -11,12 +11,12 @@ use std::{ /// The number can be either an `f64` or an `i64` depending on usage. #[allow(missing_docs)] #[derive(Clone, Copy)] -pub enum ValueNumber { +pub enum KNumber { F64(f64), I64(i64), } -impl ValueNumber { +impl KNumber { /// Returns the absolute value of the number #[must_use] pub fn abs(self) -> Self { @@ -93,7 +93,7 @@ impl ValueNumber { /// otherwise the result will be an f64. #[must_use] pub fn pow(self, other: Self) -> Self { - use ValueNumber::*; + use KNumber::*; match (self, other) { (F64(a), F64(b)) => F64(a.powf(b)), @@ -120,39 +120,39 @@ impl ValueNumber { } } -impl fmt::Debug for ValueNumber { +impl fmt::Debug for KNumber { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ValueNumber::F64(n) => write!(f, "Float({n})"), - ValueNumber::I64(n) => write!(f, "Int({n})"), + KNumber::F64(n) => write!(f, "Float({n})"), + KNumber::I64(n) => write!(f, "Int({n})"), } } } -impl fmt::Display for ValueNumber { +impl fmt::Display for KNumber { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ValueNumber::F64(n) => { + KNumber::F64(n) => { if n.fract() > 0.0 { write!(f, "{n}") } else { write!(f, "{n:.1}") } } - ValueNumber::I64(n) => write!(f, "{n}"), + KNumber::I64(n) => write!(f, "{n}"), } } } -impl Hash for ValueNumber { +impl Hash for KNumber { fn hash(&self, state: &mut H) { state.write_u64(self.to_bits()) } } -impl PartialEq for ValueNumber { +impl PartialEq for KNumber { fn eq(&self, other: &Self) -> bool { - use ValueNumber::*; + use KNumber::*; match (self, other) { (F64(a), F64(b)) => a == b, @@ -163,17 +163,17 @@ impl PartialEq for ValueNumber { } } -impl Eq for ValueNumber {} +impl Eq for KNumber {} -impl PartialOrd for ValueNumber { +impl PartialOrd for KNumber { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } -impl Ord for ValueNumber { +impl Ord for KNumber { fn cmp(&self, other: &Self) -> Ordering { - use ValueNumber::*; + use KNumber::*; let result = match (self, other) { (F64(a), F64(b)) => a.partial_cmp(b), @@ -193,11 +193,11 @@ impl Ord for ValueNumber { } } -impl ops::Neg for ValueNumber { - type Output = ValueNumber; +impl ops::Neg for KNumber { + type Output = KNumber; - fn neg(self) -> ValueNumber { - use ValueNumber::*; + fn neg(self) -> KNumber { + use KNumber::*; match self { F64(n) => F64(-n), @@ -206,11 +206,11 @@ impl ops::Neg for ValueNumber { } } -impl ops::Neg for &ValueNumber { - type Output = ValueNumber; +impl ops::Neg for &KNumber { + type Output = KNumber; - fn neg(self) -> ValueNumber { - use ValueNumber::*; + fn neg(self) -> KNumber { + use KNumber::*; match *self { F64(n) => F64(-n), @@ -221,15 +221,15 @@ impl ops::Neg for &ValueNumber { macro_rules! number_traits_float { ($type:ident) => { - impl From<$type> for ValueNumber { - fn from(n: $type) -> ValueNumber { - ValueNumber::F64(n as f64) + impl From<$type> for KNumber { + fn from(n: $type) -> KNumber { + KNumber::F64(n as f64) } } - impl From<&$type> for ValueNumber { - fn from(n: &$type) -> ValueNumber { - ValueNumber::F64(*n as f64) + impl From<&$type> for KNumber { + fn from(n: &$type) -> KNumber { + KNumber::F64(*n as f64) } } @@ -245,22 +245,22 @@ macro_rules! number_traits_float { } } - impl PartialEq<$type> for ValueNumber { + impl PartialEq<$type> for KNumber { fn eq(&self, b: &$type) -> bool { let b = *b as f64; match self { - ValueNumber::F64(a) => *a == b, - ValueNumber::I64(a) => *a as f64 == b, + KNumber::F64(a) => *a == b, + KNumber::I64(a) => *a as f64 == b, } } } - impl PartialOrd<$type> for ValueNumber { + impl PartialOrd<$type> for KNumber { fn partial_cmp(&self, b: &$type) -> Option { let b = *b as f64; match self { - ValueNumber::F64(a) => a.partial_cmp(&b), - ValueNumber::I64(a) => (*a as f64).partial_cmp(&b), + KNumber::F64(a) => a.partial_cmp(&b), + KNumber::I64(a) => (*a as f64).partial_cmp(&b), } } } @@ -269,15 +269,15 @@ macro_rules! number_traits_float { macro_rules! number_traits_int { ($type:ident) => { - impl From<$type> for ValueNumber { - fn from(n: $type) -> ValueNumber { - ValueNumber::I64(n as i64) + impl From<$type> for KNumber { + fn from(n: $type) -> KNumber { + KNumber::I64(n as i64) } } - impl From<&$type> for ValueNumber { - fn from(n: &$type) -> ValueNumber { - ValueNumber::I64(*n as i64) + impl From<&$type> for KNumber { + fn from(n: &$type) -> KNumber { + KNumber::I64(*n as i64) } } @@ -293,22 +293,22 @@ macro_rules! number_traits_int { } } - impl PartialEq<$type> for ValueNumber { + impl PartialEq<$type> for KNumber { fn eq(&self, b: &$type) -> bool { let b = *b as i64; match self { - ValueNumber::F64(a) => (*a as i64) == b, - ValueNumber::I64(a) => *a == b, + KNumber::F64(a) => (*a as i64) == b, + KNumber::I64(a) => *a == b, } } } - impl PartialOrd<$type> for ValueNumber { + impl PartialOrd<$type> for KNumber { fn partial_cmp(&self, b: &$type) -> Option { let b = *b as i64; match self { - ValueNumber::F64(a) => (*a as i64).partial_cmp(&b), - ValueNumber::I64(a) => a.partial_cmp(&b), + KNumber::F64(a) => (*a as i64).partial_cmp(&b), + KNumber::I64(a) => a.partial_cmp(&b), } } } @@ -331,20 +331,20 @@ number_traits_int!(usize); macro_rules! from_number { ($type:ident) => { - impl From for $type { - fn from(n: ValueNumber) -> $type { + impl From for $type { + fn from(n: KNumber) -> $type { match n { - ValueNumber::F64(f) => f as $type, - ValueNumber::I64(i) => i as $type, + KNumber::F64(f) => f as $type, + KNumber::I64(i) => i as $type, } } } - impl From<&ValueNumber> for $type { - fn from(n: &ValueNumber) -> $type { + impl From<&KNumber> for $type { + fn from(n: &KNumber) -> $type { match n { - ValueNumber::F64(f) => *f as $type, - ValueNumber::I64(i) => *i as $type, + KNumber::F64(f) => *f as $type, + KNumber::I64(i) => *i as $type, } } } @@ -363,11 +363,11 @@ from_number!(usize); macro_rules! number_op { ($trait:ident, $fn:ident, $op:tt) => { - impl ops::$trait for ValueNumber { - type Output = ValueNumber; + impl ops::$trait for KNumber { + type Output = KNumber; - fn $fn(self, other: ValueNumber) -> ValueNumber { - use ValueNumber::*; + fn $fn(self, other: KNumber) -> KNumber { + use KNumber::*; match (self, other) { (F64(a), F64(b)) => F64(a $op b), @@ -378,11 +378,11 @@ macro_rules! number_op { } } - impl ops::$trait for &ValueNumber { - type Output = ValueNumber; + impl ops::$trait for &KNumber { + type Output = KNumber; - fn $fn(self, other: &ValueNumber) -> ValueNumber { - use ValueNumber::*; + fn $fn(self, other: &KNumber) -> KNumber { + use KNumber::*; match (*self, *other) { (F64(a), F64(b)) => F64(a $op b), @@ -400,11 +400,11 @@ number_op!(Sub, sub, -); number_op!(Mul, mul, *); number_op!(Rem, rem, %); -impl ops::Div for ValueNumber { - type Output = ValueNumber; +impl ops::Div for KNumber { + type Output = KNumber; - fn div(self, other: ValueNumber) -> ValueNumber { - use ValueNumber::*; + fn div(self, other: KNumber) -> KNumber { + use KNumber::*; match (self, other) { (F64(a), F64(b)) => F64(a / b), @@ -415,11 +415,11 @@ impl ops::Div for ValueNumber { } } -impl ops::Div for &ValueNumber { - type Output = ValueNumber; +impl ops::Div for &KNumber { + type Output = KNumber; - fn div(self, other: &ValueNumber) -> ValueNumber { - use ValueNumber::*; + fn div(self, other: &KNumber) -> KNumber { + use KNumber::*; match (*self, *other) { (F64(a), F64(b)) => F64(a / b), diff --git a/core/runtime/src/vm.rs b/core/runtime/src/vm.rs index 86f794b64..bc62fdfce 100644 --- a/core/runtime/src/vm.rs +++ b/core/runtime/src/vm.rs @@ -1466,7 +1466,7 @@ impl Vm { let lhs_value = self.get_register(lhs); let rhs_value = self.get_register(rhs); let result_value = match (lhs_value, rhs_value) { - (Number(_), Number(ValueNumber::I64(b))) if *b == 0 => { + (Number(_), Number(KNumber::I64(b))) if *b == 0 => { // Special case for integer remainder when the divisor is zero, // avoid a panic and return NaN instead. Number(f64::NAN.into()) @@ -2124,7 +2124,7 @@ impl Vm { Ok(()) } - fn validate_index(&self, n: ValueNumber, size: Option) -> Result { + fn validate_index(&self, n: KNumber, size: Option) -> Result { let index = usize::from(n); if n < 0.0 { diff --git a/libs/color/src/lib.rs b/libs/color/src/lib.rs index 1b8ba1ae9..046cb4004 100644 --- a/libs/color/src/lib.rs +++ b/libs/color/src/lib.rs @@ -63,10 +63,10 @@ fn named(name: &str) -> Result { } } -fn rgb(r: &ValueNumber, g: &ValueNumber, b: &ValueNumber) -> Result { +fn rgb(r: &KNumber, g: &KNumber, b: &KNumber) -> Result { Ok(Color::rgb(r.into(), g.into(), b.into()).into()) } -fn rgba(r: &ValueNumber, g: &ValueNumber, b: &ValueNumber, a: &ValueNumber) -> Result { +fn rgba(r: &KNumber, g: &KNumber, b: &KNumber, a: &KNumber) -> Result { Ok(Color::rgba(r.into(), g.into(), b.into(), a.into()).into()) } From 069dc0a69374659083a7f87f1814f65e6241ed9b Mon Sep 17 00:00:00 2001 From: Ian Hobson Date: Wed, 11 Oct 2023 11:20:39 +0200 Subject: [PATCH 05/13] Rename ValueString -> KString --- core/koto/tests/docs_examples.rs | 2 +- core/koto/tests/repl_mode_tests.rs | 2 +- core/runtime/src/core_lib/io.rs | 8 ++-- .../runtime/src/core_lib/iterator/peekable.rs | 4 +- core/runtime/src/core_lib/os.rs | 8 ++-- core/runtime/src/core_lib/string/iterators.rs | 22 +++++----- core/runtime/src/display_context.rs | 22 +++++----- core/runtime/src/io/file.rs | 6 +-- core/runtime/src/io/stdio.rs | 14 +++---- core/runtime/src/lib.rs | 6 +-- core/runtime/src/prelude.rs | 5 +-- core/runtime/src/types/meta_map.rs | 14 +++---- core/runtime/src/types/mod.rs | 2 +- core/runtime/src/types/object.rs | 16 +++---- core/runtime/src/types/value.rs | 40 +++++++++--------- core/runtime/src/types/value_iterator.rs | 6 +-- core/runtime/src/types/value_key.rs | 6 +-- core/runtime/src/types/value_string.rs | 42 +++++++++---------- core/runtime/src/vm.rs | 6 +-- core/runtime/tests/object_tests.rs | 8 ++-- core/runtime/tests/runtime_test_utils.rs | 2 +- examples/poetry/src/koto_bindings.rs | 2 +- examples/wasm/src/lib.rs | 4 +- libs/color/src/color.rs | 4 +- libs/geometry/src/rect.rs | 4 +- libs/geometry/src/vec2.rs | 4 +- libs/geometry/src/vec3.rs | 4 +- libs/random/src/lib.rs | 4 +- 28 files changed, 133 insertions(+), 134 deletions(-) diff --git a/core/koto/tests/docs_examples.rs b/core/koto/tests/docs_examples.rs index 437baaad0..08bbbf103 100644 --- a/core/koto/tests/docs_examples.rs +++ b/core/koto/tests/docs_examples.rs @@ -74,7 +74,7 @@ struct OutputCapture { } impl KotoFile for OutputCapture { - fn id(&self) -> ValueString { + fn id(&self) -> KString { "_stdout_".into() } } diff --git a/core/koto/tests/repl_mode_tests.rs b/core/koto/tests/repl_mode_tests.rs index 24b3e9ee2..4d96a8884 100644 --- a/core/koto/tests/repl_mode_tests.rs +++ b/core/koto/tests/repl_mode_tests.rs @@ -56,7 +56,7 @@ struct OutputCapture { } impl KotoFile for OutputCapture { - fn id(&self) -> ValueString { + fn id(&self) -> KString { "_stdout_".into() } } diff --git a/core/runtime/src/core_lib/io.rs b/core/runtime/src/core_lib/io.rs index 5493412bf..c156ccb59 100644 --- a/core/runtime/src/core_lib/io.rs +++ b/core/runtime/src/core_lib/io.rs @@ -193,7 +193,7 @@ impl KotoType for File { } impl KotoObject for File { - fn object_type(&self) -> ValueString { + fn object_type(&self) -> KString { FILE_TYPE_STRING.with(|t| t.clone()) } @@ -276,7 +276,7 @@ fn file_entries() -> ValueMap { } thread_local! { - static FILE_TYPE_STRING: ValueString = File::TYPE.into(); + static FILE_TYPE_STRING: KString = File::TYPE.into(); static FILE_ENTRIES: ValueMap = file_entries(); } @@ -304,11 +304,11 @@ impl KotoFile for BufferedSystemFile where T: Read + Write + Seek, { - fn id(&self) -> ValueString { + fn id(&self) -> KString { self.path.to_string_lossy().to_string().into() } - fn path(&self) -> Result { + fn path(&self) -> Result { Ok(self.id()) } diff --git a/core/runtime/src/core_lib/iterator/peekable.rs b/core/runtime/src/core_lib/iterator/peekable.rs index 15130b33b..fb42fad95 100644 --- a/core/runtime/src/core_lib/iterator/peekable.rs +++ b/core/runtime/src/core_lib/iterator/peekable.rs @@ -74,7 +74,7 @@ impl KotoType for Peekable { } impl KotoObject for Peekable { - fn object_type(&self) -> ValueString { + fn object_type(&self) -> KString { PEEKABLE_TYPE_STRING.with(|t| t.clone()) } @@ -119,7 +119,7 @@ fn peekable_entries() -> ValueMap { } thread_local! { - static PEEKABLE_TYPE_STRING: ValueString = Peekable::TYPE.into(); + static PEEKABLE_TYPE_STRING: KString = Peekable::TYPE.into(); static PEEKABLE_ENTRIES: ValueMap = peekable_entries(); } diff --git a/core/runtime/src/core_lib/os.rs b/core/runtime/src/core_lib/os.rs index 47162a2d3..3a1826470 100644 --- a/core/runtime/src/core_lib/os.rs +++ b/core/runtime/src/core_lib/os.rs @@ -75,7 +75,7 @@ impl KotoType for DateTime { } impl KotoObject for DateTime { - fn object_type(&self) -> ValueString { + fn object_type(&self) -> KString { DATETIME_TYPE_STRING.with(|t| t.clone()) } @@ -117,7 +117,7 @@ fn datetime_entries() -> ValueMap { } thread_local! { - static DATETIME_TYPE_STRING: ValueString = DateTime::TYPE.into(); + static DATETIME_TYPE_STRING: KString = DateTime::TYPE.into(); static DATETIME_ENTRIES: ValueMap = datetime_entries(); } @@ -149,7 +149,7 @@ impl KotoType for Timer { } impl KotoObject for Timer { - fn object_type(&self) -> ValueString { + fn object_type(&self) -> KString { TIMER_TYPE_STRING.with(|t| t.clone()) } @@ -193,6 +193,6 @@ fn named_timer_entries() -> ValueMap { } thread_local! { - static TIMER_TYPE_STRING: ValueString = Timer::TYPE.into(); + static TIMER_TYPE_STRING: KString = Timer::TYPE.into(); static TIMER_ENTRIES: ValueMap = named_timer_entries(); } diff --git a/core/runtime/src/core_lib/string/iterators.rs b/core/runtime/src/core_lib/string/iterators.rs index 5289ca72c..7df5f1a57 100644 --- a/core/runtime/src/core_lib/string/iterators.rs +++ b/core/runtime/src/core_lib/string/iterators.rs @@ -1,21 +1,21 @@ //! A collection of string iterators use crate::{ - make_runtime_error, CallArgs, KIterator, KIteratorOutput as Output, KotoIterator, Result, - Value, ValueString, Vm, + make_runtime_error, CallArgs, KIterator, KIteratorOutput as Output, KString, KotoIterator, + Result, Value, Vm, }; use unicode_segmentation::UnicodeSegmentation; /// An iterator that outputs the individual bytes contained in a string #[derive(Clone)] pub struct Bytes { - input: ValueString, + input: KString, index: usize, } impl Bytes { /// Creates a new [Bytes] iterator - pub fn new(input: ValueString) -> Self { + pub fn new(input: KString) -> Self { Self { input, index: 0 } } } @@ -52,13 +52,13 @@ impl Iterator for Bytes { /// - Empty lines are yielded as empty strings. #[derive(Clone)] pub struct Lines { - input: ValueString, + input: KString, start: usize, } impl Lines { /// Creates a new [Lines] iterator - pub fn new(input: ValueString) -> Self { + pub fn new(input: KString) -> Self { Self { input, start: 0 } } } @@ -107,14 +107,14 @@ impl Iterator for Lines { /// An iterator that splits up a string into parts, separated by a provided pattern #[derive(Clone)] pub struct Split { - input: ValueString, - pattern: ValueString, + input: KString, + pattern: KString, start: usize, } impl Split { /// Creates a new [Split] iterator - pub fn new(input: ValueString, pattern: ValueString) -> Self { + pub fn new(input: KString, pattern: KString) -> Self { Self { input, pattern, @@ -156,7 +156,7 @@ impl Iterator for Split { /// An iterator that splits up a string into parts, separated when a char passes a predicate pub struct SplitWith { - input: ValueString, + input: KString, predicate: Value, vm: Vm, start: usize, @@ -164,7 +164,7 @@ pub struct SplitWith { impl SplitWith { /// Creates a new [SplitWith] iterator - pub fn new(input: ValueString, predicate: Value, vm: Vm) -> Self { + pub fn new(input: KString, predicate: Value, vm: Vm) -> Self { Self { input, predicate, diff --git a/core/runtime/src/display_context.rs b/core/runtime/src/display_context.rs index cf3d935c7..64b847763 100644 --- a/core/runtime/src/display_context.rs +++ b/core/runtime/src/display_context.rs @@ -2,7 +2,7 @@ use std::fmt; use koto_memory::Address; -use crate::{ValueString, Vm}; +use crate::{KString, Vm}; /// A helper for converting Koto values to strings #[derive(Default)] @@ -88,8 +88,8 @@ pub enum StringBuilderAppend<'a> { Char(char), Str(&'a str), String(String), - ValueString(ValueString), - ValueStringRef(&'a ValueString), + KString(KString), + KStringRef(&'a KString), } impl From for StringBuilderAppend<'_> { @@ -110,15 +110,15 @@ impl From for StringBuilderAppend<'_> { } } -impl From for StringBuilderAppend<'_> { - fn from(value: ValueString) -> Self { - StringBuilderAppend::ValueString(value) +impl From for StringBuilderAppend<'_> { + fn from(value: KString) -> Self { + StringBuilderAppend::KString(value) } } -impl<'a> From<&'a ValueString> for StringBuilderAppend<'a> { - fn from(value: &'a ValueString) -> Self { - StringBuilderAppend::ValueStringRef(value) +impl<'a> From<&'a KString> for StringBuilderAppend<'a> { + fn from(value: &'a KString) -> Self { + StringBuilderAppend::KStringRef(value) } } @@ -128,8 +128,8 @@ impl<'a> StringBuilderAppend<'a> { StringBuilderAppend::Char(c) => string.push(c), StringBuilderAppend::Str(s) => string.push_str(s), StringBuilderAppend::String(s) => string.push_str(&s), - StringBuilderAppend::ValueString(s) => string.push_str(&s), - StringBuilderAppend::ValueStringRef(s) => string.push_str(s), + StringBuilderAppend::KString(s) => string.push_str(&s), + StringBuilderAppend::KStringRef(s) => string.push_str(s), } } } diff --git a/core/runtime/src/io/file.rs b/core/runtime/src/io/file.rs index ae242fa66..fb22dd44d 100644 --- a/core/runtime/src/io/file.rs +++ b/core/runtime/src/io/file.rs @@ -1,12 +1,12 @@ -use crate::{runtime_error, RuntimeError, ValueString}; +use crate::{runtime_error, KString, RuntimeError}; /// A trait used for file-like-things in Koto pub trait KotoFile: KotoRead + KotoWrite { /// An identifier for the file, accessed when displaying the file in strings - fn id(&self) -> ValueString; + fn id(&self) -> KString; /// Returns the path of the file - fn path(&self) -> Result { + fn path(&self) -> Result { runtime_error!("unsupported for this file type") } diff --git a/core/runtime/src/io/stdio.rs b/core/runtime/src/io/stdio.rs index 869515049..9271b381e 100644 --- a/core/runtime/src/io/stdio.rs +++ b/core/runtime/src/io/stdio.rs @@ -1,4 +1,4 @@ -use crate::{core_lib::io::map_io_err, KotoFile, KotoRead, KotoWrite, RuntimeError, ValueString}; +use crate::{core_lib::io::map_io_err, KString, KotoFile, KotoRead, KotoWrite, RuntimeError}; use std::io::{self, Read, Write}; /// The default stdin used in Koto @@ -6,7 +6,7 @@ use std::io::{self, Read, Write}; pub struct DefaultStdin {} impl KotoFile for DefaultStdin { - fn id(&self) -> ValueString { + fn id(&self) -> KString { STDIN_ID.with(|id| id.clone()) } } @@ -34,7 +34,7 @@ impl KotoRead for DefaultStdin { pub struct DefaultStdout {} impl KotoFile for DefaultStdout { - fn id(&self) -> ValueString { + fn id(&self) -> KString { STDOUT_ID.with(|id| id.clone()) } } @@ -62,7 +62,7 @@ impl KotoWrite for DefaultStdout { pub struct DefaultStderr {} impl KotoFile for DefaultStderr { - fn id(&self) -> ValueString { + fn id(&self) -> KString { STDERR_ID.with(|id| id.clone()) } } @@ -86,7 +86,7 @@ impl KotoWrite for DefaultStderr { } thread_local! { - static STDIN_ID: ValueString = "_stdin_".into(); - static STDOUT_ID: ValueString = "_stdout_".into(); - static STDERR_ID: ValueString = "_stderr_".into(); + static STDIN_ID: KString = "_stdin_".into(); + static STDOUT_ID: KString = "_stdout_".into(); + static STDERR_ID: KString = "_stderr_".into(); } diff --git a/core/runtime/src/lib.rs b/core/runtime/src/lib.rs index c488793b3..7741d4670 100644 --- a/core/runtime/src/lib.rs +++ b/core/runtime/src/lib.rs @@ -17,9 +17,9 @@ pub use crate::{ io::{BufferedFile, DefaultStderr, DefaultStdin, DefaultStdout, KotoFile, KotoRead, KotoWrite}, types::{ BinaryOp, CallContext, CaptureFunctionInfo, ExternalFunction, FunctionInfo, IntRange, - IsIterable, KIterator, KIteratorOutput, KList, KMap, KNumber, KotoHasher, KotoIterator, - KotoObject, KotoType, MetaKey, MetaMap, MethodContext, Object, ObjectEntryBuilder, UnaryOp, - Value, ValueKey, ValueMap, ValueString, ValueTuple, ValueVec, + IsIterable, KIterator, KIteratorOutput, KList, KMap, KNumber, KString, KotoHasher, + KotoIterator, KotoObject, KotoType, MetaKey, MetaMap, MethodContext, Object, + ObjectEntryBuilder, UnaryOp, Value, ValueKey, ValueMap, ValueTuple, ValueVec, }, vm::{CallArgs, ModuleImportedCallback, Vm, VmSettings}, }; diff --git a/core/runtime/src/prelude.rs b/core/runtime/src/prelude.rs index d31258746..fd91a5bd3 100644 --- a/core/runtime/src/prelude.rs +++ b/core/runtime/src/prelude.rs @@ -4,8 +4,7 @@ pub use crate::{ make_runtime_error, runtime_error, type_error, type_error_with_slice, BinaryOp, Borrow, BorrowMut, CallArgs, CallContext, DisplayContext, ExternalFunction, IntRange, IsIterable, - KIterator, KIteratorOutput, KList, KMap, KNumber, KotoFile, KotoHasher, KotoIterator, + KIterator, KIteratorOutput, KList, KMap, KNumber, KString, KotoFile, KotoHasher, KotoIterator, KotoObject, KotoRead, KotoType, KotoWrite, MetaKey, MetaMap, Object, ObjectEntryBuilder, Ptr, - PtrMut, RuntimeError, UnaryOp, Value, ValueKey, ValueMap, ValueString, ValueTuple, ValueVec, - Vm, VmSettings, + PtrMut, RuntimeError, UnaryOp, Value, ValueKey, ValueMap, ValueTuple, ValueVec, Vm, VmSettings, }; diff --git a/core/runtime/src/types/meta_map.rs b/core/runtime/src/types/meta_map.rs index 3692e7aa6..ffd34f69b 100644 --- a/core/runtime/src/types/meta_map.rs +++ b/core/runtime/src/types/meta_map.rs @@ -68,11 +68,11 @@ pub enum MetaKey { /// /// Named entries are used in [KMaps][crate::KMap], so that shared named items can be /// made available without them being inserted into the map's contents. - Named(ValueString), + Named(KString), /// A test function /// /// e.g. `@test my_test` - Test(ValueString), + Test(KString), /// `@tests` /// /// Tests are defined together in a [KMap](crate::KMap). @@ -91,7 +91,7 @@ pub enum MetaKey { Main, /// `@type` /// - /// Used to define a [ValueString](crate::ValueString) that declare the value's type. + /// Used to define a [KString](crate::KString) that declare the value's type. Type, /// `@base` /// @@ -105,8 +105,8 @@ impl From<&str> for MetaKey { } } -impl From for MetaKey { - fn from(name: ValueString) -> Self { +impl From for MetaKey { + fn from(name: KString) -> Self { Self::Named(name) } } @@ -214,7 +214,7 @@ pub enum UnaryOp { } /// Converts a [MetaKeyId](koto_parser::MetaKeyId) into a [MetaKey] -pub fn meta_id_to_key(id: MetaKeyId, name: Option) -> Result { +pub fn meta_id_to_key(id: MetaKeyId, name: Option) -> Result { use BinaryOp::*; use UnaryOp::*; @@ -271,7 +271,7 @@ impl Equivalent for str { } } -impl Equivalent for ValueString { +impl Equivalent for KString { fn equivalent(&self, other: &MetaKey) -> bool { match &other { MetaKey::Named(s) => self == s, diff --git a/core/runtime/src/types/mod.rs b/core/runtime/src/types/mod.rs index 7d337736e..b008c896e 100644 --- a/core/runtime/src/types/mod.rs +++ b/core/runtime/src/types/mod.rs @@ -24,6 +24,6 @@ pub use self::{ value_list::{KList, ValueVec}, value_map::{KMap, KotoHasher, ValueMap}, value_number::KNumber, - value_string::ValueString, + value_string::KString, value_tuple::ValueTuple, }; diff --git a/core/runtime/src/types/object.rs b/core/runtime/src/types/object.rs index ffa247991..8291c9f05 100644 --- a/core/runtime/src/types/object.rs +++ b/core/runtime/src/types/object.rs @@ -6,13 +6,13 @@ use std::{cell::RefCell, marker::PhantomData, rc::Rc}; /// /// See also: [Object]. pub trait KotoObject: Downcast { - /// The type of the Object as a [ValueString] + /// The type of the Object as a [KString] /// /// A typical pattern will be to implement [KotoType] for use with [ObjectEntryBuilder], /// and then defer to [KotoType::TYPE]. /// /// This will be called whenever the object's type is needed by the runtime, - /// e.g. when a script calls `koto.type`, so it can make sense to cache a [ValueString], + /// e.g. when a script calls `koto.type`, so it can make sense to cache a [KString], /// and then return clones of it to avoid creating lots of strings. /// /// ``` @@ -26,7 +26,7 @@ pub trait KotoObject: Downcast { /// } /// /// impl KotoObject for Foo { - /// fn object_type(&self) -> ValueString { + /// fn object_type(&self) -> KString { /// FOO_TYPE_STRING.with(|t| t.clone()) /// } /// @@ -36,10 +36,10 @@ pub trait KotoObject: Downcast { /// } /// /// thread_local! { - /// static FOO_TYPE_STRING: ValueString = Foo::TYPE.into(); + /// static FOO_TYPE_STRING: KString = Foo::TYPE.into(); /// } /// ``` - fn object_type(&self) -> ValueString; + fn object_type(&self) -> KString; /// How the object should behave when called from `koto.copy` /// @@ -293,7 +293,7 @@ pub trait KotoType { /// } /// /// impl KotoObject for Foo { -/// fn object_type(&self) -> ValueString { +/// fn object_type(&self) -> KString { /// FOO_TYPE_STRING.with(|t| t.clone()) /// } /// @@ -334,7 +334,7 @@ pub trait KotoType { /// } /// /// thread_local! { -/// static FOO_TYPE_STRING: ValueString = Foo::TYPE.into(); +/// static FOO_TYPE_STRING: KString = Foo::TYPE.into(); /// static FOO_ENTRIES: ValueMap = make_foo_entries(); /// } /// ``` @@ -449,7 +449,7 @@ impl<'a, T: KotoObject> MethodContext<'a, T> { } /// Creates an error that describes an unimplemented method -fn unimplemented_error(method: &str, object_type: ValueString) -> Result { +fn unimplemented_error(method: &str, object_type: KString) -> Result { runtime_error!("{method} is unimplemented for {object_type}") } diff --git a/core/runtime/src/types/value.rs b/core/runtime/src/types/value.rs index e683e6bb2..daa24ff03 100644 --- a/core/runtime/src/types/value.rs +++ b/core/runtime/src/types/value.rs @@ -30,7 +30,7 @@ pub enum Value { Map(KMap), /// The string type used in Koto - Str(ValueString), + Str(KString), /// A Koto function Function(FunctionInfo), @@ -163,8 +163,8 @@ impl Value { } } - /// Returns the value's type as a ValueString - pub fn type_as_string(&self) -> ValueString { + /// Returns the value's type as a [KString] + pub fn type_as_string(&self) -> KString { use Value::*; match &self { Null => TYPE_NULL.with(|x| x.clone()), @@ -241,21 +241,21 @@ impl Value { } thread_local! { - static TYPE_NULL: ValueString = "Null".into(); - static TYPE_BOOL: ValueString = "Bool".into(); - static TYPE_FLOAT: ValueString = "Float".into(); - static TYPE_INT: ValueString = "Int".into(); - static TYPE_LIST: ValueString = "List".into(); - static TYPE_RANGE: ValueString = "Range".into(); - static TYPE_MAP: ValueString = "Map".into(); - static TYPE_OBJECT: ValueString = "Object".into(); - static TYPE_STRING: ValueString = "String".into(); - static TYPE_TUPLE: ValueString = "Tuple".into(); - static TYPE_FUNCTION: ValueString = "Function".into(); - static TYPE_GENERATOR: ValueString = "Generator".into(); - static TYPE_EXTERNAL_FUNCTION: ValueString = "ExternalFunction".into(); - static TYPE_ITERATOR: ValueString = "Iterator".into(); - static TYPE_TEMPORARY_TUPLE: ValueString = "TemporaryTuple".into(); + static TYPE_NULL: KString = "Null".into(); + static TYPE_BOOL: KString = "Bool".into(); + static TYPE_FLOAT: KString = "Float".into(); + static TYPE_INT: KString = "Int".into(); + static TYPE_LIST: KString = "List".into(); + static TYPE_RANGE: KString = "Range".into(); + static TYPE_MAP: KString = "Map".into(); + static TYPE_OBJECT: KString = "Object".into(); + static TYPE_STRING: KString = "String".into(); + static TYPE_TUPLE: KString = "Tuple".into(); + static TYPE_FUNCTION: KString = "Function".into(); + static TYPE_GENERATOR: KString = "Generator".into(); + static TYPE_EXTERNAL_FUNCTION: KString = "ExternalFunction".into(); + static TYPE_ITERATOR: KString = "Iterator".into(); + static TYPE_TEMPORARY_TUPLE: KString = "TemporaryTuple".into(); } impl From<()> for Value { @@ -294,8 +294,8 @@ impl From for Value { } } -impl From for Value { - fn from(value: ValueString) -> Self { +impl From for Value { + fn from(value: KString) -> Self { Self::Str(value) } } diff --git a/core/runtime/src/types/value_iterator.rs b/core/runtime/src/types/value_iterator.rs index 3dc556285..ce7a997b0 100644 --- a/core/runtime/src/types/value_iterator.rs +++ b/core/runtime/src/types/value_iterator.rs @@ -113,7 +113,7 @@ impl KIterator { } /// Creates a new KIterator from a String - pub fn with_string(s: ValueString) -> Self { + pub fn with_string(s: KString) -> Self { Self::new(StringIterator::new(s)) } @@ -515,10 +515,10 @@ impl Iterator for ObjectIterator { /// An iterator that yields the characters contained in the string #[derive(Clone)] -pub struct StringIterator(ValueString); +pub struct StringIterator(KString); impl StringIterator { - pub fn new(s: ValueString) -> Self { + pub fn new(s: KString) -> Self { Self(s) } } diff --git a/core/runtime/src/types/value_key.rs b/core/runtime/src/types/value_key.rs index f9b40c581..932b3ff4f 100644 --- a/core/runtime/src/types/value_key.rs +++ b/core/runtime/src/types/value_key.rs @@ -127,8 +127,8 @@ impl fmt::Display for ValueKey { } } -impl From for ValueKey { - fn from(value: ValueString) -> Self { +impl From for ValueKey { + fn from(value: KString) -> Self { Self(Value::Str(value)) } } @@ -149,7 +149,7 @@ impl Equivalent for str { } } -impl Equivalent for ValueString { +impl Equivalent for KString { fn equivalent(&self, other: &ValueKey) -> bool { match &other.0 { Value::Str(s) => self == s, diff --git a/core/runtime/src/types/value_string.rs b/core/runtime/src/types/value_string.rs index 30ec6fa28..a77086a27 100644 --- a/core/runtime/src/types/value_string.rs +++ b/core/runtime/src/types/value_string.rs @@ -14,11 +14,11 @@ use unicode_segmentation::UnicodeSegmentation; /// [`AsRef`](std::convert::AsRef) is implemented for &str, which automatically resolves to the /// correct slice of the string data. #[derive(Clone)] -pub struct ValueString(Inner); +pub struct KString(Inner); // Either the full string, or a slice // -// By heap-allocating slice bounds we can keep ValueString's size down to 16 bytes; otherwise it +// By heap-allocating slice bounds we can keep KString's size down to 16 bytes; otherwise it // would have a size of 32 bytes. #[derive(Clone)] enum Inner { @@ -32,15 +32,15 @@ pub struct StringSlice { bounds: Range, } -impl ValueString { +impl KString { /// Returns the empty string /// - /// This returns a clone of an empty ValueString which is initialized once per thread. + /// This returns a clone of an empty KString which is initialized once per thread. pub fn empty() -> Self { Self::from(EMPTY_STRING.with(|s| s.clone())) } - /// Initializes a new ValueString with the provided data and bounds + /// Initializes a new KString with the provided data and bounds /// /// If the bounds aren't valid for the data then `None` is returned. pub fn new_with_bounds(string: Ptr, bounds: Range) -> Option { @@ -51,7 +51,7 @@ impl ValueString { } } - /// Returns a new ValueString with shared data and new bounds + /// Returns a new KString with shared data and new bounds /// /// If the bounds aren't valid for the string then `None` is returned. pub fn with_bounds(&self, mut new_bounds: Range) -> Option { @@ -76,7 +76,7 @@ impl ValueString { } } - /// Returns a new ValueString with shared data and bounds defined by the grapheme indices + /// Returns a new KString with shared data and bounds defined by the grapheme indices /// /// This allows for subslicing by index, with the index referring to unicode graphemes. /// @@ -161,12 +161,12 @@ impl ValueString { } } - /// Returns the number of graphemes contained within the ValueString's bounds + /// Returns the number of graphemes contained within the KString's bounds pub fn grapheme_count(&self) -> usize { self.graphemes(true).count() } - /// Returns the `&str` within the ValueString's bounds + /// Returns the `&str` within the KString's bounds pub fn as_str(&self) -> &str { match &self.0 { Inner::Full(string) => string, @@ -206,26 +206,26 @@ impl StringSlice { } } -impl PartialEq<&str> for ValueString { +impl PartialEq<&str> for KString { fn eq(&self, other: &&str) -> bool { self.as_str() == *other } } -impl PartialEq for ValueString { +impl PartialEq for KString { fn eq(&self, other: &Self) -> bool { self.as_str() == other.as_str() } } -impl Eq for ValueString {} +impl Eq for KString {} -impl Hash for ValueString { +impl Hash for KString { fn hash(&self, state: &mut H) { self.as_str().hash(state) } } -impl Deref for ValueString { +impl Deref for KString { type Target = str; fn deref(&self) -> &str { @@ -233,43 +233,43 @@ impl Deref for ValueString { } } -impl AsRef for ValueString { +impl AsRef for KString { fn as_ref(&self) -> &str { self.as_str() } } -impl From> for ValueString { +impl From> for KString { fn from(string: Ptr) -> Self { Self(Inner::Full(string)) } } -impl From for ValueString { +impl From for KString { fn from(slice: StringSlice) -> Self { Self(Inner::Slice(slice.into())) } } -impl From for ValueString { +impl From for KString { fn from(s: String) -> Self { Self::from(Ptr::::from(s.into_boxed_str())) } } -impl From<&str> for ValueString { +impl From<&str> for KString { fn from(s: &str) -> Self { Self::from(Ptr::::from(s)) } } -impl fmt::Display for ValueString { +impl fmt::Display for KString { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) } } -impl fmt::Debug for ValueString { +impl fmt::Debug for KString { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) } diff --git a/core/runtime/src/vm.rs b/core/runtime/src/vm.rs index bc62fdfce..7ae59f3e8 100644 --- a/core/runtime/src/vm.rs +++ b/core/runtime/src/vm.rs @@ -2293,7 +2293,7 @@ impl Vm { &mut self, result_register: u8, value_register: u8, - key_string: ValueString, + key_string: KString, ) -> Result<()> { use Value::*; @@ -2915,11 +2915,11 @@ impl Vm { self.reader.chunk.constants.get_str(constant_index) } - fn value_string_from_constant(&self, constant_index: ConstantIndex) -> ValueString { + fn value_string_from_constant(&self, constant_index: ConstantIndex) -> KString { let constants = &self.reader.chunk.constants; let bounds = constants.get_str_bounds(constant_index); - ValueString::new_with_bounds(constants.string_data().clone(), bounds) + KString::new_with_bounds(constants.string_data().clone(), bounds) // The bounds have been already checked in the constant pool .unwrap() } diff --git a/core/runtime/tests/object_tests.rs b/core/runtime/tests/object_tests.rs index c1264e9a9..af8e79064 100644 --- a/core/runtime/tests/object_tests.rs +++ b/core/runtime/tests/object_tests.rs @@ -84,7 +84,7 @@ mod objects { } impl KotoObject for TestObject { - fn object_type(&self) -> ValueString { + fn object_type(&self) -> KString { TEST_OBJECT_TYPE_STRING.with(|s| s.clone()) } @@ -223,7 +223,7 @@ mod objects { } thread_local! { - static TEST_OBJECT_TYPE_STRING: ValueString = TestObject::TYPE.into(); + static TEST_OBJECT_TYPE_STRING: KString = TestObject::TYPE.into(); static TEST_OBJECT_ENTRIES: ValueMap = test_object_entries(); } @@ -243,7 +243,7 @@ mod objects { } impl KotoObject for TestIterator { - fn object_type(&self) -> ValueString { + fn object_type(&self) -> KString { TEST_ITERATOR_TYPE_STRING.with(|s| s.clone()) } @@ -267,7 +267,7 @@ mod objects { } thread_local! { - static TEST_ITERATOR_TYPE_STRING: ValueString = TestIterator::TYPE.into(); + static TEST_ITERATOR_TYPE_STRING: KString = TestIterator::TYPE.into(); } fn test_object_script(script: &str, expected_output: impl Into) { diff --git a/core/runtime/tests/runtime_test_utils.rs b/core/runtime/tests/runtime_test_utils.rs index 167ebf39c..1b9d729b6 100644 --- a/core/runtime/tests/runtime_test_utils.rs +++ b/core/runtime/tests/runtime_test_utils.rs @@ -129,7 +129,7 @@ pub struct TestStdout { } impl KotoFile for TestStdout { - fn id(&self) -> ValueString { + fn id(&self) -> KString { "_teststdout_".into() } } diff --git a/examples/poetry/src/koto_bindings.rs b/examples/poetry/src/koto_bindings.rs index 18ea60157..1ba6e9376 100644 --- a/examples/poetry/src/koto_bindings.rs +++ b/examples/poetry/src/koto_bindings.rs @@ -23,7 +23,7 @@ impl KotoType for Poetry { } impl KotoObject for Poetry { - fn object_type(&self) -> ValueString { + fn object_type(&self) -> KString { Self::TYPE.into() } diff --git a/examples/wasm/src/lib.rs b/examples/wasm/src/lib.rs index 51ef07182..b59ad318c 100644 --- a/examples/wasm/src/lib.rs +++ b/examples/wasm/src/lib.rs @@ -8,7 +8,7 @@ struct OutputCapture { } impl KotoFile for OutputCapture { - fn id(&self) -> ValueString { + fn id(&self) -> KString { "_stdout_".into() } } @@ -39,7 +39,7 @@ impl KotoWrite for OutputCapture { struct BlockedInput {} impl KotoFile for BlockedInput { - fn id(&self) -> ValueString { + fn id(&self) -> KString { "_stdin_".into() } } diff --git a/libs/color/src/color.rs b/libs/color/src/color.rs index 6f6cc122a..ae844f616 100644 --- a/libs/color/src/color.rs +++ b/libs/color/src/color.rs @@ -166,7 +166,7 @@ impl KotoType for Color { } impl KotoObject for Color { - fn object_type(&self) -> ValueString { + fn object_type(&self) -> KString { COLOR_TYPE_STRING.with(|s| s.clone()) } @@ -314,7 +314,7 @@ fn make_color_entries() -> ValueMap { } thread_local! { - static COLOR_TYPE_STRING: ValueString = Color::TYPE.into(); + static COLOR_TYPE_STRING: KString = Color::TYPE.into(); static COLOR_ENTRIES: ValueMap = make_color_entries(); } diff --git a/libs/geometry/src/rect.rs b/libs/geometry/src/rect.rs index ce074e518..323cd54e5 100644 --- a/libs/geometry/src/rect.rs +++ b/libs/geometry/src/rect.rs @@ -18,7 +18,7 @@ impl KotoType for Rect { } impl KotoObject for Rect { - fn object_type(&self) -> ValueString { + fn object_type(&self) -> KString { RECT_TYPE_STRING.with(|s| s.clone()) } @@ -103,7 +103,7 @@ fn make_rect_entries() -> ValueMap { } thread_local! { - static RECT_TYPE_STRING: ValueString = Rect::TYPE.into(); + static RECT_TYPE_STRING: KString = Rect::TYPE.into(); static RECT_ENTRIES: ValueMap = make_rect_entries(); } diff --git a/libs/geometry/src/vec2.rs b/libs/geometry/src/vec2.rs index 0912edec2..3061f85b9 100644 --- a/libs/geometry/src/vec2.rs +++ b/libs/geometry/src/vec2.rs @@ -24,7 +24,7 @@ impl KotoType for Vec2 { } impl KotoObject for Vec2 { - fn object_type(&self) -> ValueString { + fn object_type(&self) -> KString { VEC2_TYPE_STRING.with(|s| s.clone()) } @@ -128,7 +128,7 @@ fn make_vec2_entries() -> ValueMap { } thread_local! { - static VEC2_TYPE_STRING: ValueString = Vec2::TYPE.into(); + static VEC2_TYPE_STRING: KString = Vec2::TYPE.into(); static VEC2_ENTRIES: ValueMap = make_vec2_entries(); } diff --git a/libs/geometry/src/vec3.rs b/libs/geometry/src/vec3.rs index abfc4e50a..ae978f7f8 100644 --- a/libs/geometry/src/vec3.rs +++ b/libs/geometry/src/vec3.rs @@ -19,7 +19,7 @@ impl KotoType for Vec3 { } impl KotoObject for Vec3 { - fn object_type(&self) -> ValueString { + fn object_type(&self) -> KString { VEC3_TYPE_STRING.with(|s| s.clone()) } @@ -126,7 +126,7 @@ fn make_vec3_entries() -> ValueMap { } thread_local! { - static VEC3_TYPE_STRING: ValueString = Vec3::TYPE.into(); + static VEC3_TYPE_STRING: KString = Vec3::TYPE.into(); static VEC3_ENTRIES: ValueMap = make_vec3_entries(); } diff --git a/libs/random/src/lib.rs b/libs/random/src/lib.rs index 285e6a291..741977adf 100644 --- a/libs/random/src/lib.rs +++ b/libs/random/src/lib.rs @@ -104,7 +104,7 @@ impl KotoType for ChaChaRng { } impl KotoObject for ChaChaRng { - fn object_type(&self) -> ValueString { + fn object_type(&self) -> KString { RNG_TYPE_STRING.with(|s| s.clone()) } @@ -128,6 +128,6 @@ fn rng_entries() -> ValueMap { thread_local! { static THREAD_RNG: RefCell = RefCell::new(ChaChaRng(ChaCha8Rng::from_entropy())); - static RNG_TYPE_STRING: ValueString = ChaChaRng::TYPE.into(); + static RNG_TYPE_STRING: KString = ChaChaRng::TYPE.into(); static RNG_ENTRIES: ValueMap = rng_entries(); } From 73e97a63f222cdc48477c0971f27e9856b9dc044 Mon Sep 17 00:00:00 2001 From: Ian Hobson Date: Wed, 11 Oct 2023 11:28:48 +0200 Subject: [PATCH 06/13] Rename ValueTuple -> KTuple --- core/runtime/src/core_lib/iterator/adaptors.rs | 4 ++-- core/runtime/src/core_lib/koto.rs | 2 +- core/runtime/src/lib.rs | 4 ++-- core/runtime/src/prelude.rs | 7 ++++--- core/runtime/src/types/mod.rs | 2 +- core/runtime/src/types/value.rs | 6 +++--- core/runtime/src/types/value_iterator.rs | 6 +++--- core/runtime/src/types/value_tuple.rs | 16 ++++++++-------- core/runtime/src/vm.rs | 7 +++---- core/runtime/tests/vm_tests.rs | 2 +- libs/random/src/lib.rs | 2 +- 11 files changed, 29 insertions(+), 29 deletions(-) diff --git a/core/runtime/src/core_lib/iterator/adaptors.rs b/core/runtime/src/core_lib/iterator/adaptors.rs index 519632963..baa1bd4d6 100644 --- a/core/runtime/src/core_lib/iterator/adaptors.rs +++ b/core/runtime/src/core_lib/iterator/adaptors.rs @@ -111,7 +111,7 @@ impl Iterator for Chunks { } } - chunk.map(|chunk| ValueTuple::from(chunk).into()) + chunk.map(|chunk| KTuple::from(chunk).into()) } fn size_hint(&self) -> (usize, Option) { @@ -832,7 +832,7 @@ impl Iterator for Windows { if self.cache.len() == self.window_size { let result: Vec<_> = self.cache.iter().cloned().collect(); - Some(ValueTuple::from(result).into()) + Some(KTuple::from(result).into()) } else { None } diff --git a/core/runtime/src/core_lib/koto.rs b/core/runtime/src/core_lib/koto.rs index 167e967ea..9d408ccae 100644 --- a/core/runtime/src/core_lib/koto.rs +++ b/core/runtime/src/core_lib/koto.rs @@ -7,7 +7,7 @@ use std::hash::{Hash, Hasher}; pub fn make_module() -> KMap { let result = KMap::with_type("core.koto"); - result.add_value("args", Value::Tuple(ValueTuple::default())); + result.add_value("args", Value::Tuple(KTuple::default())); result.add_fn("copy", |ctx| match ctx.args() { [Value::Iterator(iter)] => Ok(iter.make_copy()?.into()), diff --git a/core/runtime/src/lib.rs b/core/runtime/src/lib.rs index 7741d4670..feb872592 100644 --- a/core/runtime/src/lib.rs +++ b/core/runtime/src/lib.rs @@ -17,9 +17,9 @@ pub use crate::{ io::{BufferedFile, DefaultStderr, DefaultStdin, DefaultStdout, KotoFile, KotoRead, KotoWrite}, types::{ BinaryOp, CallContext, CaptureFunctionInfo, ExternalFunction, FunctionInfo, IntRange, - IsIterable, KIterator, KIteratorOutput, KList, KMap, KNumber, KString, KotoHasher, + IsIterable, KIterator, KIteratorOutput, KList, KMap, KNumber, KString, KTuple, KotoHasher, KotoIterator, KotoObject, KotoType, MetaKey, MetaMap, MethodContext, Object, - ObjectEntryBuilder, UnaryOp, Value, ValueKey, ValueMap, ValueTuple, ValueVec, + ObjectEntryBuilder, UnaryOp, Value, ValueKey, ValueMap, ValueVec, }, vm::{CallArgs, ModuleImportedCallback, Vm, VmSettings}, }; diff --git a/core/runtime/src/prelude.rs b/core/runtime/src/prelude.rs index fd91a5bd3..28a411ded 100644 --- a/core/runtime/src/prelude.rs +++ b/core/runtime/src/prelude.rs @@ -4,7 +4,8 @@ pub use crate::{ make_runtime_error, runtime_error, type_error, type_error_with_slice, BinaryOp, Borrow, BorrowMut, CallArgs, CallContext, DisplayContext, ExternalFunction, IntRange, IsIterable, - KIterator, KIteratorOutput, KList, KMap, KNumber, KString, KotoFile, KotoHasher, KotoIterator, - KotoObject, KotoRead, KotoType, KotoWrite, MetaKey, MetaMap, Object, ObjectEntryBuilder, Ptr, - PtrMut, RuntimeError, UnaryOp, Value, ValueKey, ValueMap, ValueTuple, ValueVec, Vm, VmSettings, + KIterator, KIteratorOutput, KList, KMap, KNumber, KString, KTuple, KotoFile, KotoHasher, + KotoIterator, KotoObject, KotoRead, KotoType, KotoWrite, MetaKey, MetaMap, Object, + ObjectEntryBuilder, Ptr, PtrMut, RuntimeError, UnaryOp, Value, ValueKey, ValueMap, ValueVec, + Vm, VmSettings, }; diff --git a/core/runtime/src/types/mod.rs b/core/runtime/src/types/mod.rs index b008c896e..c77243e6a 100644 --- a/core/runtime/src/types/mod.rs +++ b/core/runtime/src/types/mod.rs @@ -25,5 +25,5 @@ pub use self::{ value_map::{KMap, KotoHasher, ValueMap}, value_number::KNumber, value_string::KString, - value_tuple::ValueTuple, + value_tuple::KTuple, }; diff --git a/core/runtime/src/types/value.rs b/core/runtime/src/types/value.rs index daa24ff03..d85720284 100644 --- a/core/runtime/src/types/value.rs +++ b/core/runtime/src/types/value.rs @@ -24,7 +24,7 @@ pub enum Value { List(KList), /// The tuple type used in Koto - Tuple(ValueTuple), + Tuple(KTuple), /// The hash map type used in Koto Map(KMap), @@ -306,8 +306,8 @@ impl From for Value { } } -impl From for Value { - fn from(value: ValueTuple) -> Self { +impl From for Value { + fn from(value: KTuple) -> Self { Self::Tuple(value) } } diff --git a/core/runtime/src/types/value_iterator.rs b/core/runtime/src/types/value_iterator.rs index ce7a997b0..7485a9561 100644 --- a/core/runtime/src/types/value_iterator.rs +++ b/core/runtime/src/types/value_iterator.rs @@ -103,7 +103,7 @@ impl KIterator { } /// Creates a new KIterator from a Tuple - pub fn with_tuple(tuple: ValueTuple) -> Self { + pub fn with_tuple(tuple: KTuple) -> Self { Self::new(TupleIterator::new(tuple)) } @@ -298,10 +298,10 @@ impl Iterator for ListIterator { } #[derive(Clone)] -struct TupleIterator(ValueTuple); +struct TupleIterator(KTuple); impl TupleIterator { - fn new(tuple: ValueTuple) -> Self { + fn new(tuple: KTuple) -> Self { Self(tuple) } } diff --git a/core/runtime/src/types/value_tuple.rs b/core/runtime/src/types/value_tuple.rs index 87ebd8199..079b7d16f 100644 --- a/core/runtime/src/types/value_tuple.rs +++ b/core/runtime/src/types/value_tuple.rs @@ -3,11 +3,11 @@ use std::ops::{Deref, Range}; /// The Tuple type used by the Koto runtime #[derive(Clone)] -pub struct ValueTuple(Inner); +pub struct KTuple(Inner); // Either the full tuple, or a slice // -// By heap-allocating slice bounds we can keep ValueTuple's size down to 16 bytes; otherwise it +// By heap-allocating slice bounds we can keep KTuple's size down to 16 bytes; otherwise it // would have a size of 32 bytes. #[derive(Clone)] enum Inner { @@ -21,7 +21,7 @@ struct TupleSlice { bounds: Range, } -impl ValueTuple { +impl KTuple { /// Returns a new tuple with shared data and with restricted bounds /// /// The provided bounds should have indices relative to the current tuple's bounds @@ -131,7 +131,7 @@ impl ValueTuple { } } -impl Deref for ValueTuple { +impl Deref for KTuple { type Target = [Value]; fn deref(&self) -> &[Value] { @@ -142,19 +142,19 @@ impl Deref for ValueTuple { } } -impl Default for ValueTuple { +impl Default for KTuple { fn default() -> Self { Vec::new().into() } } -impl From<&[Value]> for ValueTuple { +impl From<&[Value]> for KTuple { fn from(data: &[Value]) -> Self { Self(Inner::Full(data.into())) } } -impl From> for ValueTuple { +impl From> for KTuple { fn from(data: Vec) -> Self { Self(Inner::Full(data.into())) } @@ -176,7 +176,7 @@ impl From> for TupleSlice { } } -impl From for ValueTuple { +impl From for KTuple { fn from(slice: TupleSlice) -> Self { Self(Inner::Slice(slice.into())) } diff --git a/core/runtime/src/vm.rs b/core/runtime/src/vm.rs index 7ae59f3e8..b21041c09 100644 --- a/core/runtime/src/vm.rs +++ b/core/runtime/src/vm.rs @@ -967,9 +967,8 @@ impl Vm { fn run_temp_tuple_to_tuple(&mut self, register: u8, source_register: u8) -> Result<()> { match self.clone_register(source_register) { Value::TemporaryTuple(temp_registers) => { - let tuple = ValueTuple::from( - self.register_slice(temp_registers.start, temp_registers.count), - ); + let tuple = + KTuple::from(self.register_slice(temp_registers.start, temp_registers.count)); self.set_register(register, Value::Tuple(tuple)); } _ => unreachable!(), @@ -2728,7 +2727,7 @@ impl Vm { fn run_sequence_to_tuple(&mut self, register: u8) -> Result<()> { if let Some(result) = self.sequence_builders.pop() { - self.set_register(register, ValueTuple::from(result).into()); + self.set_register(register, KTuple::from(result).into()); Ok(()) } else { runtime_error!("Missing a sequence buider") diff --git a/core/runtime/tests/vm_tests.rs b/core/runtime/tests/vm_tests.rs index ace2bcf33..cf86c2084 100644 --- a/core/runtime/tests/vm_tests.rs +++ b/core/runtime/tests/vm_tests.rs @@ -205,7 +205,7 @@ a %= 5 #[test] fn empty() { - test_script("(,)", Value::Tuple(ValueTuple::default())); + test_script("(,)", Value::Tuple(KTuple::default())); } #[test] diff --git a/libs/random/src/lib.rs b/libs/random/src/lib.rs index 741977adf..1165eab9e 100644 --- a/libs/random/src/lib.rs +++ b/libs/random/src/lib.rs @@ -70,7 +70,7 @@ impl ChaChaRng { match m.data().get_index(index) { Some((key, value)) => { let data = vec![key.value().clone(), value.clone()]; - Ok(Tuple(ValueTuple::from(data))) + Ok(Tuple(KTuple::from(data))) } None => unreachable!(), // The index is guaranteed to be within range } From 1e31887e8058bc2d162710727b0bd13ed33db03d Mon Sep 17 00:00:00 2001 From: Ian Hobson Date: Wed, 11 Oct 2023 11:35:38 +0200 Subject: [PATCH 07/13] Rename IntRange -> KRange --- core/runtime/src/core_lib/range.rs | 12 +++--- core/runtime/src/lib.rs | 4 +- core/runtime/src/prelude.rs | 4 +- core/runtime/src/types/int_range.rs | 52 ++++++++++++------------ core/runtime/src/types/mod.rs | 2 +- core/runtime/src/types/value.rs | 6 +-- core/runtime/src/types/value_iterator.rs | 6 +-- core/runtime/src/vm.rs | 8 ++-- core/runtime/tests/vm_tests.rs | 12 +++--- 9 files changed, 53 insertions(+), 53 deletions(-) diff --git a/core/runtime/src/core_lib/range.rs b/core/runtime/src/core_lib/range.rs index dbc2c3ce5..c359b40d9 100644 --- a/core/runtime/src/core_lib/range.rs +++ b/core/runtime/src/core_lib/range.rs @@ -40,9 +40,9 @@ pub fn make_module() -> KMap { (Some(start), Some((end, inclusive))) => { let n = i64::from(n); let result = if r.is_ascending() { - IntRange::bounded(start - n, end + n, inclusive) + KRange::bounded(start - n, end + n, inclusive) } else { - IntRange::bounded(start + n, end - n, inclusive) + KRange::bounded(start + n, end - n, inclusive) }; Ok(result.into()) } @@ -104,9 +104,9 @@ pub fn make_module() -> KMap { match (r.start(), r.end()) { (Some(start), Some((end, inclusive))) => { let result = if start <= end { - IntRange::bounded(start.min(n), end.max(n + 1), inclusive) + KRange::bounded(start.min(n), end.max(n + 1), inclusive) } else { - IntRange::bounded(start.max(n), end.min(n - 1), inclusive) + KRange::bounded(start.max(n), end.min(n - 1), inclusive) }; Ok(result.into()) } @@ -117,9 +117,9 @@ pub fn make_module() -> KMap { (Some(start), Some((end, inclusive))) => { let r_b = b.as_sorted_range(); let result = if start <= end { - IntRange::bounded(start.min(r_b.start), end.max(r_b.end), inclusive) + KRange::bounded(start.min(r_b.start), end.max(r_b.end), inclusive) } else { - IntRange::bounded(start.max(r_b.end - 1), end.min(r_b.start), inclusive) + KRange::bounded(start.max(r_b.end - 1), end.min(r_b.start), inclusive) }; Ok(result.into()) } diff --git a/core/runtime/src/lib.rs b/core/runtime/src/lib.rs index feb872592..f1a50009f 100644 --- a/core/runtime/src/lib.rs +++ b/core/runtime/src/lib.rs @@ -16,8 +16,8 @@ pub use crate::{ error::{type_error, type_error_with_slice, Result, RuntimeError}, io::{BufferedFile, DefaultStderr, DefaultStdin, DefaultStdout, KotoFile, KotoRead, KotoWrite}, types::{ - BinaryOp, CallContext, CaptureFunctionInfo, ExternalFunction, FunctionInfo, IntRange, - IsIterable, KIterator, KIteratorOutput, KList, KMap, KNumber, KString, KTuple, KotoHasher, + BinaryOp, CallContext, CaptureFunctionInfo, ExternalFunction, FunctionInfo, IsIterable, + KIterator, KIteratorOutput, KList, KMap, KNumber, KRange, KString, KTuple, KotoHasher, KotoIterator, KotoObject, KotoType, MetaKey, MetaMap, MethodContext, Object, ObjectEntryBuilder, UnaryOp, Value, ValueKey, ValueMap, ValueVec, }, diff --git a/core/runtime/src/prelude.rs b/core/runtime/src/prelude.rs index 28a411ded..de479858e 100644 --- a/core/runtime/src/prelude.rs +++ b/core/runtime/src/prelude.rs @@ -3,8 +3,8 @@ #[doc(inline)] pub use crate::{ make_runtime_error, runtime_error, type_error, type_error_with_slice, BinaryOp, Borrow, - BorrowMut, CallArgs, CallContext, DisplayContext, ExternalFunction, IntRange, IsIterable, - KIterator, KIteratorOutput, KList, KMap, KNumber, KString, KTuple, KotoFile, KotoHasher, + BorrowMut, CallArgs, CallContext, DisplayContext, ExternalFunction, IsIterable, KIterator, + KIteratorOutput, KList, KMap, KNumber, KRange, KString, KTuple, KotoFile, KotoHasher, KotoIterator, KotoObject, KotoRead, KotoType, KotoWrite, MetaKey, MetaMap, Object, ObjectEntryBuilder, Ptr, PtrMut, RuntimeError, UnaryOp, Value, ValueKey, ValueMap, ValueVec, Vm, VmSettings, diff --git a/core/runtime/src/types/int_range.rs b/core/runtime/src/types/int_range.rs index ae7b309b8..6c60e471e 100644 --- a/core/runtime/src/types/int_range.rs +++ b/core/runtime/src/types/int_range.rs @@ -5,7 +5,7 @@ use std::{cmp::Ordering, fmt, hash::Hash, ops::Range}; /// /// See [Value::Range] #[derive(Clone, Debug, Hash, PartialEq, Eq)] -pub struct IntRange(Inner); +pub struct KRange(Inner); #[derive(Clone, Debug, Hash, PartialEq, Eq)] enum Inner { @@ -22,7 +22,7 @@ enum Inner { end: i32, inclusive: bool, }, - // Placing ranges with i64 bounds to the heap allows the size of IntRange to be 16 bytes + // Placing ranges with i64 bounds to the heap allows the size of KRange to be 16 bytes BoundedLarge(Ptr), } @@ -39,7 +39,7 @@ impl From for Inner { } } -impl IntRange { +impl KRange { /// Initializes a From range pub fn from(start: i64) -> Self { Self(Inner::From { start }) @@ -100,7 +100,7 @@ impl IntRange { /// Returns a sorted translation of the range with missing boundaries replaced by min/max values /// - /// No clamping of the range boundaries is performed (as in [IntRange::indices]), + /// No clamping of the range boundaries is performed (as in [KRange::indices]), /// so negative indices will be preserved. pub fn as_sorted_range(&self) -> Range { use std::i64::{MAX, MIN}; @@ -153,7 +153,7 @@ impl IntRange { } /// Returns the intersection of two ranges - pub fn intersection(&self, other: &IntRange) -> Option { + pub fn intersection(&self, other: &KRange) -> Option { let this = self.as_sorted_range(); // let mut result = Self::with_bounds(start, end, inclusive); let other = other.as_sorted_range(); @@ -257,7 +257,7 @@ impl IntRange { } } } - _ => return runtime_error!("IntRange::pop_front can only be used with bounded ranges"), + _ => return runtime_error!("KRange::pop_front can only be used with bounded ranges"), }; Ok(result) @@ -322,14 +322,14 @@ impl IntRange { } } } - _ => return runtime_error!("IntRange::pop_back can only be used with bounded ranges"), + _ => return runtime_error!("KRange::pop_back can only be used with bounded ranges"), }; Ok(result) } } -impl fmt::Display for IntRange { +impl fmt::Display for KRange { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(start) = self.start() { write!(f, "{start}")?; @@ -354,53 +354,53 @@ mod tests { #[test] fn size_of() { - assert_eq!(std::mem::size_of::(), 16); + assert_eq!(std::mem::size_of::(), 16); } #[test] fn as_sorted_range() { use std::i64::{MAX, MIN}; - assert_eq!(10..20, IntRange::bounded(10, 20, false).as_sorted_range()); - assert_eq!(10..21, IntRange::bounded(10, 20, true).as_sorted_range()); - assert_eq!(11..21, IntRange::bounded(20, 10, false).as_sorted_range()); - assert_eq!(10..21, IntRange::bounded(20, 10, true).as_sorted_range()); + assert_eq!(10..20, KRange::bounded(10, 20, false).as_sorted_range()); + assert_eq!(10..21, KRange::bounded(10, 20, true).as_sorted_range()); + assert_eq!(11..21, KRange::bounded(20, 10, false).as_sorted_range()); + assert_eq!(10..21, KRange::bounded(20, 10, true).as_sorted_range()); - assert_eq!(10..MAX, IntRange::from(10).as_sorted_range(),); - assert_eq!(MIN..10, IntRange::to(10, false).as_sorted_range(),); + assert_eq!(10..MAX, KRange::from(10).as_sorted_range(),); + assert_eq!(MIN..10, KRange::to(10, false).as_sorted_range(),); } #[test] fn intersection() { assert_eq!( - Some(IntRange::bounded(15, 20, false)), - IntRange::bounded(10, 20, false).intersection(&IntRange::bounded(15, 25, false)) + Some(KRange::bounded(15, 20, false)), + KRange::bounded(10, 20, false).intersection(&KRange::bounded(15, 25, false)) ); assert_eq!( - Some(IntRange::bounded(200, 201, false)), - IntRange::bounded(100, 200, true).intersection(&IntRange::bounded(300, 200, true)) + Some(KRange::bounded(200, 201, false)), + KRange::bounded(100, 200, true).intersection(&KRange::bounded(300, 200, true)) ); assert_eq!( None, - IntRange::bounded(100, 200, false).intersection(&IntRange::bounded(0, 50, false)) + KRange::bounded(100, 200, false).intersection(&KRange::bounded(0, 50, false)) ); } #[test] fn is_ascending() { - assert!(IntRange::bounded(10, 20, false).is_ascending()); - assert!(!IntRange::bounded(30, 20, false).is_ascending()); - assert!(IntRange::to(1, true).is_ascending()); - assert!(IntRange::from(20).is_ascending()); + assert!(KRange::bounded(10, 20, false).is_ascending()); + assert!(!KRange::bounded(30, 20, false).is_ascending()); + assert!(KRange::to(1, true).is_ascending()); + assert!(KRange::from(20).is_ascending()); } #[test] fn bounded_large() { let start_big = 2_i64.pow(42); let end_big = 2_i64.pow(43); - assert!(IntRange::bounded(start_big, end_big, false).is_ascending()); + assert!(KRange::bounded(start_big, end_big, false).is_ascending()); assert_eq!( - IntRange::bounded(start_big, end_big, false).size().unwrap(), + KRange::bounded(start_big, end_big, false).size().unwrap(), (end_big - start_big) as usize ); } diff --git a/core/runtime/src/types/mod.rs b/core/runtime/src/types/mod.rs index c77243e6a..1afb9d6ea 100644 --- a/core/runtime/src/types/mod.rs +++ b/core/runtime/src/types/mod.rs @@ -15,7 +15,7 @@ mod value_tuple; pub use self::{ external_function::{CallContext, ExternalFunction}, - int_range::IntRange, + int_range::KRange, meta_map::{meta_id_to_key, BinaryOp, MetaKey, MetaMap, UnaryOp}, object::{IsIterable, KotoObject, KotoType, MethodContext, Object, ObjectEntryBuilder}, value::{CaptureFunctionInfo, FunctionInfo, Value}, diff --git a/core/runtime/src/types/value.rs b/core/runtime/src/types/value.rs index d85720284..9b014a33c 100644 --- a/core/runtime/src/types/value.rs +++ b/core/runtime/src/types/value.rs @@ -18,7 +18,7 @@ pub enum Value { Number(KNumber), /// A range with start/end boundaries - Range(IntRange), + Range(KRange), /// The list type used in Koto List(KList), @@ -276,8 +276,8 @@ impl From for Value { } } -impl From for Value { - fn from(value: IntRange) -> Self { +impl From for Value { + fn from(value: KRange) -> Self { Self::Range(value) } } diff --git a/core/runtime/src/types/value_iterator.rs b/core/runtime/src/types/value_iterator.rs index 7485a9561..d285cd4fd 100644 --- a/core/runtime/src/types/value_iterator.rs +++ b/core/runtime/src/types/value_iterator.rs @@ -93,7 +93,7 @@ impl KIterator { } /// Creates a new KIterator from a Range - pub fn with_range(range: IntRange) -> Result { + pub fn with_range(range: KRange) -> Result { Ok(Self::new(RangeIterator::new(range)?)) } @@ -185,11 +185,11 @@ type Output = KIteratorOutput; #[derive(Clone)] struct RangeIterator { - range: IntRange, + range: KRange, } impl RangeIterator { - fn new(range: IntRange) -> Result { + fn new(range: KRange) -> Result { if range.is_bounded() { Ok(Self { range }) } else { diff --git a/core/runtime/src/vm.rs b/core/runtime/src/vm.rs index b21041c09..4f1efb2ef 100644 --- a/core/runtime/src/vm.rs +++ b/core/runtime/src/vm.rs @@ -990,13 +990,13 @@ impl Vm { let range = match (start, end) { (Some(Number(start)), Some(Number(end))) => { - IntRange::bounded(start.into(), end.into(), inclusive) + KRange::bounded(start.into(), end.into(), inclusive) } - (Some(Number(start)), None) => IntRange::from(start.into()), - (None, Some(Number(end))) => IntRange::to(end.into(), inclusive), + (Some(Number(start)), None) => KRange::from(start.into()), + (None, Some(Number(end))) => KRange::to(end.into(), inclusive), (Some(unexpected), _) => return type_error("Number for range start", unexpected), (_, Some(unexpected)) => return type_error("Number for range end", unexpected), - (None, None) => IntRange::unbounded(), + (None, None) => KRange::unbounded(), }; self.set_register(register, range.into()); diff --git a/core/runtime/tests/vm_tests.rs b/core/runtime/tests/vm_tests.rs index cf86c2084..8b5d882e4 100644 --- a/core/runtime/tests/vm_tests.rs +++ b/core/runtime/tests/vm_tests.rs @@ -187,16 +187,16 @@ a %= 5 #[test] fn range() { - test_script("0..10", Value::Range(IntRange::bounded(0, 10, false))); - test_script("0..-10", Value::Range(IntRange::bounded(0, -10, false))); - test_script("1 + 1..2 + 2", Value::Range(IntRange::bounded(2, 4, false))); + test_script("0..10", Value::Range(KRange::bounded(0, 10, false))); + test_script("0..-10", Value::Range(KRange::bounded(0, -10, false))); + test_script("1 + 1..2 + 2", Value::Range(KRange::bounded(2, 4, false))); } #[test] fn range_inclusive() { - test_script("10..=20", Value::Range(IntRange::bounded(10, 20, true))); - test_script("4..=0", Value::Range(IntRange::bounded(4, 0, true))); - test_script("2 * 2..=3 * 3", Value::Range(IntRange::bounded(4, 9, true))); + test_script("10..=20", Value::Range(KRange::bounded(10, 20, true))); + test_script("4..=0", Value::Range(KRange::bounded(4, 0, true))); + test_script("2 * 2..=3 * 3", Value::Range(KRange::bounded(4, 9, true))); } } From bc932c0673a5629ef36f0e9dc2e32e59e714c2fa Mon Sep 17 00:00:00 2001 From: Ian Hobson Date: Wed, 11 Oct 2023 11:38:28 +0200 Subject: [PATCH 08/13] Rename FunctionInfo -> KFunction and CaptureFunctionInfo -> KCaptureFunction --- core/runtime/src/lib.rs | 2 +- core/runtime/src/types/mod.rs | 2 +- core/runtime/src/types/value.rs | 10 +++++----- core/runtime/src/vm.rs | 12 ++++++------ 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/core/runtime/src/lib.rs b/core/runtime/src/lib.rs index f1a50009f..7cafdb6c3 100644 --- a/core/runtime/src/lib.rs +++ b/core/runtime/src/lib.rs @@ -16,7 +16,7 @@ pub use crate::{ error::{type_error, type_error_with_slice, Result, RuntimeError}, io::{BufferedFile, DefaultStderr, DefaultStdin, DefaultStdout, KotoFile, KotoRead, KotoWrite}, types::{ - BinaryOp, CallContext, CaptureFunctionInfo, ExternalFunction, FunctionInfo, IsIterable, + BinaryOp, CallContext, ExternalFunction, IsIterable, KCaptureFunction, KFunction, KIterator, KIteratorOutput, KList, KMap, KNumber, KRange, KString, KTuple, KotoHasher, KotoIterator, KotoObject, KotoType, MetaKey, MetaMap, MethodContext, Object, ObjectEntryBuilder, UnaryOp, Value, ValueKey, ValueMap, ValueVec, diff --git a/core/runtime/src/types/mod.rs b/core/runtime/src/types/mod.rs index 1afb9d6ea..a5f2cf862 100644 --- a/core/runtime/src/types/mod.rs +++ b/core/runtime/src/types/mod.rs @@ -18,7 +18,7 @@ pub use self::{ int_range::KRange, meta_map::{meta_id_to_key, BinaryOp, MetaKey, MetaMap, UnaryOp}, object::{IsIterable, KotoObject, KotoType, MethodContext, Object, ObjectEntryBuilder}, - value::{CaptureFunctionInfo, FunctionInfo, Value}, + value::{KCaptureFunction, KFunction, Value}, value_iterator::{KIterator, KIteratorOutput, KotoIterator}, value_key::ValueKey, value_list::{KList, ValueVec}, diff --git a/core/runtime/src/types/value.rs b/core/runtime/src/types/value.rs index 9b014a33c..abc884953 100644 --- a/core/runtime/src/types/value.rs +++ b/core/runtime/src/types/value.rs @@ -33,10 +33,10 @@ pub enum Value { Str(KString), /// A Koto function - Function(FunctionInfo), + Function(KFunction), /// A Koto function with captures - CaptureFunction(Ptr), + CaptureFunction(Ptr), /// A function that's defined outside of the Koto runtime ExternalFunction(ExternalFunction), @@ -336,7 +336,7 @@ impl From for Value { /// * [Value::Function] /// * [Value::CaptureFunction] #[derive(Clone, Debug, PartialEq)] -pub struct FunctionInfo { +pub struct KFunction { /// The [Chunk] in which the function can be found. pub chunk: Ptr, /// The start ip of the function. @@ -363,9 +363,9 @@ pub struct FunctionInfo { /// * [Value::Function] /// * [Value::CaptureFunction] #[derive(Clone)] -pub struct CaptureFunctionInfo { +pub struct KCaptureFunction { /// The function's properties - pub info: FunctionInfo, + pub info: KFunction, /// The optional list of captures that should be copied into scope when the function is called. // // Q. Why use a KList? diff --git a/core/runtime/src/vm.rs b/core/runtime/src/vm.rs index 4f1efb2ef..ffbff4019 100644 --- a/core/runtime/src/vm.rs +++ b/core/runtime/src/vm.rs @@ -4,9 +4,9 @@ use crate::{ prelude::*, types::{ meta_id_to_key, - value::{FunctionInfo, RegisterSlice}, + value::{KFunction, RegisterSlice}, }, - CaptureFunctionInfo, DefaultStderr, DefaultStdin, DefaultStdout, Result, + DefaultStderr, DefaultStdin, DefaultStdout, KCaptureFunction, Result, }; use koto_bytecode::{Chunk, Instruction, InstructionReader, Loader, TypeId}; use koto_parser::{ConstantIndex, MetaKeyId}; @@ -1266,7 +1266,7 @@ impl Vm { arg_is_unpacked_tuple, size, } => { - let info = FunctionInfo { + let info = KFunction { chunk: self.chunk(), ip: self.ip(), arg_count, @@ -1279,7 +1279,7 @@ impl Vm { // Initialize the function's captures with Null let mut captures = ValueVec::new(); captures.resize(capture_count as usize, Null); - CaptureFunction(Ptr::new(CaptureFunctionInfo { + CaptureFunction(Ptr::new(KCaptureFunction { info, captures: KList::with_data(captures), })) @@ -2441,7 +2441,7 @@ impl Vm { fn call_generator( &mut self, call_info: &CallInfo, - f: &FunctionInfo, + f: &KFunction, captures: Option<&KList>, temp_tuple_values: Option<&[Value]>, ) -> Result<()> { @@ -2532,7 +2532,7 @@ impl Vm { fn call_function( &mut self, call_info: &CallInfo, - f: &FunctionInfo, + f: &KFunction, captures: Option<&KList>, temp_tuple_values: Option<&[Value]>, ) -> Result<()> { From 8ef35db0adcf2a594bcea74213631f01260f7b02 Mon Sep 17 00:00:00 2001 From: Ian Hobson Date: Wed, 11 Oct 2023 11:44:02 +0200 Subject: [PATCH 09/13] Rename Object -> KObject --- core/runtime/src/core_lib/io.rs | 4 ++-- .../runtime/src/core_lib/iterator/peekable.rs | 4 ++-- core/runtime/src/core_lib/os.rs | 8 +++---- core/runtime/src/lib.rs | 4 ++-- core/runtime/src/prelude.rs | 7 +++--- core/runtime/src/types/mod.rs | 2 +- core/runtime/src/types/object.rs | 24 +++++++++---------- core/runtime/src/types/value.rs | 6 ++--- core/runtime/src/types/value_iterator.rs | 6 ++--- core/runtime/src/vm.rs | 2 +- core/runtime/tests/object_tests.rs | 10 ++++---- examples/poetry/src/koto_bindings.rs | 4 ++-- libs/color/src/color.rs | 4 ++-- libs/geometry/src/rect.rs | 4 ++-- libs/geometry/src/vec2.rs | 4 ++-- libs/geometry/src/vec3.rs | 4 ++-- libs/random/src/lib.rs | 4 ++-- 17 files changed, 50 insertions(+), 51 deletions(-) diff --git a/core/runtime/src/core_lib/io.rs b/core/runtime/src/core_lib/io.rs index c156ccb59..6359af17c 100644 --- a/core/runtime/src/core_lib/io.rs +++ b/core/runtime/src/core_lib/io.rs @@ -197,7 +197,7 @@ impl KotoObject for File { FILE_TYPE_STRING.with(|t| t.clone()) } - fn copy(&self) -> Object { + fn copy(&self) -> KObject { self.clone().into() } @@ -213,7 +213,7 @@ impl KotoObject for File { impl From for Value { fn from(file: File) -> Self { - Object::from(file).into() + KObject::from(file).into() } } diff --git a/core/runtime/src/core_lib/iterator/peekable.rs b/core/runtime/src/core_lib/iterator/peekable.rs index fb42fad95..031fed484 100644 --- a/core/runtime/src/core_lib/iterator/peekable.rs +++ b/core/runtime/src/core_lib/iterator/peekable.rs @@ -23,7 +23,7 @@ impl Peekable { /// Makes an instance of Peekable along with a meta map that allows it be used as a Koto Value pub fn make_value(iter: KIterator) -> Value { - Object::from(Self::new(iter)).into() + KObject::from(Self::new(iter)).into() } fn peek(&mut self) -> Result { @@ -78,7 +78,7 @@ impl KotoObject for Peekable { PEEKABLE_TYPE_STRING.with(|t| t.clone()) } - fn copy(&self) -> Object { + fn copy(&self) -> KObject { self.clone().into() } diff --git a/core/runtime/src/core_lib/os.rs b/core/runtime/src/core_lib/os.rs index 3a1826470..65243b502 100644 --- a/core/runtime/src/core_lib/os.rs +++ b/core/runtime/src/core_lib/os.rs @@ -44,7 +44,7 @@ impl Deref for DateTime { impl DateTime { fn with_chrono_datetime(time: chrono::DateTime) -> Value { - Object::from(Self(time)).into() + KObject::from(Self(time)).into() } fn now() -> Value { @@ -79,7 +79,7 @@ impl KotoObject for DateTime { DATETIME_TYPE_STRING.with(|t| t.clone()) } - fn copy(&self) -> Object { + fn copy(&self) -> KObject { self.clone().into() } @@ -136,7 +136,7 @@ impl Deref for Timer { impl Timer { fn now() -> Value { let timer = Self(Instant::now()); - Object::from(timer).into() + KObject::from(timer).into() } fn elapsed_seconds(&self) -> f64 { @@ -153,7 +153,7 @@ impl KotoObject for Timer { TIMER_TYPE_STRING.with(|t| t.clone()) } - fn copy(&self) -> Object { + fn copy(&self) -> KObject { self.clone().into() } diff --git a/core/runtime/src/lib.rs b/core/runtime/src/lib.rs index 7cafdb6c3..846b4bcd0 100644 --- a/core/runtime/src/lib.rs +++ b/core/runtime/src/lib.rs @@ -17,8 +17,8 @@ pub use crate::{ io::{BufferedFile, DefaultStderr, DefaultStdin, DefaultStdout, KotoFile, KotoRead, KotoWrite}, types::{ BinaryOp, CallContext, ExternalFunction, IsIterable, KCaptureFunction, KFunction, - KIterator, KIteratorOutput, KList, KMap, KNumber, KRange, KString, KTuple, KotoHasher, - KotoIterator, KotoObject, KotoType, MetaKey, MetaMap, MethodContext, Object, + KIterator, KIteratorOutput, KList, KMap, KNumber, KObject, KRange, KString, KTuple, + KotoHasher, KotoIterator, KotoObject, KotoType, MetaKey, MetaMap, MethodContext, ObjectEntryBuilder, UnaryOp, Value, ValueKey, ValueMap, ValueVec, }, vm::{CallArgs, ModuleImportedCallback, Vm, VmSettings}, diff --git a/core/runtime/src/prelude.rs b/core/runtime/src/prelude.rs index de479858e..29bbb89f9 100644 --- a/core/runtime/src/prelude.rs +++ b/core/runtime/src/prelude.rs @@ -4,8 +4,7 @@ pub use crate::{ make_runtime_error, runtime_error, type_error, type_error_with_slice, BinaryOp, Borrow, BorrowMut, CallArgs, CallContext, DisplayContext, ExternalFunction, IsIterable, KIterator, - KIteratorOutput, KList, KMap, KNumber, KRange, KString, KTuple, KotoFile, KotoHasher, - KotoIterator, KotoObject, KotoRead, KotoType, KotoWrite, MetaKey, MetaMap, Object, - ObjectEntryBuilder, Ptr, PtrMut, RuntimeError, UnaryOp, Value, ValueKey, ValueMap, ValueVec, - Vm, VmSettings, + KIteratorOutput, KList, KMap, KNumber, KObject, KRange, KString, KTuple, KotoFile, KotoHasher, + KotoIterator, KotoObject, KotoRead, KotoType, KotoWrite, MetaKey, MetaMap, ObjectEntryBuilder, + Ptr, PtrMut, RuntimeError, UnaryOp, Value, ValueKey, ValueMap, ValueVec, Vm, VmSettings, }; diff --git a/core/runtime/src/types/mod.rs b/core/runtime/src/types/mod.rs index a5f2cf862..f87f96871 100644 --- a/core/runtime/src/types/mod.rs +++ b/core/runtime/src/types/mod.rs @@ -17,7 +17,7 @@ pub use self::{ external_function::{CallContext, ExternalFunction}, int_range::KRange, meta_map::{meta_id_to_key, BinaryOp, MetaKey, MetaMap, UnaryOp}, - object::{IsIterable, KotoObject, KotoType, MethodContext, Object, ObjectEntryBuilder}, + object::{IsIterable, KObject, KotoObject, KotoType, MethodContext, ObjectEntryBuilder}, value::{KCaptureFunction, KFunction, Value}, value_iterator::{KIterator, KIteratorOutput, KotoIterator}, value_key::ValueKey, diff --git a/core/runtime/src/types/object.rs b/core/runtime/src/types/object.rs index 8291c9f05..35191c960 100644 --- a/core/runtime/src/types/object.rs +++ b/core/runtime/src/types/object.rs @@ -4,7 +4,7 @@ use std::{cell::RefCell, marker::PhantomData, rc::Rc}; /// A trait for implementing objects that can be added to the Koto runtime /// -/// See also: [Object]. +/// See also: [KObject]. pub trait KotoObject: Downcast { /// The type of the Object as a [KString] /// @@ -30,8 +30,8 @@ pub trait KotoObject: Downcast { /// FOO_TYPE_STRING.with(|t| t.clone()) /// } /// - /// fn copy(&self) -> Object { - /// Object::from(self.clone()) + /// fn copy(&self) -> KObject { + /// KObject::from(self.clone()) /// } /// } /// @@ -45,13 +45,13 @@ pub trait KotoObject: Downcast { /// /// A default implementation can't be provided here, but a typical implementation will look /// similar to: `Object::from(self.clone())` - fn copy(&self) -> Object; + fn copy(&self) -> KObject; /// How the object should behave when called from `koto.deep_copy` /// /// Deep copies should ensure that deep copies are performed for any Koto values that are owned /// by the object (see [Value::deep_copy]). - fn deep_copy(&self) -> Object { + fn deep_copy(&self) -> KObject { self.copy() } @@ -217,11 +217,11 @@ impl_downcast!(KotoObject); /// A wrapper for [KotoObject]s used in the Koto runtime #[derive(Clone)] -pub struct Object { +pub struct KObject { object: PtrMut, } -impl Object { +impl KObject { /// Checks if the object is of the given type pub fn is_a(&self) -> bool { match self.object.try_borrow() { @@ -262,7 +262,7 @@ impl Object { } } -impl From for Object { +impl From for KObject { fn from(object: T) -> Self { Self { object: PtrMut::from(Rc::new(RefCell::new(object)) as Rc>), @@ -297,7 +297,7 @@ pub trait KotoType { /// FOO_TYPE_STRING.with(|t| t.clone()) /// } /// -/// fn copy(&self) -> Object { +/// fn copy(&self) -> KObject { /// self.clone().into() /// } /// @@ -308,7 +308,7 @@ pub trait KotoType { /// /// impl From for Value { /// fn from(foo: Foo) -> Self { -/// Object::from(foo).into() +/// KObject::from(foo).into() /// } /// } /// @@ -416,14 +416,14 @@ pub struct MethodContext<'a, T> { pub vm: &'a Vm, // The instance of the object for the method call, // accessable via the context's `instance`/`instance_mut` functions - object: &'a Object, + object: &'a KObject, // We want access to `T` in the implementation _phantom: PhantomData, } impl<'a, T: KotoObject> MethodContext<'a, T> { /// Makes a new method context - fn new(object: &'a Object, args: &'a [Value], vm: &'a Vm) -> Self { + fn new(object: &'a KObject, args: &'a [Value], vm: &'a Vm) -> Self { Self { object, args, diff --git a/core/runtime/src/types/value.rs b/core/runtime/src/types/value.rs index abc884953..e31678945 100644 --- a/core/runtime/src/types/value.rs +++ b/core/runtime/src/types/value.rs @@ -45,7 +45,7 @@ pub enum Value { Iterator(KIterator), /// An object with behaviour defined via the [KotoObject] trait - Object(Object), + Object(KObject), /// A tuple of values that are packed into a contiguous series of registers /// @@ -318,8 +318,8 @@ impl From for Value { } } -impl From for Value { - fn from(value: Object) -> Self { +impl From for Value { + fn from(value: KObject) -> Self { Self::Object(value) } } diff --git a/core/runtime/src/types/value_iterator.rs b/core/runtime/src/types/value_iterator.rs index d285cd4fd..c02debf48 100644 --- a/core/runtime/src/types/value_iterator.rs +++ b/core/runtime/src/types/value_iterator.rs @@ -128,7 +128,7 @@ impl KIterator { } /// Creates a new KIterator from an Object that implements [KotoIterator] - pub fn with_object(vm: Vm, o: Object) -> Result { + pub fn with_object(vm: Vm, o: KObject) -> Result { Ok(Self::new(ObjectIterator::new(vm, o)?)) } @@ -461,11 +461,11 @@ impl Iterator for MetaIterator { #[derive(Clone)] struct ObjectIterator { vm: Vm, - object: Object, + object: KObject, } impl ObjectIterator { - fn new(vm: Vm, object: Object) -> Result { + fn new(vm: Vm, object: KObject) -> Result { use IsIterable::*; if matches!( diff --git a/core/runtime/src/vm.rs b/core/runtime/src/vm.rs index ffbff4019..db63c36f4 100644 --- a/core/runtime/src/vm.rs +++ b/core/runtime/src/vm.rs @@ -3029,7 +3029,7 @@ impl Frame { // See Vm::call_external enum ExternalCallable { Function(ExternalFunction), - Object(Object), + Object(KObject), } // See Vm::call_callable diff --git a/core/runtime/tests/object_tests.rs b/core/runtime/tests/object_tests.rs index af8e79064..44526ad39 100644 --- a/core/runtime/tests/object_tests.rs +++ b/core/runtime/tests/object_tests.rs @@ -11,7 +11,7 @@ mod objects { impl TestObject { fn make_value(x: i64) -> Value { - Object::from(Self { x }).into() + KObject::from(Self { x }).into() } } @@ -88,7 +88,7 @@ mod objects { TEST_OBJECT_TYPE_STRING.with(|s| s.clone()) } - fn copy(&self) -> Object { + fn copy(&self) -> KObject { (*self).into() } @@ -233,8 +233,8 @@ mod objects { } impl TestIterator { - fn make_object(x: i64) -> Object { - Object::from(Self { x }) + fn make_object(x: i64) -> KObject { + KObject::from(Self { x }) } } @@ -247,7 +247,7 @@ mod objects { TEST_ITERATOR_TYPE_STRING.with(|s| s.clone()) } - fn copy(&self) -> Object { + fn copy(&self) -> KObject { (*self).into() } diff --git a/examples/poetry/src/koto_bindings.rs b/examples/poetry/src/koto_bindings.rs index 1ba6e9376..22d2cae5d 100644 --- a/examples/poetry/src/koto_bindings.rs +++ b/examples/poetry/src/koto_bindings.rs @@ -27,7 +27,7 @@ impl KotoObject for Poetry { Self::TYPE.into() } - fn copy(&self) -> Object { + fn copy(&self) -> KObject { self.clone().into() } @@ -43,6 +43,6 @@ impl KotoObject for Poetry { impl From for Value { fn from(poetry: Poetry) -> Self { - Object::from(poetry).into() + KObject::from(poetry).into() } } diff --git a/libs/color/src/color.rs b/libs/color/src/color.rs index ae844f616..ff0c06cd7 100644 --- a/libs/color/src/color.rs +++ b/libs/color/src/color.rs @@ -170,7 +170,7 @@ impl KotoObject for Color { COLOR_TYPE_STRING.with(|s| s.clone()) } - fn copy(&self) -> Object { + fn copy(&self) -> KObject { (*self).into() } @@ -334,7 +334,7 @@ impl DerefMut for Color { impl From for Value { fn from(color: Color) -> Self { - Object::from(color).into() + KObject::from(color).into() } } diff --git a/libs/geometry/src/rect.rs b/libs/geometry/src/rect.rs index 323cd54e5..3fda39b02 100644 --- a/libs/geometry/src/rect.rs +++ b/libs/geometry/src/rect.rs @@ -22,7 +22,7 @@ impl KotoObject for Rect { RECT_TYPE_STRING.with(|s| s.clone()) } - fn copy(&self) -> Object { + fn copy(&self) -> KObject { (*self).into() } @@ -129,7 +129,7 @@ impl From<(f64, f64, f64, f64)> for Rect { impl From for Value { fn from(point: Rect) -> Self { - Object::from(point).into() + KObject::from(point).into() } } diff --git a/libs/geometry/src/vec2.rs b/libs/geometry/src/vec2.rs index 3061f85b9..2b0faf553 100644 --- a/libs/geometry/src/vec2.rs +++ b/libs/geometry/src/vec2.rs @@ -28,7 +28,7 @@ impl KotoObject for Vec2 { VEC2_TYPE_STRING.with(|s| s.clone()) } - fn copy(&self) -> Object { + fn copy(&self) -> KObject { (*self).into() } @@ -148,7 +148,7 @@ impl From for Vec2 { impl From for Value { fn from(point: Vec2) -> Self { - Object::from(point).into() + KObject::from(point).into() } } diff --git a/libs/geometry/src/vec3.rs b/libs/geometry/src/vec3.rs index ae978f7f8..2733297e8 100644 --- a/libs/geometry/src/vec3.rs +++ b/libs/geometry/src/vec3.rs @@ -23,7 +23,7 @@ impl KotoObject for Vec3 { VEC3_TYPE_STRING.with(|s| s.clone()) } - fn copy(&self) -> Object { + fn copy(&self) -> KObject { (*self).into() } @@ -152,7 +152,7 @@ impl From<(f64, f64, f64)> for Vec3 { impl From for Value { fn from(vec3: Vec3) -> Self { - Object::from(vec3).into() + KObject::from(vec3).into() } } diff --git a/libs/random/src/lib.rs b/libs/random/src/lib.rs index 1165eab9e..1edaccfc5 100644 --- a/libs/random/src/lib.rs +++ b/libs/random/src/lib.rs @@ -46,7 +46,7 @@ struct ChaChaRng(ChaCha8Rng); impl ChaChaRng { fn make_value(rng: ChaCha8Rng) -> Value { - Object::from(Self(rng)).into() + KObject::from(Self(rng)).into() } fn gen_bool(&mut self) -> Result { @@ -108,7 +108,7 @@ impl KotoObject for ChaChaRng { RNG_TYPE_STRING.with(|s| s.clone()) } - fn copy(&self) -> Object { + fn copy(&self) -> KObject { self.clone().into() } From 4c30f2fcb0c282a0bee6eb4ebcf63a7a86370087 Mon Sep 17 00:00:00 2001 From: Ian Hobson Date: Wed, 11 Oct 2023 12:18:30 +0200 Subject: [PATCH 10/13] Rename ExternalFunction to KNativeFunction --- core/runtime/src/lib.rs | 8 ++++---- core/runtime/src/prelude.rs | 4 ++-- core/runtime/src/types/external_function.rs | 14 +++++++------- core/runtime/src/types/meta_map.rs | 2 +- core/runtime/src/types/mod.rs | 2 +- core/runtime/src/types/object.rs | 4 ++-- core/runtime/src/types/value.rs | 16 ++++++++-------- core/runtime/src/types/value_map.rs | 2 +- core/runtime/src/vm.rs | 4 ++-- 9 files changed, 28 insertions(+), 28 deletions(-) diff --git a/core/runtime/src/lib.rs b/core/runtime/src/lib.rs index 846b4bcd0..0d50f1a81 100644 --- a/core/runtime/src/lib.rs +++ b/core/runtime/src/lib.rs @@ -16,10 +16,10 @@ pub use crate::{ error::{type_error, type_error_with_slice, Result, RuntimeError}, io::{BufferedFile, DefaultStderr, DefaultStdin, DefaultStdout, KotoFile, KotoRead, KotoWrite}, types::{ - BinaryOp, CallContext, ExternalFunction, IsIterable, KCaptureFunction, KFunction, - KIterator, KIteratorOutput, KList, KMap, KNumber, KObject, KRange, KString, KTuple, - KotoHasher, KotoIterator, KotoObject, KotoType, MetaKey, MetaMap, MethodContext, - ObjectEntryBuilder, UnaryOp, Value, ValueKey, ValueMap, ValueVec, + BinaryOp, CallContext, IsIterable, KCaptureFunction, KFunction, KIterator, KIteratorOutput, + KList, KMap, KNativeFunction, KNumber, KObject, KRange, KString, KTuple, KotoHasher, + KotoIterator, KotoObject, KotoType, MetaKey, MetaMap, MethodContext, ObjectEntryBuilder, + UnaryOp, Value, ValueKey, ValueMap, ValueVec, }, vm::{CallArgs, ModuleImportedCallback, Vm, VmSettings}, }; diff --git a/core/runtime/src/prelude.rs b/core/runtime/src/prelude.rs index 29bbb89f9..c4bb26c74 100644 --- a/core/runtime/src/prelude.rs +++ b/core/runtime/src/prelude.rs @@ -3,8 +3,8 @@ #[doc(inline)] pub use crate::{ make_runtime_error, runtime_error, type_error, type_error_with_slice, BinaryOp, Borrow, - BorrowMut, CallArgs, CallContext, DisplayContext, ExternalFunction, IsIterable, KIterator, - KIteratorOutput, KList, KMap, KNumber, KObject, KRange, KString, KTuple, KotoFile, KotoHasher, + BorrowMut, CallArgs, CallContext, DisplayContext, IsIterable, KIterator, KIteratorOutput, + KList, KMap, KNativeFunction, KNumber, KObject, KRange, KString, KTuple, KotoFile, KotoHasher, KotoIterator, KotoObject, KotoRead, KotoType, KotoWrite, MetaKey, MetaMap, ObjectEntryBuilder, Ptr, PtrMut, RuntimeError, UnaryOp, Value, ValueKey, ValueMap, ValueVec, Vm, VmSettings, }; diff --git a/core/runtime/src/types/external_function.rs b/core/runtime/src/types/external_function.rs index 398b01a6d..35c8292c1 100644 --- a/core/runtime/src/types/external_function.rs +++ b/core/runtime/src/types/external_function.rs @@ -7,8 +7,8 @@ use std::{ /// An function that's defined outside of the Koto runtime /// -/// See [Value::ExternalFunction] -pub struct ExternalFunction { +/// See [Value::NativeFunction] +pub struct KNativeFunction { /// The function implementation that should be called when calling the external function // // Disable a clippy false positive, see https://github.com/rust-lang/rust-clippy/issues/9299 @@ -18,7 +18,7 @@ pub struct ExternalFunction { pub function: Rc Result + 'static>, } -impl ExternalFunction { +impl KNativeFunction { /// Creates a new external function pub fn new(function: impl Fn(&mut CallContext) -> Result + 'static) -> Self { Self { @@ -27,7 +27,7 @@ impl ExternalFunction { } } -impl Clone for ExternalFunction { +impl Clone for KNativeFunction { fn clone(&self) -> Self { Self { function: self.function.clone(), @@ -35,20 +35,20 @@ impl Clone for ExternalFunction { } } -impl fmt::Debug for ExternalFunction { +impl fmt::Debug for KNativeFunction { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let raw = Rc::into_raw(self.function.clone()); write!(f, "external function: {raw:?}",) } } -impl Hash for ExternalFunction { +impl Hash for KNativeFunction { fn hash(&self, state: &mut H) { state.write_usize(Rc::as_ptr(&self.function) as *const () as usize); } } -/// The context provided when a call to an [ExternalFunction] is made +/// The context provided when a call to a [KNativeFunction] is made #[allow(missing_docs)] pub struct CallContext<'a> { /// The VM making the call diff --git a/core/runtime/src/types/meta_map.rs b/core/runtime/src/types/meta_map.rs index ffd34f69b..2cc1b4872 100644 --- a/core/runtime/src/types/meta_map.rs +++ b/core/runtime/src/types/meta_map.rs @@ -29,7 +29,7 @@ impl MetaMap { f: impl Fn(&mut CallContext) -> Result + 'static, ) { self.0 - .insert(key, Value::ExternalFunction(ExternalFunction::new(f))); + .insert(key, Value::NativeFunction(KNativeFunction::new(f))); } } diff --git a/core/runtime/src/types/mod.rs b/core/runtime/src/types/mod.rs index f87f96871..46ed11557 100644 --- a/core/runtime/src/types/mod.rs +++ b/core/runtime/src/types/mod.rs @@ -14,7 +14,7 @@ mod value_string; mod value_tuple; pub use self::{ - external_function::{CallContext, ExternalFunction}, + external_function::{CallContext, KNativeFunction}, int_range::KRange, meta_map::{meta_id_to_key, BinaryOp, MetaKey, MetaMap, UnaryOp}, object::{IsIterable, KObject, KotoObject, KotoType, MethodContext, ObjectEntryBuilder}, diff --git a/core/runtime/src/types/object.rs b/core/runtime/src/types/object.rs index 35191c960..e2d1bd0cd 100644 --- a/core/runtime/src/types/object.rs +++ b/core/runtime/src/types/object.rs @@ -1,4 +1,4 @@ -use crate::{prelude::*, ExternalFunction, Result}; +use crate::{prelude::*, KNativeFunction, Result}; use downcast_rs::{impl_downcast, Downcast}; use std::{cell::RefCell, marker::PhantomData, rc::Rc}; @@ -398,7 +398,7 @@ impl ObjectEntryBuilder { for key in keys { self.map.insert( key.clone().into(), - Value::ExternalFunction(ExternalFunction::new(wrapped_function.clone())), + Value::NativeFunction(KNativeFunction::new(wrapped_function.clone())), ); } diff --git a/core/runtime/src/types/value.rs b/core/runtime/src/types/value.rs index e31678945..409ec3be6 100644 --- a/core/runtime/src/types/value.rs +++ b/core/runtime/src/types/value.rs @@ -1,6 +1,6 @@ //! The core value type used in the Koto runtime -use crate::{prelude::*, ExternalFunction, KMap, Result}; +use crate::{prelude::*, KMap, KNativeFunction, Result}; use koto_bytecode::Chunk; use std::fmt::Write; @@ -38,8 +38,8 @@ pub enum Value { /// A Koto function with captures CaptureFunction(Ptr), - /// A function that's defined outside of the Koto runtime - ExternalFunction(ExternalFunction), + /// A function that's implemented outside of the Koto runtime + NativeFunction(KNativeFunction), /// The iterator type used in Koto Iterator(KIterator), @@ -100,7 +100,7 @@ impl Value { match self { Function(f) if f.generator => false, CaptureFunction(f) if f.info.generator => false, - Function(_) | CaptureFunction(_) | ExternalFunction(_) => true, + Function(_) | CaptureFunction(_) | NativeFunction(_) => true, Map(m) => m.contains_meta_key(&MetaKey::Call), _ => false, } @@ -183,8 +183,9 @@ impl Value { Tuple(_) => TYPE_TUPLE.with(|x| x.clone()), Function(f) if f.generator => TYPE_GENERATOR.with(|x| x.clone()), CaptureFunction(f) if f.info.generator => TYPE_GENERATOR.with(|x| x.clone()), - Function(_) | CaptureFunction(_) => TYPE_FUNCTION.with(|x| x.clone()), - ExternalFunction(_) => TYPE_EXTERNAL_FUNCTION.with(|x| x.clone()), + Function(_) | CaptureFunction(_) | NativeFunction(_) => { + TYPE_FUNCTION.with(|x| x.clone()) + } Object(o) => o.try_borrow().map_or_else( |_| "Error: object already borrowed".into(), |o| o.object_type(), @@ -222,7 +223,7 @@ impl Value { Range(r) => write!(ctx, "{r}"), Function(_) | CaptureFunction(_) => write!(ctx, "||"), Iterator(_) => write!(ctx, "Iterator"), - ExternalFunction(_) => write!(ctx, "||"), + NativeFunction(_) => write!(ctx, "||"), TemporaryTuple(RegisterSlice { start, count }) => { write!(ctx, "TemporaryTuple [{start}..{}]", start + count) } @@ -253,7 +254,6 @@ thread_local! { static TYPE_TUPLE: KString = "Tuple".into(); static TYPE_FUNCTION: KString = "Function".into(); static TYPE_GENERATOR: KString = "Generator".into(); - static TYPE_EXTERNAL_FUNCTION: KString = "ExternalFunction".into(); static TYPE_ITERATOR: KString = "Iterator".into(); static TYPE_TEMPORARY_TUPLE: KString = "TemporaryTuple".into(); } diff --git a/core/runtime/src/types/value_map.rs b/core/runtime/src/types/value_map.rs index 8502890ac..f86d80eb1 100644 --- a/core/runtime/src/types/value_map.rs +++ b/core/runtime/src/types/value_map.rs @@ -145,7 +145,7 @@ impl KMap { /// Adds a function to the KMap's data map pub fn add_fn(&self, id: &str, f: impl Fn(&mut CallContext) -> Result + 'static) { - self.add_value(id, Value::ExternalFunction(ExternalFunction::new(f))); + self.add_value(id, Value::NativeFunction(KNativeFunction::new(f))); } /// Adds a map to the KMap's data map diff --git a/core/runtime/src/vm.rs b/core/runtime/src/vm.rs index db63c36f4..1180ae05d 100644 --- a/core/runtime/src/vm.rs +++ b/core/runtime/src/vm.rs @@ -2612,7 +2612,7 @@ impl Vm { CaptureFunction(f) => { self.call_function(info, &f.info, Some(&f.captures), temp_tuple_values) } - ExternalFunction(f) => self.call_external(info, ExternalCallable::Function(f)), + NativeFunction(f) => self.call_external(info, ExternalCallable::Function(f)), Object(o) => self.call_external(info, ExternalCallable::Object(o)), ref v if v.contains_meta_key(&MetaKey::Call) => { let f = v.get_meta_value(&MetaKey::Call).unwrap(); @@ -3028,7 +3028,7 @@ impl Frame { // See Vm::call_external enum ExternalCallable { - Function(ExternalFunction), + Function(KNativeFunction), Object(KObject), } From c3ddd16e4e41d69ef222c434f2bd8a21359dcf12 Mon Sep 17 00:00:00 2001 From: Ian Hobson Date: Wed, 11 Oct 2023 12:58:36 +0200 Subject: [PATCH 11/13] Rename files to match the new type names --- .../types/{value_iterator.rs => iterator.rs} | 0 .../src/types/{value_list.rs => list.rs} | 0 .../src/types/{value_map.rs => map.rs} | 0 core/runtime/src/types/mod.rs | 32 +++++++++---------- ...xternal_function.rs => native_function.rs} | 0 .../src/types/{value_number.rs => number.rs} | 0 .../src/types/{int_range.rs => range.rs} | 0 .../src/types/{value_string.rs => string.rs} | 0 .../src/types/{value_tuple.rs => tuple.rs} | 0 core/runtime/src/types/value.rs | 8 ++--- 10 files changed, 20 insertions(+), 20 deletions(-) rename core/runtime/src/types/{value_iterator.rs => iterator.rs} (100%) rename core/runtime/src/types/{value_list.rs => list.rs} (100%) rename core/runtime/src/types/{value_map.rs => map.rs} (100%) rename core/runtime/src/types/{external_function.rs => native_function.rs} (100%) rename core/runtime/src/types/{value_number.rs => number.rs} (100%) rename core/runtime/src/types/{int_range.rs => range.rs} (100%) rename core/runtime/src/types/{value_string.rs => string.rs} (100%) rename core/runtime/src/types/{value_tuple.rs => tuple.rs} (100%) diff --git a/core/runtime/src/types/value_iterator.rs b/core/runtime/src/types/iterator.rs similarity index 100% rename from core/runtime/src/types/value_iterator.rs rename to core/runtime/src/types/iterator.rs diff --git a/core/runtime/src/types/value_list.rs b/core/runtime/src/types/list.rs similarity index 100% rename from core/runtime/src/types/value_list.rs rename to core/runtime/src/types/list.rs diff --git a/core/runtime/src/types/value_map.rs b/core/runtime/src/types/map.rs similarity index 100% rename from core/runtime/src/types/value_map.rs rename to core/runtime/src/types/map.rs diff --git a/core/runtime/src/types/mod.rs b/core/runtime/src/types/mod.rs index 46ed11557..d8c665074 100644 --- a/core/runtime/src/types/mod.rs +++ b/core/runtime/src/types/mod.rs @@ -1,29 +1,29 @@ //! The core types used in the Koto runtime -mod external_function; -mod int_range; +mod iterator; +mod list; +mod map; mod meta_map; +mod native_function; +mod number; mod object; +mod range; +mod string; +mod tuple; pub mod value; -mod value_iterator; mod value_key; -mod value_list; -mod value_map; -mod value_number; -mod value_string; -mod value_tuple; pub use self::{ - external_function::{CallContext, KNativeFunction}, - int_range::KRange, + iterator::{KIterator, KIteratorOutput, KotoIterator}, + list::{KList, ValueVec}, + map::{KMap, KotoHasher, ValueMap}, meta_map::{meta_id_to_key, BinaryOp, MetaKey, MetaMap, UnaryOp}, + native_function::{CallContext, KNativeFunction}, + number::KNumber, object::{IsIterable, KObject, KotoObject, KotoType, MethodContext, ObjectEntryBuilder}, + range::KRange, + string::KString, + tuple::KTuple, value::{KCaptureFunction, KFunction, Value}, - value_iterator::{KIterator, KIteratorOutput, KotoIterator}, value_key::ValueKey, - value_list::{KList, ValueVec}, - value_map::{KMap, KotoHasher, ValueMap}, - value_number::KNumber, - value_string::KString, - value_tuple::KTuple, }; diff --git a/core/runtime/src/types/external_function.rs b/core/runtime/src/types/native_function.rs similarity index 100% rename from core/runtime/src/types/external_function.rs rename to core/runtime/src/types/native_function.rs diff --git a/core/runtime/src/types/value_number.rs b/core/runtime/src/types/number.rs similarity index 100% rename from core/runtime/src/types/value_number.rs rename to core/runtime/src/types/number.rs diff --git a/core/runtime/src/types/int_range.rs b/core/runtime/src/types/range.rs similarity index 100% rename from core/runtime/src/types/int_range.rs rename to core/runtime/src/types/range.rs diff --git a/core/runtime/src/types/value_string.rs b/core/runtime/src/types/string.rs similarity index 100% rename from core/runtime/src/types/value_string.rs rename to core/runtime/src/types/string.rs diff --git a/core/runtime/src/types/value_tuple.rs b/core/runtime/src/types/tuple.rs similarity index 100% rename from core/runtime/src/types/value_tuple.rs rename to core/runtime/src/types/tuple.rs diff --git a/core/runtime/src/types/value.rs b/core/runtime/src/types/value.rs index 409ec3be6..7bf777edf 100644 --- a/core/runtime/src/types/value.rs +++ b/core/runtime/src/types/value.rs @@ -68,7 +68,7 @@ impl Value { .iter() .map(|v| v.deep_copy()) .collect::>()?; - Value::List(KList::with_data(result)) + KList::with_data(result).into() } Value::Tuple(t) => { let result = t @@ -84,10 +84,10 @@ impl Value { .map(|(k, v)| v.deep_copy().map(|v| (k.clone(), v))) .collect::>()?; let meta = m.meta_map().map(|meta| meta.borrow().clone()); - Value::Map(KMap::with_contents(data, meta)) + KMap::with_contents(data, meta).into() } - Value::Iterator(i) => Value::Iterator(i.make_copy()?), - Value::Object(o) => Value::Object(o.try_borrow()?.copy()), + Value::Iterator(i) => i.make_copy()?.into(), + Value::Object(o) => o.try_borrow()?.copy().into(), _ => self.clone(), }; From d36088e93adf6720af22be090952911b38be9bf2 Mon Sep 17 00:00:00 2001 From: Ian Hobson Date: Wed, 11 Oct 2023 13:02:10 +0200 Subject: [PATCH 12/13] Extract KFunction and KCaptureFunction into a separate module --- core/runtime/src/types/function.rs | 57 ++++++++++++++++++++++++++++++ core/runtime/src/types/mod.rs | 4 ++- core/runtime/src/types/value.rs | 55 +--------------------------- core/runtime/src/vm.rs | 7 ++-- 4 files changed, 63 insertions(+), 60 deletions(-) create mode 100644 core/runtime/src/types/function.rs diff --git a/core/runtime/src/types/function.rs b/core/runtime/src/types/function.rs new file mode 100644 index 000000000..581c5cdad --- /dev/null +++ b/core/runtime/src/types/function.rs @@ -0,0 +1,57 @@ +use crate::KList; +use koto_bytecode::Chunk; +use koto_memory::Ptr; + +/// A Koto function +/// +/// See also: +/// * [KCaptureFunction] +/// * [KNativeFunction](crate::KNativeFunction) +/// * [Value::Function](crate::Value::Function) +#[derive(Clone, Debug, PartialEq)] +pub struct KFunction { + /// The [Chunk] in which the function can be found. + pub chunk: Ptr, + /// The start ip of the function. + pub ip: u32, + /// The expected number of arguments for the function + pub arg_count: u8, + /// If the function is variadic, then extra args will be captured in a tuple. + pub variadic: bool, + /// If the function has a single arg, and that arg is an unpacked tuple + /// + /// This is used to optimize calls where the caller has a series of args that might be unpacked + /// by the function, and it would be wasteful to create a Tuple when it's going to be + /// immediately unpacked and discarded. + pub arg_is_unpacked_tuple: bool, + /// If the function is a generator, then calling the function will yield an iterator that + /// executes the function's body for each iteration step, pausing when a yield instruction is + /// encountered. See Vm::call_generator and Iterable::Generator. + pub generator: bool, +} + +/// A Koto function with captured values +/// +/// See also: +/// * [KFunction] +/// * [KNativeFunction](crate::KNativeFunction) +/// * [Value::CaptureFunction](crate::Value::CaptureFunction) +#[derive(Clone)] +pub struct KCaptureFunction { + /// The function's properties + pub info: KFunction, + /// The optional list of captures that should be copied into scope when the function is called. + // + // Q. Why use a KList? + // A. Because capturing values currently works by assigning by index, after the function + // itself has been created. + // Q. Why not use a SequenceBuilder? + // A. Recursive functions need to capture themselves into the list, and the captured function + // and the assigned function need to share the same captures list. Currently the only way + // for this to work is to allow mutation of the shared list after the creation of the + // function, so a KList is a reasonable choice. + // Q. After capturing is complete, what about using Ptr<[Value]> for non-recursive functions, + // or Option for non-recursive functions with a single capture? + // A. These could be worth investigating, but for now the KList will do. + pub captures: KList, +} diff --git a/core/runtime/src/types/mod.rs b/core/runtime/src/types/mod.rs index d8c665074..03a9ff97a 100644 --- a/core/runtime/src/types/mod.rs +++ b/core/runtime/src/types/mod.rs @@ -1,5 +1,6 @@ //! The core types used in the Koto runtime +mod function; mod iterator; mod list; mod map; @@ -14,6 +15,7 @@ pub mod value; mod value_key; pub use self::{ + function::{KCaptureFunction, KFunction}, iterator::{KIterator, KIteratorOutput, KotoIterator}, list::{KList, ValueVec}, map::{KMap, KotoHasher, ValueMap}, @@ -24,6 +26,6 @@ pub use self::{ range::KRange, string::KString, tuple::KTuple, - value::{KCaptureFunction, KFunction, Value}, + value::Value, value_key::ValueKey, }; diff --git a/core/runtime/src/types/value.rs b/core/runtime/src/types/value.rs index 7bf777edf..11c6c4b80 100644 --- a/core/runtime/src/types/value.rs +++ b/core/runtime/src/types/value.rs @@ -1,7 +1,6 @@ //! The core value type used in the Koto runtime -use crate::{prelude::*, KMap, KNativeFunction, Result}; -use koto_bytecode::Chunk; +use crate::{prelude::*, KCaptureFunction, KFunction, KMap, KNativeFunction, Result}; use std::fmt::Write; /// The core Value type for Koto @@ -330,58 +329,6 @@ impl From for Value { } } -/// A Koto function -/// -/// See also: -/// * [Value::Function] -/// * [Value::CaptureFunction] -#[derive(Clone, Debug, PartialEq)] -pub struct KFunction { - /// The [Chunk] in which the function can be found. - pub chunk: Ptr, - /// The start ip of the function. - pub ip: u32, - /// The expected number of arguments for the function - pub arg_count: u8, - /// If the function is variadic, then extra args will be captured in a tuple. - pub variadic: bool, - /// If the function has a single arg, and that arg is an unpacked tuple - /// - /// This is used to optimize calls where the caller has a series of args that might be unpacked - /// by the function, and it would be wasteful to create a Tuple when it's going to be - /// immediately unpacked and discarded. - pub arg_is_unpacked_tuple: bool, - /// If the function is a generator, then calling the function will yield an iterator that - /// executes the function's body for each iteration step, pausing when a yield instruction is - /// encountered. See Vm::call_generator and Iterable::Generator. - pub generator: bool, -} - -/// A Koto function with captured values -/// -/// See also: -/// * [Value::Function] -/// * [Value::CaptureFunction] -#[derive(Clone)] -pub struct KCaptureFunction { - /// The function's properties - pub info: KFunction, - /// The optional list of captures that should be copied into scope when the function is called. - // - // Q. Why use a KList? - // A. Because capturing values currently works by assigning by index, after the function - // itself has been created. - // Q. Why not use a SequenceBuilder? - // A. Recursive functions need to capture themselves into the list, and the captured function - // and the assigned function need to share the same captures list. Currently the only way - // for this to work is to allow mutation of the shared list after the creation of the - // function, so a KList is a reasonable choice. - // Q. After capturing is complete, what about using Ptr<[Value]> for non-recursive functions, - // or Option for non-recursive functions with a single capture? - // A. These could be worth investigating, but for now the KList will do. - pub captures: KList, -} - /// A slice of a VM's registers /// /// See [Value::TemporaryTuple] diff --git a/core/runtime/src/vm.rs b/core/runtime/src/vm.rs index 1180ae05d..eed37a295 100644 --- a/core/runtime/src/vm.rs +++ b/core/runtime/src/vm.rs @@ -2,11 +2,8 @@ use crate::{ core_lib::CoreLib, error::RuntimeErrorType, prelude::*, - types::{ - meta_id_to_key, - value::{KFunction, RegisterSlice}, - }, - DefaultStderr, DefaultStdin, DefaultStdout, KCaptureFunction, Result, + types::{meta_id_to_key, value::RegisterSlice}, + DefaultStderr, DefaultStdin, DefaultStdout, KCaptureFunction, KFunction, Result, }; use koto_bytecode::{Chunk, Instruction, InstructionReader, Loader, TypeId}; use koto_parser::{ConstantIndex, MetaKeyId}; From b727ad280751348d360212a162e6015031a87021 Mon Sep 17 00:00:00 2001 From: Ian Hobson Date: Wed, 11 Oct 2023 13:05:33 +0200 Subject: [PATCH 13/13] Update the changelog --- CHANGELOG.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd333dbe7..dba2a50b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -119,10 +119,13 @@ The Koto project adheres to provides access to the VM and its arguments. - Functions that need access to the `self` instance can access it via `CallContext::instance`. -- `ValueTuple::data` has been removed, with a `Deref` impl to `&[Value]` taking +- The core Koto runtime types have been renamed for consistency, + and now use a `K` prefix to help disambiguate them in context + (e.g. `KIterator` vs. `Iterator`). +- `KTuple::data` has been removed, with a `Deref` impl to `&[Value]` taking its place. - Type strings and strings returned by `KotoFile` implementations are now - expected to be `ValueString`s. + expected to be `KString`s. - `unexpected_type_error_with_slice` has been renamed to `type_error_with_slice`, and has had the prefix argument removed. - `DataMap::get_with_string` has been replaced with a simplified `ValueKey`