Skip to content

Commit

Permalink
rune: Store String in AnyObj instead of Mutable (relates #844)
Browse files Browse the repository at this point in the history
  • Loading branch information
udoprog committed Oct 28, 2024
1 parent 7a35743 commit 989f41b
Show file tree
Hide file tree
Showing 42 changed files with 546 additions and 459 deletions.
3 changes: 1 addition & 2 deletions crates/rune-modules/src/base64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,6 @@ impl From<base64::DecodeSliceError> for DecodeError {
impl DecodeError {
#[rune::function(instance, protocol = STRING_DISPLAY)]
fn string_display(&self, f: &mut Formatter) -> VmResult<()> {
rune::vm_write!(f, "{}", self.inner);
VmResult::Ok(())
rune::vm_write!(f, "{}", self.inner)
}
}
6 changes: 2 additions & 4 deletions crates/rune-modules/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,7 @@ impl From<reqwest::Error> for Error {
impl Error {
#[rune::function(instance, protocol = STRING_DISPLAY)]
fn string_display(&self, f: &mut Formatter) -> VmResult<()> {
rune::vm_write!(f, "{}", self.inner);
VmResult::Ok(())
rune::vm_write!(f, "{}", self.inner)
}
}

Expand Down Expand Up @@ -189,8 +188,7 @@ pub struct StatusCode {
impl StatusCode {
#[rune::function(instance, protocol = STRING_DISPLAY)]
fn string_display(&self, f: &mut Formatter) -> VmResult<()> {
rune::vm_write!(f, "{}", self.inner);
VmResult::Ok(())
rune::vm_write!(f, "{}", self.inner)
}
}

Expand Down
14 changes: 7 additions & 7 deletions crates/rune-modules/src/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
//! ```
use rune::{ContextError, Module, vm_write, Any};
use rune::runtime::{Bytes, Value, Formatter};
use rune::runtime::{Bytes, Formatter, Value, VmResult};
use rune::alloc::{Vec, String};
use rune::alloc::fmt::TryWrite;

Expand Down Expand Up @@ -64,14 +64,14 @@ struct Error {
}

impl Error {
#[rune::function(vm_result, protocol = STRING_DISPLAY)]
pub(crate) fn display(&self, f: &mut Formatter) {
vm_write!(f, "{}", self.error);
#[rune::function(protocol = STRING_DISPLAY)]
pub(crate) fn display(&self, f: &mut Formatter) -> VmResult<()> {
vm_write!(f, "{}", self.error)
}

#[rune::function(vm_result, protocol = STRING_DEBUG)]
pub(crate) fn debug(&self, f: &mut Formatter) {
vm_write!(f, "{:?}", self.error);
#[rune::function(protocol = STRING_DEBUG)]
pub(crate) fn debug(&self, f: &mut Formatter) -> VmResult<()> {
vm_write!(f, "{:?}", self.error)
}
}

Expand Down
3 changes: 1 addition & 2 deletions crates/rune-modules/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,7 @@ struct ExitStatus {
impl ExitStatus {
#[rune::function(protocol = STRING_DISPLAY)]
fn string_display(&self, f: &mut Formatter) -> VmResult<()> {
rune::vm_write!(f, "{}", self.status);
VmResult::Ok(())
rune::vm_write!(f, "{}", self.status)
}

#[rune::function]
Expand Down
20 changes: 9 additions & 11 deletions crates/rune-modules/src/toml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,12 @@ pub mod de {
impl Error {
#[rune::function(protocol = STRING_DISPLAY)]
pub(crate) fn display(&self, f: &mut Formatter) -> VmResult<()> {
vm_write!(f, "{}", self.error);
VmResult::Ok(())
vm_write!(f, "{}", self.error)
}

#[rune::function(protocol = STRING_DEBUG)]
pub(crate) fn debug(&self, f: &mut Formatter) -> VmResult<()> {
vm_write!(f, "{:?}", self.error);
VmResult::Ok(())
vm_write!(f, "{:?}", self.error)
}
}

Expand All @@ -89,7 +87,7 @@ pub mod ser {
//! Serializer types for the toml module.
use rune::{Any, Module, ContextError, vm_write};
use rune::runtime::Formatter;
use rune::runtime::{Formatter, VmResult};
use rune::alloc::fmt::TryWrite;

pub fn module(_stdio: bool) -> Result<Module, ContextError> {
Expand All @@ -107,14 +105,14 @@ pub mod ser {
}

impl Error {
#[rune::function(vm_result, protocol = STRING_DISPLAY)]
pub(crate) fn display(&self, f: &mut Formatter) {
vm_write!(f, "{}", self.error);
#[rune::function(protocol = STRING_DISPLAY)]
pub(crate) fn display(&self, f: &mut Formatter) -> VmResult<()> {
vm_write!(f, "{}", self.error)
}

#[rune::function(vm_result, protocol = STRING_DEBUG)]
pub(crate) fn debug(&self, f: &mut Formatter) {
vm_write!(f, "{:?}", self.error);
#[rune::function(protocol = STRING_DEBUG)]
pub(crate) fn debug(&self, f: &mut Formatter) -> VmResult<()> {
vm_write!(f, "{:?}", self.error)
}
}

Expand Down
3 changes: 3 additions & 0 deletions crates/rune/src/any.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use core::any;

use crate::alloc::String;
use crate::compile::Named;
use crate::runtime::{AnyTypeInfo, TypeHash};

Expand Down Expand Up @@ -124,3 +125,5 @@ cfg_std! {
}

crate::__internal_impl_any!(::std::error, anyhow::Error);

impl Any for String {}
9 changes: 8 additions & 1 deletion crates/rune/src/compile/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::macros::{SyntheticId, SyntheticKind};
use crate::parse::{Expectation, IntoExpectation, LexerMode};
use crate::runtime::debug::DebugSignature;
use crate::runtime::unit::EncodeError;
use crate::runtime::{AccessError, RuntimeError, TypeInfo, TypeOf, VmError};
use crate::runtime::{AccessError, AnyObjError, RuntimeError, TypeInfo, TypeOf, VmError};
#[cfg(feature = "std")]
use crate::source;
use crate::{Hash, Item, ItemBuf, SourceId};
Expand Down Expand Up @@ -1307,6 +1307,13 @@ impl From<RuntimeError> for ErrorKind {
}
}

impl From<AnyObjError> for ErrorKind {
#[inline]
fn from(error: AnyObjError) -> Self {
Self::from(RuntimeError::from(error))
}
}

impl From<EncodeError> for ErrorKind {
#[inline]
fn from(error: EncodeError) -> Self {
Expand Down
26 changes: 16 additions & 10 deletions crates/rune/src/compile/ir/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ use crate::ast::{Span, Spanned};
use crate::compile::ir::{self};
use crate::compile::{self, WithSpan};
use crate::query::Used;
use crate::runtime::{Inline, Mutable, Object, OwnedTuple, Value, ValueBorrowRef};
use crate::runtime::{Inline, Object, OwnedTuple, Value, ValueBorrowRef};
use crate::TypeHash;

/// The outcome of a constant evaluation.
pub enum EvalOutcome {
Expand Down Expand Up @@ -139,18 +140,22 @@ fn eval_ir_binary(

return Ok(Value::from(out));
}
(ValueBorrowRef::Mutable(a), ValueBorrowRef::Mutable(b)) => {
let out = 'out: {
if let (Mutable::String(a), Mutable::String(b)) = (&*a, &*b) {
(ValueBorrowRef::Any(a), ValueBorrowRef::Any(b)) => {
let value = 'out: {
if let (String::HASH, String::HASH) = (a.type_hash(), b.type_hash()) {
let a = a.borrow_ref::<String>().with_span(span)?;
let b = b.borrow_ref::<String>().with_span(span)?;

if let ir::IrBinaryOp::Add = ir.op {
break 'out Mutable::String(add_strings(a, b).with_span(span)?);
let string = add_strings(&a, &b).with_span(span)?;
break 'out Value::new(string).with_span(span)?;
}
}

return Err(EvalOutcome::not_const(span));
};

return Ok(Value::try_from(out).with_span(span)?);
return Ok(value);
}
_ => (),
}
Expand Down Expand Up @@ -366,15 +371,16 @@ fn eval_ir_template(
return Err(EvalOutcome::not_const(ir));
}
},
ValueBorrowRef::Mutable(value) => match &*value {
Mutable::String(s) => {
buf.try_push_str(s)?;
ValueBorrowRef::Any(value) => match value.type_hash() {
String::HASH => {
let s = value.borrow_ref::<String>().with_span(ir)?;
buf.try_push_str(&s)?;
}
_ => {
return Err(EvalOutcome::not_const(ir));
}
},
ValueBorrowRef::Any(..) => {
ValueBorrowRef::Mutable(..) => {
return Err(EvalOutcome::not_const(ir));
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/rune/src/exported_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ macro_rules! vm_panic {
macro_rules! vm_write {
($($tt:tt)*) => {
match core::write!($($tt)*) {
Ok(()) => (),
Ok(()) => $crate::runtime::VmResult::Ok(()),
Err(err) => {
return $crate::runtime::VmResult::Err($crate::runtime::VmError::from(err));
}
Expand Down
12 changes: 2 additions & 10 deletions crates/rune/src/macros/format_args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ use crate::ast::{self, Span, Spanned};
use crate::compile::{self, WithSpan};
use crate::macros::{quote, MacroContext, Quote, ToTokens, TokenStream};
use crate::parse::{Parse, Parser, Peek, Peeker};
use crate::runtime::format;
use crate::runtime::{Inline, Mutable, OwnedValue};
use crate::runtime::{format, Inline};

/// A format specification: A format string followed by arguments to be
/// formatted in accordance with that string.
Expand Down Expand Up @@ -49,14 +48,7 @@ impl FormatArgs {
}
}

let format = format.take_value().with_span(&self.format)?;

let OwnedValue::Mutable(Mutable::String(format)) = format else {
return Err(compile::Error::msg(
&self.format,
"format argument must be a string",
));
};
let format = format.into_any::<String>().with_span(&self.format)?;

let mut unused_pos = (0..pos.len()).try_collect::<BTreeSet<_>>()?;
let mut unused_named = named
Expand Down
3 changes: 1 addition & 2 deletions crates/rune/src/modules/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,7 @@ fn type_of_val(value: Value) -> VmResult<Type> {
/// ```
#[rune::function(instance, protocol = STRING_DISPLAY)]
fn format_type(ty: Type, f: &mut Formatter) -> VmResult<()> {
vm_write!(f, "{:?}", ty);
VmResult::Ok(())
vm_write!(f, "{:?}", ty)
}

/// Get the type name of a value.
Expand Down
3 changes: 1 addition & 2 deletions crates/rune/src/modules/cmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,5 @@ fn ordering_eq(this: Ordering, other: Ordering) -> bool {
/// ```
#[rune::function(instance, protocol = STRING_DEBUG)]
fn ordering_string_debug(this: Ordering, s: &mut Formatter) -> VmResult<()> {
vm_write!(s, "{:?}", this);
VmResult::Ok(())
vm_write!(s, "{:?}", this)
}
8 changes: 4 additions & 4 deletions crates/rune/src/modules/collections/hash_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,21 +516,21 @@ impl HashMap {
f: &mut Formatter,
caller: &mut dyn ProtocolCaller,
) -> VmResult<()> {
vm_write!(f, "{{");
vm_try!(vm_write!(f, "{{"));

let mut it = self.table.iter().peekable();

while let Some((key, value)) = it.next() {
vm_try!(key.string_debug_with(f, caller));
vm_write!(f, ": ");
vm_try!(vm_write!(f, ": "));
vm_try!(value.string_debug_with(f, caller));

if it.peek().is_some() {
vm_write!(f, ", ");
vm_try!(vm_write!(f, ", "));
}
}

vm_write!(f, "}}");
vm_try!(vm_write!(f, "}}"));
VmResult::Ok(())
}

Expand Down
8 changes: 4 additions & 4 deletions crates/rune/src/modules/collections/hash_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,19 +428,19 @@ impl HashSet {
}

fn string_debug_with(&self, f: &mut Formatter, _: &mut dyn ProtocolCaller) -> VmResult<()> {
vm_write!(f, "{{");
vm_try!(vm_write!(f, "{{"));

let mut it = self.table.iter().peekable();

while let Some(value) = it.next() {
vm_write!(f, "{:?}", value);
vm_try!(vm_write!(f, "{:?}", value));

if it.peek().is_some() {
vm_write!(f, ", ");
vm_try!(vm_write!(f, ", "));
}
}

vm_write!(f, "}}");
vm_try!(vm_write!(f, "}}"));
VmResult::Ok(())
}

Expand Down
6 changes: 3 additions & 3 deletions crates/rune/src/modules/collections/vec_deque.rs
Original file line number Diff line number Diff line change
Expand Up @@ -588,17 +588,17 @@ impl VecDeque {
) -> VmResult<()> {
let mut it = self.inner.iter().peekable();

vm_write!(f, "[");
vm_try!(vm_write!(f, "["));

while let Some(value) = it.next() {
vm_try!(value.string_debug_with(f, caller));

if it.peek().is_some() {
vm_write!(f, ", ");
vm_try!(vm_write!(f, ", "));
}
}

vm_write!(f, "]");
vm_try!(vm_write!(f, "]"));
VmResult::Ok(())
}

Expand Down
2 changes: 1 addition & 1 deletion crates/rune/src/modules/f64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ fn partial_cmp(this: f64, rhs: f64) -> Option<Ordering> {
this.partial_cmp(&rhs)
}

/// Perform a partial ordered comparison between two floats.
/// Perform a totally ordered comparison between two floats.
///
/// # Examples
///
Expand Down
3 changes: 1 addition & 2 deletions crates/rune/src/modules/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ pub fn module() -> Result<Module, ContextError> {

#[rune::function(instance, protocol = STRING_DISPLAY)]
fn fmt_error_string_display(error: &fmt::Error, f: &mut Formatter) -> VmResult<()> {
vm_write!(f, "{}", error);
VmResult::Ok(())
vm_write!(f, "{error}")
}

/// Format a string using a format specifier.
Expand Down
2 changes: 1 addition & 1 deletion crates/rune/src/modules/i64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,7 @@ fn partial_cmp(this: i64, rhs: i64) -> Option<Ordering> {
this.partial_cmp(&rhs)
}

/// Perform a partial ordered comparison between two integers.
/// Perform a totally ordered comparison between two integers.
///
/// # Examples
///
Expand Down
11 changes: 9 additions & 2 deletions crates/rune/src/modules/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ pub fn module(
module.ty::<io::Error>()?;
#[cfg(feature = "std")]
module.function_meta(io_error_string_display)?;
#[cfg(feature = "std")]
module.function_meta(io_error_string_debug)?;

#[cfg(feature = "std")]
if stdio {
Expand Down Expand Up @@ -81,8 +83,13 @@ pub fn module(
#[rune::function(instance, protocol = STRING_DISPLAY)]
#[cfg(feature = "std")]
fn io_error_string_display(error: &io::Error, f: &mut Formatter) -> VmResult<()> {
vm_write!(f, "{error}");
VmResult::Ok(())
vm_write!(f, "{error}")
}

#[rune::function(instance, protocol = STRING_DEBUG)]
#[cfg(feature = "std")]
fn io_error_string_debug(error: &io::Error, f: &mut Formatter) -> VmResult<()> {
vm_write!(f, "{error:?}")
}

#[cfg(feature = "std")]
Expand Down
Loading

0 comments on commit 989f41b

Please sign in to comment.