rune/runtime/
args.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
use core::fmt;

use crate::alloc::Vec;
use crate::runtime::{GuardedArgs, Stack, ToValue, Value, VmResult};

#[derive(Debug)]
#[cfg_attr(test, derive(PartialEq))]
pub(crate) struct DynArgsUsed;

impl fmt::Display for DynArgsUsed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Dynamic arguments have already been used")
    }
}

/// Object safe variant of args which errors instead of consumed itself.
pub(crate) trait DynArgs {
    /// Encode arguments onto a stack.
    fn push_to_stack(&mut self, stack: &mut Stack) -> VmResult<()>;

    /// Get the number of arguments.
    fn count(&self) -> usize;
}

impl DynArgs for () {
    fn push_to_stack(&mut self, _: &mut Stack) -> VmResult<()> {
        VmResult::Ok(())
    }

    fn count(&self) -> usize {
        0
    }
}

impl<T> DynArgs for Option<T>
where
    T: Args,
{
    fn push_to_stack(&mut self, stack: &mut Stack) -> VmResult<()> {
        let Some(args) = self.take() else {
            return VmResult::err(DynArgsUsed);
        };

        vm_try!(args.into_stack(stack));
        VmResult::Ok(())
    }

    fn count(&self) -> usize {
        self.as_ref().map_or(0, Args::count)
    }
}

pub(crate) struct DynGuardedArgs<T>
where
    T: GuardedArgs,
{
    value: Option<T>,
    guard: Option<T::Guard>,
}

impl<T> DynGuardedArgs<T>
where
    T: GuardedArgs,
{
    pub(crate) fn new(value: T) -> Self {
        Self {
            value: Some(value),
            guard: None,
        }
    }
}

impl<T> DynArgs for DynGuardedArgs<T>
where
    T: GuardedArgs,
{
    fn push_to_stack(&mut self, stack: &mut Stack) -> VmResult<()> {
        let Some(value) = self.value.take() else {
            return VmResult::err(DynArgsUsed);
        };

        // SAFETY: We've setup the type so that the caller cannot ignore the guard.
        self.guard = unsafe { Some(vm_try!(GuardedArgs::guarded_into_stack(value, stack))) };

        VmResult::Ok(())
    }

    fn count(&self) -> usize {
        self.value.as_ref().map_or(0, GuardedArgs::count)
    }
}

/// Trait for converting arguments into an array.
pub trait FixedArgs<const N: usize> {
    /// Encode arguments as array.
    fn into_array(self) -> VmResult<[Value; N]>;
}

/// Trait for converting arguments onto the stack.
pub trait Args {
    /// Encode arguments onto a stack.
    fn into_stack(self, stack: &mut Stack) -> VmResult<()>;

    /// Convert arguments into a vector.
    fn try_into_vec(self) -> VmResult<Vec<Value>>;

    /// The number of arguments.
    fn count(&self) -> usize;
}

macro_rules! impl_into_args {
    ($count:expr $(, $ty:ident $value:ident $_:expr)*) => {
        impl<$($ty,)*> FixedArgs<$count> for ($($ty,)*)
        where
            $($ty: ToValue,)*
        {
            #[allow(unused)]
            fn into_array(self) -> VmResult<[Value; $count]> {
                let ($($value,)*) = self;
                $(let $value = vm_try!($value.to_value());)*
                VmResult::Ok([$($value),*])
            }
        }

        impl<$($ty,)*> Args for ($($ty,)*)
        where
            $($ty: ToValue,)*
        {
            #[allow(unused)]
            fn into_stack(self, stack: &mut Stack) -> VmResult<()> {
                let ($($value,)*) = self;
                $(vm_try!(stack.push(vm_try!($value.to_value())));)*
                VmResult::Ok(())
            }

            #[allow(unused)]
            fn try_into_vec(self) -> VmResult<Vec<Value>> {
                let ($($value,)*) = self;
                let mut vec = vm_try!(Vec::try_with_capacity($count));
                $(vm_try!(vec.try_push(vm_try!(<$ty>::to_value($value))));)*
                VmResult::Ok(vec)
            }

            #[inline]
            fn count(&self) -> usize {
                $count
            }
        }
    };
}

repeat_macro!(impl_into_args);

impl Args for Vec<Value> {
    fn into_stack(self, stack: &mut Stack) -> VmResult<()> {
        for value in self {
            vm_try!(stack.push(value));
        }

        VmResult::Ok(())
    }

    #[inline]
    fn try_into_vec(self) -> VmResult<Vec<Value>> {
        VmResult::Ok(self)
    }

    #[inline]
    fn count(&self) -> usize {
        self.len()
    }
}

#[cfg(feature = "alloc")]
impl Args for ::rust_alloc::vec::Vec<Value> {
    fn into_stack(self, stack: &mut Stack) -> VmResult<()> {
        for value in self {
            vm_try!(stack.push(value));
        }

        VmResult::Ok(())
    }

    #[inline]
    fn try_into_vec(self) -> VmResult<Vec<Value>> {
        VmResult::Ok(vm_try!(Vec::try_from(self)))
    }

    #[inline]
    fn count(&self) -> usize {
        self.len()
    }
}