forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcallable.rs
More file actions
280 lines (258 loc) · 9.14 KB
/
Copy pathcallable.rs
File metadata and controls
280 lines (258 loc) · 9.14 KB
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
use crate::{
builtins::{PyBoundMethod, PyFunction},
function::{FuncArgs, IntoFuncArgs},
types::{GenericMethod, VectorCallFunc},
{PyObject, PyObjectRef, PyResult, VirtualMachine},
};
impl PyObject {
#[inline]
#[must_use]
pub fn to_callable(&self) -> Option<PyCallable<'_>> {
PyCallable::new(self)
}
#[inline]
#[must_use]
pub fn is_callable(&self) -> bool {
self.to_callable().is_some()
}
/// PyObject_Call*Arg* series
#[inline]
pub fn call(&self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult {
let args = args.into_args(vm);
self.call_with_args(args, vm)
}
/// PyObject_Call
pub fn call_with_args(&self, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
let Some(callable) = self.to_callable() else {
return Err(
vm.new_type_error(format!("'{}' object is not callable", self.class().name()))
);
};
vm_trace!("Invoke: {:?} {:?}", callable, args);
callable.invoke(args, vm)
}
/// Vectorcall: call with owned positional args + optional kwnames.
/// Falls back to FuncArgs-based call if no vectorcall slot.
#[inline]
pub fn vectorcall(
&self,
args: Vec<PyObjectRef>,
nargs: usize,
kwnames: Option<&[PyObjectRef]>,
vm: &VirtualMachine,
) -> PyResult {
let Some(callable) = self.to_callable() else {
return Err(
vm.new_type_error(format!("'{}' object is not callable", self.class().name()))
);
};
callable.invoke_vectorcall(args, nargs, kwnames, vm)
}
}
#[derive(Debug)]
pub struct PyCallable<'a> {
pub obj: &'a PyObject,
pub call: GenericMethod,
pub vectorcall: Option<VectorCallFunc>,
}
impl<'a> PyCallable<'a> {
pub fn new(obj: &'a PyObject) -> Option<Self> {
let slots = &obj.class().slots;
let call = slots.call.load()?;
let vectorcall = slots.vectorcall.load();
Some(PyCallable {
obj,
call,
vectorcall,
})
}
pub fn invoke(&self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult {
let args = args.into_args(vm);
if !vm.use_tracing.get() {
return (self.call)(self.obj, args, vm);
}
// Python functions get 'call'/'return' events from with_frame().
// Bound methods delegate to the inner callable, which fires its own events.
// All other callables (built-in functions, etc.) get 'c_call'/'c_return'/'c_exception'.
let is_python_callable = self.obj.downcast_ref::<PyFunction>().is_some()
|| self.obj.downcast_ref::<PyBoundMethod>().is_some();
if is_python_callable {
(self.call)(self.obj, args, vm)
} else {
let callable = self.obj.to_owned();
vm.trace_event(TraceEvent::CCall, Some(callable.clone()))?;
let result = (self.call)(self.obj, args, vm);
if result.is_ok() {
vm.trace_event(TraceEvent::CReturn, Some(callable))?;
} else {
let _ = vm.trace_event(TraceEvent::CException, Some(callable));
}
result
}
}
/// Vectorcall dispatch: use vectorcall slot if available, else fall back to FuncArgs.
#[inline]
pub fn invoke_vectorcall(
&self,
args: Vec<PyObjectRef>,
nargs: usize,
kwnames: Option<&[PyObjectRef]>,
vm: &VirtualMachine,
) -> PyResult {
if let Some(vc) = self.vectorcall {
if !vm.use_tracing.get() {
return vc(self.obj, args, nargs, kwnames, vm);
}
let is_python_callable = self.obj.downcast_ref::<PyFunction>().is_some()
|| self.obj.downcast_ref::<PyBoundMethod>().is_some();
if is_python_callable {
vc(self.obj, args, nargs, kwnames, vm)
} else {
let callable = self.obj.to_owned();
vm.trace_event(TraceEvent::CCall, Some(callable.clone()))?;
let result = vc(self.obj, args, nargs, kwnames, vm);
if result.is_ok() {
vm.trace_event(TraceEvent::CReturn, Some(callable))?;
} else {
let _ = vm.trace_event(TraceEvent::CException, Some(callable));
}
result
}
} else {
// Fallback: convert owned Vec to FuncArgs (move, no clone)
let func_args = FuncArgs::from_vectorcall_owned(args, nargs, kwnames);
self.invoke(func_args, vm)
}
}
}
/// Trace events for sys.settrace and sys.setprofile.
#[derive(Clone, Copy, Eq, PartialEq)]
pub(crate) enum TraceEvent {
Call,
Return,
Exception,
Line,
Opcode,
CCall,
CReturn,
CException,
}
impl TraceEvent {
/// Whether sys.settrace receives this event.
#[must_use]
const fn is_trace_event(&self) -> bool {
matches!(
self,
Self::Call | Self::Return | Self::Exception | Self::Line | Self::Opcode
)
}
/// Whether sys.setprofile receives this event.
/// In legacy_tracing.c, profile callbacks are only registered for
/// PY_RETURN, PY_UNWIND, C_CALL, C_RETURN, C_RAISE.
#[must_use]
const fn is_profile_event(&self) -> bool {
matches!(
self,
Self::Call | Self::Return | Self::CCall | Self::CReturn | Self::CException
)
}
/// Whether this event is dispatched only when f_trace_opcodes is set.
#[must_use]
pub(crate) const fn is_opcode_event(&self) -> bool {
matches!(self, Self::Opcode)
}
}
impl core::fmt::Display for TraceEvent {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
use TraceEvent::*;
match self {
Call => write!(f, "call"),
Return => write!(f, "return"),
Exception => write!(f, "exception"),
Line => write!(f, "line"),
Opcode => write!(f, "opcode"),
CCall => write!(f, "c_call"),
CReturn => write!(f, "c_return"),
CException => write!(f, "c_exception"),
}
}
}
impl VirtualMachine {
/// Call registered trace function.
///
/// Returns the trace function's return value:
/// - `Some(obj)` if the trace function returned a non-None value
/// - `None` if it returned Python None or no trace function was active
///
/// In CPython's trace protocol:
/// - For 'call' events: the return value determines the per-frame `f_trace`
/// - For 'line'/'return' events: the return value can update `f_trace`
#[inline]
pub(crate) fn trace_event(
&self,
event: TraceEvent,
arg: Option<PyObjectRef>,
) -> PyResult<Option<PyObjectRef>> {
if self.use_tracing.get() {
self._trace_event_inner(event, arg)
} else {
Ok(None)
}
}
fn _trace_event_inner(
&self,
event: TraceEvent,
arg: Option<PyObjectRef>,
) -> PyResult<Option<PyObjectRef>> {
let trace_func = self.trace_func.borrow().to_owned();
let profile_func = self.profile_func.borrow().to_owned();
if self.is_none(&trace_func) && self.is_none(&profile_func) {
return Ok(None);
}
let is_trace_event = event.is_trace_event();
let is_profile_event = event.is_profile_event();
let is_opcode_event = event.is_opcode_event();
let Some(frame_ref) = self.current_frame() else {
return Ok(None);
};
// Opcode events are only dispatched when f_trace_opcodes is set.
if is_opcode_event && !*frame_ref.trace_opcodes.lock() {
return Ok(None);
}
let frame: PyObjectRef = frame_ref.into();
let event = self.ctx.new_str(event.to_string()).into();
let args = vec![frame, event, arg.unwrap_or_else(|| self.ctx.none())];
let mut trace_result = None;
// temporarily disable tracing, during the call to the
// tracing function itself.
if is_trace_event && !self.is_none(&trace_func) {
self.use_tracing.set(false);
let res = trace_func.call(args.clone(), self);
self.use_tracing.set(true);
match res {
Ok(result) => {
if !self.is_none(&result) {
trace_result = Some(result);
}
}
Err(e) => {
// trace_trampoline behavior: clear per-frame f_trace
// and propagate the error.
if let Some(frame_ref) = self.current_frame() {
*frame_ref.trace.lock() = self.ctx.none();
}
return Err(e);
}
}
}
if is_profile_event && !self.is_none(&profile_func) {
self.use_tracing.set(false);
let res = profile_func.call(args, self);
self.use_tracing.set(true);
if res.is_err() {
*self.profile_func.borrow_mut() = self.ctx.none();
}
}
Ok(trace_result)
}
}