Skip to main content

datex_core/traits/
apply.rs

1use core::fmt::Display;
2
3use crate::{
4    global::stack_index::StackIndex,
5    prelude::*,
6    runtime::Runtime,
7    types::type_definition::callable::InvalidArgumentError,
8    values::{
9        core_values::callable::error::CallableError, value::Value,
10        value_container::ValueContainer,
11    },
12};
13use alloc::boxed::Box;
14
15#[derive(Debug, PartialEq, Eq)]
16pub enum ApplyError {
17    UnsupportedApply,
18    AsyncCallableRequiresAsyncExecution,
19    CallableError(Box<CallableError>),
20    InvalidArgumentError(Box<InvalidArgumentError>),
21}
22impl Display for ApplyError {
23    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
24        match self {
25            ApplyError::UnsupportedApply => {
26                write!(f, "Value does not support apply operation")
27            }
28            ApplyError::CallableError(error) => {
29                write!(f, "Error during callable application: {}", error)
30            }
31            ApplyError::AsyncCallableRequiresAsyncExecution => {
32                write!(f, "Async callable requires async execution")
33            }
34            ApplyError::InvalidArgumentError(error) => {
35                write!(f, "{}", error)
36            }
37        }
38    }
39}
40impl From<CallableError> for ApplyError {
41    fn from(error: CallableError) -> Self {
42        ApplyError::CallableError(Box::new(error))
43    }
44}
45impl From<InvalidArgumentError> for ApplyError {
46    fn from(error: InvalidArgumentError) -> Self {
47        ApplyError::InvalidArgumentError(Box::new(error))
48    }
49}
50
51/// Represents an argument to be applied to a callable value.
52#[derive(Debug)]
53pub struct ApplyArgument {
54    /// The value of the argument to be applied.
55    pub value: ValueContainer,
56    /// If the argument is passed as a local reference, the `passed_as_ref` field is set to true.
57    pub passed_as_ref: bool,
58}
59
60impl ApplyArgument {
61    pub fn referenced<T: Into<ValueContainer>>(value: T) -> Self {
62        ApplyArgument {
63            value: value.into(),
64            passed_as_ref: true,
65        }
66    }
67    pub fn owned<T: Into<ValueContainer>>(value: T) -> Self {
68        ApplyArgument {
69            value: value.into(),
70            passed_as_ref: false,
71        }
72    }
73}
74
75impl From<ValueContainer> for ApplyArgument {
76    fn from(value: ValueContainer) -> Self {
77        ApplyArgument::owned(value)
78    }
79}
80
81impl<T: Into<Value>> From<T> for ApplyArgument {
82    fn from(value: T) -> Self {
83        ApplyArgument {
84            value: ValueContainer::Local(value.into()),
85            passed_as_ref: false,
86        }
87    }
88}
89
90impl From<ApplyArgument> for ValueContainer {
91    fn from(arg: ApplyArgument) -> Self {
92        arg.value
93    }
94}
95
96/// Returns a vector of ValueContainers for all arguments that were passed as local references.
97pub fn get_borrowed_apply_argument_values(
98    values: Vec<ApplyArgument>,
99) -> Vec<ValueContainer> {
100    values
101        .into_iter()
102        .filter(|arg| arg.passed_as_ref)
103        .map(|arg| arg.value)
104        .collect()
105}
106
107/// Returns a vector of ApplyArguments with the passed_as_ref field set based on the provided borrowed_args_stack_indices.
108pub fn into_apply_arguments_with_stack_indices(
109    values: Vec<ValueContainer>,
110    borrowed_args_stack_indices: &[Option<StackIndex>],
111) -> Vec<ApplyArgument> {
112    values
113        .into_iter()
114        .enumerate()
115        .map(|(i, v)| ApplyArgument {
116            value: v,
117            passed_as_ref: borrowed_args_stack_indices[i].is_some(),
118        })
119        .collect()
120}
121
122// TODO #351: return ApplyErrors including call stack information (or store call stack directly in ExecutionError)
123pub trait Apply {
124    /// Calls the [try_apply_sync] method and checks that the number of returned local references
125    /// matches the number of arguments that were passed as local references.
126    fn try_apply_sync_checked(
127        &self,
128        runtime: &Runtime,
129        args: Vec<ApplyArgument>,
130    ) -> Result<(Option<ValueContainer>, Vec<ValueContainer>), ApplyError> {
131        let expected_ref_count =
132            args.iter().filter(|arg| arg.passed_as_ref).count();
133        let res = self.try_apply_sync(runtime, args)?;
134
135        if res.1.len() != expected_ref_count {
136            return Err(ApplyError::CallableError(Box::new(
137                CallableError::LostBorrowedArguments {
138                    expected: expected_ref_count,
139                    actual: res.1.len(),
140                },
141            )));
142        }
143
144        Ok(res)
145    }
146
147    /// Calls the [try_apply_async] method and checks that the number of returned local references
148    /// matches the number of arguments that were passed as local references.
149    async fn try_apply_async_checked(
150        &self,
151        runtime: &Runtime,
152        args: Vec<ApplyArgument>,
153    ) -> Result<(Option<ValueContainer>, Vec<ValueContainer>), ApplyError> {
154        let expected_ref_count =
155            args.iter().filter(|arg| arg.passed_as_ref).count();
156        let res = self.try_apply_async(runtime, args).await?;
157
158        if res.1.len() != expected_ref_count {
159            return Err(ApplyError::CallableError(Box::new(
160                CallableError::LostBorrowedArguments {
161                    expected: expected_ref_count,
162                    actual: res.1.len(),
163                },
164            )));
165        }
166
167        Ok(res)
168    }
169
170    /// Applies multiple ValueContainer arguments to self
171    /// Returns an Error if the value does not support sync apply.
172    /// The return value is a tuple of the return value of the apply operation,
173    /// and a vector containing all value containers for apply arguments that were passed as local references.
174    /// Note: the count of the returned [Vec<ValueContainer>] corresponds to the count of arguments that have [passed_as_ref] set to [true].
175    fn try_apply_sync(
176        &self,
177        runtime: &Runtime,
178        args: Vec<ApplyArgument>,
179    ) -> Result<(Option<ValueContainer>, Vec<ValueContainer>), ApplyError>;
180
181    /// Applies multiple ValueContainer arguments to self on a sync or async callable.
182    /// The return value is a tuple of the return value of the apply operation,
183    /// and a vector containing all value containers for apply arguments that were passed as local references.
184    /// Note: the count of the returned [Vec<ValueContainer>] corresponds to the count of arguments that have [passed_as_ref] set to [true].
185    async fn try_apply_async(
186        &self,
187        runtime: &Runtime,
188        args: Vec<ApplyArgument>,
189    ) -> Result<(Option<ValueContainer>, Vec<ValueContainer>), ApplyError>;
190}