mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-28 10:44:36 +08:00
* Implement _collections.OrderedDict Extracted from #6799: native OrderedDict as a dict subclass, iterator mutation tracking, and mapping-view set operations. * Add OrderedDict, warnings source lines, and socket sendmsg Implement _collections.OrderedDict as a dict subclass with a linked list of insertion-order nodes. Pack struct F/D as native float/double complex pairs, and report unexpected __replace__ field names as a list repr. Register encodings.latin_1 at startup. Reject NUL in input() prompts. Copy non-exact type dicts in mapping order. Fetch warning source lines through _bless_my_loader and unicode splitlines. Keep the last warnings.filters list after deletion. Snapshot sendmsg sequences before converting buffers, parse ancillary ints with __index__, and dispatch AF_CAN by protocol. Store sys.trace and sys.profile on each ThreadSlot so _settraceallthreads/_setprofileallthreads are visible to sys.gettrace/getprofile on other threads. Use <frozen importlib._bootstrap> as frozen importlib co_filename. Keep HEAPTYPE socket objects GC-tracked. Assisted-by: Grok:grok-4.6 * Load marshal via readinto and dump sets in dumps order marshal.load fills a scratch buffer with readinto on a contiguous writable memoryview, and rejects a returned length other than the requested size. set and frozenset dumps write elements in sorted(v, key=marshal.dumps) order. Assisted-by: Grok:grok-4.6 * Add classmethod_descriptor and ABC IS_ABSTRACT flags Give METH_CLASS methods a distinct classmethod_descriptor type. Store Py_TPFLAGS_IS_ABSTRACT from __abstractmethods__ and look up that attribute only in the type's own dict. Expose defaultdict.default_factory as a member descriptor. Inherit bool's unused number slots from int. Mark set and frozenset __contains__ as METH_COEXIST. Parse classmethod, staticmethod, object.__new__, and heap type text signatures. Register interactive source in linecache. Assisted-by: Grok:grok-4.6 * address review: odict reuse, descr call, new wrapper Reuse odict node slots and walk the live list in next_after. Require both | operands to be dicts. Drop the odict iterator on GC clear. Bind classmethod descriptors through descr_get and update IS_ABSTRACT under the type lock. Give odict keys and items sq_contains. Walk tp_new_wrapper past new_wrapper so HEAPTYPE socket subclasses can call socket.__new__. Split FreeBSD Bluetooth protocol constants from Linux values. Assisted-by: Grok:grok-4.6 * Represent chflags bits with bitflagset Assisted-by: Grok:grok-4.6 * Represent access and mode bits with bitflagset Assisted-by: Grok:grok-4.6 * Continue unfinished REPL suites as incomplete input Assisted-by: Grok:grok-4.6 * Add pickle and os.stat inspect signatures Give _pickle.Pickler the clinic constructor text signature and accept fix_imports and buffer_callback as positional-or-keyword. Allow #[pyfunction(text_signature)] and use it so os.stat reports (path, *, dir_fd=None, follow_symlinks=True). Uncomment import _pickle and drop the pickle inspect expectedFailures. Assisted-by: Grok:grok-4.6 * Add Unpickler, dump/load, and lstat signatures Give _pickle Unpickler, dump, dumps, load, and loads clinic text signatures, and os.lstat (path, *, dir_fd=None). Assisted-by: Grok:grok-4.6 * Complete OrderedDict with insertion-order links Move the native OrderedDict into ordered_dict.rs and track order with a linked list of nodes, keeping mapping-view set operations. Assisted-by: Grok:grok-4.6 * address CI: stat casts, HCI_DATA_DIR, passing xfails Compare stat permission bits as Mode so Linux clippy does not flag a u32-to-u32 cast. Export HCI_DATA_DIR with the Bluetooth socket option values. Drop expectedFailure from tests that now pass. Assisted-by: Grok:grok-4.6 * Fix wasm teardown deadlock and bluetooth constants Assisted-by: Grok:grok-4.6 * Clear process-wide eval breaker bits in STW test Assisted-by: Grok:grok-4.6 * Drop exclusive-held panic that tripped wasm clippy Assisted-by: Grok:grok-4.6 * Fix OrderedDict contains and export Windows BDADDR Assisted-by: Grok:grok-4.6 * Add cmp_to_key and hash-once LRU cache _functools.cmp_to_key now returns KeyWrapper. LRU lookups store the key hash on _lru_list_elem so __hash__ is not called again on hits or eviction. Assisted-by: Grok:grok-4.6 * Allow subclass keywords on list, tuple, and float list.__init__ rejects keywords only when tp_new is still list's. tuple/float.__new__ reject them only when tp_init is still the base's. Assisted-by: Grok:grok-4.6 * Fix CI lint, test re-export, and structseq members Drop the duplicate clear_eval_breaker_for_test re-export. Format structseq imports. Expose struct sequence fields as readonly members so assignment raises "readonly attribute". Assisted-by: Grok:grok-4.6 * Allow subclass keywords on itertools and filter Positional-only constructors ignore extra keywords when a subclass has replaced tp_init, matching list/tuple/float. Assisted-by: Grok:grok-4.6 * Remove text_signature derive parameter Drop the string override on #[pyfunction] and #[pyclass]. Signatures are generated from the Rust parameter list only. Restore inspect expectedFailures that depended on the override. Assisted-by: Grok:grok-4.6 * Rename set contains_method to __contains__ Keep a borrowed contains helper for slots and C-API. The coexist pymethod is named __contains__. Assisted-by: Grok:grok-4.6 * Use MonitoringEvent instead of EVENT_* aliases Drop the unused MonitoringEvents bitflags and the EVENT_PY_START style mask constants. Call sites use the enum and .mask(). Assisted-by: Grok:grok-4.6 * Store warnings filters as PyListRef The list already serializes its elements. Drop the extra mutex around the cached list pointer. Assisted-by: Grok:grok-4.6 * Re-export clear_eval_breaker_for_test after rebase Keep the STW test helper visible without bringing back stop_bit_set. Assisted-by: Grok:grok-4.6 * Fix groupby reentrancy and islice arguments Give _grouper its own tgtkey and take currvalue after the key comparison. Accept __index__ on islice bounds, reject step 0, and drain the source up to stop. Assisted-by: Grok:grok-4.6 * SETREF warnings filters, onceregistry, and defaultaction Keep the last list, dict, or str after the module attributes are deleted by swapping the interpreter cache pointer. Do not store a None fallback for _warnings_context. Assisted-by: Grok:grok-4.6 * Iterate OrderedDict inner dict via next_entry &PyDict is not an iterator after the borrowed-ref signature change. Assisted-by: Grok:grok-4.6 * Remove expectedFailure from testBluetoothConstants Linux now exports BTPROTO_HCI and the rest of the set. Assisted-by: Grok:grok-4.6 * Borrow get_filter arguments as PyObject Match the warn_explicit call site that passes borrowed handles after the internal-helper borrow change. Assisted-by: Grok:grok-4.6 * Fix bool slots and SemHandle safety docs Leave unused bool number slots unset so inspect reports __add__ on int. Document SemHandle::from_raw safety. Assisted-by: Grok:grok-4.6 * Keep sendmsg errors and drop duplicate linecache Replace sendmsg iterable TypeError only. Register REPL source in linecache once per compiled input. Assisted-by: Grok:grok-4.6 * Nest REPL parse or-patterns for clippy Assisted-by: Grok:grok-4.6 * Mark pydoc os.stat signature test expectedFailure Assisted-by: Grok:grok-4.6 --------- Co-authored-by: Lee Dogeon <dev.moreal@gmail.com>
340 lines
11 KiB
Rust
340 lines
11 KiB
Rust
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().slot_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().slot_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)
|
|
}
|
|
|
|
/// Default `what_event` for this legacy event.
|
|
#[must_use]
|
|
const fn default_what(self) -> crate::stdlib::sys::monitoring::MonitoringEvent {
|
|
use crate::stdlib::sys::monitoring::MonitoringEvent as Ev;
|
|
match self {
|
|
Self::Call => Ev::PyStart,
|
|
Self::Return => Ev::PyReturn,
|
|
Self::Exception => Ev::Raise,
|
|
Self::Line => Ev::Line,
|
|
Self::Opcode => Ev::Instruction,
|
|
Self::CCall => Ev::Call,
|
|
Self::CReturn => Ev::CReturn,
|
|
Self::CException => Ev::CRaise,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl core::fmt::Display for TraceEvent {
|
|
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
|
match self {
|
|
Self::Call => write!(f, "call"),
|
|
Self::Return => write!(f, "return"),
|
|
Self::Exception => write!(f, "exception"),
|
|
Self::Line => write!(f, "line"),
|
|
Self::Opcode => write!(f, "opcode"),
|
|
Self::CCall => write!(f, "c_call"),
|
|
Self::CReturn => write!(f, "c_return"),
|
|
Self::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>> {
|
|
self.trace_event_what(event, event.default_what(), arg)
|
|
}
|
|
|
|
/// Like [`Self::trace_event`], but records `what` as `tstate->what_event`
|
|
/// for the duration of the callback (so `f_lineno` assignment can tell
|
|
/// a 'line' event from a 'call'/'return'/'exception').
|
|
#[inline]
|
|
pub(crate) fn trace_event_what(
|
|
&self,
|
|
event: TraceEvent,
|
|
what: crate::stdlib::sys::monitoring::MonitoringEvent,
|
|
arg: Option<PyObjectRef>,
|
|
) -> PyResult<Option<PyObjectRef>> {
|
|
if self.use_tracing.get() && !self.tracing_is_suppressed() {
|
|
let old = self.what_event.replace(Some(what));
|
|
let result = self._trace_event_inner(event, arg);
|
|
self.what_event.set(old);
|
|
result
|
|
} 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) = crate::frame::current_thread_frame_materialize(self) else {
|
|
return Ok(None);
|
|
};
|
|
|
|
// Opcode events are only dispatched when f_trace_opcodes is set.
|
|
if is_opcode_event
|
|
&& !frame_ref
|
|
.iframe()
|
|
.cold_opt()
|
|
.is_some_and(|c| *c.trace_opcodes.lock())
|
|
{
|
|
return Ok(None);
|
|
}
|
|
|
|
// trace_trampoline: CALL uses the global callback; every other
|
|
// event uses the per-frame f_trace (and is a no-op if that is unset).
|
|
let callback = if event == TraceEvent::Call {
|
|
if self.is_none(&trace_func) {
|
|
None
|
|
} else {
|
|
Some(trace_func)
|
|
}
|
|
} else {
|
|
frame_ref
|
|
.iframe()
|
|
.cold_opt()
|
|
.and_then(|c| c.trace.lock().clone())
|
|
};
|
|
|
|
let frame: PyObjectRef = frame_ref.to_owned().into();
|
|
let event_str: PyObjectRef = self.ctx.new_str(event.to_string()).into();
|
|
let args = vec![frame, event_str, 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 && let Some(callback) = callback {
|
|
self.use_tracing.set(false);
|
|
self.enter_tracing();
|
|
let res = callback.call(args.clone(), self);
|
|
self.leave_tracing();
|
|
self.use_tracing.set(true);
|
|
match res {
|
|
Ok(result) => {
|
|
if !self.is_none(&result) {
|
|
*frame_ref.iframe().cold().trace.lock() = Some(result.clone());
|
|
trace_result = Some(result);
|
|
}
|
|
}
|
|
Err(e) => {
|
|
// trace_trampoline: disable the global tracer and clear
|
|
// this frame's f_trace, then propagate.
|
|
*self.trace_func.borrow_mut() = self.ctx.none();
|
|
*frame_ref.iframe().cold().trace.lock() = None;
|
|
let profile_is_none = self.is_none(&self.profile_func.borrow());
|
|
self.use_tracing.set(!profile_is_none);
|
|
return Err(e);
|
|
}
|
|
}
|
|
}
|
|
|
|
if is_profile_event && !self.is_none(&profile_func) {
|
|
self.use_tracing.set(false);
|
|
self.enter_tracing();
|
|
let res = profile_func.call(args, self);
|
|
self.leave_tracing();
|
|
self.use_tracing.set(true);
|
|
if res.is_err() {
|
|
*self.profile_func.borrow_mut() = self.ctx.none();
|
|
}
|
|
}
|
|
Ok(trace_result)
|
|
}
|
|
}
|