1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
use super::IntoFuncArgs;
use crate::{
    builtins::{iter::PySequenceIterator, PyDict, PyDictRef},
    convert::ToPyObject,
    identifier,
    object::{Traverse, TraverseFn},
    protocol::{PyIter, PyIterIter, PyMapping, PyMappingMethods},
    types::{AsMapping, GenericMethod},
    AsObject, PyObject, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine,
};
use std::{borrow::Borrow, marker::PhantomData, ops::Deref};

#[derive(Clone, Traverse)]
pub struct ArgCallable {
    obj: PyObjectRef,
    #[pytraverse(skip)]
    call: GenericMethod,
}

impl ArgCallable {
    #[inline(always)]
    pub fn invoke(&self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult {
        let args = args.into_args(vm);
        (self.call)(&self.obj, args, vm)
    }
}

impl std::fmt::Debug for ArgCallable {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ArgCallable")
            .field("obj", &self.obj)
            .field("call", &format!("{:08x}", self.call as usize))
            .finish()
    }
}

impl Borrow<PyObject> for ArgCallable {
    #[inline(always)]
    fn borrow(&self) -> &PyObject {
        &self.obj
    }
}

impl AsRef<PyObject> for ArgCallable {
    #[inline(always)]
    fn as_ref(&self) -> &PyObject {
        &self.obj
    }
}

impl From<ArgCallable> for PyObjectRef {
    #[inline(always)]
    fn from(value: ArgCallable) -> PyObjectRef {
        value.obj
    }
}

impl TryFromObject for ArgCallable {
    fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
        let Some(callable) = obj.to_callable() else {
            return Err(
                vm.new_type_error(format!("'{}' object is not callable", obj.class().name()))
            );
        };
        let call = callable.call;
        Ok(ArgCallable { obj, call })
    }
}

/// An iterable Python object.
///
/// `ArgIterable` implements `FromArgs` so that a built-in function can accept
/// an object that is required to conform to the Python iterator protocol.
///
/// ArgIterable can optionally perform type checking and conversions on iterated
/// objects using a generic type parameter that implements `TryFromObject`.
pub struct ArgIterable<T = PyObjectRef> {
    iterable: PyObjectRef,
    iterfn: Option<crate::types::IterFunc>,
    _item: PhantomData<T>,
}

unsafe impl<T: Traverse> Traverse for ArgIterable<T> {
    fn traverse(&self, tracer_fn: &mut TraverseFn) {
        self.iterable.traverse(tracer_fn)
    }
}

impl<T> ArgIterable<T> {
    /// Returns an iterator over this sequence of objects.
    ///
    /// This operation may fail if an exception is raised while invoking the
    /// `__iter__` method of the iterable object.
    pub fn iter<'a>(&self, vm: &'a VirtualMachine) -> PyResult<PyIterIter<'a, T>> {
        let iter = PyIter::new(match self.iterfn {
            Some(f) => f(self.iterable.clone(), vm)?,
            None => PySequenceIterator::new(self.iterable.clone(), vm)?.into_pyobject(vm),
        });
        iter.into_iter(vm)
    }
}

impl<T> TryFromObject for ArgIterable<T>
where
    T: TryFromObject,
{
    fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
        let iterfn = {
            let cls = obj.class();
            let iterfn = cls.mro_find_map(|x| x.slots.iter.load());
            if iterfn.is_none() && !cls.has_attr(identifier!(vm, __getitem__)) {
                return Err(vm.new_type_error(format!("'{}' object is not iterable", cls.name())));
            }
            iterfn
        };
        Ok(Self {
            iterable: obj,
            iterfn,
            _item: PhantomData,
        })
    }
}

#[derive(Debug, Clone, Traverse)]
pub struct ArgMapping {
    obj: PyObjectRef,
    #[pytraverse(skip)]
    methods: &'static PyMappingMethods,
}

impl ArgMapping {
    #[inline]
    pub fn with_methods(obj: PyObjectRef, methods: &'static PyMappingMethods) -> Self {
        Self { obj, methods }
    }

    #[inline(always)]
    pub fn from_dict_exact(dict: PyDictRef) -> Self {
        Self {
            obj: dict.into(),
            methods: PyDict::as_mapping(),
        }
    }

    #[inline(always)]
    pub fn mapping(&self) -> PyMapping {
        PyMapping {
            obj: &self.obj,
            methods: self.methods,
        }
    }
}

impl Borrow<PyObject> for ArgMapping {
    #[inline(always)]
    fn borrow(&self) -> &PyObject {
        &self.obj
    }
}

impl AsRef<PyObject> for ArgMapping {
    #[inline(always)]
    fn as_ref(&self) -> &PyObject {
        &self.obj
    }
}

impl Deref for ArgMapping {
    type Target = PyObject;
    #[inline(always)]
    fn deref(&self) -> &PyObject {
        &self.obj
    }
}

impl From<ArgMapping> for PyObjectRef {
    #[inline(always)]
    fn from(value: ArgMapping) -> PyObjectRef {
        value.obj
    }
}

impl ToPyObject for ArgMapping {
    #[inline(always)]
    fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef {
        self.obj
    }
}

impl TryFromObject for ArgMapping {
    fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
        let mapping = PyMapping::try_protocol(&obj, vm)?;
        let methods = mapping.methods;
        Ok(Self { obj, methods })
    }
}

// this is not strictly related to PySequence protocol.
#[derive(Clone)]
pub struct ArgSequence<T = PyObjectRef>(Vec<T>);

unsafe impl<T: Traverse> Traverse for ArgSequence<T> {
    fn traverse(&self, tracer_fn: &mut TraverseFn) {
        self.0.traverse(tracer_fn);
    }
}

impl<T> ArgSequence<T> {
    #[inline(always)]
    pub fn into_vec(self) -> Vec<T> {
        self.0
    }
    #[inline(always)]
    pub fn as_slice(&self) -> &[T] {
        &self.0
    }
}

impl<T> std::ops::Deref for ArgSequence<T> {
    type Target = [T];
    #[inline(always)]
    fn deref(&self) -> &[T] {
        self.as_slice()
    }
}

impl<T: TryFromObject> TryFromObject for ArgSequence<T> {
    fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
        obj.try_to_value(vm).map(Self)
    }
}