repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/codecs.rs
crates/vm/src/codecs.rs
use rustpython_common::{ borrow::BorrowedValue, encodings::{ CodecContext, DecodeContext, DecodeErrorHandler, EncodeContext, EncodeErrorHandler, EncodeReplace, StrBuffer, StrSize, errors, }, str::StrKind, wtf8::{CodePoint, Wtf8, Wtf8Buf}, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine, builtins::{PyBaseExceptionRef, PyBytes, PyBytesRef, PyStr, PyStrRef, PyTuple, PyTupleRef}, common::{ascii, lock::PyRwLock}, convert::ToPyObject, function::{ArgBytesLike, PyMethodDef}, }; use alloc::borrow::Cow; use core::ops::{self, Range}; use once_cell::unsync::OnceCell; use std::collections::HashMap; pub struct CodecsRegistry { inner: PyRwLock<RegistryInner>, } struct RegistryInner { search_path: Vec<PyObjectRef>, search_cache: HashMap<String, PyCodec>, errors: HashMap<String, PyObjectRef>, } pub const DEFAULT_ENCODING: &str = "utf-8"; #[derive(Clone)] #[repr(transparent)] pub struct PyCodec(PyTupleRef); impl PyCodec { #[inline] pub fn from_tuple(tuple: PyTupleRef) -> Result<Self, PyTupleRef> { if tuple.len() == 4 { Ok(Self(tuple)) } else { Err(tuple) } } #[inline] pub fn into_tuple(self) -> PyTupleRef { self.0 } #[inline] pub fn as_tuple(&self) -> &Py<PyTuple> { &self.0 } #[inline] pub fn get_encode_func(&self) -> &PyObject { &self.0[0] } #[inline] pub fn get_decode_func(&self) -> &PyObject { &self.0[1] } pub fn is_text_codec(&self, vm: &VirtualMachine) -> PyResult<bool> { let is_text = vm.get_attribute_opt(self.0.clone().into(), "_is_text_encoding")?; is_text.map_or(Ok(true), |is_text| is_text.try_to_bool(vm)) } pub fn encode( &self, obj: PyObjectRef, errors: Option<PyStrRef>, vm: &VirtualMachine, ) -> PyResult { let args = match errors { Some(errors) => vec![obj, errors.into()], None => vec![obj], }; let res = self.get_encode_func().call(args, vm)?; let res = res .downcast::<PyTuple>() .ok() .filter(|tuple| tuple.len() == 2) .ok_or_else(|| vm.new_type_error("encoder must return a tuple (object, integer)"))?; // we don't actually care about the integer Ok(res[0].clone()) } pub fn decode( &self, obj: PyObjectRef, errors: Option<PyStrRef>, vm: &VirtualMachine, ) -> PyResult { let args = match errors { Some(errors) => vec![obj, errors.into()], None => vec![obj], }; let res = self.get_decode_func().call(args, vm)?; let res = res .downcast::<PyTuple>() .ok() .filter(|tuple| tuple.len() == 2) .ok_or_else(|| vm.new_type_error("decoder must return a tuple (object,integer)"))?; // we don't actually care about the integer Ok(res[0].clone()) } pub fn get_incremental_encoder( &self, errors: Option<PyStrRef>, vm: &VirtualMachine, ) -> PyResult { let args = match errors { Some(e) => vec![e.into()], None => vec![], }; vm.call_method(self.0.as_object(), "incrementalencoder", args) } pub fn get_incremental_decoder( &self, errors: Option<PyStrRef>, vm: &VirtualMachine, ) -> PyResult { let args = match errors { Some(e) => vec![e.into()], None => vec![], }; vm.call_method(self.0.as_object(), "incrementaldecoder", args) } } impl TryFromObject for PyCodec { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { obj.downcast::<PyTuple>() .ok() .and_then(|tuple| Self::from_tuple(tuple).ok()) .ok_or_else(|| vm.new_type_error("codec search functions must return 4-tuples")) } } impl ToPyObject for PyCodec { #[inline] fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { self.0.into() } } impl CodecsRegistry { pub(crate) fn new(ctx: &Context) -> Self { ::rustpython_vm::common::static_cell! { static METHODS: Box<[PyMethodDef]>; } let methods = METHODS.get_or_init(|| { crate::define_methods![ "strict_errors" => strict_errors as EMPTY, "ignore_errors" => ignore_errors as EMPTY, "replace_errors" => replace_errors as EMPTY, "xmlcharrefreplace_errors" => xmlcharrefreplace_errors as EMPTY, "backslashreplace_errors" => backslashreplace_errors as EMPTY, "namereplace_errors" => namereplace_errors as EMPTY, "surrogatepass_errors" => surrogatepass_errors as EMPTY, "surrogateescape_errors" => surrogateescape_errors as EMPTY ] .into_boxed_slice() }); let errors = [ ("strict", methods[0].build_function(ctx)), ("ignore", methods[1].build_function(ctx)), ("replace", methods[2].build_function(ctx)), ("xmlcharrefreplace", methods[3].build_function(ctx)), ("backslashreplace", methods[4].build_function(ctx)), ("namereplace", methods[5].build_function(ctx)), ("surrogatepass", methods[6].build_function(ctx)), ("surrogateescape", methods[7].build_function(ctx)), ]; let errors = errors .into_iter() .map(|(name, f)| (name.to_owned(), f.into())) .collect(); let inner = RegistryInner { search_path: Vec::new(), search_cache: HashMap::new(), errors, }; Self { inner: PyRwLock::new(inner), } } pub fn register(&self, search_function: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { if !search_function.is_callable() { return Err(vm.new_type_error("argument must be callable")); } self.inner.write().search_path.push(search_function); Ok(()) } pub fn unregister(&self, search_function: PyObjectRef) -> PyResult<()> { let mut inner = self.inner.write(); // Do nothing if search_path is not created yet or was cleared. if inner.search_path.is_empty() { return Ok(()); } for (i, item) in inner.search_path.iter().enumerate() { if item.get_id() == search_function.get_id() { if !inner.search_cache.is_empty() { inner.search_cache.clear(); } inner.search_path.remove(i); return Ok(()); } } Ok(()) } pub(crate) fn register_manual(&self, name: &str, codec: PyCodec) -> PyResult<()> { self.inner .write() .search_cache .insert(name.to_owned(), codec); Ok(()) } pub fn lookup(&self, encoding: &str, vm: &VirtualMachine) -> PyResult<PyCodec> { let encoding = normalize_encoding_name(encoding); let search_path = { let inner = self.inner.read(); if let Some(codec) = inner.search_cache.get(encoding.as_ref()) { // hit cache return Ok(codec.clone()); } inner.search_path.clone() }; let encoding = PyStr::from(encoding.into_owned()).into_ref(&vm.ctx); for func in search_path { let res = func.call((encoding.clone(),), vm)?; let res: Option<PyCodec> = res.try_into_value(vm)?; if let Some(codec) = res { let mut inner = self.inner.write(); // someone might have raced us to this, so use theirs let codec = inner .search_cache .entry(encoding.as_str().to_owned()) .or_insert(codec); return Ok(codec.clone()); } } Err(vm.new_lookup_error(format!("unknown encoding: {encoding}"))) } fn _lookup_text_encoding( &self, encoding: &str, generic_func: &str, vm: &VirtualMachine, ) -> PyResult<PyCodec> { let codec = self.lookup(encoding, vm)?; if codec.is_text_codec(vm)? { Ok(codec) } else { Err(vm.new_lookup_error(format!( "'{encoding}' is not a text encoding; use {generic_func} to handle arbitrary codecs" ))) } } pub fn forget(&self, encoding: &str) -> Option<PyCodec> { let encoding = normalize_encoding_name(encoding); self.inner.write().search_cache.remove(encoding.as_ref()) } pub fn encode( &self, obj: PyObjectRef, encoding: &str, errors: Option<PyStrRef>, vm: &VirtualMachine, ) -> PyResult { let codec = self.lookup(encoding, vm)?; codec.encode(obj, errors, vm) } pub fn decode( &self, obj: PyObjectRef, encoding: &str, errors: Option<PyStrRef>, vm: &VirtualMachine, ) -> PyResult { let codec = self.lookup(encoding, vm)?; codec.decode(obj, errors, vm) } pub fn encode_text( &self, obj: PyStrRef, encoding: &str, errors: Option<PyStrRef>, vm: &VirtualMachine, ) -> PyResult<PyBytesRef> { let codec = self._lookup_text_encoding(encoding, "codecs.encode()", vm)?; codec .encode(obj.into(), errors, vm)? .downcast() .map_err(|obj| { vm.new_type_error(format!( "'{}' encoder returned '{}' instead of 'bytes'; use codecs.encode() to \ encode arbitrary types", encoding, obj.class().name(), )) }) } pub fn decode_text( &self, obj: PyObjectRef, encoding: &str, errors: Option<PyStrRef>, vm: &VirtualMachine, ) -> PyResult<PyStrRef> { let codec = self._lookup_text_encoding(encoding, "codecs.decode()", vm)?; codec.decode(obj, errors, vm)?.downcast().map_err(|obj| { vm.new_type_error(format!( "'{}' decoder returned '{}' instead of 'str'; use codecs.decode() \ to encode arbitrary types", encoding, obj.class().name(), )) }) } pub fn register_error(&self, name: String, handler: PyObjectRef) -> Option<PyObjectRef> { self.inner.write().errors.insert(name, handler) } pub fn lookup_error_opt(&self, name: &str) -> Option<PyObjectRef> { self.inner.read().errors.get(name).cloned() } pub fn lookup_error(&self, name: &str, vm: &VirtualMachine) -> PyResult<PyObjectRef> { self.lookup_error_opt(name) .ok_or_else(|| vm.new_lookup_error(format!("unknown error handler name '{name}'"))) } } fn normalize_encoding_name(encoding: &str) -> Cow<'_, str> { if let Some(i) = encoding.find(|c: char| c == ' ' || c.is_ascii_uppercase()) { let mut out = encoding.as_bytes().to_owned(); for byte in &mut out[i..] { if *byte == b' ' { *byte = b'-'; } else { byte.make_ascii_lowercase(); } } String::from_utf8(out).unwrap().into() } else { encoding.into() } } #[derive(Eq, PartialEq)] enum StandardEncoding { Utf8, Utf16Be, Utf16Le, Utf32Be, Utf32Le, } impl StandardEncoding { #[cfg(target_endian = "little")] const UTF_16_NE: Self = Self::Utf16Le; #[cfg(target_endian = "big")] const UTF_16_NE: Self = Self::Utf16Be; #[cfg(target_endian = "little")] const UTF_32_NE: Self = Self::Utf32Le; #[cfg(target_endian = "big")] const UTF_32_NE: Self = Self::Utf32Be; fn parse(encoding: &str) -> Option<Self> { if let Some(encoding) = encoding.to_lowercase().strip_prefix("utf") { let encoding = encoding .strip_prefix(|c| ['-', '_'].contains(&c)) .unwrap_or(encoding); if encoding == "8" { Some(Self::Utf8) } else if let Some(encoding) = encoding.strip_prefix("16") { if encoding.is_empty() { return Some(Self::UTF_16_NE); } let encoding = encoding.strip_prefix(['-', '_']).unwrap_or(encoding); match encoding { "be" => Some(Self::Utf16Be), "le" => Some(Self::Utf16Le), _ => None, } } else if let Some(encoding) = encoding.strip_prefix("32") { if encoding.is_empty() { return Some(Self::UTF_32_NE); } let encoding = encoding.strip_prefix(['-', '_']).unwrap_or(encoding); match encoding { "be" => Some(Self::Utf32Be), "le" => Some(Self::Utf32Le), _ => None, } } else { None } } else if encoding == "CP_UTF8" { Some(Self::Utf8) } else { None } } } struct SurrogatePass; impl<'a> EncodeErrorHandler<PyEncodeContext<'a>> for SurrogatePass { fn handle_encode_error( &self, ctx: &mut PyEncodeContext<'a>, range: Range<StrSize>, reason: Option<&str>, ) -> PyResult<(EncodeReplace<PyEncodeContext<'a>>, StrSize)> { let standard_encoding = StandardEncoding::parse(ctx.encoding) .ok_or_else(|| ctx.error_encoding(range.clone(), reason))?; let err_str = &ctx.full_data()[range.start.bytes..range.end.bytes]; let num_chars = range.end.chars - range.start.chars; let mut out: Vec<u8> = Vec::with_capacity(num_chars * 4); for ch in err_str.code_points() { let c = ch.to_u32(); let 0xd800..=0xdfff = c else { // Not a surrogate, fail with original exception return Err(ctx.error_encoding(range, reason)); }; match standard_encoding { StandardEncoding::Utf8 => out.extend(ch.encode_wtf8(&mut [0; 4]).as_bytes()), StandardEncoding::Utf16Le => out.extend((c as u16).to_le_bytes()), StandardEncoding::Utf16Be => out.extend((c as u16).to_be_bytes()), StandardEncoding::Utf32Le => out.extend(c.to_le_bytes()), StandardEncoding::Utf32Be => out.extend(c.to_be_bytes()), } } Ok((EncodeReplace::Bytes(ctx.bytes(out)), range.end)) } } impl<'a> DecodeErrorHandler<PyDecodeContext<'a>> for SurrogatePass { fn handle_decode_error( &self, ctx: &mut PyDecodeContext<'a>, byte_range: Range<usize>, reason: Option<&str>, ) -> PyResult<(PyStrRef, usize)> { let standard_encoding = StandardEncoding::parse(ctx.encoding) .ok_or_else(|| ctx.error_decoding(byte_range.clone(), reason))?; let s = ctx.full_data(); debug_assert!(byte_range.start <= 0.max(s.len() - 1)); debug_assert!(byte_range.end >= 1.min(s.len())); debug_assert!(byte_range.end <= s.len()); // Try decoding a single surrogate character. If there are more, // let the codec call us again. let p = &s[byte_range.start..]; fn slice<const N: usize>(p: &[u8]) -> Option<[u8; N]> { p.get(..N).map(|x| x.try_into().unwrap()) } let c = match standard_encoding { StandardEncoding::Utf8 => { // it's a three-byte code slice::<3>(p) .filter(|&[a, b, c]| { (u32::from(a) & 0xf0) == 0xe0 && (u32::from(b) & 0xc0) == 0x80 && (u32::from(c) & 0xc0) == 0x80 }) .map(|[a, b, c]| { ((u32::from(a) & 0x0f) << 12) + ((u32::from(b) & 0x3f) << 6) + (u32::from(c) & 0x3f) }) } StandardEncoding::Utf16Le => slice(p).map(u16::from_le_bytes).map(u32::from), StandardEncoding::Utf16Be => slice(p).map(u16::from_be_bytes).map(u32::from), StandardEncoding::Utf32Le => slice(p).map(u32::from_le_bytes), StandardEncoding::Utf32Be => slice(p).map(u32::from_be_bytes), }; let byte_length = match standard_encoding { StandardEncoding::Utf8 => 3, StandardEncoding::Utf16Be | StandardEncoding::Utf16Le => 2, StandardEncoding::Utf32Be | StandardEncoding::Utf32Le => 4, }; // !Py_UNICODE_IS_SURROGATE let c = c .and_then(CodePoint::from_u32) .filter(|c| matches!(c.to_u32(), 0xd800..=0xdfff)) .ok_or_else(|| ctx.error_decoding(byte_range.clone(), reason))?; Ok((ctx.string(c.into()), byte_range.start + byte_length)) } } pub struct PyEncodeContext<'a> { vm: &'a VirtualMachine, encoding: &'a str, data: &'a Py<PyStr>, pos: StrSize, exception: OnceCell<PyBaseExceptionRef>, } impl<'a> PyEncodeContext<'a> { pub fn new(encoding: &'a str, data: &'a Py<PyStr>, vm: &'a VirtualMachine) -> Self { Self { vm, encoding, data, pos: StrSize::default(), exception: OnceCell::new(), } } } impl CodecContext for PyEncodeContext<'_> { type Error = PyBaseExceptionRef; type StrBuf = PyStrRef; type BytesBuf = PyBytesRef; fn string(&self, s: Wtf8Buf) -> Self::StrBuf { self.vm.ctx.new_str(s) } fn bytes(&self, b: Vec<u8>) -> Self::BytesBuf { self.vm.ctx.new_bytes(b) } } impl EncodeContext for PyEncodeContext<'_> { fn full_data(&self) -> &Wtf8 { self.data.as_wtf8() } fn data_len(&self) -> StrSize { StrSize { bytes: self.data.byte_len(), chars: self.data.char_len(), } } fn remaining_data(&self) -> &Wtf8 { &self.full_data()[self.pos.bytes..] } fn position(&self) -> StrSize { self.pos } fn restart_from(&mut self, pos: StrSize) -> Result<(), Self::Error> { if pos.chars > self.data.char_len() { return Err(self.vm.new_index_error(format!( "position {} from error handler out of bounds", pos.chars ))); } assert!( self.data.as_wtf8().is_code_point_boundary(pos.bytes), "invalid pos {pos:?} for {:?}", self.data.as_wtf8() ); self.pos = pos; Ok(()) } fn error_encoding(&self, range: Range<StrSize>, reason: Option<&str>) -> Self::Error { let vm = self.vm; match self.exception.get() { Some(exc) => { match update_unicode_error_attrs( exc.as_object(), range.start.chars, range.end.chars, reason, vm, ) { Ok(()) => exc.clone(), Err(e) => e, } } None => self .exception .get_or_init(|| { let reason = reason.expect( "should only ever pass reason: None if an exception is already set", ); vm.new_unicode_encode_error_real( vm.ctx.new_str(self.encoding), self.data.to_owned(), range.start.chars, range.end.chars, vm.ctx.new_str(reason), ) }) .clone(), } } } pub struct PyDecodeContext<'a> { vm: &'a VirtualMachine, encoding: &'a str, data: PyDecodeData<'a>, orig_bytes: Option<&'a Py<PyBytes>>, pos: usize, exception: OnceCell<PyBaseExceptionRef>, } enum PyDecodeData<'a> { Original(BorrowedValue<'a, [u8]>), Modified(PyBytesRef), } impl ops::Deref for PyDecodeData<'_> { type Target = [u8]; fn deref(&self) -> &Self::Target { match self { PyDecodeData::Original(data) => data, PyDecodeData::Modified(data) => data, } } } impl<'a> PyDecodeContext<'a> { pub fn new(encoding: &'a str, data: &'a ArgBytesLike, vm: &'a VirtualMachine) -> Self { Self { vm, encoding, data: PyDecodeData::Original(data.borrow_buf()), orig_bytes: data.as_object().downcast_ref(), pos: 0, exception: OnceCell::new(), } } } impl CodecContext for PyDecodeContext<'_> { type Error = PyBaseExceptionRef; type StrBuf = PyStrRef; type BytesBuf = PyBytesRef; fn string(&self, s: Wtf8Buf) -> Self::StrBuf { self.vm.ctx.new_str(s) } fn bytes(&self, b: Vec<u8>) -> Self::BytesBuf { self.vm.ctx.new_bytes(b) } } impl DecodeContext for PyDecodeContext<'_> { fn full_data(&self) -> &[u8] { &self.data } fn remaining_data(&self) -> &[u8] { &self.data[self.pos..] } fn position(&self) -> usize { self.pos } fn advance(&mut self, by: usize) { self.pos += by; } fn restart_from(&mut self, pos: usize) -> Result<(), Self::Error> { if pos > self.data.len() { return Err(self .vm .new_index_error(format!("position {pos} from error handler out of bounds",))); } self.pos = pos; Ok(()) } fn error_decoding(&self, byte_range: Range<usize>, reason: Option<&str>) -> Self::Error { let vm = self.vm; match self.exception.get() { Some(exc) => { match update_unicode_error_attrs( exc.as_object(), byte_range.start, byte_range.end, reason, vm, ) { Ok(()) => exc.clone(), Err(e) => e, } } None => self .exception .get_or_init(|| { let reason = reason.expect( "should only ever pass reason: None if an exception is already set", ); let data = if let Some(bytes) = self.orig_bytes { bytes.to_owned() } else { vm.ctx.new_bytes(self.data.to_vec()) }; vm.new_unicode_decode_error_real( vm.ctx.new_str(self.encoding), data, byte_range.start, byte_range.end, vm.ctx.new_str(reason), ) }) .clone(), } } } #[derive(strum_macros::EnumString)] #[strum(serialize_all = "lowercase")] enum StandardError { Strict, Ignore, Replace, XmlCharRefReplace, BackslashReplace, SurrogatePass, SurrogateEscape, } impl<'a> EncodeErrorHandler<PyEncodeContext<'a>> for StandardError { fn handle_encode_error( &self, ctx: &mut PyEncodeContext<'a>, range: Range<StrSize>, reason: Option<&str>, ) -> PyResult<(EncodeReplace<PyEncodeContext<'a>>, StrSize)> { use StandardError::*; // use errors::*; match self { Strict => errors::Strict.handle_encode_error(ctx, range, reason), Ignore => errors::Ignore.handle_encode_error(ctx, range, reason), Replace => errors::Replace.handle_encode_error(ctx, range, reason), XmlCharRefReplace => errors::XmlCharRefReplace.handle_encode_error(ctx, range, reason), BackslashReplace => errors::BackslashReplace.handle_encode_error(ctx, range, reason), SurrogatePass => SurrogatePass.handle_encode_error(ctx, range, reason), SurrogateEscape => errors::SurrogateEscape.handle_encode_error(ctx, range, reason), } } } impl<'a> DecodeErrorHandler<PyDecodeContext<'a>> for StandardError { fn handle_decode_error( &self, ctx: &mut PyDecodeContext<'a>, byte_range: Range<usize>, reason: Option<&str>, ) -> PyResult<(PyStrRef, usize)> { use StandardError::*; match self { Strict => errors::Strict.handle_decode_error(ctx, byte_range, reason), Ignore => errors::Ignore.handle_decode_error(ctx, byte_range, reason), Replace => errors::Replace.handle_decode_error(ctx, byte_range, reason), XmlCharRefReplace => Err(ctx .vm .new_type_error("don't know how to handle UnicodeDecodeError in error callback")), BackslashReplace => { errors::BackslashReplace.handle_decode_error(ctx, byte_range, reason) } SurrogatePass => self::SurrogatePass.handle_decode_error(ctx, byte_range, reason), SurrogateEscape => errors::SurrogateEscape.handle_decode_error(ctx, byte_range, reason), } } } pub struct ErrorsHandler<'a> { errors: &'a Py<PyStr>, resolved: OnceCell<ResolvedError>, } enum ResolvedError { Standard(StandardError), Handler(PyObjectRef), } impl<'a> ErrorsHandler<'a> { #[inline] pub fn new(errors: Option<&'a Py<PyStr>>, vm: &VirtualMachine) -> Self { match errors { Some(errors) => Self { errors, resolved: OnceCell::new(), }, None => Self { errors: identifier!(vm, strict).as_ref(), resolved: OnceCell::with_value(ResolvedError::Standard(StandardError::Strict)), }, } } #[inline] fn resolve(&self, vm: &VirtualMachine) -> PyResult<&ResolvedError> { self.resolved.get_or_try_init(|| { if let Ok(standard) = self.errors.as_str().parse() { Ok(ResolvedError::Standard(standard)) } else { vm.state .codec_registry .lookup_error(self.errors.as_str(), vm) .map(ResolvedError::Handler) } }) } } impl StrBuffer for PyStrRef { fn is_compatible_with(&self, kind: StrKind) -> bool { self.kind() <= kind } } impl<'a> EncodeErrorHandler<PyEncodeContext<'a>> for ErrorsHandler<'_> { fn handle_encode_error( &self, ctx: &mut PyEncodeContext<'a>, range: Range<StrSize>, reason: Option<&str>, ) -> PyResult<(EncodeReplace<PyEncodeContext<'a>>, StrSize)> { let vm = ctx.vm; let handler = match self.resolve(vm)? { ResolvedError::Standard(standard) => { return standard.handle_encode_error(ctx, range, reason); } ResolvedError::Handler(handler) => handler, }; let encode_exc = ctx.error_encoding(range.clone(), reason); let res = handler.call((encode_exc.clone(),), vm)?; let tuple_err = || vm.new_type_error("encoding error handler must return (str/bytes, int) tuple"); let (replace, restart) = match res.downcast_ref::<PyTuple>().map(|tup| tup.as_slice()) { Some([replace, restart]) => (replace.clone(), restart), _ => return Err(tuple_err()), }; let replace = match_class!(match replace { s @ PyStr => EncodeReplace::Str(s), b @ PyBytes => EncodeReplace::Bytes(b), _ => return Err(tuple_err()), }); let restart = isize::try_from_borrowed_object(vm, restart).map_err(|_| tuple_err())?; let restart = if restart < 0 { // will still be out of bounds if it underflows ¯\_(ツ)_/¯ ctx.data.char_len().wrapping_sub(restart.unsigned_abs()) } else { restart as usize }; let restart = if restart == range.end.chars { range.end } else { StrSize { chars: restart, bytes: ctx .data .as_wtf8() .code_point_indices() .nth(restart) .map_or(ctx.data.byte_len(), |(i, _)| i), } }; Ok((replace, restart)) } } impl<'a> DecodeErrorHandler<PyDecodeContext<'a>> for ErrorsHandler<'_> { fn handle_decode_error( &self, ctx: &mut PyDecodeContext<'a>, byte_range: Range<usize>, reason: Option<&str>, ) -> PyResult<(PyStrRef, usize)> { let vm = ctx.vm; let handler = match self.resolve(vm)? { ResolvedError::Standard(standard) => { return standard.handle_decode_error(ctx, byte_range, reason); } ResolvedError::Handler(handler) => handler, }; let decode_exc = ctx.error_decoding(byte_range.clone(), reason); let data_bytes: PyObjectRef = decode_exc.as_object().get_attr("object", vm)?; let res = handler.call((decode_exc.clone(),), vm)?; let new_data = decode_exc.as_object().get_attr("object", vm)?; if !new_data.is(&data_bytes) { let new_data: PyBytesRef = new_data .downcast() .map_err(|_| vm.new_type_error("object attribute must be bytes"))?; ctx.data = PyDecodeData::Modified(new_data); } let data = &*ctx.data; let tuple_err = || vm.new_type_error("decoding error handler must return (str, int) tuple"); match res.downcast_ref::<PyTuple>().map(|tup| tup.as_slice()) { Some([replace, restart]) => { let replace = replace .downcast_ref::<PyStr>() .ok_or_else(tuple_err)? .to_owned(); let restart = isize::try_from_borrowed_object(vm, restart).map_err(|_| tuple_err())?; let restart = if restart < 0 { // will still be out of bounds if it underflows ¯\_(ツ)_/¯ data.len().wrapping_sub(restart.unsigned_abs()) } else { restart as usize }; Ok((replace, restart)) } _ => Err(tuple_err()), } } } fn call_native_encode_error<E>( handler: E, err: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<(PyObjectRef, usize)> where for<'a> E: EncodeErrorHandler<PyEncodeContext<'a>>, { // let err = err. let range = extract_unicode_error_range(&err, vm)?; let s = PyStrRef::try_from_object(vm, err.get_attr("object", vm)?)?; let s_encoding = PyStrRef::try_from_object(vm, err.get_attr("encoding", vm)?)?; let mut ctx = PyEncodeContext { vm, encoding: s_encoding.as_str(), data: &s, pos: StrSize::default(), exception: OnceCell::with_value(err.downcast().unwrap()), }; let mut iter = s.as_wtf8().code_point_indices(); let start = StrSize { chars: range.start, bytes: iter.nth(range.start).unwrap().0, }; let end = StrSize { chars: range.end, bytes: if let Some(n) = range.len().checked_sub(1) { iter.nth(n).map_or(s.byte_len(), |(i, _)| i) } else { start.bytes }, }; let (replace, restart) = handler.handle_encode_error(&mut ctx, start..end, None)?; let replace = match replace { EncodeReplace::Str(s) => s.into(), EncodeReplace::Bytes(b) => b.into(), }; Ok((replace, restart.chars)) } fn call_native_decode_error<E>( handler: E, err: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<(PyObjectRef, usize)> where for<'a> E: DecodeErrorHandler<PyDecodeContext<'a>>, { let range = extract_unicode_error_range(&err, vm)?; let s = ArgBytesLike::try_from_object(vm, err.get_attr("object", vm)?)?; let s_encoding = PyStrRef::try_from_object(vm, err.get_attr("encoding", vm)?)?;
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/readline.rs
crates/vm/src/readline.rs
//! Readline interface for REPLs //! //! This module provides a common interface for reading lines from the console, with support for history and completion. //! It uses the [`rustyline`] crate on non-WASM platforms and a custom implementation on WASM platforms. use std::{io, path::Path}; type OtherError = Box<dyn core::error::Error>; type OtherResult<T> = Result<T, OtherError>; pub enum ReadlineResult { Line(String), Eof, Interrupt, Io(std::io::Error), #[cfg(unix)] OsError(nix::Error), Other(OtherError), } #[allow(unused)] mod basic_readline { use super::*; pub trait Helper {} impl<T> Helper for T {} pub struct Readline<H: Helper> { helper: H, } impl<H: Helper> Readline<H> { pub const fn new(helper: H) -> Self { Self { helper } } pub fn load_history(&mut self, _path: &Path) -> OtherResult<()> { Ok(()) } pub fn save_history(&mut self, _path: &Path) -> OtherResult<()> { Ok(()) } pub fn add_history_entry(&mut self, _entry: &str) -> OtherResult<()> { Ok(()) } pub fn readline(&mut self, prompt: &str) -> ReadlineResult { use std::io::prelude::*; print!("{prompt}"); if let Err(e) = io::stdout().flush() { return ReadlineResult::Io(e); } let next_line = io::stdin().lock().lines().next(); match next_line { Some(Ok(line)) => ReadlineResult::Line(line), None => ReadlineResult::Eof, Some(Err(e)) if e.kind() == io::ErrorKind::Interrupted => ReadlineResult::Interrupt, Some(Err(e)) => ReadlineResult::Io(e), } } } } #[cfg(not(target_arch = "wasm32"))] mod rustyline_readline { use super::*; pub trait Helper: rustyline::Helper {} impl<T: rustyline::Helper> Helper for T {} /// Readline: the REPL pub struct Readline<H: Helper> { repl: rustyline::Editor<H, rustyline::history::DefaultHistory>, } #[cfg(windows)] const EOF_CHAR: &str = "\u{001A}"; impl<H: Helper> Readline<H> { pub fn new(helper: H) -> Self { use rustyline::*; let mut repl = Editor::with_config( Config::builder() .completion_type(CompletionType::List) .tab_stop(8) .bracketed_paste(false) // multi-line paste .build(), ) .expect("failed to initialize line editor"); repl.set_helper(Some(helper)); // Bind CTRL + Z to insert EOF character on Windows #[cfg(windows)] { repl.bind_sequence( KeyEvent::new('z', Modifiers::CTRL), EventHandler::Simple(Cmd::Insert(1, EOF_CHAR.into())), ); } Self { repl } } pub fn load_history(&mut self, path: &Path) -> OtherResult<()> { self.repl.load_history(path)?; Ok(()) } pub fn save_history(&mut self, path: &Path) -> OtherResult<()> { if !path.exists() && let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } self.repl.save_history(path)?; Ok(()) } pub fn add_history_entry(&mut self, entry: &str) -> OtherResult<()> { self.repl.add_history_entry(entry)?; Ok(()) } pub fn readline(&mut self, prompt: &str) -> ReadlineResult { use rustyline::error::ReadlineError; loop { break match self.repl.readline(prompt) { Ok(line) => { // Check for CTRL + Z on Windows #[cfg(windows)] { use std::io::IsTerminal; let trimmed = line.trim_end_matches(&['\r', '\n'][..]); if trimmed == EOF_CHAR && io::stdin().is_terminal() { return ReadlineResult::Eof; } } ReadlineResult::Line(line) } Err(ReadlineError::Interrupted) => ReadlineResult::Interrupt, Err(ReadlineError::Eof) => ReadlineResult::Eof, Err(ReadlineError::Io(e)) => ReadlineResult::Io(e), Err(ReadlineError::Signal(_)) => continue, #[cfg(unix)] Err(ReadlineError::Errno(num)) => ReadlineResult::OsError(num), Err(e) => ReadlineResult::Other(e.into()), }; } } } } #[cfg(target_arch = "wasm32")] use basic_readline as readline_inner; #[cfg(not(target_arch = "wasm32"))] use rustyline_readline as readline_inner; pub use readline_inner::Helper; pub struct Readline<H: Helper>(readline_inner::Readline<H>); impl<H: Helper> Readline<H> { pub fn new(helper: H) -> Self { Self(readline_inner::Readline::new(helper)) } pub fn load_history(&mut self, path: &Path) -> OtherResult<()> { self.0.load_history(path) } pub fn save_history(&mut self, path: &Path) -> OtherResult<()> { self.0.save_history(path) } pub fn add_history_entry(&mut self, entry: &str) -> OtherResult<()> { self.0.add_history_entry(entry) } pub fn readline(&mut self, prompt: &str) -> ReadlineResult { self.0.readline(prompt) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/scope.rs
crates/vm/src/scope.rs
use crate::{VirtualMachine, builtins::PyDictRef, function::ArgMapping}; use alloc::fmt; #[derive(Clone)] pub struct Scope { pub locals: ArgMapping, pub globals: PyDictRef, } impl fmt::Debug for Scope { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // TODO: have a more informative Debug impl that DOESN'T recurse and cause a stack overflow f.write_str("Scope") } } impl Scope { #[inline] pub fn new(locals: Option<ArgMapping>, globals: PyDictRef) -> Self { let locals = locals.unwrap_or_else(|| ArgMapping::from_dict_exact(globals.clone())); Self { locals, globals } } pub fn with_builtins( locals: Option<ArgMapping>, globals: PyDictRef, vm: &VirtualMachine, ) -> Self { if !globals.contains_key("__builtins__", vm) { globals .set_item("__builtins__", vm.builtins.clone().into(), vm) .unwrap(); } Self::new(locals, globals) } // pub fn get_locals(&self) -> &Py<PyDict> { // match self.locals.first() { // Some(dict) => dict, // None => &self.globals, // } // } // pub fn get_only_locals(&self) -> Option<PyDictRef> { // self.locals.first().cloned() // } // pub fn new_child_scope_with_locals(&self, locals: PyDictRef) -> Scope { // let mut new_locals = Vec::with_capacity(self.locals.len() + 1); // new_locals.push(locals); // new_locals.extend_from_slice(&self.locals); // Scope { // locals: new_locals, // globals: self.globals.clone(), // } // } // pub fn new_child_scope(&self, ctx: &Context) -> Scope { // self.new_child_scope_with_locals(ctx.new_dict()) // } // #[cfg_attr(feature = "flame-it", flame("Scope"))] // pub fn load_name(&self, vm: &VirtualMachine, name: impl PyName) -> Option<PyObjectRef> { // for dict in self.locals.iter() { // if let Some(value) = dict.get_item_option(name.clone(), vm).unwrap() { // return Some(value); // } // } // // Fall back to loading a global after all scopes have been searched! // self.load_global(vm, name) // } // #[cfg_attr(feature = "flame-it", flame("Scope"))] // /// Load a local name. Only check the local dictionary for the given name. // pub fn load_local(&self, vm: &VirtualMachine, name: impl PyName) -> Option<PyObjectRef> { // self.get_locals().get_item_option(name, vm).unwrap() // } // #[cfg_attr(feature = "flame-it", flame("Scope"))] // pub fn load_cell(&self, vm: &VirtualMachine, name: impl PyName) -> Option<PyObjectRef> { // for dict in self.locals.iter().skip(1) { // if let Some(value) = dict.get_item_option(name.clone(), vm).unwrap() { // return Some(value); // } // } // None // } // pub fn store_cell(&self, vm: &VirtualMachine, name: impl PyName, value: PyObjectRef) { // // find the innermost outer scope that contains the symbol name // if let Some(locals) = self // .locals // .iter() // .rev() // .find(|l| l.contains_key(name.clone(), vm)) // { // // add to the symbol // locals.set_item(name, value, vm).unwrap(); // } else { // // somewhat limited solution -> fallback to the old rustpython strategy // // and store the next outer scope // // This case is usually considered as a failure case, but kept for the moment // // to support the scope propagation for named expression assignments to so far // // unknown names in comprehensions. We need to consider here more context // // information for correct handling. // self.locals // .get(1) // .expect("no outer scope for non-local") // .set_item(name, value, vm) // .unwrap(); // } // } // pub fn store_name(&self, vm: &VirtualMachine, key: impl PyName, value: PyObjectRef) { // self.get_locals().set_item(key, value, vm).unwrap(); // } // pub fn delete_name(&self, vm: &VirtualMachine, key: impl PyName) -> PyResult { // self.get_locals().del_item(key, vm) // } // #[cfg_attr(feature = "flame-it", flame("Scope"))] // /// Load a global name. // pub fn load_global(&self, vm: &VirtualMachine, name: impl PyName) -> Option<PyObjectRef> { // if let Some(value) = self.globals.get_item_option(name.clone(), vm).unwrap() { // Some(value) // } else { // vm.builtins.get_attr(name, vm).ok() // } // } // pub fn store_global(&self, vm: &VirtualMachine, name: impl PyName, value: PyObjectRef) { // self.globals.set_item(name, value, vm).unwrap(); // } } // mod sealed { // pub trait Sealed {} // impl Sealed for &str {} // impl Sealed for super::PyStrRef {} // } // pub trait PyName: // sealed::Sealed + crate::dict_inner::DictKey + Clone + ToPyObject // { // } // impl PyName for str {} // impl PyName for Py<PyStr> {}
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/utils.rs
crates/vm/src/utils.rs
use rustpython_common::wtf8::Wtf8; use crate::{ PyObjectRef, PyResult, VirtualMachine, builtins::{PyStr, PyUtf8Str}, convert::{ToPyException, ToPyObject}, exceptions::cstring_error, }; pub fn hash_iter<'a, I: IntoIterator<Item = &'a PyObjectRef>>( iter: I, vm: &VirtualMachine, ) -> PyResult<rustpython_common::hash::PyHash> { vm.state.hash_secret.hash_iter(iter, |obj| obj.hash(vm)) } impl ToPyObject for core::convert::Infallible { fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { match self {} } } pub trait ToCString: AsRef<Wtf8> { fn to_cstring(&self, vm: &VirtualMachine) -> PyResult<alloc::ffi::CString> { alloc::ffi::CString::new(self.as_ref().as_bytes()).map_err(|err| err.to_pyexception(vm)) } fn ensure_no_nul(&self, vm: &VirtualMachine) -> PyResult<()> { if self.as_ref().as_bytes().contains(&b'\0') { Err(cstring_error(vm)) } else { Ok(()) } } } impl ToCString for &str {} impl ToCString for PyStr {} impl ToCString for PyUtf8Str {} pub(crate) fn collection_repr<'a, I>( class_name: Option<&str>, prefix: &str, suffix: &str, iter: I, vm: &VirtualMachine, ) -> PyResult<String> where I: core::iter::Iterator<Item = &'a PyObjectRef>, { let mut repr = String::new(); if let Some(name) = class_name { repr.push_str(name); repr.push('('); } repr.push_str(prefix); { let mut parts_iter = iter.map(|o| o.repr(vm)); repr.push_str( parts_iter .next() .transpose()? .expect("this is not called for empty collection") .as_str(), ); for part in parts_iter { repr.push_str(", "); repr.push_str(part?.as_str()); } } repr.push_str(suffix); if class_name.is_some() { repr.push(')'); } Ok(repr) }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/macros.rs
crates/vm/src/macros.rs
#[macro_export] macro_rules! extend_module { ( $vm:expr, $module:expr, { $($name:expr => $value:expr),* $(,)? }) => {{ $( $vm.__module_set_attr($module, $vm.ctx.intern_str($name), $value).unwrap(); )* }}; } #[macro_export] macro_rules! py_class { ( $ctx:expr, $class_name:expr, $class_base:expr, { $($name:tt => $value:expr),* $(,)* }) => { py_class!($ctx, $class_name, $class_base, $crate::types::PyTypeFlags::BASETYPE, { $($name => $value),* }) }; ( $ctx:expr, $class_name:expr, $class_base:expr, $flags:expr, { $($name:tt => $value:expr),* $(,)* }) => { { #[allow(unused_mut)] let mut slots = $crate::types::PyTypeSlots::heap_default(); slots.flags = $flags; $($crate::py_class!(@extract_slots($ctx, &mut slots, $name, $value));)* let py_class = $ctx.new_class(None, $class_name, $class_base, slots); $($crate::py_class!(@extract_attrs($ctx, &py_class, $name, $value));)* py_class } }; (@extract_slots($ctx:expr, $slots:expr, (slot $slot_name:ident), $value:expr)) => { $slots.$slot_name.store(Some($value)); }; (@extract_slots($ctx:expr, $class:expr, $name:expr, $value:expr)) => {}; (@extract_attrs($ctx:expr, $slots:expr, (slot $slot_name:ident), $value:expr)) => {}; (@extract_attrs($ctx:expr, $class:expr, $name:expr, $value:expr)) => { $class.set_attr($name, $value); }; } #[macro_export] macro_rules! extend_class { ( $ctx:expr, $class:expr, { $($name:expr => $value:expr),* $(,)* }) => { $( $class.set_attr($ctx.intern_str($name), $value.into()); )* }; } #[macro_export] macro_rules! py_namespace { ( $vm:expr, { $($name:expr => $value:expr),* $(,)* }) => { { let namespace = $crate::object::PyPayload::into_ref($crate::builtins::PyNamespace {}, &$vm.ctx); let obj = $crate::object::AsObject::as_object(&namespace); $( obj.generic_setattr($vm.ctx.intern_str($name), $crate::function::PySetterValue::Assign($value.into()), $vm).unwrap(); )* namespace } } } /// Macro to match on the built-in class of a Python object. /// /// Like `match`, `match_class!` must be exhaustive, so a default arm without /// casting is required. /// /// # Examples /// /// ``` /// use malachite_bigint::ToBigInt; /// use num_traits::Zero; /// /// use rustpython_vm::match_class; /// use rustpython_vm::builtins::{PyFloat, PyInt}; /// use rustpython_vm::{PyPayload}; /// /// # rustpython_vm::Interpreter::without_stdlib(Default::default()).enter(|vm| { /// let obj = PyInt::from(0).into_pyobject(vm); /// assert_eq!( /// "int", /// match_class!(match obj { /// PyInt => "int", /// PyFloat => "float", /// _ => "neither", /// }) /// ); /// # }); /// /// ``` /// /// With a binding to the downcasted type: /// /// ``` /// use malachite_bigint::ToBigInt; /// use num_traits::Zero; /// /// use rustpython_vm::match_class; /// use rustpython_vm::builtins::{PyFloat, PyInt}; /// use rustpython_vm::{ PyPayload}; /// /// # rustpython_vm::Interpreter::without_stdlib(Default::default()).enter(|vm| { /// let obj = PyInt::from(0).into_pyobject(vm); /// /// let int_value = match_class!(match obj { /// i @ PyInt => i.as_bigint().clone(), /// f @ PyFloat => f.to_f64().to_bigint().unwrap(), /// obj => panic!("non-numeric object {:?}", obj), /// }); /// /// assert!(int_value.is_zero()); /// # }); /// ``` #[macro_export] macro_rules! match_class { // The default arm. (match ($obj:expr) { _ => $default:expr $(,)? }) => { $default }; // The default arm, binding the original object to the specified identifier. (match ($obj:expr) { $binding:ident => $default:expr $(,)? }) => {{ #[allow(clippy::redundant_locals)] let $binding = $obj; $default }}; (match ($obj:expr) { ref $binding:ident => $default:expr $(,)? }) => {{ #[allow(clippy::redundant_locals)] let $binding = &$obj; $default }}; // An arm taken when the object is an instance of the specified built-in // class and binding the downcasted object to the specified identifier and // the target expression is a block. (match ($obj:expr) { $binding:ident @ $class:ty => $expr:block $($rest:tt)* }) => { $crate::match_class!(match ($obj) { $binding @ $class => ($expr), $($rest)* }) }; (match ($obj:expr) { ref $binding:ident @ $class:ty => $expr:block $($rest:tt)* }) => { $crate::match_class!(match ($obj) { ref $binding @ $class => ($expr), $($rest)* }) }; // An arm taken when the object is an instance of the specified built-in // class and binding the downcasted object to the specified identifier. (match ($obj:expr) { $binding:ident @ $class:ty => $expr:expr, $($rest:tt)* }) => { match $obj.downcast::<$class>() { Ok($binding) => $expr, Err(_obj) => $crate::match_class!(match (_obj) { $($rest)* }), } }; (match ($obj:expr) { ref $binding:ident @ $class:ty => $expr:expr, $($rest:tt)* }) => { match $obj.downcast_ref::<$class>() { core::option::Option::Some($binding) => $expr, core::option::Option::None => $crate::match_class!(match ($obj) { $($rest)* }), } }; // An arm taken when the object is an instance of the specified built-in // class and the target expression is a block. (match ($obj:expr) { $class:ty => $expr:block $($rest:tt)* }) => { $crate::match_class!(match ($obj) { $class => ($expr), $($rest)* }) }; // An arm taken when the object is an instance of the specified built-in // class. (match ($obj:expr) { $class:ty => $expr:expr, $($rest:tt)* }) => { if $obj.downcastable::<$class>() { $expr } else { $crate::match_class!(match ($obj) { $($rest)* }) } }; // To allow match expressions without parens around the match target (match $($rest:tt)*) => { $crate::match_class!(@parse_match () ($($rest)*)) }; (@parse_match ($($target:tt)*) ({ $($inner:tt)* })) => { $crate::match_class!(match ($($target)*) { $($inner)* }) }; (@parse_match ($($target:tt)*) ($next:tt $($rest:tt)*)) => { $crate::match_class!(@parse_match ($($target)* $next) ($($rest)*)) }; } #[macro_export] macro_rules! identifier( ($as_ctx:expr, $name:ident) => { $as_ctx.as_ref().names.$name }; ); #[macro_export] macro_rules! identifier_utf8( ($as_ctx:expr, $name:ident) => { // Safety: All known identifiers are ascii strings. #[allow(clippy::macro_metavars_in_unsafe)] unsafe { $as_ctx.as_ref().names.$name.as_object().downcast_unchecked_ref::<$crate::builtins::PyUtf8Str>() } }; ); /// Super detailed logging. Might soon overflow your log buffers /// Default, this logging is discarded, except when a the `vm-tracing-logging` /// build feature is enabled. macro_rules! vm_trace { ($($arg:tt)+) => { #[cfg(feature = "vm-tracing-logging")] trace!($($arg)+); } } macro_rules! flame_guard { ($name:expr) => { #[cfg(feature = "flame-it")] let _guard = ::flame::start_guard($name); }; } #[macro_export] macro_rules! class_or_notimplemented { ($t:ty, $obj:expr) => {{ let a: &$crate::PyObject = &*$obj; match $crate::PyObject::downcast_ref::<$t>(&a) { Some(pyref) => pyref, None => return Ok($crate::function::PyArithmeticValue::NotImplemented), } }}; } #[macro_export] macro_rules! named_function { ($ctx:expr, $module:ident, $func:ident) => {{ #[allow(unused_variables)] // weird lint, something to do with paste probably let ctx: &$crate::Context = &$ctx; $crate::__exports::paste::expr! { ctx.new_method_def( stringify!($func), [<$module _ $func>], ::rustpython_vm::function::PyMethodFlags::empty(), ) .to_function() .with_module(ctx.intern_str(stringify!($module)).into()) .into_ref(ctx) } }}; } // can't use PyThreadingConstraint for stuff like this since it's not an auto trait, and // therefore we can't add it ad-hoc to a trait object cfg_if::cfg_if! { if #[cfg(feature = "threading")] { macro_rules! py_dyn_fn { (dyn Fn($($arg:ty),*$(,)*) -> $ret:ty) => { dyn Fn($($arg),*) -> $ret + Send + Sync + 'static }; } } else { macro_rules! py_dyn_fn { (dyn Fn($($arg:ty),*$(,)*) -> $ret:ty) => { dyn Fn($($arg),*) -> $ret + 'static }; } } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/windows.rs
crates/vm/src/windows.rs
use crate::common::fileutils::{ StatStruct, windows::{FILE_INFO_BY_NAME_CLASS, get_file_information_by_name}, }; use crate::{ PyObjectRef, PyResult, TryFromObject, VirtualMachine, convert::{ToPyObject, ToPyResult}, }; use rustpython_common::windows::ToWideString; use std::ffi::OsStr; use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE}; /// Windows HANDLE wrapper for Python interop #[derive(Clone, Copy)] pub struct WinHandle(pub HANDLE); pub(crate) trait WindowsSysResultValue { type Ok: ToPyObject; fn is_err(&self) -> bool; fn into_ok(self) -> Self::Ok; } impl WindowsSysResultValue for HANDLE { type Ok = WinHandle; fn is_err(&self) -> bool { *self == INVALID_HANDLE_VALUE } fn into_ok(self) -> Self::Ok { WinHandle(self) } } // BOOL is i32 in windows-sys 0.61+ impl WindowsSysResultValue for i32 { type Ok = (); fn is_err(&self) -> bool { *self == 0 } fn into_ok(self) -> Self::Ok {} } pub(crate) struct WindowsSysResult<T>(pub T); impl<T: WindowsSysResultValue> WindowsSysResult<T> { pub fn is_err(&self) -> bool { self.0.is_err() } pub fn into_pyresult(self, vm: &VirtualMachine) -> PyResult<T::Ok> { if !self.is_err() { Ok(self.0.into_ok()) } else { Err(vm.new_last_os_error()) } } } impl<T: WindowsSysResultValue> ToPyResult for WindowsSysResult<T> { fn to_pyresult(self, vm: &VirtualMachine) -> PyResult { let ok = self.into_pyresult(vm)?; Ok(ok.to_pyobject(vm)) } } type HandleInt = usize; // TODO: change to isize when fully ported to windows-rs impl TryFromObject for WinHandle { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { let handle = HandleInt::try_from_object(vm, obj)?; Ok(WinHandle(handle as HANDLE)) } } impl ToPyObject for WinHandle { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { (self.0 as HandleInt).to_pyobject(vm) } } pub fn init_winsock() { static WSA_INIT: parking_lot::Once = parking_lot::Once::new(); WSA_INIT.call_once(|| unsafe { let mut wsa_data = std::mem::MaybeUninit::uninit(); let _ = windows_sys::Win32::Networking::WinSock::WSAStartup(0x0101, wsa_data.as_mut_ptr()); }) } // win32_xstat in cpython pub fn win32_xstat(path: &OsStr, traverse: bool) -> std::io::Result<StatStruct> { let mut result = win32_xstat_impl(path, traverse)?; // ctime is only deprecated from 3.12, so we copy birthtime across result.st_ctime = result.st_birthtime; result.st_ctime_nsec = result.st_birthtime_nsec; Ok(result) } fn is_reparse_tag_name_surrogate(tag: u32) -> bool { (tag & 0x20000000) > 0 } // Constants const IO_REPARSE_TAG_SYMLINK: u32 = 0xA000000C; const S_IFMT: u16 = libc::S_IFMT as u16; const S_IFDIR: u16 = libc::S_IFDIR as u16; const S_IFREG: u16 = libc::S_IFREG as u16; const S_IFCHR: u16 = libc::S_IFCHR as u16; const S_IFLNK: u16 = crate::common::fileutils::windows::S_IFLNK as u16; const S_IFIFO: u16 = crate::common::fileutils::windows::S_IFIFO as u16; /// FILE_ATTRIBUTE_TAG_INFO structure for GetFileInformationByHandleEx #[repr(C)] #[derive(Default)] struct FileAttributeTagInfo { file_attributes: u32, reparse_tag: u32, } /// Ported from attributes_to_mode (fileutils.c) fn attributes_to_mode(attr: u32) -> u16 { use windows_sys::Win32::Storage::FileSystem::{ FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_READONLY, }; let mut m: u16 = 0; if attr & FILE_ATTRIBUTE_DIRECTORY != 0 { m |= S_IFDIR | 0o111; // IFEXEC for user,group,other } else { m |= S_IFREG; } if attr & FILE_ATTRIBUTE_READONLY != 0 { m |= 0o444; } else { m |= 0o666; } m } /// Ported from _Py_attribute_data_to_stat (fileutils.c) /// Converts BY_HANDLE_FILE_INFORMATION to StatStruct fn attribute_data_to_stat( info: &windows_sys::Win32::Storage::FileSystem::BY_HANDLE_FILE_INFORMATION, reparse_tag: u32, basic_info: Option<&windows_sys::Win32::Storage::FileSystem::FILE_BASIC_INFO>, id_info: Option<&windows_sys::Win32::Storage::FileSystem::FILE_ID_INFO>, ) -> StatStruct { use crate::common::fileutils::windows::SECS_BETWEEN_EPOCHS; use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT; let mut st_mode = attributes_to_mode(info.dwFileAttributes); let st_size = ((info.nFileSizeHigh as u64) << 32) | (info.nFileSizeLow as u64); let st_dev = id_info .map(|id| id.VolumeSerialNumber as u32) .unwrap_or(info.dwVolumeSerialNumber); let st_nlink = info.nNumberOfLinks as i32; // Convert FILETIME/LARGE_INTEGER to (time_t, nsec) let filetime_to_time = |ft_low: u32, ft_high: u32| -> (libc::time_t, i32) { let ticks = ((ft_high as i64) << 32) | (ft_low as i64); let nsec = ((ticks % 10_000_000) * 100) as i32; let sec = (ticks / 10_000_000 - SECS_BETWEEN_EPOCHS) as libc::time_t; (sec, nsec) }; let large_integer_to_time = |li: i64| -> (libc::time_t, i32) { let nsec = ((li % 10_000_000) * 100) as i32; let sec = (li / 10_000_000 - SECS_BETWEEN_EPOCHS) as libc::time_t; (sec, nsec) }; let (st_birthtime, st_birthtime_nsec); let (st_mtime, st_mtime_nsec); let (st_atime, st_atime_nsec); if let Some(bi) = basic_info { (st_birthtime, st_birthtime_nsec) = large_integer_to_time(bi.CreationTime); (st_mtime, st_mtime_nsec) = large_integer_to_time(bi.LastWriteTime); (st_atime, st_atime_nsec) = large_integer_to_time(bi.LastAccessTime); } else { (st_birthtime, st_birthtime_nsec) = filetime_to_time( info.ftCreationTime.dwLowDateTime, info.ftCreationTime.dwHighDateTime, ); (st_mtime, st_mtime_nsec) = filetime_to_time( info.ftLastWriteTime.dwLowDateTime, info.ftLastWriteTime.dwHighDateTime, ); (st_atime, st_atime_nsec) = filetime_to_time( info.ftLastAccessTime.dwLowDateTime, info.ftLastAccessTime.dwHighDateTime, ); } // Get file ID from id_info or fallback to file index let (st_ino, st_ino_high) = if let Some(id) = id_info { // FILE_ID_INFO.FileId is FILE_ID_128 which is [u8; 16] let bytes = id.FileId.Identifier; let low = u64::from_le_bytes(bytes[0..8].try_into().unwrap()); let high = u64::from_le_bytes(bytes[8..16].try_into().unwrap()); (low, high) } else { let ino = ((info.nFileIndexHigh as u64) << 32) | (info.nFileIndexLow as u64); (ino, 0u64) }; // Set symlink mode if applicable if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 && reparse_tag == IO_REPARSE_TAG_SYMLINK { st_mode = (st_mode & !S_IFMT) | S_IFLNK; } StatStruct { st_dev, st_ino, st_ino_high, st_mode, st_nlink, st_uid: 0, st_gid: 0, st_rdev: 0, st_size, st_atime, st_atime_nsec, st_mtime, st_mtime_nsec, st_ctime: 0, // Will be set by caller st_ctime_nsec: 0, st_birthtime, st_birthtime_nsec, st_file_attributes: info.dwFileAttributes, st_reparse_tag: reparse_tag, } } /// Get file info using FindFirstFileW (fallback when CreateFileW fails) /// Ported from attributes_from_dir fn attributes_from_dir( path: &OsStr, ) -> std::io::Result<( windows_sys::Win32::Storage::FileSystem::BY_HANDLE_FILE_INFORMATION, u32, )> { use windows_sys::Win32::Storage::FileSystem::{ BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT, FindClose, FindFirstFileW, WIN32_FIND_DATAW, }; let wide: Vec<u16> = path.to_wide_with_nul(); let mut find_data: WIN32_FIND_DATAW = unsafe { std::mem::zeroed() }; let handle = unsafe { FindFirstFileW(wide.as_ptr(), &mut find_data) }; if handle == INVALID_HANDLE_VALUE { return Err(std::io::Error::last_os_error()); } unsafe { FindClose(handle) }; let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() }; info.dwFileAttributes = find_data.dwFileAttributes; info.ftCreationTime = find_data.ftCreationTime; info.ftLastAccessTime = find_data.ftLastAccessTime; info.ftLastWriteTime = find_data.ftLastWriteTime; info.nFileSizeHigh = find_data.nFileSizeHigh; info.nFileSizeLow = find_data.nFileSizeLow; let reparse_tag = if find_data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 { find_data.dwReserved0 } else { 0 }; Ok((info, reparse_tag)) } /// Ported from win32_xstat_slow_impl fn win32_xstat_slow_impl(path: &OsStr, traverse: bool) -> std::io::Result<StatStruct> { use windows_sys::Win32::{ Foundation::{ CloseHandle, ERROR_ACCESS_DENIED, ERROR_CANT_ACCESS_FILE, ERROR_INVALID_FUNCTION, ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, ERROR_SHARING_VIOLATION, GENERIC_READ, INVALID_HANDLE_VALUE, }, Storage::FileSystem::{ BY_HANDLE_FILE_INFORMATION, CreateFileW, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_NORMAL, FILE_ATTRIBUTE_REPARSE_POINT, FILE_BASIC_INFO, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_ID_INFO, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_TYPE_CHAR, FILE_TYPE_DISK, FILE_TYPE_PIPE, FILE_TYPE_UNKNOWN, FileAttributeTagInfo, FileBasicInfo, FileIdInfo, GetFileAttributesW, GetFileInformationByHandle, GetFileInformationByHandleEx, GetFileType, INVALID_FILE_ATTRIBUTES, OPEN_EXISTING, }, }; let wide: Vec<u16> = path.to_wide_with_nul(); let access = FILE_READ_ATTRIBUTES; let mut flags = FILE_FLAG_BACKUP_SEMANTICS; if !traverse { flags |= FILE_FLAG_OPEN_REPARSE_POINT; } let mut h_file = unsafe { CreateFileW( wide.as_ptr(), access, 0, core::ptr::null(), OPEN_EXISTING, flags, std::ptr::null_mut(), ) }; let mut file_info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() }; let mut tag_info = FileAttributeTagInfo::default(); let mut is_unhandled_tag = false; if h_file == INVALID_HANDLE_VALUE { let error = std::io::Error::last_os_error(); let error_code = error.raw_os_error().unwrap_or(0) as u32; match error_code { ERROR_ACCESS_DENIED | ERROR_SHARING_VIOLATION => { // Try reading the parent directory using FindFirstFileW let (info, reparse_tag) = attributes_from_dir(path)?; file_info = info; tag_info.reparse_tag = reparse_tag; if file_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 && (traverse || !is_reparse_tag_name_surrogate(tag_info.reparse_tag)) { return Err(error); } // h_file remains INVALID_HANDLE_VALUE, we'll use file_info from FindFirstFileW } ERROR_INVALID_PARAMETER => { // Retry with GENERIC_READ (needed for \\.\con) h_file = unsafe { CreateFileW( wide.as_ptr(), access | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, core::ptr::null(), OPEN_EXISTING, flags, std::ptr::null_mut(), ) }; if h_file == INVALID_HANDLE_VALUE { return Err(error); } } ERROR_CANT_ACCESS_FILE if traverse => { // bpo37834: open unhandled reparse points if traverse fails is_unhandled_tag = true; h_file = unsafe { CreateFileW( wide.as_ptr(), access, 0, core::ptr::null(), OPEN_EXISTING, flags | FILE_FLAG_OPEN_REPARSE_POINT, std::ptr::null_mut(), ) }; if h_file == INVALID_HANDLE_VALUE { return Err(error); } } _ => return Err(error), } } // Scope for handle cleanup let result = (|| -> std::io::Result<StatStruct> { if h_file != INVALID_HANDLE_VALUE { // Handle types other than files on disk let file_type = unsafe { GetFileType(h_file) }; if file_type != FILE_TYPE_DISK { if file_type == FILE_TYPE_UNKNOWN { let err = std::io::Error::last_os_error(); if err.raw_os_error().unwrap_or(0) != 0 { return Err(err); } } let file_attributes = unsafe { GetFileAttributesW(wide.as_ptr()) }; let mut st_mode: u16 = 0; if file_attributes != INVALID_FILE_ATTRIBUTES && file_attributes & FILE_ATTRIBUTE_DIRECTORY != 0 { st_mode = S_IFDIR; } else if file_type == FILE_TYPE_CHAR { st_mode = S_IFCHR; } else if file_type == FILE_TYPE_PIPE { st_mode = S_IFIFO; } return Ok(StatStruct { st_mode, ..Default::default() }); } // Query the reparse tag if !traverse || is_unhandled_tag { let mut local_tag_info: FileAttributeTagInfo = unsafe { std::mem::zeroed() }; let ret = unsafe { GetFileInformationByHandleEx( h_file, FileAttributeTagInfo, &mut local_tag_info as *mut _ as *mut _, std::mem::size_of::<FileAttributeTagInfo>() as u32, ) }; if ret == 0 { let err_code = std::io::Error::last_os_error().raw_os_error().unwrap_or(0) as u32; match err_code { ERROR_INVALID_PARAMETER | ERROR_INVALID_FUNCTION | ERROR_NOT_SUPPORTED => { local_tag_info.file_attributes = FILE_ATTRIBUTE_NORMAL; local_tag_info.reparse_tag = 0; } _ => return Err(std::io::Error::last_os_error()), } } else if local_tag_info.file_attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 { if is_reparse_tag_name_surrogate(local_tag_info.reparse_tag) { if is_unhandled_tag { return Err(std::io::Error::from_raw_os_error( ERROR_CANT_ACCESS_FILE as i32, )); } // This is a symlink, keep the tag info } else if !is_unhandled_tag { // Traverse a non-link reparse point unsafe { CloseHandle(h_file) }; return win32_xstat_slow_impl(path, true); } } tag_info = local_tag_info; } // Get file information let ret = unsafe { GetFileInformationByHandle(h_file, &mut file_info) }; if ret == 0 { let err_code = std::io::Error::last_os_error().raw_os_error().unwrap_or(0) as u32; match err_code { ERROR_INVALID_PARAMETER | ERROR_INVALID_FUNCTION | ERROR_NOT_SUPPORTED => { // Volumes and physical disks are block devices return Ok(StatStruct { st_mode: 0x6000, // S_IFBLK ..Default::default() }); } _ => return Err(std::io::Error::last_os_error()), } } // Get FILE_BASIC_INFO let mut basic_info: FILE_BASIC_INFO = unsafe { std::mem::zeroed() }; let has_basic_info = unsafe { GetFileInformationByHandleEx( h_file, FileBasicInfo, &mut basic_info as *mut _ as *mut _, std::mem::size_of::<FILE_BASIC_INFO>() as u32, ) } != 0; // Get FILE_ID_INFO (optional) let mut id_info: FILE_ID_INFO = unsafe { std::mem::zeroed() }; let has_id_info = unsafe { GetFileInformationByHandleEx( h_file, FileIdInfo, &mut id_info as *mut _ as *mut _, std::mem::size_of::<FILE_ID_INFO>() as u32, ) } != 0; let mut result = attribute_data_to_stat( &file_info, tag_info.reparse_tag, if has_basic_info { Some(&basic_info) } else { None }, if has_id_info { Some(&id_info) } else { None }, ); result.update_st_mode_from_path(path, file_info.dwFileAttributes); Ok(result) } else { // We got file_info from attributes_from_dir let mut result = attribute_data_to_stat(&file_info, tag_info.reparse_tag, None, None); result.update_st_mode_from_path(path, file_info.dwFileAttributes); Ok(result) } })(); // Cleanup if h_file != INVALID_HANDLE_VALUE { unsafe { CloseHandle(h_file) }; } result } fn win32_xstat_impl(path: &OsStr, traverse: bool) -> std::io::Result<StatStruct> { use windows_sys::Win32::{Foundation, Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT}; let stat_info = get_file_information_by_name(path, FILE_INFO_BY_NAME_CLASS::FileStatBasicByNameInfo); match stat_info { Ok(stat_info) => { if (stat_info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0) || (!traverse && is_reparse_tag_name_surrogate(stat_info.ReparseTag)) { let mut result = crate::common::fileutils::windows::stat_basic_info_to_stat(&stat_info); // If st_ino is 0, fall through to slow path to get proper file ID if result.st_ino != 0 || result.st_ino_high != 0 { result.update_st_mode_from_path(path, stat_info.FileAttributes); return Ok(result); } } } Err(e) => { if let Some(errno) = e.raw_os_error() && matches!( errno as u32, Foundation::ERROR_FILE_NOT_FOUND | Foundation::ERROR_PATH_NOT_FOUND | Foundation::ERROR_NOT_READY | Foundation::ERROR_BAD_NET_NAME ) { return Err(e); } } } // Fallback to slow implementation win32_xstat_slow_impl(path, traverse) }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/py_serde.rs
crates/vm/src/py_serde.rs
use num_traits::cast::ToPrimitive; use num_traits::sign::Signed; use serde::de::{DeserializeSeed, Visitor}; use serde::ser::{Serialize, SerializeMap, SerializeSeq}; use crate::builtins::{PyStr, bool_, dict::PyDictRef, float, int, list::PyList, tuple::PyTuple}; use crate::{AsObject, PyObject, PyObjectRef, VirtualMachine}; #[inline] pub fn serialize<S>( vm: &VirtualMachine, pyobject: &PyObject, serializer: S, ) -> Result<S::Ok, S::Error> where S: serde::Serializer, { PyObjectSerializer { pyobject, vm }.serialize(serializer) } #[inline] pub fn deserialize<'de, D>( vm: &'de VirtualMachine, deserializer: D, ) -> Result<<PyObjectDeserializer<'de> as DeserializeSeed<'de>>::Value, D::Error> where D: serde::Deserializer<'de>, { PyObjectDeserializer { vm }.deserialize(deserializer) } // We need to have a VM available to serialize a PyObject based on its subclass, so we implement // PyObject serialization via a proxy object which holds a reference to a VM pub struct PyObjectSerializer<'s> { pyobject: &'s PyObject, vm: &'s VirtualMachine, } impl<'s> PyObjectSerializer<'s> { pub fn new(vm: &'s VirtualMachine, pyobject: &'s PyObjectRef) -> Self { PyObjectSerializer { pyobject, vm } } fn clone_with_object(&self, pyobject: &'s PyObjectRef) -> PyObjectSerializer<'_> { PyObjectSerializer { pyobject, vm: self.vm, } } } impl serde::Serialize for PyObjectSerializer<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let serialize_seq_elements = |serializer: S, elements: &[PyObjectRef]| -> Result<S::Ok, S::Error> { let mut seq = serializer.serialize_seq(Some(elements.len()))?; for e in elements { seq.serialize_element(&self.clone_with_object(e))?; } seq.end() }; if let Some(s) = self.pyobject.downcast_ref::<PyStr>() { serializer.serialize_str(s.as_ref()) } else if self.pyobject.fast_isinstance(self.vm.ctx.types.float_type) { serializer.serialize_f64(float::get_value(self.pyobject)) } else if self.pyobject.fast_isinstance(self.vm.ctx.types.bool_type) { serializer.serialize_bool(bool_::get_value(self.pyobject)) } else if self.pyobject.fast_isinstance(self.vm.ctx.types.int_type) { let v = int::get_value(self.pyobject); let int_too_large = || serde::ser::Error::custom("int too large to serialize"); // TODO: serialize BigInt when it does not fit into i64 // BigInt implements serialization to a tuple of sign and a list of u32s, // eg. -1 is [-1, [1]], 0 is [0, []], 12345678900000654321 is [1, [2710766577,2874452364]] // CPython serializes big ints as long decimal integer literals if v.is_positive() { serializer.serialize_u64(v.to_u64().ok_or_else(int_too_large)?) } else { serializer.serialize_i64(v.to_i64().ok_or_else(int_too_large)?) } } else if let Some(list) = self.pyobject.downcast_ref::<PyList>() { serialize_seq_elements(serializer, &list.borrow_vec()) } else if let Some(tuple) = self.pyobject.downcast_ref::<PyTuple>() { serialize_seq_elements(serializer, tuple) } else if self.pyobject.fast_isinstance(self.vm.ctx.types.dict_type) { let dict: PyDictRef = self.pyobject.to_owned().downcast().unwrap(); let pairs: Vec<_> = dict.into_iter().collect(); let mut map = serializer.serialize_map(Some(pairs.len()))?; for (key, e) in &pairs { map.serialize_entry(&self.clone_with_object(key), &self.clone_with_object(e))?; } map.end() } else if self.vm.is_none(self.pyobject) { serializer.serialize_none() } else { Err(serde::ser::Error::custom(format!( "Object of type '{}' is not serializable", self.pyobject.class() ))) } } } // This object is used as the seed for deserialization so we have access to the Context for type // creation #[derive(Clone)] pub struct PyObjectDeserializer<'c> { vm: &'c VirtualMachine, } impl<'c> PyObjectDeserializer<'c> { pub fn new(vm: &'c VirtualMachine) -> Self { PyObjectDeserializer { vm } } } impl<'de> DeserializeSeed<'de> for PyObjectDeserializer<'de> { type Value = PyObjectRef; fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_any(self) } } impl<'de> Visitor<'de> for PyObjectDeserializer<'de> { type Value = PyObjectRef; fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { formatter.write_str("a type that can deserialize in Python") } fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(self.vm.ctx.new_bool(value).into()) } // Other signed integers delegate to this method by default, it’s the only one needed fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(self.vm.ctx.new_int(value).into()) } // Other unsigned integers delegate to this method by default, it’s the only one needed fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(self.vm.ctx.new_int(value).into()) } fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(self.vm.ctx.new_float(value).into()) } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: serde::de::Error, { // Owned value needed anyway, delegate to visit_string self.visit_string(value.to_owned()) } fn visit_string<E>(self, value: String) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(self.vm.ctx.new_str(value).into()) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(self.vm.ctx.none()) } fn visit_seq<A>(self, mut access: A) -> Result<Self::Value, A::Error> where A: serde::de::SeqAccess<'de>, { let mut seq = Vec::with_capacity(access.size_hint().unwrap_or(0)); while let Some(value) = access.next_element_seed(self.clone())? { seq.push(value); } Ok(self.vm.ctx.new_list(seq).into()) } fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error> where M: serde::de::MapAccess<'de>, { let dict = self.vm.ctx.new_dict(); // Although JSON keys must be strings, implementation accepts any keys // and can be reused by other deserializers without such limit while let Some((key_obj, value)) = access.next_entry_seed(self.clone(), self.clone())? { dict.set_item(&*key_obj, value, self.vm).unwrap(); } Ok(dict.into()) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/format.rs
crates/vm/src/format.rs
use crate::{ PyObject, PyResult, VirtualMachine, builtins::PyBaseExceptionRef, convert::{IntoPyException, ToPyException}, function::FuncArgs, stdlib::builtins, }; use crate::common::format::*; use crate::common::wtf8::{Wtf8, Wtf8Buf}; impl IntoPyException for FormatSpecError { fn into_pyexception(self, vm: &VirtualMachine) -> PyBaseExceptionRef { match self { Self::DecimalDigitsTooMany => { vm.new_value_error("Too many decimal digits in format string") } Self::PrecisionTooBig => vm.new_value_error("Precision too big"), Self::InvalidFormatSpecifier => vm.new_value_error("Invalid format specifier"), Self::UnspecifiedFormat(c1, c2) => { let msg = format!("Cannot specify '{c1}' with '{c2}'."); vm.new_value_error(msg) } Self::ExclusiveFormat(c1, c2) => { let msg = format!("Cannot specify both '{c1}' and '{c2}'."); vm.new_value_error(msg) } Self::UnknownFormatCode(c, s) => { let msg = format!("Unknown format code '{c}' for object of type '{s}'"); vm.new_value_error(msg) } Self::PrecisionNotAllowed => { vm.new_value_error("Precision not allowed in integer format specifier") } Self::NotAllowed(s) => { let msg = format!("{s} not allowed with integer format specifier 'c'"); vm.new_value_error(msg) } Self::UnableToConvert => vm.new_value_error("Unable to convert int to float"), Self::CodeNotInRange => vm.new_overflow_error("%c arg not in range(0x110000)"), Self::ZeroPadding => { vm.new_value_error("Zero padding is not allowed in complex format specifier") } Self::AlignmentFlag => { vm.new_value_error("'=' alignment flag is not allowed in complex format specifier") } Self::NotImplemented(c, s) => { let msg = format!("Format code '{c}' for object of type '{s}' not implemented yet"); vm.new_value_error(msg) } } } } impl ToPyException for FormatParseError { fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef { match self { Self::UnmatchedBracket => vm.new_value_error("expected '}' before end of string"), _ => vm.new_value_error("Unexpected error parsing format string"), } } } fn format_internal( vm: &VirtualMachine, format: &FormatString, field_func: &mut impl FnMut(FieldType) -> PyResult, ) -> PyResult<Wtf8Buf> { let mut final_string = Wtf8Buf::new(); for part in &format.format_parts { let pystr; let result_string: &Wtf8 = match part { FormatPart::Field { field_name, conversion_spec, format_spec, } => { let FieldName { field_type, parts } = FieldName::parse(field_name).map_err(|e| e.to_pyexception(vm))?; let mut argument = field_func(field_type)?; for name_part in parts { match name_part { FieldNamePart::Attribute(attribute) => { argument = argument.get_attr(&vm.ctx.new_str(attribute), vm)?; } FieldNamePart::Index(index) => { argument = argument.get_item(&index, vm)?; } FieldNamePart::StringIndex(index) => { argument = argument.get_item(&index, vm)?; } } } let nested_format = FormatString::from_str(format_spec).map_err(|e| e.to_pyexception(vm))?; let format_spec = format_internal(vm, &nested_format, field_func)?; let argument = match conversion_spec.and_then(FormatConversion::from_char) { Some(FormatConversion::Str) => argument.str(vm)?.into(), Some(FormatConversion::Repr) => argument.repr(vm)?.into(), Some(FormatConversion::Ascii) => { vm.ctx.new_str(builtins::ascii(argument, vm)?).into() } Some(FormatConversion::Bytes) => { vm.call_method(&argument, identifier!(vm, decode).as_str(), ())? } None => argument, }; // FIXME: compiler can intern specs using parser tree. Then this call can be interned_str pystr = vm.format(&argument, vm.ctx.new_str(format_spec))?; pystr.as_wtf8() } FormatPart::Literal(literal) => literal, }; final_string.push_wtf8(result_string); } Ok(final_string) } pub(crate) fn format( format: &FormatString, arguments: &FuncArgs, vm: &VirtualMachine, ) -> PyResult<Wtf8Buf> { let mut auto_argument_index: usize = 0; let mut seen_index = false; format_internal(vm, format, &mut |field_type| match field_type { FieldType::Auto => { if seen_index { return Err(vm.new_value_error( "cannot switch from manual field specification to automatic field numbering", )); } auto_argument_index += 1; arguments .args .get(auto_argument_index - 1) .cloned() .ok_or_else(|| vm.new_index_error("tuple index out of range")) } FieldType::Index(index) => { if auto_argument_index != 0 { return Err(vm.new_value_error( "cannot switch from automatic field numbering to manual field specification", )); } seen_index = true; arguments .args .get(index) .cloned() .ok_or_else(|| vm.new_index_error("tuple index out of range")) } FieldType::Keyword(keyword) => keyword .as_str() .ok() .and_then(|keyword| arguments.get_optional_kwarg(keyword)) .ok_or_else(|| vm.new_key_error(vm.ctx.new_str(keyword).into())), }) } pub(crate) fn format_map( format: &FormatString, dict: &PyObject, vm: &VirtualMachine, ) -> PyResult<Wtf8Buf> { format_internal(vm, format, &mut |field_type| match field_type { FieldType::Auto | FieldType::Index(_) => { Err(vm.new_value_error("Format string contains positional fields")) } FieldType::Keyword(keyword) => dict.get_item(&keyword, vm), }) }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/ospath.rs
crates/vm/src/ospath.rs
use rustpython_common::crt_fd; use crate::{ PyObjectRef, PyResult, VirtualMachine, builtins::{PyBytes, PyStr}, convert::{IntoPyException, ToPyException, ToPyObject, TryFromObject}, function::FsPath, }; use std::path::{Path, PathBuf}; /// path_converter #[derive(Clone, Copy, Default)] pub struct PathConverter { /// Function name for error messages (e.g., "rename") pub function_name: Option<&'static str>, /// Argument name for error messages (e.g., "src", "dst") pub argument_name: Option<&'static str>, /// If true, embedded null characters are allowed pub non_strict: bool, } impl PathConverter { pub const fn new() -> Self { Self { function_name: None, argument_name: None, non_strict: false, } } pub const fn function(mut self, name: &'static str) -> Self { self.function_name = Some(name); self } pub const fn argument(mut self, name: &'static str) -> Self { self.argument_name = Some(name); self } pub const fn non_strict(mut self) -> Self { self.non_strict = true; self } /// Generate error message prefix like "rename: " fn error_prefix(&self) -> String { match self.function_name { Some(func) => format!("{}: ", func), None => String::new(), } } /// Get argument name for error messages, defaults to "path" fn arg_name(&self) -> &'static str { self.argument_name.unwrap_or("path") } /// Format a type error message fn type_error_msg(&self, type_name: &str, allow_fd: bool) -> String { let expected = if allow_fd { "string, bytes, os.PathLike or integer" } else { "string, bytes or os.PathLike" }; format!( "{}{} should be {}, not {}", self.error_prefix(), self.arg_name(), expected, type_name ) } /// Convert to OsPathOrFd (path or file descriptor) pub(crate) fn try_path_or_fd<'fd>( &self, obj: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<OsPathOrFd<'fd>> { // Handle fd (before __fspath__ check, like CPython) if let Some(int) = obj.try_index_opt(vm) { let fd = int?.try_to_primitive(vm)?; return unsafe { crt_fd::Borrowed::try_borrow_raw(fd) } .map(OsPathOrFd::Fd) .map_err(|e| e.into_pyexception(vm)); } self.try_path_inner(obj, true, vm).map(OsPathOrFd::Path) } /// Convert to OsPath only (no fd support) fn try_path_inner( &self, obj: PyObjectRef, allow_fd: bool, vm: &VirtualMachine, ) -> PyResult<OsPath> { // Try direct str/bytes match let obj = match self.try_match_str_bytes(obj.clone(), vm)? { Ok(path) => return Ok(path), Err(obj) => obj, }; // Call __fspath__ let type_error_msg = || self.type_error_msg(&obj.class().name(), allow_fd); let method = vm.get_method_or_type_error(obj.clone(), identifier!(vm, __fspath__), type_error_msg)?; if vm.is_none(&method) { return Err(vm.new_type_error(type_error_msg())); } let result = method.call((), vm)?; // Match __fspath__ result self.try_match_str_bytes(result.clone(), vm)?.map_err(|_| { vm.new_type_error(format!( "{}expected {}.__fspath__() to return str or bytes, not {}", self.error_prefix(), obj.class().name(), result.class().name(), )) }) } /// Try to match str or bytes, returns Err(obj) if neither fn try_match_str_bytes( &self, obj: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<Result<OsPath, PyObjectRef>> { let check_nul = |b: &[u8]| { if self.non_strict || memchr::memchr(b'\0', b).is_none() { Ok(()) } else { Err(vm.new_value_error(format!( "{}embedded null character in {}", self.error_prefix(), self.arg_name() ))) } }; match_class!(match obj { s @ PyStr => { check_nul(s.as_bytes())?; let path = vm.fsencode(&s)?.into_owned(); Ok(Ok(OsPath { path, origin: Some(s.into()), })) } b @ PyBytes => { check_nul(&b)?; let path = FsPath::bytes_as_os_str(&b, vm)?.to_owned(); Ok(Ok(OsPath { path, origin: Some(b.into()), })) } obj => Ok(Err(obj)), }) } /// Convert to OsPath directly pub fn try_path(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<OsPath> { self.try_path_inner(obj, false, vm) } } /// path_t output - the converted path #[derive(Clone)] pub struct OsPath { pub path: std::ffi::OsString, /// Original Python object for identity preservation in OSError pub(super) origin: Option<PyObjectRef>, } #[derive(Debug, Copy, Clone)] pub enum OutputMode { String, Bytes, } impl OutputMode { pub(super) fn process_path(self, path: impl Into<PathBuf>, vm: &VirtualMachine) -> PyObjectRef { fn inner(mode: OutputMode, path: PathBuf, vm: &VirtualMachine) -> PyObjectRef { match mode { OutputMode::String => vm.fsdecode(path).into(), OutputMode::Bytes => vm .ctx .new_bytes(path.into_os_string().into_encoded_bytes()) .into(), } } inner(self, path.into(), vm) } } impl OsPath { pub fn new_str(path: impl Into<std::ffi::OsString>) -> Self { let path = path.into(); Self { path, origin: None } } pub(crate) fn from_fspath(fspath: FsPath, vm: &VirtualMachine) -> PyResult<Self> { let path = fspath.as_os_str(vm)?.into_owned(); let origin = match fspath { FsPath::Str(s) => s.into(), FsPath::Bytes(b) => b.into(), }; Ok(Self { path, origin: Some(origin), }) } /// Convert an object to OsPath using the os.fspath-style error message. /// This is used by open() which should report "expected str, bytes or os.PathLike object, not" /// instead of "should be string, bytes or os.PathLike, not". pub(crate) fn try_from_fspath(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> { let fspath = FsPath::try_from_path_like(obj, true, vm)?; Self::from_fspath(fspath, vm) } pub fn as_path(&self) -> &Path { Path::new(&self.path) } pub fn into_bytes(self) -> Vec<u8> { self.path.into_encoded_bytes() } pub fn to_string_lossy(&self) -> alloc::borrow::Cow<'_, str> { self.path.to_string_lossy() } pub fn into_cstring(self, vm: &VirtualMachine) -> PyResult<alloc::ffi::CString> { alloc::ffi::CString::new(self.into_bytes()).map_err(|err| err.to_pyexception(vm)) } #[cfg(windows)] pub fn to_wide_cstring(&self, vm: &VirtualMachine) -> PyResult<widestring::WideCString> { widestring::WideCString::from_os_str(&self.path).map_err(|err| err.to_pyexception(vm)) } pub fn filename(&self, vm: &VirtualMachine) -> PyObjectRef { if let Some(ref origin) = self.origin { origin.clone() } else { // Default to string when no origin (e.g., from new_str) OutputMode::String.process_path(self.path.clone(), vm) } } /// Get the output mode based on origin type (bytes -> Bytes, otherwise -> String) pub fn mode(&self) -> OutputMode { match &self.origin { Some(obj) if obj.downcast_ref::<PyBytes>().is_some() => OutputMode::Bytes, _ => OutputMode::String, } } } impl AsRef<Path> for OsPath { fn as_ref(&self) -> &Path { self.as_path() } } impl TryFromObject for OsPath { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { PathConverter::new().try_path(obj, vm) } } // path_t with allow_fd in CPython #[derive(Clone)] pub(crate) enum OsPathOrFd<'fd> { Path(OsPath), Fd(crt_fd::Borrowed<'fd>), } impl TryFromObject for OsPathOrFd<'_> { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { PathConverter::new().try_path_or_fd(obj, vm) } } impl From<OsPath> for OsPathOrFd<'_> { fn from(path: OsPath) -> Self { Self::Path(path) } } impl OsPathOrFd<'_> { pub fn filename(&self, vm: &VirtualMachine) -> PyObjectRef { match self { Self::Path(path) => path.filename(vm), Self::Fd(fd) => fd.to_pyobject(vm), } } } impl crate::exceptions::OSErrorBuilder { #[must_use] pub(crate) fn with_filename<'a>( error: &std::io::Error, filename: impl Into<OsPathOrFd<'a>>, vm: &VirtualMachine, ) -> crate::builtins::PyBaseExceptionRef { // TODO: return type to PyRef<PyOSError> use crate::exceptions::ToOSErrorBuilder; let builder = error.to_os_error_builder(vm); let builder = builder.filename(filename.into().filename(vm)); builder.build(vm).upcast() } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/bytes_inner.rs
crates/vm/src/bytes_inner.rs
// spell-checker:ignore unchunked use crate::{ AsObject, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, VirtualMachine, anystr::{self, AnyStr, AnyStrContainer, AnyStrWrapper}, builtins::{ PyBaseExceptionRef, PyByteArray, PyBytes, PyBytesRef, PyInt, PyIntRef, PyStr, PyStrRef, pystr, }, byte::bytes_from_object, cformat::cformat_bytes, common::hash, function::{ArgIterable, Either, OptionalArg, OptionalOption, PyComparisonValue}, literal::escape::Escape, protocol::PyBuffer, sequence::{SequenceExt, SequenceMutExt}, types::PyComparisonOp, }; use bstr::ByteSlice; use itertools::Itertools; use malachite_bigint::BigInt; use num_traits::ToPrimitive; const STRING_WITHOUT_ENCODING: &str = "string argument without an encoding"; const ENCODING_WITHOUT_STRING: &str = "encoding without a string argument"; #[derive(Debug, Default, Clone)] pub struct PyBytesInner { pub(super) elements: Vec<u8>, } impl From<Vec<u8>> for PyBytesInner { fn from(elements: Vec<u8>) -> Self { Self { elements } } } impl<'a> TryFromBorrowedObject<'a> for PyBytesInner { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> { bytes_from_object(vm, obj).map(Self::from) } } #[derive(FromArgs)] pub struct ByteInnerNewOptions { #[pyarg(any, optional)] pub source: OptionalArg<PyObjectRef>, #[pyarg(any, optional)] pub encoding: OptionalArg<PyStrRef>, #[pyarg(any, optional)] pub errors: OptionalArg<PyStrRef>, } impl ByteInnerNewOptions { fn get_value_from_string( s: PyStrRef, encoding: PyStrRef, errors: OptionalArg<PyStrRef>, vm: &VirtualMachine, ) -> PyResult<PyBytesInner> { let bytes = pystr::encode_string(s, Some(encoding), errors.into_option(), vm)?; Ok(bytes.as_bytes().to_vec().into()) } fn get_value_from_source(source: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyBytesInner> { bytes_from_object(vm, &source).map(|x| x.into()) } fn get_value_from_size(size: PyIntRef, vm: &VirtualMachine) -> PyResult<PyBytesInner> { let size = size .as_bigint() .to_isize() .ok_or_else(|| vm.new_overflow_error("cannot fit 'int' into an index-sized integer"))?; let size = if size < 0 { return Err(vm.new_value_error("negative count")); } else { size as usize }; Ok(vec![0; size].into()) } fn handle_object_fallback(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyBytesInner> { match_class!(match obj { i @ PyInt => { Self::get_value_from_size(i, vm) } _s @ PyStr => Err(vm.new_type_error(STRING_WITHOUT_ENCODING.to_owned())), obj => { Self::get_value_from_source(obj, vm) } }) } pub fn get_bytearray_inner(self, vm: &VirtualMachine) -> PyResult<PyBytesInner> { match (self.source, self.encoding, self.errors) { (OptionalArg::Present(obj), OptionalArg::Missing, OptionalArg::Missing) => { // Try __index__ first to handle int-like objects that might raise custom exceptions if let Some(index_result) = obj.try_index_opt(vm) { match index_result { Ok(index) => Self::get_value_from_size(index, vm), Err(e) => { // Only propagate non-TypeError exceptions // TypeError means the object doesn't support __index__, so fall back if e.fast_isinstance(vm.ctx.exceptions.type_error) { // Fall back to treating as buffer-like object Self::handle_object_fallback(obj, vm) } else { // Propagate other exceptions (e.g., ZeroDivisionError) Err(e) } } } } else { Self::handle_object_fallback(obj, vm) } } (OptionalArg::Present(obj), OptionalArg::Present(encoding), errors) => { if let Ok(s) = obj.downcast::<PyStr>() { Self::get_value_from_string(s, encoding, errors, vm) } else { Err(vm.new_type_error(ENCODING_WITHOUT_STRING.to_owned())) } } (OptionalArg::Missing, OptionalArg::Missing, OptionalArg::Missing) => { Ok(PyBytesInner::default()) } (OptionalArg::Missing, OptionalArg::Present(_), _) => { Err(vm.new_type_error(ENCODING_WITHOUT_STRING.to_owned())) } (OptionalArg::Missing, _, OptionalArg::Present(_)) => { Err(vm.new_type_error("errors without a string argument")) } (OptionalArg::Present(_), OptionalArg::Missing, OptionalArg::Present(_)) => { Err(vm.new_type_error(STRING_WITHOUT_ENCODING.to_owned())) } } } } #[derive(FromArgs)] pub struct ByteInnerFindOptions { #[pyarg(positional)] sub: Either<PyBytesInner, PyIntRef>, #[pyarg(positional, default)] start: Option<PyIntRef>, #[pyarg(positional, default)] end: Option<PyIntRef>, } impl ByteInnerFindOptions { pub fn get_value( self, len: usize, vm: &VirtualMachine, ) -> PyResult<(Vec<u8>, core::ops::Range<usize>)> { let sub = match self.sub { Either::A(v) => v.elements.to_vec(), Either::B(int) => vec![int.as_bigint().byte_or(vm)?], }; let range = anystr::adjust_indices(self.start, self.end, len); Ok((sub, range)) } } #[derive(FromArgs)] pub struct ByteInnerPaddingOptions { #[pyarg(positional)] width: isize, #[pyarg(positional, optional)] fillchar: OptionalArg<PyObjectRef>, } impl ByteInnerPaddingOptions { fn get_value(self, fn_name: &str, vm: &VirtualMachine) -> PyResult<(isize, u8)> { let fillchar = if let OptionalArg::Present(v) = self.fillchar { try_as_bytes(v.clone(), |bytes| bytes.iter().copied().exactly_one().ok()) .flatten() .ok_or_else(|| { vm.new_type_error(format!( "{}() argument 2 must be a byte string of length 1, not {}", fn_name, v.class().name() )) })? } else { b' ' // default is space }; Ok((self.width, fillchar)) } } #[derive(FromArgs)] pub struct ByteInnerTranslateOptions { #[pyarg(positional)] table: Option<PyObjectRef>, #[pyarg(any, optional)] delete: OptionalArg<PyObjectRef>, } impl ByteInnerTranslateOptions { pub fn get_value(self, vm: &VirtualMachine) -> PyResult<(Vec<u8>, Vec<u8>)> { let table = self.table.map_or_else( || Ok((0..=u8::MAX).collect::<Vec<u8>>()), |v| { let bytes = v .try_into_value::<PyBytesInner>(vm) .ok() .filter(|v| v.elements.len() == 256) .ok_or_else(|| { vm.new_value_error("translation table must be 256 characters long") })?; Ok(bytes.elements.to_vec()) }, )?; let delete = match self.delete { OptionalArg::Present(byte) => { let byte: PyBytesInner = byte.try_into_value(vm)?; byte.elements } _ => vec![], }; Ok((table, delete)) } } pub type ByteInnerSplitOptions = anystr::SplitArgs<PyBytesInner>; impl PyBytesInner { #[inline] pub fn as_bytes(&self) -> &[u8] { &self.elements } fn new_repr_overflow_error(vm: &VirtualMachine) -> PyBaseExceptionRef { vm.new_overflow_error("bytes object is too large to make repr") } pub fn repr_with_name(&self, class_name: &str, vm: &VirtualMachine) -> PyResult<String> { const DECORATION_LEN: isize = 2 + 3; // 2 for (), 3 for b"" => bytearray(b"") let escape = crate::literal::escape::AsciiEscape::new_repr(&self.elements); let len = escape .layout() .len .and_then(|len| (len as isize).checked_add(DECORATION_LEN + class_name.len() as isize)) .ok_or_else(|| Self::new_repr_overflow_error(vm))? as usize; let mut buf = String::with_capacity(len); buf.push_str(class_name); buf.push('('); escape.bytes_repr().write(&mut buf).unwrap(); buf.push(')'); debug_assert_eq!(buf.len(), len); Ok(buf) } pub fn repr_bytes(&self, vm: &VirtualMachine) -> PyResult<String> { let escape = crate::literal::escape::AsciiEscape::new_repr(&self.elements); let len = 3 + escape .layout() .len .ok_or_else(|| Self::new_repr_overflow_error(vm))?; let mut buf = String::with_capacity(len); escape.bytes_repr().write(&mut buf).unwrap(); debug_assert_eq!(buf.len(), len); Ok(buf) } #[inline] pub const fn len(&self) -> usize { self.elements.len() } #[inline] pub const fn capacity(&self) -> usize { self.elements.capacity() } #[inline] pub const fn is_empty(&self) -> bool { self.elements.is_empty() } pub fn cmp( &self, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyComparisonValue { // TODO: bytes can compare with any object implemented buffer protocol // but not memoryview, and not equal if compare with unicode str(PyStr) PyComparisonValue::from_option( other .try_bytes_like(vm, |other| op.eval_ord(self.elements.as_slice().cmp(other))) .ok(), ) } pub fn hash(&self, vm: &VirtualMachine) -> hash::PyHash { vm.state.hash_secret.hash_bytes(&self.elements) } pub fn add(&self, other: &[u8]) -> Vec<u8> { self.elements.py_add(other) } pub fn contains(&self, needle: Either<Self, PyIntRef>, vm: &VirtualMachine) -> PyResult<bool> { Ok(match needle { Either::A(byte) => self.elements.contains_str(byte.elements.as_slice()), Either::B(int) => self.elements.contains(&int.as_bigint().byte_or(vm)?), }) } pub fn isalnum(&self) -> bool { !self.elements.is_empty() && self .elements .iter() .all(|x| char::from(*x).is_alphanumeric()) } pub fn isalpha(&self) -> bool { !self.elements.is_empty() && self.elements.iter().all(|x| char::from(*x).is_alphabetic()) } pub fn isascii(&self) -> bool { self.elements.iter().all(|x| char::from(*x).is_ascii()) } pub fn isdigit(&self) -> bool { !self.elements.is_empty() && self .elements .iter() .all(|x| char::from(*x).is_ascii_digit()) } pub fn islower(&self) -> bool { self.elements.py_islower() } pub fn isupper(&self) -> bool { self.elements.py_isupper() } pub fn isspace(&self) -> bool { !self.elements.is_empty() && self .elements .iter() .all(|x| char::from(*x).is_ascii_whitespace()) } pub fn istitle(&self) -> bool { if self.elements.is_empty() { return false; } let mut iter = self.elements.iter().peekable(); let mut prev_cased = false; while let Some(c) = iter.next() { let current = char::from(*c); let next = if let Some(k) = iter.peek() { char::from(**k) } else if current.is_uppercase() { return !prev_cased; } else { return prev_cased; }; let is_cased = current.to_uppercase().next().unwrap() != current || current.to_lowercase().next().unwrap() != current; if (is_cased && next.is_uppercase() && !prev_cased) || (!is_cased && next.is_lowercase()) { return false; } prev_cased = is_cased; } true } pub fn lower(&self) -> Vec<u8> { self.elements.to_ascii_lowercase() } pub fn upper(&self) -> Vec<u8> { self.elements.to_ascii_uppercase() } pub fn capitalize(&self) -> Vec<u8> { let mut new: Vec<u8> = Vec::with_capacity(self.elements.len()); if let Some((first, second)) = self.elements.split_first() { new.push(first.to_ascii_uppercase()); second.iter().for_each(|x| new.push(x.to_ascii_lowercase())); } new } pub fn swapcase(&self) -> Vec<u8> { let mut new: Vec<u8> = Vec::with_capacity(self.elements.len()); for w in &self.elements { match w { b'A'..=b'Z' => new.push(w.to_ascii_lowercase()), b'a'..=b'z' => new.push(w.to_ascii_uppercase()), x => new.push(*x), } } new } pub fn hex( &self, sep: OptionalArg<Either<PyStrRef, PyBytesRef>>, bytes_per_sep: OptionalArg<isize>, vm: &VirtualMachine, ) -> PyResult<String> { bytes_to_hex(self.elements.as_slice(), sep, bytes_per_sep, vm) } pub fn fromhex(bytes: &[u8], vm: &VirtualMachine) -> PyResult<Vec<u8>> { let mut iter = bytes.iter().enumerate(); let mut bytes: Vec<u8> = Vec::with_capacity(bytes.len() / 2); let i = loop { let (i, &b) = match iter.next() { Some(val) => val, None => { return Ok(bytes); } }; if is_py_ascii_whitespace(b) { continue; } let top = match b { b'0'..=b'9' => b - b'0', b'a'..=b'f' => 10 + b - b'a', b'A'..=b'F' => 10 + b - b'A', _ => break i, }; let (i, b) = match iter.next() { Some(val) => val, None => break i + 1, }; let bot = match b { b'0'..=b'9' => b - b'0', b'a'..=b'f' => 10 + b - b'a', b'A'..=b'F' => 10 + b - b'A', _ => break i, }; bytes.push((top << 4) + bot); }; Err(vm.new_value_error(format!( "non-hexadecimal number found in fromhex() arg at position {i}" ))) } #[inline] fn _pad( &self, options: ByteInnerPaddingOptions, pad: fn(&[u8], usize, u8, usize) -> Vec<u8>, vm: &VirtualMachine, ) -> PyResult<Vec<u8>> { let (width, fillchar) = options.get_value("center", vm)?; let len = self.len(); Ok(if len as isize >= width { Vec::from(&self.elements[..]) } else { pad(&self.elements, width as usize, fillchar, len) }) } pub fn center( &self, options: ByteInnerPaddingOptions, vm: &VirtualMachine, ) -> PyResult<Vec<u8>> { self._pad(options, AnyStr::py_center, vm) } pub fn ljust( &self, options: ByteInnerPaddingOptions, vm: &VirtualMachine, ) -> PyResult<Vec<u8>> { self._pad(options, AnyStr::py_ljust, vm) } pub fn rjust( &self, options: ByteInnerPaddingOptions, vm: &VirtualMachine, ) -> PyResult<Vec<u8>> { self._pad(options, AnyStr::py_rjust, vm) } pub fn count(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> { let (needle, range) = options.get_value(self.elements.len(), vm)?; Ok(self .elements .py_count(needle.as_slice(), range, |h, n| h.find_iter(n).count())) } pub fn join(&self, iterable: ArgIterable<Self>, vm: &VirtualMachine) -> PyResult<Vec<u8>> { let iter = iterable.iter(vm)?; self.elements.py_join(iter) } #[inline] pub fn find<F>( &self, options: ByteInnerFindOptions, find: F, vm: &VirtualMachine, ) -> PyResult<Option<usize>> where F: Fn(&[u8], &[u8]) -> Option<usize>, { let (needle, range) = options.get_value(self.elements.len(), vm)?; Ok(self.elements.py_find(&needle, range, find)) } pub fn maketrans(from: Self, to: Self, vm: &VirtualMachine) -> PyResult<Vec<u8>> { if from.len() != to.len() { return Err(vm.new_value_error("the two maketrans arguments must have equal length")); } let mut res = vec![]; for i in 0..=u8::MAX { res.push(if let Some(position) = from.elements.find_byte(i) { to.elements[position] } else { i }); } Ok(res) } pub fn translate( &self, options: ByteInnerTranslateOptions, vm: &VirtualMachine, ) -> PyResult<Vec<u8>> { let (table, delete) = options.get_value(vm)?; let mut res = if delete.is_empty() { Vec::with_capacity(self.elements.len()) } else { Vec::new() }; for i in &self.elements { if !delete.contains(i) { res.push(table[*i as usize]); } } Ok(res) } pub fn strip(&self, chars: OptionalOption<Self>) -> Vec<u8> { self.elements .py_strip( chars, |s, chars| s.trim_with(|c| chars.contains(&(c as u8))), |s| s.trim(), ) .to_vec() } pub fn lstrip(&self, chars: OptionalOption<Self>) -> &[u8] { self.elements.py_strip( chars, |s, chars| s.trim_start_with(|c| chars.contains(&(c as u8))), |s| s.trim_start(), ) } pub fn rstrip(&self, chars: OptionalOption<Self>) -> &[u8] { self.elements.py_strip( chars, |s, chars| s.trim_end_with(|c| chars.contains(&(c as u8))), |s| s.trim_end(), ) } // new in Python 3.9 pub fn removeprefix(&self, prefix: Self) -> Vec<u8> { self.elements .py_removeprefix(&prefix.elements, prefix.elements.len(), |s, p| { s.starts_with(p) }) .to_vec() } // new in Python 3.9 pub fn removesuffix(&self, suffix: Self) -> Vec<u8> { self.elements .py_removesuffix(&suffix.elements, suffix.elements.len(), |s, p| { s.ends_with(p) }) .to_vec() } pub fn split<F>( &self, options: ByteInnerSplitOptions, convert: F, vm: &VirtualMachine, ) -> PyResult<Vec<PyObjectRef>> where F: Fn(&[u8], &VirtualMachine) -> PyObjectRef, { let elements = self.elements.py_split( options, vm, || convert(&self.elements, vm), |v, s, vm| v.split_str(s).map(|v| convert(v, vm)).collect(), |v, s, n, vm| v.splitn_str(n, s).map(|v| convert(v, vm)).collect(), |v, n, vm| v.py_split_whitespace(n, |v| convert(v, vm)), )?; Ok(elements) } pub fn rsplit<F>( &self, options: ByteInnerSplitOptions, convert: F, vm: &VirtualMachine, ) -> PyResult<Vec<PyObjectRef>> where F: Fn(&[u8], &VirtualMachine) -> PyObjectRef, { let mut elements = self.elements.py_split( options, vm, || convert(&self.elements, vm), |v, s, vm| v.rsplit_str(s).map(|v| convert(v, vm)).collect(), |v, s, n, vm| v.rsplitn_str(n, s).map(|v| convert(v, vm)).collect(), |v, n, vm| v.py_rsplit_whitespace(n, |v| convert(v, vm)), )?; elements.reverse(); Ok(elements) } pub fn partition(&self, sub: &Self, vm: &VirtualMachine) -> PyResult<(Vec<u8>, bool, Vec<u8>)> { self.elements.py_partition( &sub.elements, || self.elements.splitn_str(2, &sub.elements), vm, ) } pub fn rpartition( &self, sub: &Self, vm: &VirtualMachine, ) -> PyResult<(Vec<u8>, bool, Vec<u8>)> { self.elements.py_partition( &sub.elements, || self.elements.rsplitn_str(2, &sub.elements), vm, ) } pub fn expandtabs(&self, options: anystr::ExpandTabsArgs) -> Vec<u8> { let tabsize = options.tabsize(); let mut counter: usize = 0; let mut res = vec![]; if tabsize == 0 { return self .elements .iter() .copied() .filter(|x| *x != b'\t') .collect(); } for i in &self.elements { if *i == b'\t' { let len = tabsize - counter % tabsize; res.extend_from_slice(&vec![b' '; len]); counter += len; } else { res.push(*i); if *i == b'\r' || *i == b'\n' { counter = 0; } else { counter += 1; } } } res } pub fn splitlines<FW, W>(&self, options: anystr::SplitLinesArgs, into_wrapper: FW) -> Vec<W> where FW: Fn(&[u8]) -> W, { self.elements.py_bytes_splitlines(options, into_wrapper) } pub fn zfill(&self, width: isize) -> Vec<u8> { self.elements.py_zfill(width) } // len(self)>=1, from="", len(to)>=1, max_count>=1 fn replace_interleave(&self, to: Self, max_count: Option<usize>) -> Vec<u8> { let place_count = self.elements.len() + 1; let count = max_count.map_or(place_count, |v| core::cmp::min(v, place_count)) - 1; let capacity = self.elements.len() + count * to.len(); let mut result = Vec::with_capacity(capacity); let to_slice = to.elements.as_slice(); result.extend_from_slice(to_slice); for c in &self.elements[..count] { result.push(*c); result.extend_from_slice(to_slice); } result.extend_from_slice(&self.elements[count..]); result } fn replace_delete(&self, from: Self, max_count: Option<usize>) -> Vec<u8> { let count = count_substring( self.elements.as_slice(), from.elements.as_slice(), max_count, ); if count == 0 { // no matches return self.elements.clone(); } let result_len = self.len() - (count * from.len()); debug_assert!(self.len() >= count * from.len()); let mut result = Vec::with_capacity(result_len); let mut last_end = 0; let mut count = count; for offset in self.elements.find_iter(&from.elements) { result.extend_from_slice(&self.elements[last_end..offset]); last_end = offset + from.len(); count -= 1; if count == 0 { break; } } result.extend_from_slice(&self.elements[last_end..]); result } pub fn replace_in_place(&self, from: Self, to: Self, max_count: Option<usize>) -> Vec<u8> { let len = from.len(); let mut iter = self.elements.find_iter(&from.elements); let mut new = if let Some(offset) = iter.next() { let mut new = self.elements.clone(); new[offset..offset + len].clone_from_slice(to.elements.as_slice()); if max_count == Some(1) { return new; } else { new } } else { return self.elements.clone(); }; let mut count = max_count.unwrap_or(usize::MAX) - 1; for offset in iter { new[offset..offset + len].clone_from_slice(to.elements.as_slice()); count -= 1; if count == 0 { break; } } new } fn replace_general( &self, from: Self, to: Self, max_count: Option<usize>, vm: &VirtualMachine, ) -> PyResult<Vec<u8>> { let count = count_substring( self.elements.as_slice(), from.elements.as_slice(), max_count, ); if count == 0 { // no matches, return unchanged return Ok(self.elements.clone()); } // Check for overflow // result_len = self_len + count * (to_len-from_len) debug_assert!(count > 0); if to.len() as isize - from.len() as isize > (isize::MAX - self.elements.len() as isize) / count as isize { return Err(vm.new_overflow_error("replace bytes is too long")); } let result_len = (self.elements.len() as isize + count as isize * (to.len() as isize - from.len() as isize)) as usize; let mut result = Vec::with_capacity(result_len); let mut last_end = 0; let mut count = count; for offset in self.elements.find_iter(&from.elements) { result.extend_from_slice(&self.elements[last_end..offset]); result.extend_from_slice(to.elements.as_slice()); last_end = offset + from.len(); count -= 1; if count == 0 { break; } } result.extend_from_slice(&self.elements[last_end..]); Ok(result) } pub fn replace( &self, from: Self, to: Self, max_count: OptionalArg<isize>, vm: &VirtualMachine, ) -> PyResult<Vec<u8>> { // stringlib_replace in CPython let max_count = match max_count { OptionalArg::Present(max_count) if max_count >= 0 => { if max_count == 0 || (self.elements.is_empty() && !from.is_empty()) { // nothing to do; return the original bytes return Ok(self.elements.clone()); } else if self.elements.is_empty() && from.is_empty() { return Ok(to.elements); } Some(max_count as usize) } _ => None, }; // Handle zero-length special cases if from.elements.is_empty() { if to.elements.is_empty() { // nothing to do; return the original bytes return Ok(self.elements.clone()); } // insert the 'to' bytes everywhere. // >>> b"Python".replace(b"", b".") // b'.P.y.t.h.o.n.' return Ok(self.replace_interleave(to, max_count)); } // Except for b"".replace(b"", b"A") == b"A" there is no way beyond this // point for an empty self bytes to generate a non-empty bytes // Special case so the remaining code always gets a non-empty bytes if self.elements.is_empty() { return Ok(self.elements.clone()); } if to.elements.is_empty() { // delete all occurrences of 'from' bytes Ok(self.replace_delete(from, max_count)) } else if from.len() == to.len() { // Handle special case where both bytes have the same length Ok(self.replace_in_place(from, to, max_count)) } else { // Otherwise use the more generic algorithms self.replace_general(from, to, max_count, vm) } } pub fn title(&self) -> Vec<u8> { let mut res = vec![]; let mut spaced = true; for i in &self.elements { match i { b'A'..=b'Z' | b'a'..=b'z' => { if spaced { res.push(i.to_ascii_uppercase()); spaced = false } else { res.push(i.to_ascii_lowercase()); } } _ => { res.push(*i); spaced = true } } } res } pub fn cformat(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult<Vec<u8>> { cformat_bytes(vm, self.elements.as_slice(), values) } pub fn mul(&self, n: isize, vm: &VirtualMachine) -> PyResult<Vec<u8>> { self.elements.mul(vm, n) } pub fn imul(&mut self, n: isize, vm: &VirtualMachine) -> PyResult<()> { self.elements.imul(vm, n) } pub fn concat(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult<Vec<u8>> { let buffer = PyBuffer::try_from_borrowed_object(vm, other)?; let borrowed = buffer.as_contiguous(); if let Some(other) = borrowed { let mut v = Vec::with_capacity(self.elements.len() + other.len()); v.extend_from_slice(&self.elements); v.extend_from_slice(&other); Ok(v) } else { let mut v = self.elements.clone(); buffer.append_to(&mut v); Ok(v) } } } pub fn try_as_bytes<F, R>(obj: PyObjectRef, f: F) -> Option<R> where F: Fn(&[u8]) -> R, { match_class!(match obj { i @ PyBytes => Some(f(i.as_bytes())), j @ PyByteArray => Some(f(&j.borrow_buf())), _ => None, }) } #[inline] fn count_substring(haystack: &[u8], needle: &[u8], max_count: Option<usize>) -> usize { let substrings = haystack.find_iter(needle); if let Some(max_count) = max_count { core::cmp::min(substrings.take(max_count).count(), max_count) } else { substrings.count() } } pub trait ByteOr: ToPrimitive { fn byte_or(&self, vm: &VirtualMachine) -> PyResult<u8> { match self.to_u8() { Some(value) => Ok(value), None => Err(vm.new_value_error("byte must be in range(0, 256)")), } } } impl ByteOr for BigInt {} impl AnyStrWrapper<[u8]> for PyBytesInner { fn as_ref(&self) -> Option<&[u8]> { Some(&self.elements) } fn is_empty(&self) -> bool { self.elements.is_empty() } } impl AnyStrContainer<[u8]> for Vec<u8> { fn new() -> Self { Self::new() } fn with_capacity(capacity: usize) -> Self { Self::with_capacity(capacity) } fn push_str(&mut self, other: &[u8]) { self.extend(other) } } const ASCII_WHITESPACES: [u8; 6] = [0x20, 0x09, 0x0a, 0x0c, 0x0d, 0x0b]; impl anystr::AnyChar for u8 { fn is_lowercase(self) -> bool { self.is_ascii_lowercase() } fn is_uppercase(self) -> bool { self.is_ascii_uppercase() } fn bytes_len(self) -> usize { 1 } } impl AnyStr for [u8] { type Char = u8; type Container = Vec<u8>; fn to_container(&self) -> Self::Container { self.to_vec() } fn as_bytes(&self) -> &[u8] { self } fn elements(&self) -> impl Iterator<Item = u8> { self.iter().copied() } fn get_bytes(&self, range: core::ops::Range<usize>) -> &Self { &self[range] } fn get_chars(&self, range: core::ops::Range<usize>) -> &Self { &self[range] } fn is_empty(&self) -> bool { Self::is_empty(self) } fn bytes_len(&self) -> usize { Self::len(self) } fn py_split_whitespace<F>(&self, maxsplit: isize, convert: F) -> Vec<PyObjectRef> where F: Fn(&Self) -> PyObjectRef, { let mut splits = Vec::new(); let mut count = maxsplit; let mut haystack = self; while let Some(offset) = haystack.find_byteset(ASCII_WHITESPACES) { if offset != 0 { if count == 0 { break; } splits.push(convert(&haystack[..offset])); count -= 1; } haystack = &haystack[offset + 1..]; } if !haystack.is_empty() { splits.push(convert(haystack)); } splits } fn py_rsplit_whitespace<F>(&self, maxsplit: isize, convert: F) -> Vec<PyObjectRef> where
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/intern.rs
crates/vm/src/intern.rs
use rustpython_common::wtf8::{Wtf8, Wtf8Buf}; use crate::{ AsObject, Py, PyExact, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact, VirtualMachine, builtins::{PyStr, PyStrInterned, PyTypeRef}, common::lock::PyRwLock, convert::ToPyObject, }; use alloc::borrow::ToOwned; use core::{borrow::Borrow, ops::Deref}; #[derive(Debug)] pub struct StringPool { inner: PyRwLock<std::collections::HashSet<CachedPyStrRef, ahash::RandomState>>, } impl Default for StringPool { fn default() -> Self { Self { inner: PyRwLock::new(Default::default()), } } } impl Clone for StringPool { fn clone(&self) -> Self { Self { inner: PyRwLock::new(self.inner.read().clone()), } } } impl StringPool { #[inline] pub unsafe fn intern<S: InternableString>( &self, s: S, typ: PyTypeRef, ) -> &'static PyStrInterned { if let Some(found) = self.interned(s.as_ref()) { return found; } #[cold] fn miss(zelf: &StringPool, s: PyRefExact<PyStr>) -> &'static PyStrInterned { let cache = CachedPyStrRef { inner: s }; let inserted = zelf.inner.write().insert(cache.clone()); if inserted { let interned = unsafe { cache.as_interned_str() }; unsafe { interned.as_object().mark_intern() }; interned } else { unsafe { zelf.inner .read() .get(cache.as_ref()) .expect("inserted is false") .as_interned_str() } } } let str_ref = s.into_pyref_exact(typ); miss(self, str_ref) } #[inline] pub fn interned<S: MaybeInternedString + ?Sized>( &self, s: &S, ) -> Option<&'static PyStrInterned> { if let Some(interned) = s.as_interned() { return Some(interned); } self.inner .read() .get(s.as_ref()) .map(|cached| unsafe { cached.as_interned_str() }) } } #[derive(Debug, Clone)] #[repr(transparent)] pub struct CachedPyStrRef { inner: PyRefExact<PyStr>, } impl core::hash::Hash for CachedPyStrRef { fn hash<H: core::hash::Hasher>(&self, state: &mut H) { self.inner.as_wtf8().hash(state) } } impl PartialEq for CachedPyStrRef { fn eq(&self, other: &Self) -> bool { self.inner.as_wtf8() == other.inner.as_wtf8() } } impl Eq for CachedPyStrRef {} impl core::borrow::Borrow<Wtf8> for CachedPyStrRef { #[inline] fn borrow(&self) -> &Wtf8 { self.as_wtf8() } } impl AsRef<Wtf8> for CachedPyStrRef { #[inline] fn as_ref(&self) -> &Wtf8 { self.as_wtf8() } } impl CachedPyStrRef { /// # Safety /// the given cache must be alive while returned reference is alive #[inline] const unsafe fn as_interned_str(&self) -> &'static PyStrInterned { unsafe { core::mem::transmute_copy(self) } } #[inline] fn as_wtf8(&self) -> &Wtf8 { self.inner.as_wtf8() } } pub struct PyInterned<T> { inner: Py<T>, } impl<T: PyPayload> PyInterned<T> { #[inline] pub fn leak(cache: PyRef<T>) -> &'static Self { unsafe { core::mem::transmute(cache) } } #[inline] const fn as_ptr(&self) -> *const Py<T> { self as *const _ as *const _ } #[inline] pub fn to_owned(&'static self) -> PyRef<T> { unsafe { (*(&self as *const _ as *const PyRef<T>)).clone() } } #[inline] pub fn to_object(&'static self) -> PyObjectRef { self.to_owned().into() } } impl<T: PyPayload> Borrow<PyObject> for PyInterned<T> { #[inline(always)] fn borrow(&self) -> &PyObject { self.inner.borrow() } } // NOTE: std::hash::Hash of Self and Self::Borrowed *must* be the same // This is ok only because PyObject doesn't implement Hash impl<T: PyPayload> core::hash::Hash for PyInterned<T> { #[inline(always)] fn hash<H: core::hash::Hasher>(&self, state: &mut H) { self.get_id().hash(state) } } impl<T> AsRef<Py<T>> for PyInterned<T> { #[inline(always)] fn as_ref(&self) -> &Py<T> { &self.inner } } impl<T> Deref for PyInterned<T> { type Target = Py<T>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.inner } } impl<T: PyPayload> PartialEq for PyInterned<T> { #[inline(always)] fn eq(&self, other: &Self) -> bool { core::ptr::eq(self, other) } } impl<T: PyPayload> Eq for PyInterned<T> {} impl<T: core::fmt::Debug + PyPayload> core::fmt::Debug for PyInterned<T> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { core::fmt::Debug::fmt(&**self, f)?; write!(f, "@{:p}", self.as_ptr()) } } impl<T: PyPayload> ToPyObject for &'static PyInterned<T> { fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { self.to_owned().into() } } mod sealed { use rustpython_common::wtf8::{Wtf8, Wtf8Buf}; use crate::{ builtins::PyStr, object::{Py, PyExact, PyRefExact}, }; pub trait SealedInternable {} impl SealedInternable for String {} impl SealedInternable for &str {} impl SealedInternable for Wtf8Buf {} impl SealedInternable for &Wtf8 {} impl SealedInternable for PyRefExact<PyStr> {} pub trait SealedMaybeInterned {} impl SealedMaybeInterned for str {} impl SealedMaybeInterned for Wtf8 {} impl SealedMaybeInterned for PyExact<PyStr> {} impl SealedMaybeInterned for Py<PyStr> {} } /// A sealed marker trait for `DictKey` types that always become an exact instance of `str` pub trait InternableString: sealed::SealedInternable + ToPyObject + AsRef<Self::Interned> { type Interned: MaybeInternedString + ?Sized; fn into_pyref_exact(self, str_type: PyTypeRef) -> PyRefExact<PyStr>; } impl InternableString for String { type Interned = str; #[inline] fn into_pyref_exact(self, str_type: PyTypeRef) -> PyRefExact<PyStr> { let obj = PyRef::new_ref(PyStr::from(self), str_type, None); unsafe { PyRefExact::new_unchecked(obj) } } } impl InternableString for &str { type Interned = str; #[inline] fn into_pyref_exact(self, str_type: PyTypeRef) -> PyRefExact<PyStr> { self.to_owned().into_pyref_exact(str_type) } } impl InternableString for Wtf8Buf { type Interned = Wtf8; fn into_pyref_exact(self, str_type: PyTypeRef) -> PyRefExact<PyStr> { let obj = PyRef::new_ref(PyStr::from(self), str_type, None); unsafe { PyRefExact::new_unchecked(obj) } } } impl InternableString for &Wtf8 { type Interned = Wtf8; fn into_pyref_exact(self, str_type: PyTypeRef) -> PyRefExact<PyStr> { self.to_owned().into_pyref_exact(str_type) } } impl InternableString for PyRefExact<PyStr> { type Interned = Py<PyStr>; #[inline] fn into_pyref_exact(self, _str_type: PyTypeRef) -> PyRefExact<PyStr> { self } } pub trait MaybeInternedString: AsRef<Wtf8> + crate::dict_inner::DictKey + sealed::SealedMaybeInterned { fn as_interned(&self) -> Option<&'static PyStrInterned>; } impl MaybeInternedString for str { #[inline(always)] fn as_interned(&self) -> Option<&'static PyStrInterned> { None } } impl MaybeInternedString for Wtf8 { #[inline(always)] fn as_interned(&self) -> Option<&'static PyStrInterned> { None } } impl MaybeInternedString for PyExact<PyStr> { #[inline(always)] fn as_interned(&self) -> Option<&'static PyStrInterned> { None } } impl MaybeInternedString for Py<PyStr> { #[inline(always)] fn as_interned(&self) -> Option<&'static PyStrInterned> { if self.as_object().is_interned() { Some(unsafe { core::mem::transmute::<&Self, &PyInterned<PyStr>>(self) }) } else { None } } } impl PyObject { #[inline] pub fn as_interned_str(&self, vm: &crate::VirtualMachine) -> Option<&'static PyStrInterned> { let s: Option<&Py<PyStr>> = self.downcast_ref(); if self.is_interned() { s.unwrap().as_interned() } else if let Some(s) = s { vm.ctx.interned_str(s.as_wtf8()) } else { None } } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/eval.rs
crates/vm/src/eval.rs
use crate::{PyResult, VirtualMachine, compiler, scope::Scope}; pub fn eval(vm: &VirtualMachine, source: &str, scope: Scope, source_path: &str) -> PyResult { match vm.compile(source, compiler::Mode::Eval, source_path.to_owned()) { Ok(bytecode) => { debug!("Code object: {bytecode:?}"); vm.run_code_obj(bytecode, scope) } Err(err) => Err(vm.new_syntax_error(&err, Some(source))), } } #[cfg(test)] mod tests { use super::*; use crate::Interpreter; #[test] fn test_print_42() { Interpreter::without_stdlib(Default::default()).enter(|vm| { let source = String::from("print('Hello world')"); let vars = vm.new_scope_with_builtins(); let result = eval(vm, &source, vars, "<unittest>").expect("this should pass"); assert!(vm.is_none(&result)); }) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/frame.rs
crates/vm/src/frame.rs
use crate::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, builtins::{ PyBaseException, PyBaseExceptionRef, PyCode, PyCoroutine, PyDict, PyDictRef, PyGenerator, PyList, PySet, PySlice, PyStr, PyStrInterned, PyStrRef, PyTraceback, PyType, asyncgenerator::PyAsyncGenWrappedValue, function::{PyCell, PyCellRef, PyFunction}, tuple::{PyTuple, PyTupleRef}, }, bytecode, convert::{IntoObject, ToPyResult}, coroutine::Coro, exceptions::ExceptionCtor, function::{ArgMapping, Either, FuncArgs}, protocol::{PyIter, PyIterReturn}, scope::Scope, stdlib::{builtins, typing}, types::PyTypeFlags, vm::{Context, PyMethod}, }; use alloc::fmt; use core::iter::zip; #[cfg(feature = "threading")] use core::sync::atomic; use indexmap::IndexMap; use itertools::Itertools; use rustpython_common::{boxvec::BoxVec, lock::PyMutex, wtf8::Wtf8Buf}; use rustpython_compiler_core::SourceLocation; pub type FrameRef = PyRef<Frame>; /// The reason why we might be unwinding a block. /// This could be return of function, exception being /// raised, a break or continue being hit, etc.. #[derive(Clone, Debug)] enum UnwindReason { /// We are returning a value from a return statement. Returning { value: PyObjectRef }, /// We hit an exception, so unwind any try-except and finally blocks. The exception should be /// on top of the vm exception stack. Raising { exception: PyBaseExceptionRef }, // NoWorries, /// We are unwinding blocks, since we hit break Break { target: bytecode::Label }, /// We are unwinding blocks since we hit a continue statements. Continue { target: bytecode::Label }, } #[derive(Debug)] struct FrameState { // We need 1 stack per frame /// The main data frame of the stack machine stack: BoxVec<PyObjectRef>, /// index of last instruction ran #[cfg(feature = "threading")] lasti: u32, } #[cfg(feature = "threading")] type Lasti = atomic::AtomicU32; #[cfg(not(feature = "threading"))] type Lasti = core::cell::Cell<u32>; #[pyclass(module = false, name = "frame")] pub struct Frame { pub code: PyRef<PyCode>, pub func_obj: Option<PyObjectRef>, pub fastlocals: PyMutex<Box<[Option<PyObjectRef>]>>, pub(crate) cells_frees: Box<[PyCellRef]>, pub locals: ArgMapping, pub globals: PyDictRef, pub builtins: PyDictRef, // on feature=threading, this is a duplicate of FrameState.lasti, but it's faster to do an // atomic store than it is to do a fetch_add, for every instruction executed /// index of last instruction ran pub lasti: Lasti, /// tracer function for this frame (usually is None) pub trace: PyMutex<PyObjectRef>, state: PyMutex<FrameState>, // member pub trace_lines: PyMutex<bool>, pub temporary_refs: PyMutex<Vec<PyObjectRef>>, } impl PyPayload for Frame { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.frame_type } } // Running a frame can result in one of the below: pub enum ExecutionResult { Return(PyObjectRef), Yield(PyObjectRef), } /// A valid execution result, or an exception type FrameResult = PyResult<Option<ExecutionResult>>; impl Frame { pub(crate) fn new( code: PyRef<PyCode>, scope: Scope, builtins: PyDictRef, closure: &[PyCellRef], func_obj: Option<PyObjectRef>, vm: &VirtualMachine, ) -> Self { let cells_frees = core::iter::repeat_with(|| PyCell::default().into_ref(&vm.ctx)) .take(code.cellvars.len()) .chain(closure.iter().cloned()) .collect(); let state = FrameState { stack: BoxVec::new(code.max_stackdepth as usize), #[cfg(feature = "threading")] lasti: 0, }; Self { fastlocals: PyMutex::new(vec![None; code.varnames.len()].into_boxed_slice()), cells_frees, locals: scope.locals, globals: scope.globals, builtins, code, func_obj, lasti: Lasti::new(0), state: PyMutex::new(state), trace: PyMutex::new(vm.ctx.none()), trace_lines: PyMutex::new(true), temporary_refs: PyMutex::new(vec![]), } } pub fn current_location(&self) -> SourceLocation { self.code.locations[self.lasti() as usize - 1].0 } pub fn lasti(&self) -> u32 { #[cfg(feature = "threading")] { self.lasti.load(atomic::Ordering::Relaxed) } #[cfg(not(feature = "threading"))] { self.lasti.get() } } pub fn locals(&self, vm: &VirtualMachine) -> PyResult<ArgMapping> { let locals = &self.locals; let code = &**self.code; let map = &code.varnames; let j = core::cmp::min(map.len(), code.varnames.len()); if !code.varnames.is_empty() { let fastlocals = self.fastlocals.lock(); for (&k, v) in zip(&map[..j], &**fastlocals) { match locals.mapping().ass_subscript(k, v.clone(), vm) { Ok(()) => {} Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {} Err(e) => return Err(e), } } } if !code.cellvars.is_empty() || !code.freevars.is_empty() { let map_to_dict = |keys: &[&PyStrInterned], values: &[PyCellRef]| { for (&k, v) in zip(keys, values) { if let Some(value) = v.get() { locals.mapping().ass_subscript(k, Some(value), vm)?; } else { match locals.mapping().ass_subscript(k, None, vm) { Ok(()) => {} Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {} Err(e) => return Err(e), } } } Ok(()) }; map_to_dict(&code.cellvars, &self.cells_frees)?; if code.flags.contains(bytecode::CodeFlags::IS_OPTIMIZED) { map_to_dict(&code.freevars, &self.cells_frees[code.cellvars.len()..])?; } } Ok(locals.clone()) } } impl Py<Frame> { #[inline(always)] fn with_exec<R>(&self, f: impl FnOnce(ExecutingFrame<'_>) -> R) -> R { let mut state = self.state.lock(); let exec = ExecutingFrame { code: &self.code, fastlocals: &self.fastlocals, cells_frees: &self.cells_frees, locals: &self.locals, globals: &self.globals, builtins: &self.builtins, lasti: &self.lasti, object: self, state: &mut state, }; f(exec) } // #[cfg_attr(feature = "flame-it", flame("Frame"))] pub fn run(&self, vm: &VirtualMachine) -> PyResult<ExecutionResult> { self.with_exec(|mut exec| exec.run(vm)) } pub(crate) fn resume( &self, value: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<ExecutionResult> { self.with_exec(|mut exec| { if let Some(value) = value { exec.push_value(value) } exec.run(vm) }) } pub(crate) fn gen_throw( &self, vm: &VirtualMachine, exc_type: PyObjectRef, exc_val: PyObjectRef, exc_tb: PyObjectRef, ) -> PyResult<ExecutionResult> { self.with_exec(|mut exec| exec.gen_throw(vm, exc_type, exc_val, exc_tb)) } pub fn yield_from_target(&self) -> Option<PyObjectRef> { self.with_exec(|exec| exec.yield_from_target().map(PyObject::to_owned)) } pub fn is_internal_frame(&self) -> bool { let code = self.f_code(); let filename = code.co_filename(); let filename_s = filename.as_str(); filename_s.contains("importlib") && filename_s.contains("_bootstrap") } pub fn next_external_frame(&self, vm: &VirtualMachine) -> Option<FrameRef> { self.f_back(vm).map(|mut back| { loop { back = if let Some(back) = back.to_owned().f_back(vm) { back } else { break back; }; if !back.is_internal_frame() { break back; } } }) } } /// An executing frame; essentially just a struct to combine the immutable data outside the mutex /// with the mutable data inside struct ExecutingFrame<'a> { code: &'a PyRef<PyCode>, fastlocals: &'a PyMutex<Box<[Option<PyObjectRef>]>>, cells_frees: &'a [PyCellRef], locals: &'a ArgMapping, globals: &'a PyDictRef, builtins: &'a PyDictRef, object: &'a Py<Frame>, lasti: &'a Lasti, state: &'a mut FrameState, } impl fmt::Debug for ExecutingFrame<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ExecutingFrame") .field("code", self.code) // .field("scope", self.scope) .field("state", self.state) .finish() } } impl ExecutingFrame<'_> { #[inline(always)] fn update_lasti(&mut self, f: impl FnOnce(&mut u32)) { #[cfg(feature = "threading")] { f(&mut self.state.lasti); self.lasti .store(self.state.lasti, atomic::Ordering::Relaxed); } #[cfg(not(feature = "threading"))] { let mut lasti = self.lasti.get(); f(&mut lasti); self.lasti.set(lasti); } } #[inline(always)] const fn lasti(&self) -> u32 { #[cfg(feature = "threading")] { self.state.lasti } #[cfg(not(feature = "threading"))] { self.lasti.get() } } fn run(&mut self, vm: &VirtualMachine) -> PyResult<ExecutionResult> { flame_guard!(format!( "Frame::run({obj_name})", obj_name = self.code.obj_name )); // Execute until return or exception: let instructions = &self.code.instructions; let mut arg_state = bytecode::OpArgState::default(); loop { let idx = self.lasti() as usize; self.update_lasti(|i| *i += 1); let bytecode::CodeUnit { op, arg } = instructions[idx]; let arg = arg_state.extend(arg); let mut do_extend_arg = false; let result = self.execute_instruction(op, arg, &mut do_extend_arg, vm); match result { Ok(None) => {} Ok(Some(value)) => { break Ok(value); } // Instruction raised an exception Err(exception) => { #[cold] fn handle_exception( frame: &mut ExecutingFrame<'_>, exception: PyBaseExceptionRef, idx: usize, is_reraise: bool, vm: &VirtualMachine, ) -> FrameResult { // 1. Extract traceback from exception's '__traceback__' attr. // 2. Add new entry with current execution position (filename, lineno, code_object) to traceback. // 3. First, try to find handler in exception table // RERAISE instructions should not add traceback entries - they're just // re-raising an already-processed exception if !is_reraise { // PyTraceBack_Here always adds a new entry without // checking for duplicates. Each time an exception passes through // a frame (e.g., in a loop with repeated raise statements), // a new traceback entry is added. let (loc, _end_loc) = frame.code.locations[idx]; let next = exception.__traceback__(); let new_traceback = PyTraceback::new( next, frame.object.to_owned(), idx as u32 * 2, loc.line, ); vm_trace!("Adding to traceback: {:?} {:?}", new_traceback, loc.line); exception.set_traceback_typed(Some(new_traceback.into_ref(&vm.ctx))); } // Only contextualize exception for new raises, not re-raises // CPython only calls _PyErr_SetObject (which does chaining) on initial raise // RERAISE just propagates the exception without modifying __context__ if !is_reraise { vm.contextualize_exception(&exception); } // Use exception table for zero-cost exception handling frame.unwind_blocks(vm, UnwindReason::Raising { exception }) } // Check if this is a RERAISE instruction // Both Instruction::Raise { kind: Reraise/ReraiseFromStack } and // Instruction::Reraise are reraise operations that should not add // new traceback entries let is_reraise = match op { bytecode::Instruction::Raise { kind } => matches!( kind.get(arg), bytecode::RaiseKind::BareRaise | bytecode::RaiseKind::ReraiseFromStack ), bytecode::Instruction::Reraise { .. } => true, _ => false, }; match handle_exception(self, exception, idx, is_reraise, vm) { Ok(None) => {} Ok(Some(result)) => break Ok(result), Err(exception) => { // Restore lasti from traceback so frame.f_lineno matches tb_lineno // The traceback was created with the correct lasti when exception // was first raised, but frame.lasti may have changed during cleanup if let Some(tb) = exception.__traceback__() && core::ptr::eq::<Py<Frame>>(&*tb.frame, self.object) { // This traceback entry is for this frame - restore its lasti // tb.lasti is in bytes (idx * 2), convert back to instruction index self.update_lasti(|i| *i = tb.lasti / 2); } break Err(exception); } } } } if !do_extend_arg { arg_state.reset() } } } fn yield_from_target(&self) -> Option<&PyObject> { // checks gi_frame_state == FRAME_SUSPENDED_YIELD_FROM // which is set when YIELD_VALUE with oparg >= 1 is executed. // In RustPython, we check: // 1. lasti points to RESUME (after YIELD_VALUE) // 2. The previous instruction was YIELD_VALUE with arg >= 1 // 3. Stack top is the delegate (receiver) // // First check if stack is empty - if so, we can't be in yield-from if self.state.stack.is_empty() { return None; } let lasti = self.lasti() as usize; if let Some(unit) = self.code.instructions.get(lasti) { match &unit.op { bytecode::Instruction::Send { .. } => return Some(self.top_value()), bytecode::Instruction::Resume { .. } => { // Check if previous instruction was YIELD_VALUE with arg >= 1 // This indicates yield-from/await context if lasti > 0 && let Some(prev_unit) = self.code.instructions.get(lasti - 1) && let bytecode::Instruction::YieldValue { .. } = &prev_unit.op { // YIELD_VALUE arg: 0 = direct yield, >= 1 = yield-from/await // OpArgByte.0 is the raw byte value if prev_unit.arg.0 >= 1 { // In yield-from/await context, delegate is on top of stack return Some(self.top_value()); } } } _ => {} } } None } /// Handle throw() on a generator/coroutine. fn gen_throw( &mut self, vm: &VirtualMachine, exc_type: PyObjectRef, exc_val: PyObjectRef, exc_tb: PyObjectRef, ) -> PyResult<ExecutionResult> { if let Some(jen) = self.yield_from_target() { // borrow checker shenanigans - we only need to use exc_type/val/tb if the following // variable is Some let thrower = if let Some(coro) = self.builtin_coro(jen) { Some(Either::A(coro)) } else { vm.get_attribute_opt(jen.to_owned(), "throw")? .map(Either::B) }; if let Some(thrower) = thrower { let ret = match thrower { Either::A(coro) => coro .throw(jen, exc_type, exc_val, exc_tb, vm) .to_pyresult(vm), Either::B(meth) => meth.call((exc_type, exc_val, exc_tb), vm), }; return ret.map(ExecutionResult::Yield).or_else(|err| { // This pushes Py_None to stack and restarts evalloop in exception mode. // Stack before throw: [receiver] (YIELD_VALUE already popped yielded value) // After pushing None: [receiver, None] // Exception handler will push exc: [receiver, None, exc] // CLEANUP_THROW expects: [sub_iter, last_sent_val, exc] self.push_value(vm.ctx.none()); // Use unwind_blocks to let exception table route to CLEANUP_THROW match self.unwind_blocks(vm, UnwindReason::Raising { exception: err }) { Ok(None) => self.run(vm), Ok(Some(result)) => Ok(result), Err(exception) => Err(exception), } }); } } // throw_here: no delegate has throw method, or not in yield-from // gen_send_ex pushes Py_None to stack and restarts evalloop in exception mode let exception = vm.normalize_exception(exc_type, exc_val, exc_tb)?; // Add traceback entry for the generator frame at the yield site let idx = self.lasti().saturating_sub(1) as usize; if idx < self.code.locations.len() { let (loc, _end_loc) = self.code.locations[idx]; let next = exception.__traceback__(); let new_traceback = PyTraceback::new(next, self.object.to_owned(), idx as u32 * 2, loc.line); exception.set_traceback_typed(Some(new_traceback.into_ref(&vm.ctx))); } // when raising an exception, set __context__ to the current exception // This is done in _PyErr_SetObject vm.contextualize_exception(&exception); // always pushes Py_None before calling gen_send_ex with exc=1 // This is needed for exception handler to have correct stack state self.push_value(vm.ctx.none()); match self.unwind_blocks(vm, UnwindReason::Raising { exception }) { Ok(None) => self.run(vm), Ok(Some(result)) => Ok(result), Err(exception) => Err(exception), } } fn unbound_cell_exception(&self, i: usize, vm: &VirtualMachine) -> PyBaseExceptionRef { if let Some(&name) = self.code.cellvars.get(i) { vm.new_exception_msg( vm.ctx.exceptions.unbound_local_error.to_owned(), format!("local variable '{name}' referenced before assignment"), ) } else { let name = self.code.freevars[i - self.code.cellvars.len()]; vm.new_name_error( format!("free variable '{name}' referenced before assignment in enclosing scope"), name.to_owned(), ) } } /// Execute a single instruction. #[inline(always)] fn execute_instruction( &mut self, instruction: bytecode::Instruction, arg: bytecode::OpArg, extend_arg: &mut bool, vm: &VirtualMachine, ) -> FrameResult { vm.check_signals()?; flame_guard!(format!( "Frame::execute_instruction({})", instruction.display(arg, &self.code.code).to_string() )); #[cfg(feature = "vm-tracing-logging")] { trace!("======="); /* TODO: for frame in self.frames.iter() { trace!(" {:?}", frame); } */ trace!(" {:#?}", self); trace!( " Executing op code: {}", instruction.display(arg, &self.code.code) ); trace!("======="); } #[cold] fn name_error(name: &'static PyStrInterned, vm: &VirtualMachine) -> PyBaseExceptionRef { vm.new_name_error(format!("name '{name}' is not defined"), name.to_owned()) } match instruction { bytecode::Instruction::BeforeAsyncWith => { let mgr = self.pop_value(); let error_string = || -> String { format!( "'{:.200}' object does not support the asynchronous context manager protocol", mgr.class().name(), ) }; let aenter_res = vm .get_special_method(&mgr, identifier!(vm, __aenter__))? .ok_or_else(|| vm.new_type_error(error_string()))? .invoke((), vm)?; let aexit = mgr .get_attr(identifier!(vm, __aexit__), vm) .map_err(|_exc| { vm.new_type_error({ format!("{} (missed __aexit__ method)", error_string()) }) })?; self.push_value(aexit); self.push_value(aenter_res); Ok(None) } bytecode::Instruction::BinaryOp { op } => self.execute_bin_op(vm, op.get(arg)), bytecode::Instruction::BinarySubscript => { let key = self.pop_value(); let container = self.pop_value(); self.state .stack .push(container.get_item(key.as_object(), vm)?); Ok(None) } bytecode::Instruction::Break { target } => self.unwind_blocks( vm, UnwindReason::Break { target: target.get(arg), }, ), bytecode::Instruction::BuildListFromTuples { size } => { // SAFETY: compiler guarantees `size` tuples are on the stack let elements = unsafe { self.flatten_tuples(size.get(arg) as usize) }; let list_obj = vm.ctx.new_list(elements); self.push_value(list_obj.into()); Ok(None) } bytecode::Instruction::BuildList { size } => { let elements = self.pop_multiple(size.get(arg) as usize).collect(); let list_obj = vm.ctx.new_list(elements); self.push_value(list_obj.into()); Ok(None) } bytecode::Instruction::BuildMapForCall { size } => { self.execute_build_map_for_call(vm, size.get(arg)) } bytecode::Instruction::BuildMap { size } => self.execute_build_map(vm, size.get(arg)), bytecode::Instruction::BuildSetFromTuples { size } => { let set = PySet::default().into_ref(&vm.ctx); for element in self.pop_multiple(size.get(arg) as usize) { // SAFETY: trust compiler let tup = unsafe { element.downcast_unchecked::<PyTuple>() }; for item in tup.iter() { set.add(item.clone(), vm)?; } } self.push_value(set.into()); Ok(None) } bytecode::Instruction::BuildSet { size } => { let set = PySet::default().into_ref(&vm.ctx); for element in self.pop_multiple(size.get(arg) as usize) { set.add(element, vm)?; } self.push_value(set.into()); Ok(None) } bytecode::Instruction::BuildSlice { argc } => { self.execute_build_slice(vm, argc.get(arg)) } /* bytecode::Instruction::ToBool => { dbg!("Shouldn't be called outside of match statements for now") let value = self.pop_value(); // call __bool__ let result = value.try_to_bool(vm)?; self.push_value(vm.ctx.new_bool(result).into()); Ok(None) } */ bytecode::Instruction::BuildString { size } => { let s = self .pop_multiple(size.get(arg) as usize) .as_slice() .iter() .map(|pyobj| pyobj.downcast_ref::<PyStr>().unwrap()) .collect::<Wtf8Buf>(); let str_obj = vm.ctx.new_str(s); self.push_value(str_obj.into()); Ok(None) } bytecode::Instruction::BuildTupleFromIter => { if !self.top_value().class().is(vm.ctx.types.tuple_type) { let elements: Vec<_> = self.pop_value().try_to_value(vm)?; let list_obj = vm.ctx.new_tuple(elements); self.push_value(list_obj.into()); } Ok(None) } bytecode::Instruction::BuildTupleFromTuples { size } => { // SAFETY: compiler guarantees `size` tuples are on the stack let elements = unsafe { self.flatten_tuples(size.get(arg) as usize) }; let list_obj = vm.ctx.new_tuple(elements); self.push_value(list_obj.into()); Ok(None) } bytecode::Instruction::BuildTuple { size } => { let elements = self.pop_multiple(size.get(arg) as usize).collect(); let list_obj = vm.ctx.new_tuple(elements); self.push_value(list_obj.into()); Ok(None) } bytecode::Instruction::CallFunctionEx { has_kwargs } => { let args = self.collect_ex_args(vm, has_kwargs.get(arg))?; self.execute_call(args, vm) } bytecode::Instruction::CallFunctionKeyword { nargs } => { let args = self.collect_keyword_args(nargs.get(arg)); self.execute_call(args, vm) } bytecode::Instruction::CallFunctionPositional { nargs } => { let args = self.collect_positional_args(nargs.get(arg)); self.execute_call(args, vm) } bytecode::Instruction::CallIntrinsic1 { func } => { let value = self.pop_value(); let result = self.call_intrinsic_1(func.get(arg), value, vm)?; self.push_value(result); Ok(None) } bytecode::Instruction::CallIntrinsic2 { func } => { let value2 = self.pop_value(); let value1 = self.pop_value(); let result = self.call_intrinsic_2(func.get(arg), value1, value2, vm)?; self.push_value(result); Ok(None) } bytecode::Instruction::CallMethodEx { has_kwargs } => { let args = self.collect_ex_args(vm, has_kwargs.get(arg))?; self.execute_method_call(args, vm) } bytecode::Instruction::CallMethodKeyword { nargs } => { let args = self.collect_keyword_args(nargs.get(arg)); self.execute_method_call(args, vm) } bytecode::Instruction::CallMethodPositional { nargs } => { let args = self.collect_positional_args(nargs.get(arg)); self.execute_method_call(args, vm) } bytecode::Instruction::CheckEgMatch => { let match_type = self.pop_value(); let exc_value = self.pop_value(); let (rest, matched) = crate::exceptions::exception_group_match(&exc_value, &match_type, vm)?; self.push_value(rest); self.push_value(matched); Ok(None) } bytecode::Instruction::CompareOperation { op } => self.execute_compare(vm, op.get(arg)), bytecode::Instruction::ContainsOp(invert) => { let b = self.pop_value(); let a = self.pop_value(); let value = match invert.get(arg) { bytecode::Invert::No => self._in(vm, &a, &b)?, bytecode::Invert::Yes => self._not_in(vm, &a, &b)?, }; self.push_value(vm.ctx.new_bool(value).into()); Ok(None) } bytecode::Instruction::Continue { target } => self.unwind_blocks( vm, UnwindReason::Continue { target: target.get(arg), }, ), bytecode::Instruction::ConvertValue { oparg: conversion } => { self.convert_value(conversion.get(arg), vm) } bytecode::Instruction::CopyItem { index } => { // CopyItem { index: 1 } copies TOS // CopyItem { index: 2 } copies second from top // This is 1-indexed to match CPython let idx = index.get(arg) as usize; let stack_len = self.state.stack.len(); if stack_len < idx { eprintln!("CopyItem ERROR: stack_len={}, idx={}", stack_len, idx); eprintln!(" code: {}", self.code.obj_name); eprintln!(" lasti: {}", self.lasti()); panic!("CopyItem: stack underflow"); } let value = self.state.stack[stack_len - idx].clone(); self.push_value(value); Ok(None) } bytecode::Instruction::DeleteAttr { idx } => self.delete_attr(vm, idx.get(arg)), bytecode::Instruction::DeleteDeref(i) => { self.cells_frees[i.get(arg) as usize].set(None); Ok(None) } bytecode::Instruction::DeleteFast(idx) => { let mut fastlocals = self.fastlocals.lock(); let idx = idx.get(arg) as usize; if fastlocals[idx].is_none() { return Err(vm.new_exception_msg( vm.ctx.exceptions.unbound_local_error.to_owned(), format!( "local variable '{}' referenced before assignment", self.code.varnames[idx] ), )); } fastlocals[idx] = None; Ok(None) } bytecode::Instruction::DeleteGlobal(idx) => { let name = self.code.names[idx.get(arg) as usize]; match self.globals.del_item(name, vm) { Ok(()) => {} Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => {
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/getpath.rs
crates/vm/src/getpath.rs
//! Path configuration for RustPython (ref: Modules/getpath.py) //! //! This module implements Python path calculation logic following getpath.py. //! It uses landmark-based search to locate prefix, exec_prefix, and stdlib directories. //! //! The main entry point is `init_path_config()` which computes Paths from Settings. use crate::vm::{Paths, Settings}; use std::env; use std::path::{Path, PathBuf}; // Platform-specific landmarks (ref: getpath.py PLATFORM CONSTANTS) #[cfg(not(windows))] mod platform { use crate::version; pub const BUILDDIR_TXT: &str = "pybuilddir.txt"; pub const BUILD_LANDMARK: &str = "Modules/Setup.local"; pub const VENV_LANDMARK: &str = "pyvenv.cfg"; pub const BUILDSTDLIB_LANDMARK: &str = "Lib/os.py"; pub fn stdlib_subdir() -> String { format!("lib/python{}.{}", version::MAJOR, version::MINOR) } pub fn stdlib_landmarks() -> [String; 2] { let subdir = stdlib_subdir(); [format!("{}/os.py", subdir), format!("{}/os.pyc", subdir)] } pub fn platstdlib_landmark() -> String { format!( "lib/python{}.{}/lib-dynload", version::MAJOR, version::MINOR ) } pub fn zip_landmark() -> String { format!("lib/python{}{}.zip", version::MAJOR, version::MINOR) } } #[cfg(windows)] mod platform { use crate::version; pub const BUILDDIR_TXT: &str = "pybuilddir.txt"; pub const BUILD_LANDMARK: &str = "Modules\\Setup.local"; pub const VENV_LANDMARK: &str = "pyvenv.cfg"; pub const BUILDSTDLIB_LANDMARK: &str = "Lib\\os.py"; pub const STDLIB_SUBDIR: &str = "Lib"; pub fn stdlib_landmarks() -> [String; 2] { ["Lib\\os.py".into(), "Lib\\os.pyc".into()] } pub fn platstdlib_landmark() -> String { "DLLs".into() } pub fn zip_landmark() -> String { format!("python{}{}.zip", version::MAJOR, version::MINOR) } } // Helper functions (ref: getpath.py HELPER FUNCTIONS) /// Search upward from a directory for landmark files/directories /// Returns the directory where a landmark was found fn search_up<P, F>(start: P, landmarks: &[&str], test: F) -> Option<PathBuf> where P: AsRef<Path>, F: Fn(&Path) -> bool, { let mut current = start.as_ref().to_path_buf(); loop { for landmark in landmarks { let path = current.join(landmark); if test(&path) { return Some(current); } } if !current.pop() { return None; } } } /// Search upward for a file landmark fn search_up_file<P: AsRef<Path>>(start: P, landmarks: &[&str]) -> Option<PathBuf> { search_up(start, landmarks, |p| p.is_file()) } /// Search upward for a directory landmark #[cfg(not(windows))] fn search_up_dir<P: AsRef<Path>>(start: P, landmarks: &[&str]) -> Option<PathBuf> { search_up(start, landmarks, |p| p.is_dir()) } // Path computation functions /// Compute path configuration from Settings /// /// This function should be called before interpreter initialization. /// It returns a Paths struct with all computed path values. pub fn init_path_config(settings: &Settings) -> Paths { let mut paths = Paths::default(); // Step 0: Get executable path let executable = get_executable_path(); let real_executable = executable .as_ref() .map(|p| p.to_string_lossy().into_owned()) .unwrap_or_default(); // Step 1: Check for __PYVENV_LAUNCHER__ environment variable // When launched from a venv launcher, __PYVENV_LAUNCHER__ contains the venv's python.exe path // In this case: // - sys.executable should be the launcher path (where user invoked Python) // - sys._base_executable should be the real Python executable let exe_dir = if let Ok(launcher) = env::var("__PYVENV_LAUNCHER__") { paths.executable = launcher.clone(); paths.base_executable = real_executable; PathBuf::from(&launcher).parent().map(PathBuf::from) } else { paths.executable = real_executable; executable .as_ref() .and_then(|p| p.parent().map(PathBuf::from)) }; // Step 2: Check for venv (pyvenv.cfg) and get 'home' let (venv_prefix, home_dir) = detect_venv(&exe_dir); let search_dir = home_dir.clone().or(exe_dir.clone()); // Step 3: Check for build directory let build_prefix = detect_build_directory(&search_dir); // Step 4: Calculate prefix via landmark search // When in venv, search_dir is home_dir, so this gives us the base Python's prefix let calculated_prefix = calculate_prefix(&search_dir, &build_prefix); // Step 5: Set prefix and base_prefix if venv_prefix.is_some() { // In venv: prefix = venv directory, base_prefix = original Python's prefix paths.prefix = venv_prefix .as_ref() .map(|p| p.to_string_lossy().into_owned()) .unwrap_or_else(|| calculated_prefix.clone()); paths.base_prefix = calculated_prefix; } else { // Not in venv: prefix == base_prefix paths.prefix = calculated_prefix.clone(); paths.base_prefix = calculated_prefix; } // Step 6: Calculate exec_prefix paths.exec_prefix = if venv_prefix.is_some() { // In venv: exec_prefix = prefix (venv directory) paths.prefix.clone() } else { calculate_exec_prefix(&search_dir, &paths.prefix) }; paths.base_exec_prefix = paths.base_prefix.clone(); // Step 7: Calculate base_executable (if not already set by __PYVENV_LAUNCHER__) if paths.base_executable.is_empty() { paths.base_executable = calculate_base_executable(executable.as_ref(), &home_dir); } // Step 8: Build module_search_paths paths.module_search_paths = build_module_search_paths(settings, &paths.prefix, &paths.exec_prefix); paths } /// Get default prefix value fn default_prefix() -> String { std::option_env!("RUSTPYTHON_PREFIX") .map(String::from) .unwrap_or_else(|| { if cfg!(windows) { "C:".to_owned() } else { "/usr/local".to_owned() } }) } /// Detect virtual environment by looking for pyvenv.cfg /// Returns (venv_prefix, home_dir from pyvenv.cfg) fn detect_venv(exe_dir: &Option<PathBuf>) -> (Option<PathBuf>, Option<PathBuf>) { // Try exe_dir/../pyvenv.cfg first (standard venv layout: venv/bin/python) if let Some(dir) = exe_dir && let Some(venv_dir) = dir.parent() { let cfg = venv_dir.join(platform::VENV_LANDMARK); if cfg.exists() && let Some(home) = parse_pyvenv_home(&cfg) { return (Some(venv_dir.to_path_buf()), Some(PathBuf::from(home))); } } // Try exe_dir/pyvenv.cfg (alternative layout) if let Some(dir) = exe_dir { let cfg = dir.join(platform::VENV_LANDMARK); if cfg.exists() && let Some(home) = parse_pyvenv_home(&cfg) { return (Some(dir.clone()), Some(PathBuf::from(home))); } } (None, None) } /// Detect if running from a build directory fn detect_build_directory(exe_dir: &Option<PathBuf>) -> Option<PathBuf> { let dir = exe_dir.as_ref()?; // Check for pybuilddir.txt (indicates build directory) if dir.join(platform::BUILDDIR_TXT).exists() { return Some(dir.clone()); } // Check for Modules/Setup.local (build landmark) if dir.join(platform::BUILD_LANDMARK).exists() { return Some(dir.clone()); } // Search up for Lib/os.py (build stdlib landmark) search_up_file(dir, &[platform::BUILDSTDLIB_LANDMARK]) } /// Calculate prefix by searching for landmarks fn calculate_prefix(exe_dir: &Option<PathBuf>, build_prefix: &Option<PathBuf>) -> String { // 1. If build directory detected, use it if let Some(bp) = build_prefix { return bp.to_string_lossy().into_owned(); } if let Some(dir) = exe_dir { // 2. Search for ZIP landmark let zip = platform::zip_landmark(); if let Some(prefix) = search_up_file(dir, &[&zip]) { return prefix.to_string_lossy().into_owned(); } // 3. Search for stdlib landmarks (os.py) let landmarks = platform::stdlib_landmarks(); let refs: Vec<&str> = landmarks.iter().map(|s| s.as_str()).collect(); if let Some(prefix) = search_up_file(dir, &refs) { return prefix.to_string_lossy().into_owned(); } } // 4. Fallback to default default_prefix() } /// Calculate exec_prefix fn calculate_exec_prefix(exe_dir: &Option<PathBuf>, prefix: &str) -> String { #[cfg(windows)] { // Windows: exec_prefix == prefix let _ = exe_dir; // silence unused warning prefix.to_owned() } #[cfg(not(windows))] { // POSIX: search for lib-dynload directory if let Some(dir) = exe_dir { let landmark = platform::platstdlib_landmark(); if let Some(exec_prefix) = search_up_dir(dir, &[&landmark]) { return exec_prefix.to_string_lossy().into_owned(); } } // Fallback: same as prefix prefix.to_owned() } } /// Calculate base_executable fn calculate_base_executable(executable: Option<&PathBuf>, home_dir: &Option<PathBuf>) -> String { // If in venv and we have home, construct base_executable from home if let (Some(exe), Some(home)) = (executable, home_dir) && let Some(exe_name) = exe.file_name() { let base = home.join(exe_name); return base.to_string_lossy().into_owned(); } // Otherwise, base_executable == executable executable .map(|p| p.to_string_lossy().into_owned()) .unwrap_or_default() } /// Build the complete module_search_paths (sys.path) fn build_module_search_paths(settings: &Settings, prefix: &str, exec_prefix: &str) -> Vec<String> { let mut paths = Vec::new(); // 1. PYTHONPATH/RUSTPYTHONPATH from settings paths.extend(settings.path_list.iter().cloned()); // 2. ZIP file path let zip_path = PathBuf::from(prefix).join(platform::zip_landmark()); paths.push(zip_path.to_string_lossy().into_owned()); // 3. stdlib and platstdlib directories #[cfg(not(windows))] { // POSIX: stdlib first, then lib-dynload let stdlib_dir = PathBuf::from(prefix).join(platform::stdlib_subdir()); paths.push(stdlib_dir.to_string_lossy().into_owned()); let platstdlib = PathBuf::from(exec_prefix).join(platform::platstdlib_landmark()); paths.push(platstdlib.to_string_lossy().into_owned()); } #[cfg(windows)] { // Windows: DLLs first, then Lib let platstdlib = PathBuf::from(exec_prefix).join(platform::platstdlib_landmark()); paths.push(platstdlib.to_string_lossy().into_owned()); let stdlib_dir = PathBuf::from(prefix).join(platform::STDLIB_SUBDIR); paths.push(stdlib_dir.to_string_lossy().into_owned()); } paths } /// Get the current executable path fn get_executable_path() -> Option<PathBuf> { #[cfg(not(target_arch = "wasm32"))] { let exec_arg = env::args_os().next()?; which::which(exec_arg).ok() } #[cfg(target_arch = "wasm32")] { let exec_arg = env::args().next()?; Some(PathBuf::from(exec_arg)) } } /// Parse pyvenv.cfg and extract the 'home' key value fn parse_pyvenv_home(pyvenv_cfg: &Path) -> Option<String> { let content = std::fs::read_to_string(pyvenv_cfg).ok()?; for line in content.lines() { if let Some((key, value)) = line.split_once('=') && key.trim().to_lowercase() == "home" { return Some(value.trim().to_string()); } } None } #[cfg(test)] mod tests { use super::*; #[test] fn test_init_path_config() { let settings = Settings::default(); let paths = init_path_config(&settings); // Just verify it doesn't panic and returns valid paths assert!(!paths.prefix.is_empty()); } #[test] fn test_search_up() { // Test with a path that doesn't have any landmarks let result = search_up_file(std::env::temp_dir(), &["nonexistent_landmark_xyz"]); assert!(result.is_none()); } #[test] fn test_default_prefix() { let prefix = default_prefix(); assert!(!prefix.is_empty()); } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/buffer.rs
crates/vm/src/buffer.rs
use crate::{ PyObjectRef, PyResult, TryFromObject, VirtualMachine, builtins::{PyBaseExceptionRef, PyBytesRef, PyTuple, PyTupleRef, PyTypeRef}, common::{static_cell, str::wchar_t}, convert::ToPyObject, function::{ArgBytesLike, ArgIntoBool, ArgIntoFloat}, }; use alloc::fmt; use core::{iter::Peekable, mem}; use half::f16; use itertools::Itertools; use malachite_bigint::BigInt; use num_traits::{PrimInt, ToPrimitive}; use std::os::raw; type PackFunc = fn(&VirtualMachine, PyObjectRef, &mut [u8]) -> PyResult<()>; type UnpackFunc = fn(&VirtualMachine, &[u8]) -> PyObjectRef; static OVERFLOW_MSG: &str = "total struct size too long"; // not a const to reduce code size #[derive(Debug, Copy, Clone, PartialEq)] pub(crate) enum Endianness { Native, Little, Big, Host, } impl Endianness { /// Parse endianness /// See also: https://docs.python.org/3/library/struct.html?highlight=struct#byte-order-size-and-alignment fn parse<I>(chars: &mut Peekable<I>) -> Self where I: Sized + Iterator<Item = u8>, { let e = match chars.peek() { Some(b'@') => Self::Native, Some(b'=') => Self::Host, Some(b'<') => Self::Little, Some(b'>') | Some(b'!') => Self::Big, _ => return Self::Native, }; chars.next().unwrap(); e } } trait ByteOrder { fn convert<I: PrimInt>(i: I) -> I; } enum BigEndian {} impl ByteOrder for BigEndian { fn convert<I: PrimInt>(i: I) -> I { i.to_be() } } enum LittleEndian {} impl ByteOrder for LittleEndian { fn convert<I: PrimInt>(i: I) -> I { i.to_le() } } #[cfg(target_endian = "big")] type NativeEndian = BigEndian; #[cfg(target_endian = "little")] type NativeEndian = LittleEndian; #[derive(Copy, Clone, num_enum::TryFromPrimitive)] #[repr(u8)] pub(crate) enum FormatType { Pad = b'x', SByte = b'b', UByte = b'B', Char = b'c', WideChar = b'u', Str = b's', Pascal = b'p', Short = b'h', UShort = b'H', Int = b'i', UInt = b'I', Long = b'l', ULong = b'L', SSizeT = b'n', SizeT = b'N', LongLong = b'q', ULongLong = b'Q', Bool = b'?', Half = b'e', Float = b'f', Double = b'd', LongDouble = b'g', VoidP = b'P', PyObject = b'O', } impl fmt::Debug for FormatType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&(*self as u8 as char), f) } } impl FormatType { fn info(self, e: Endianness) -> &'static FormatInfo { use FormatType::*; use mem::{align_of, size_of}; macro_rules! native_info { ($t:ty) => {{ &FormatInfo { size: size_of::<$t>(), align: align_of::<$t>(), pack: Some(<$t as Packable>::pack::<NativeEndian>), unpack: Some(<$t as Packable>::unpack::<NativeEndian>), } }}; } macro_rules! nonnative_info { ($t:ty, $end:ty) => {{ &FormatInfo { size: size_of::<$t>(), align: 0, pack: Some(<$t as Packable>::pack::<$end>), unpack: Some(<$t as Packable>::unpack::<$end>), } }}; } macro_rules! match_nonnative { ($zelf:expr, $end:ty) => {{ match $zelf { Pad | Str | Pascal => &FormatInfo { size: size_of::<u8>(), align: 0, pack: None, unpack: None, }, SByte => nonnative_info!(i8, $end), UByte => nonnative_info!(u8, $end), Char => &FormatInfo { size: size_of::<u8>(), align: 0, pack: Some(pack_char), unpack: Some(unpack_char), }, Short => nonnative_info!(i16, $end), UShort => nonnative_info!(u16, $end), Int | Long => nonnative_info!(i32, $end), UInt | ULong => nonnative_info!(u32, $end), LongLong => nonnative_info!(i64, $end), ULongLong => nonnative_info!(u64, $end), Bool => nonnative_info!(bool, $end), Half => nonnative_info!(f16, $end), Float => nonnative_info!(f32, $end), Double => nonnative_info!(f64, $end), LongDouble => nonnative_info!(f64, $end), // long double same as double PyObject => nonnative_info!(usize, $end), // pointer size _ => unreachable!(), // size_t or void* } }}; } match e { Endianness::Native => match self { Pad | Str | Pascal => &FormatInfo { size: size_of::<raw::c_char>(), align: 0, pack: None, unpack: None, }, SByte => native_info!(raw::c_schar), UByte => native_info!(raw::c_uchar), Char => &FormatInfo { size: size_of::<raw::c_char>(), align: 0, pack: Some(pack_char), unpack: Some(unpack_char), }, WideChar => native_info!(wchar_t), Short => native_info!(raw::c_short), UShort => native_info!(raw::c_ushort), Int => native_info!(raw::c_int), UInt => native_info!(raw::c_uint), Long => native_info!(raw::c_long), ULong => native_info!(raw::c_ulong), SSizeT => native_info!(isize), // ssize_t == isize SizeT => native_info!(usize), // size_t == usize LongLong => native_info!(raw::c_longlong), ULongLong => native_info!(raw::c_ulonglong), Bool => native_info!(bool), Half => native_info!(f16), Float => native_info!(raw::c_float), Double => native_info!(raw::c_double), LongDouble => native_info!(raw::c_double), // long double same as double for now VoidP => native_info!(*mut raw::c_void), PyObject => native_info!(*mut raw::c_void), // pointer to PyObject }, Endianness::Big => match_nonnative!(self, BigEndian), Endianness::Little => match_nonnative!(self, LittleEndian), Endianness::Host => match_nonnative!(self, NativeEndian), } } } #[derive(Debug, Clone)] pub(crate) struct FormatCode { pub repeat: usize, pub code: FormatType, pub info: &'static FormatInfo, pub pre_padding: usize, } impl FormatCode { pub const fn arg_count(&self) -> usize { match self.code { FormatType::Pad => 0, FormatType::Str | FormatType::Pascal => 1, _ => self.repeat, } } pub fn parse<I>( chars: &mut Peekable<I>, endianness: Endianness, ) -> Result<(Vec<Self>, usize, usize), String> where I: Sized + Iterator<Item = u8>, { let mut offset = 0isize; let mut arg_count = 0usize; let mut codes = vec![]; while chars.peek().is_some() { // determine repeat operator: let repeat = match chars.peek() { Some(b'0'..=b'9') => { let mut repeat = 0isize; while let Some(b'0'..=b'9') = chars.peek() { if let Some(c) = chars.next() { let current_digit = c - b'0'; repeat = repeat .checked_mul(10) .and_then(|r| r.checked_add(current_digit as _)) .ok_or_else(|| OVERFLOW_MSG.to_owned())?; } } repeat } _ => 1, }; // Skip whitespace (Python ignores whitespace in format strings) while let Some(b' ' | b'\t' | b'\n' | b'\r') = chars.peek() { chars.next(); } // determine format char: let c = match chars.next() { Some(c) => c, None => { // If we have a repeat count but only whitespace follows, error if repeat != 1 { return Err("repeat count given without format specifier".to_owned()); } // Otherwise, we're done parsing break; } }; // Check for embedded null character if c == 0 { return Err("embedded null character".to_owned()); } // PEP3118: Handle extended format specifiers // T{...} - struct, X{} - function pointer, (...) - array shape, :name: - field name if c == b'T' || c == b'X' { // Skip struct/function pointer: consume until matching '}' if chars.peek() == Some(&b'{') { chars.next(); // consume '{' let mut depth = 1; while depth > 0 { match chars.next() { Some(b'{') => depth += 1, Some(b'}') => depth -= 1, None => return Err("unmatched '{' in format".to_owned()), _ => {} } } continue; } } if c == b'(' { // Skip array shape: consume until matching ')' let mut depth = 1; while depth > 0 { match chars.next() { Some(b'(') => depth += 1, Some(b')') => depth -= 1, None => return Err("unmatched '(' in format".to_owned()), _ => {} } } continue; } if c == b':' { // Skip field name: consume until next ':' loop { match chars.next() { Some(b':') => break, None => return Err("unmatched ':' in format".to_owned()), _ => {} } } continue; } if c == b'{' || c == b'}' || c == b'&' || c == b'<' || c == b'>' || c == b'@' || c == b'=' || c == b'!' { // Skip standalone braces (pointer targets, etc.), pointer prefix, and nested endianness markers continue; } let code = FormatType::try_from(c) .ok() .filter(|c| match c { FormatType::SSizeT | FormatType::SizeT | FormatType::VoidP => { endianness == Endianness::Native } _ => true, }) .ok_or_else(|| "bad char in struct format".to_owned())?; let info = code.info(endianness); let padding = compensate_alignment(offset as usize, info.align) .ok_or_else(|| OVERFLOW_MSG.to_owned())?; offset = padding .to_isize() .and_then(|extra| offset.checked_add(extra)) .ok_or_else(|| OVERFLOW_MSG.to_owned())?; let code = Self { repeat: repeat as usize, code, info, pre_padding: padding, }; arg_count += code.arg_count(); codes.push(code); offset = (info.size as isize) .checked_mul(repeat) .and_then(|item_size| offset.checked_add(item_size)) .ok_or_else(|| OVERFLOW_MSG.to_owned())?; } Ok((codes, offset as usize, arg_count)) } } const fn compensate_alignment(offset: usize, align: usize) -> Option<usize> { if align != 0 && offset != 0 { // a % b == a & (b-1) if b is a power of 2 (align - 1).checked_sub((offset - 1) & (align - 1)) } else { // alignment is already all good Some(0) } } pub(crate) struct FormatInfo { pub size: usize, pub align: usize, pub pack: Option<PackFunc>, pub unpack: Option<UnpackFunc>, } impl fmt::Debug for FormatInfo { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("FormatInfo") .field("size", &self.size) .field("align", &self.align) .finish() } } #[derive(Debug, Clone)] pub struct FormatSpec { #[allow(dead_code)] pub(crate) endianness: Endianness, pub(crate) codes: Vec<FormatCode>, pub size: usize, pub arg_count: usize, } impl FormatSpec { pub fn parse(fmt: &[u8], vm: &VirtualMachine) -> PyResult<Self> { let mut chars = fmt.iter().copied().peekable(); // First determine "@", "<", ">","!" or "=" let endianness = Endianness::parse(&mut chars); // Now, analyze struct string further: let (codes, size, arg_count) = FormatCode::parse(&mut chars, endianness).map_err(|err| new_struct_error(vm, err))?; Ok(Self { endianness, codes, size, arg_count, }) } pub fn pack(&self, args: Vec<PyObjectRef>, vm: &VirtualMachine) -> PyResult<Vec<u8>> { // Create data vector: let mut data = vec![0; self.size]; self.pack_into(&mut data, args, vm)?; Ok(data) } pub fn pack_into( &self, mut buffer: &mut [u8], args: Vec<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<()> { if self.arg_count != args.len() { return Err(new_struct_error( vm, format!( "pack expected {} items for packing (got {})", self.codes.len(), args.len() ), )); } let mut args = args.into_iter(); // Loop over all opcodes: for code in &self.codes { buffer = &mut buffer[code.pre_padding..]; debug!("code: {code:?}"); match code.code { FormatType::Str => { let (buf, rest) = buffer.split_at_mut(code.repeat); pack_string(vm, args.next().unwrap(), buf)?; buffer = rest; } FormatType::Pascal => { let (buf, rest) = buffer.split_at_mut(code.repeat); pack_pascal(vm, args.next().unwrap(), buf)?; buffer = rest; } FormatType::Pad => { let (pad_buf, rest) = buffer.split_at_mut(code.repeat); for el in pad_buf { *el = 0 } buffer = rest; } _ => { let pack = code.info.pack.unwrap(); for arg in args.by_ref().take(code.repeat) { let (item_buf, rest) = buffer.split_at_mut(code.info.size); pack(vm, arg, item_buf)?; buffer = rest; } } } } Ok(()) } pub fn unpack(&self, mut data: &[u8], vm: &VirtualMachine) -> PyResult<PyTupleRef> { if self.size != data.len() { return Err(new_struct_error( vm, format!("unpack requires a buffer of {} bytes", self.size), )); } let mut items = Vec::with_capacity(self.arg_count); for code in &self.codes { data = &data[code.pre_padding..]; debug!("unpack code: {code:?}"); match code.code { FormatType::Pad => { data = &data[code.repeat..]; } FormatType::Str => { let (str_data, rest) = data.split_at(code.repeat); // string is just stored inline items.push(vm.ctx.new_bytes(str_data.to_vec()).into()); data = rest; } FormatType::Pascal => { let (str_data, rest) = data.split_at(code.repeat); items.push(unpack_pascal(vm, str_data)); data = rest; } _ => { let unpack = code.info.unpack.unwrap(); for _ in 0..code.repeat { let (item_data, rest) = data.split_at(code.info.size); items.push(unpack(vm, item_data)); data = rest; } } }; } Ok(PyTuple::new_ref(items, &vm.ctx)) } #[inline] pub const fn size(&self) -> usize { self.size } } trait Packable { fn pack<E: ByteOrder>(vm: &VirtualMachine, arg: PyObjectRef, data: &mut [u8]) -> PyResult<()>; fn unpack<E: ByteOrder>(vm: &VirtualMachine, data: &[u8]) -> PyObjectRef; } trait PackInt: PrimInt { fn pack_int<E: ByteOrder>(self, data: &mut [u8]); fn unpack_int<E: ByteOrder>(data: &[u8]) -> Self; } macro_rules! make_pack_prim_int { ($T:ty) => { impl PackInt for $T { fn pack_int<E: ByteOrder>(self, data: &mut [u8]) { let i = E::convert(self); data.copy_from_slice(&i.to_ne_bytes()); } #[inline] fn unpack_int<E: ByteOrder>(data: &[u8]) -> Self { let mut x = [0; core::mem::size_of::<$T>()]; x.copy_from_slice(data); E::convert(<$T>::from_ne_bytes(x)) } } impl Packable for $T { fn pack<E: ByteOrder>( vm: &VirtualMachine, arg: PyObjectRef, data: &mut [u8], ) -> PyResult<()> { let i: $T = get_int_or_index(vm, arg)?; i.pack_int::<E>(data); Ok(()) } fn unpack<E: ByteOrder>(vm: &VirtualMachine, rdr: &[u8]) -> PyObjectRef { let i = <$T>::unpack_int::<E>(rdr); vm.ctx.new_int(i).into() } } }; } fn get_int_or_index<T>(vm: &VirtualMachine, arg: PyObjectRef) -> PyResult<T> where T: PrimInt + for<'a> TryFrom<&'a BigInt>, { let index = arg .try_index_opt(vm) .unwrap_or_else(|| Err(new_struct_error(vm, "required argument is not an integer")))?; index .try_to_primitive(vm) .map_err(|_| new_struct_error(vm, "argument out of range")) } make_pack_prim_int!(i8); make_pack_prim_int!(u8); make_pack_prim_int!(i16); make_pack_prim_int!(u16); make_pack_prim_int!(i32); make_pack_prim_int!(u32); make_pack_prim_int!(i64); make_pack_prim_int!(u64); make_pack_prim_int!(usize); make_pack_prim_int!(isize); macro_rules! make_pack_float { ($T:ty) => { impl Packable for $T { fn pack<E: ByteOrder>( vm: &VirtualMachine, arg: PyObjectRef, data: &mut [u8], ) -> PyResult<()> { let f = ArgIntoFloat::try_from_object(vm, arg)?.into_float() as $T; f.to_bits().pack_int::<E>(data); Ok(()) } fn unpack<E: ByteOrder>(vm: &VirtualMachine, rdr: &[u8]) -> PyObjectRef { let i = PackInt::unpack_int::<E>(rdr); <$T>::from_bits(i).to_pyobject(vm) } } }; } make_pack_float!(f32); make_pack_float!(f64); impl Packable for f16 { fn pack<E: ByteOrder>(vm: &VirtualMachine, arg: PyObjectRef, data: &mut [u8]) -> PyResult<()> { let f_64 = ArgIntoFloat::try_from_object(vm, arg)?.into_float(); // "from_f64 should be preferred in any non-`const` context" except it gives the wrong result :/ let f_16 = Self::from_f64_const(f_64); if f_16.is_infinite() != f_64.is_infinite() { return Err(vm.new_overflow_error("float too large to pack with e format")); } f_16.to_bits().pack_int::<E>(data); Ok(()) } fn unpack<E: ByteOrder>(vm: &VirtualMachine, rdr: &[u8]) -> PyObjectRef { let i = PackInt::unpack_int::<E>(rdr); Self::from_bits(i).to_f64().to_pyobject(vm) } } impl Packable for *mut raw::c_void { fn pack<E: ByteOrder>(vm: &VirtualMachine, arg: PyObjectRef, data: &mut [u8]) -> PyResult<()> { usize::pack::<E>(vm, arg, data) } fn unpack<E: ByteOrder>(vm: &VirtualMachine, rdr: &[u8]) -> PyObjectRef { usize::unpack::<E>(vm, rdr) } } impl Packable for bool { fn pack<E: ByteOrder>(vm: &VirtualMachine, arg: PyObjectRef, data: &mut [u8]) -> PyResult<()> { let v = ArgIntoBool::try_from_object(vm, arg)?.into_bool() as u8; v.pack_int::<E>(data); Ok(()) } fn unpack<E: ByteOrder>(vm: &VirtualMachine, rdr: &[u8]) -> PyObjectRef { let i = u8::unpack_int::<E>(rdr); vm.ctx.new_bool(i != 0).into() } } fn pack_char(vm: &VirtualMachine, arg: PyObjectRef, data: &mut [u8]) -> PyResult<()> { let v = PyBytesRef::try_from_object(vm, arg)?; let ch = *v .as_bytes() .iter() .exactly_one() .map_err(|_| new_struct_error(vm, "char format requires a bytes object of length 1"))?; data[0] = ch; Ok(()) } fn pack_string(vm: &VirtualMachine, arg: PyObjectRef, buf: &mut [u8]) -> PyResult<()> { let b = ArgBytesLike::try_from_object(vm, arg)?; b.with_ref(|data| write_string(buf, data)); Ok(()) } fn pack_pascal(vm: &VirtualMachine, arg: PyObjectRef, buf: &mut [u8]) -> PyResult<()> { if buf.is_empty() { return Ok(()); } let b = ArgBytesLike::try_from_object(vm, arg)?; b.with_ref(|data| { let string_length = core::cmp::min(core::cmp::min(data.len(), 255), buf.len() - 1); buf[0] = string_length as u8; write_string(&mut buf[1..], data); }); Ok(()) } fn write_string(buf: &mut [u8], data: &[u8]) { let len_from_data = core::cmp::min(data.len(), buf.len()); buf[..len_from_data].copy_from_slice(&data[..len_from_data]); for byte in &mut buf[len_from_data..] { *byte = 0 } } fn unpack_char(vm: &VirtualMachine, data: &[u8]) -> PyObjectRef { vm.ctx.new_bytes(vec![data[0]]).into() } fn unpack_pascal(vm: &VirtualMachine, data: &[u8]) -> PyObjectRef { let (&len, data) = match data.split_first() { Some(x) => x, None => { // cpython throws an internal SystemError here return vm.ctx.new_bytes(vec![]).into(); } }; let len = core::cmp::min(len as usize, data.len()); vm.ctx.new_bytes(data[..len].to_vec()).into() } // XXX: are those functions expected to be placed here? pub fn struct_error_type(vm: &VirtualMachine) -> &'static PyTypeRef { static_cell! { static INSTANCE: PyTypeRef; } INSTANCE.get_or_init(|| vm.ctx.new_exception_type("struct", "error", None)) } pub fn new_struct_error(vm: &VirtualMachine, msg: impl Into<String>) -> PyBaseExceptionRef { // can't just STRUCT_ERROR.get().unwrap() cause this could be called before from buffer // machinery, independent of whether _struct was ever imported vm.new_exception_msg(struct_error_type(vm).clone(), msg.into()) }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/dict_inner.rs
crates/vm/src/dict_inner.rs
//! Ordered dictionary implementation. //! Inspired by: <https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html> //! And: <https://www.youtube.com/watch?v=p33CVV29OG8> //! And: <http://code.activestate.com/recipes/578375/> use crate::{ AsObject, Py, PyExact, PyObject, PyObjectRef, PyRefExact, PyResult, VirtualMachine, builtins::{PyBytes, PyInt, PyStr, PyStrInterned, PyStrRef}, convert::ToPyObject, }; use crate::{ common::{ hash, lock::{PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard}, wtf8::{Wtf8, Wtf8Buf}, }, object::{Traverse, TraverseFn}, }; use alloc::fmt; use core::{mem::size_of, ops::ControlFlow}; use num_traits::ToPrimitive; // HashIndex is intended to be same size with hash::PyHash // but it doesn't mean the values are compatible with actual PyHash value /// hash value of an object returned by __hash__ type HashValue = hash::PyHash; /// index calculated by resolving collision type HashIndex = hash::PyHash; /// index into dict.indices type IndexIndex = usize; /// index into dict.entries type EntryIndex = usize; pub struct Dict<T = PyObjectRef> { inner: PyRwLock<DictInner<T>>, } unsafe impl<T: Traverse> Traverse for Dict<T> { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { self.inner.traverse(tracer_fn); } } impl<T> fmt::Debug for Dict<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Debug").finish() } } #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[repr(transparent)] struct IndexEntry(i64); impl IndexEntry { const FREE: Self = Self(-1); const DUMMY: Self = Self(-2); /// # Safety /// idx must not be one of FREE or DUMMY const unsafe fn from_index_unchecked(idx: usize) -> Self { debug_assert!((idx as isize) >= 0); Self(idx as i64) } const fn index(self) -> Option<usize> { if self.0 >= 0 { Some(self.0 as usize) } else { None } } } #[derive(Clone)] struct DictInner<T> { used: usize, filled: usize, indices: Vec<IndexEntry>, entries: Vec<Option<DictEntry<T>>>, } unsafe impl<T: Traverse> Traverse for DictInner<T> { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { self.entries .iter() .map(|v| { if let Some(v) = v { v.key.traverse(tracer_fn); v.value.traverse(tracer_fn); } }) .count(); } } impl<T: Clone> Clone for Dict<T> { fn clone(&self) -> Self { Self { inner: PyRwLock::new(self.inner.read().clone()), } } } impl<T> Default for Dict<T> { fn default() -> Self { Self { inner: PyRwLock::new(DictInner { used: 0, filled: 0, indices: vec![IndexEntry::FREE; 8], entries: Vec::new(), }), } } } #[derive(Clone)] struct DictEntry<T> { hash: HashValue, key: PyObjectRef, index: IndexIndex, value: T, } static_assertions::assert_eq_size!(DictEntry<PyObjectRef>, Option<DictEntry<PyObjectRef>>); #[derive(Debug, PartialEq, Eq)] pub struct DictSize { indices_size: usize, pub entries_size: usize, pub used: usize, filled: usize, } struct GenIndexes { idx: HashIndex, perturb: HashValue, mask: HashIndex, } impl GenIndexes { const fn new(hash: HashValue, mask: HashIndex) -> Self { let hash = hash.abs(); Self { idx: hash, perturb: hash, mask, } } const fn next(&mut self) -> usize { let prev = self.idx; self.idx = prev .wrapping_mul(5) .wrapping_add(self.perturb) .wrapping_add(1); self.perturb >>= 5; (prev & self.mask) as usize } } impl<T> DictInner<T> { fn resize(&mut self, new_size: usize) { let new_size = { let mut i = 1; while i < new_size { i <<= 1; } i }; self.indices = vec![IndexEntry::FREE; new_size]; let mask = (new_size - 1) as i64; for (entry_idx, entry) in self.entries.iter_mut().enumerate() { if let Some(entry) = entry { let mut idxs = GenIndexes::new(entry.hash, mask); loop { let index_index = idxs.next(); unsafe { // Safety: index is always valid here // index_index is generated by idxs // entry_idx is saved one let idx = self.indices.get_unchecked_mut(index_index); if *idx == IndexEntry::FREE { *idx = IndexEntry::from_index_unchecked(entry_idx); entry.index = index_index; break; } } } } else { //removed entry } } self.filled = self.used; } fn unchecked_push( &mut self, index: IndexIndex, hash_value: HashValue, key: PyObjectRef, value: T, index_entry: IndexEntry, ) { let entry = DictEntry { hash: hash_value, key, value, index, }; let entry_index = self.entries.len(); self.entries.push(Some(entry)); self.indices[index] = unsafe { // SAFETY: entry_index is self.entries.len(). it never can // grow to `usize-2` because hash tables cannot full its index IndexEntry::from_index_unchecked(entry_index) }; self.used += 1; if let IndexEntry::FREE = index_entry { self.filled += 1; if let Some(new_size) = self.should_resize() { self.resize(new_size) } } } const fn size(&self) -> DictSize { DictSize { indices_size: self.indices.len(), entries_size: self.entries.len(), used: self.used, filled: self.filled, } } #[inline] const fn should_resize(&self) -> Option<usize> { if self.filled * 3 > self.indices.len() * 2 { Some(self.used * 2) } else { None } } #[inline] fn get_entry_checked(&self, idx: EntryIndex, index_index: IndexIndex) -> Option<&DictEntry<T>> { match self.entries.get(idx) { Some(Some(entry)) if entry.index == index_index => Some(entry), _ => None, } } } type PopInnerResult<T> = ControlFlow<Option<DictEntry<T>>>; impl<T: Clone> Dict<T> { fn read(&self) -> PyRwLockReadGuard<'_, DictInner<T>> { self.inner.read() } fn write(&self) -> PyRwLockWriteGuard<'_, DictInner<T>> { self.inner.write() } /// Store a key pub fn insert<K>(&self, vm: &VirtualMachine, key: &K, value: T) -> PyResult<()> where K: DictKey + ?Sized, { let hash = key.key_hash(vm)?; let _removed = loop { let (entry_index, index_index) = self.lookup(vm, key, hash, None)?; let mut inner = self.write(); if let Some(index) = entry_index.index() { // Update existing key if let Some(entry) = inner.entries.get_mut(index) { let Some(entry) = entry.as_mut() else { // The dict was changed since we did lookup. Let's try again. // this is very rare to happen // (and seems only happen with very high freq gc, and about one time in 10000 iters) // but still possible continue; }; if entry.index == index_index { let removed = core::mem::replace(&mut entry.value, value); // defer dec RC break Some(removed); } else { // stuff shifted around, let's try again } } else { // The dict was changed since we did lookup. Let's try again. } } else { // New key: inner.unchecked_push(index_index, hash, key.to_pyobject(vm), value, entry_index); break None; } }; Ok(()) } pub fn contains<K: DictKey + ?Sized>(&self, vm: &VirtualMachine, key: &K) -> PyResult<bool> { let key_hash = key.key_hash(vm)?; let (entry, _) = self.lookup(vm, key, key_hash, None)?; Ok(entry.index().is_some()) } /// Retrieve a key #[cfg_attr(feature = "flame-it", flame("Dict"))] pub fn get<K: DictKey + ?Sized>(&self, vm: &VirtualMachine, key: &K) -> PyResult<Option<T>> { let hash = key.key_hash(vm)?; self._get_inner(vm, key, hash) } fn _get_inner<K: DictKey + ?Sized>( &self, vm: &VirtualMachine, key: &K, hash: HashValue, ) -> PyResult<Option<T>> { let ret = loop { let (entry, index_index) = self.lookup(vm, key, hash, None)?; if let Some(index) = entry.index() { let inner = self.read(); if let Some(entry) = inner.get_entry_checked(index, index_index) { break Some(entry.value.clone()); } else { // The dict was changed since we did lookup. Let's try again. continue; } } else { break None; } }; Ok(ret) } pub fn get_chain<K: DictKey + ?Sized>( &self, other: &Self, vm: &VirtualMachine, key: &K, ) -> PyResult<Option<T>> { let hash = key.key_hash(vm)?; if let Some(x) = self._get_inner(vm, key, hash)? { Ok(Some(x)) } else { other._get_inner(vm, key, hash) } } pub fn clear(&self) { let _removed = { let mut inner = self.write(); inner.indices.clear(); inner.indices.resize(8, IndexEntry::FREE); inner.used = 0; inner.filled = 0; // defer dec rc core::mem::take(&mut inner.entries) }; } /// Delete a key pub fn delete<K>(&self, vm: &VirtualMachine, key: &K) -> PyResult<()> where K: DictKey + ?Sized, { if self.remove_if_exists(vm, key)?.is_some() { Ok(()) } else { Err(vm.new_key_error(key.to_pyobject(vm))) } } pub fn delete_if_exists<K>(&self, vm: &VirtualMachine, key: &K) -> PyResult<bool> where K: DictKey + ?Sized, { self.remove_if_exists(vm, key).map(|opt| opt.is_some()) } pub fn delete_if<K, F>(&self, vm: &VirtualMachine, key: &K, pred: F) -> PyResult<bool> where K: DictKey + ?Sized, F: Fn(&T) -> PyResult<bool>, { self.remove_if(vm, key, pred).map(|opt| opt.is_some()) } pub fn remove_if_exists<K>(&self, vm: &VirtualMachine, key: &K) -> PyResult<Option<T>> where K: DictKey + ?Sized, { self.remove_if(vm, key, |_| Ok(true)) } /// pred should be VERY CAREFUL about what it does as it is called while /// the dict's internal mutex is held pub(crate) fn remove_if<K, F>( &self, vm: &VirtualMachine, key: &K, pred: F, ) -> PyResult<Option<T>> where K: DictKey + ?Sized, F: Fn(&T) -> PyResult<bool>, { let hash = key.key_hash(vm)?; let removed = loop { let lookup = self.lookup(vm, key, hash, None)?; match self.pop_inner_if(lookup, &pred)? { ControlFlow::Break(entry) => break entry, ControlFlow::Continue(()) => continue, } }; Ok(removed.map(|entry| entry.value)) } pub fn delete_or_insert(&self, vm: &VirtualMachine, key: &PyObject, value: T) -> PyResult<()> { let hash = key.key_hash(vm)?; let _removed = loop { let lookup = self.lookup(vm, key, hash, None)?; let (entry, index_index) = lookup; if entry.index().is_some() { match self.pop_inner(lookup) { ControlFlow::Break(Some(entry)) => break Some(entry), _ => continue, } } else { let mut inner = self.write(); inner.unchecked_push(index_index, hash, key.to_owned(), value, entry); break None; } }; Ok(()) } pub fn setdefault<K, F>(&self, vm: &VirtualMachine, key: &K, default: F) -> PyResult<T> where K: DictKey + ?Sized, F: FnOnce() -> T, { let hash = key.key_hash(vm)?; let res = loop { let lookup = self.lookup(vm, key, hash, None)?; let (index_entry, index_index) = lookup; if let Some(index) = index_entry.index() { let inner = self.read(); if let Some(entry) = inner.get_entry_checked(index, index_index) { break entry.value.clone(); } else { // The dict was changed since we did lookup, let's try again. continue; } } else { let value = default(); let mut inner = self.write(); inner.unchecked_push( index_index, hash, key.to_pyobject(vm), value.clone(), index_entry, ); break value; } }; Ok(res) } #[allow(dead_code)] pub fn setdefault_entry<K, F>( &self, vm: &VirtualMachine, key: &K, default: F, ) -> PyResult<(PyObjectRef, T)> where K: DictKey + ?Sized, F: FnOnce() -> T, { let hash = key.key_hash(vm)?; let res = loop { let lookup = self.lookup(vm, key, hash, None)?; let (index_entry, index_index) = lookup; if let Some(index) = index_entry.index() { let inner = self.read(); if let Some(entry) = inner.get_entry_checked(index, index_index) { break (entry.key.clone(), entry.value.clone()); } else { // The dict was changed since we did lookup, let's try again. continue; } } else { let value = default(); let key = key.to_pyobject(vm); let mut inner = self.write(); let ret = (key.clone(), value.clone()); inner.unchecked_push(index_index, hash, key, value, index_entry); break ret; } }; Ok(res) } pub fn len(&self) -> usize { self.read().used } pub fn size(&self) -> DictSize { self.read().size() } pub fn next_entry(&self, mut position: EntryIndex) -> Option<(usize, PyObjectRef, T)> { let inner = self.read(); loop { let entry = inner.entries.get(position)?; position += 1; if let Some(entry) = entry { break Some((position, entry.key.clone(), entry.value.clone())); } } } pub fn prev_entry(&self, mut position: EntryIndex) -> Option<(usize, PyObjectRef, T)> { let inner = self.read(); loop { let entry = inner.entries.get(position)?; position = position.saturating_sub(1); if let Some(entry) = entry { break Some((position, entry.key.clone(), entry.value.clone())); } } } pub fn len_from_entry_index(&self, position: EntryIndex) -> usize { self.read().entries.len().saturating_sub(position) } pub fn has_changed_size(&self, old: &DictSize) -> bool { let current = self.read().size(); current != *old } pub fn keys(&self) -> Vec<PyObjectRef> { self.read() .entries .iter() .filter_map(|v| v.as_ref().map(|v| v.key.clone())) .collect() } pub fn try_fold_keys<Acc, Fold>(&self, init: Acc, f: Fold) -> PyResult<Acc> where Fold: FnMut(Acc, &PyObject) -> PyResult<Acc>, { self.read() .entries .iter() .filter_map(|v| v.as_ref().map(|v| v.key.as_object())) .try_fold(init, f) } /// Lookup the index for the given key. #[cfg_attr(feature = "flame-it", flame("Dict"))] fn lookup<K: DictKey + ?Sized>( &self, vm: &VirtualMachine, key: &K, hash_value: HashValue, mut lock: Option<PyRwLockReadGuard<'_, DictInner<T>>>, ) -> PyResult<LookupResult> { let mut idxs = None; let mut free_slot = None; let ret = 'outer: loop { let (entry_key, ret) = { let inner = lock.take().unwrap_or_else(|| self.read()); let idxs = idxs.get_or_insert_with(|| { GenIndexes::new(hash_value, (inner.indices.len() - 1) as i64) }); loop { let index_index = idxs.next(); let index_entry = *unsafe { // Safety: index_index is generated inner.indices.get_unchecked(index_index) }; match index_entry { IndexEntry::DUMMY => { if free_slot.is_none() { free_slot = Some(index_index); } } IndexEntry::FREE => { let idxs = match free_slot { Some(free) => (IndexEntry::DUMMY, free), None => (IndexEntry::FREE, index_index), }; return Ok(idxs); } idx => { let entry = unsafe { // Safety: DUMMY and FREE are already handled above. // i is always valid and entry always exists. let i = idx.index().unwrap_unchecked(); inner.entries.get_unchecked(i).as_ref().unwrap_unchecked() }; let ret = (idx, index_index); if key.key_is(&entry.key) { break 'outer ret; } else if entry.hash == hash_value { break (entry.key.clone(), ret); } else { // entry mismatch } } } // warn!("Perturb value: {}", i); } }; // This comparison needs to be done outside the lock. if key.key_eq(vm, &entry_key)? { break 'outer ret; } else { // hash collision } // warn!("Perturb value: {}", i); }; Ok(ret) } // returns Err(()) if changed since lookup fn pop_inner(&self, lookup: LookupResult) -> PopInnerResult<T> { self.pop_inner_if(lookup, |_| Ok::<_, core::convert::Infallible>(true)) .unwrap_or_else(|x| match x {}) } fn pop_inner_if<E>( &self, lookup: LookupResult, pred: impl Fn(&T) -> Result<bool, E>, ) -> Result<PopInnerResult<T>, E> { let (entry_index, index_index) = lookup; let Some(entry_index) = entry_index.index() else { return Ok(ControlFlow::Break(None)); }; let inner = &mut *self.write(); let slot = if let Some(slot) = inner.entries.get_mut(entry_index) { slot } else { // The dict was changed since we did lookup. Let's try again. return Ok(ControlFlow::Continue(())); }; match slot { Some(entry) if entry.index == index_index => { if !pred(&entry.value)? { return Ok(ControlFlow::Break(None)); } } // The dict was changed since we did lookup. Let's try again. _ => return Ok(ControlFlow::Continue(())), } *unsafe { // index_index is result of lookup inner.indices.get_unchecked_mut(index_index) } = IndexEntry::DUMMY; inner.used -= 1; let removed = slot.take(); Ok(ControlFlow::Break(removed)) } /// Retrieve and delete a key pub fn pop<K: DictKey + ?Sized>(&self, vm: &VirtualMachine, key: &K) -> PyResult<Option<T>> { let hash_value = key.key_hash(vm)?; let removed = loop { let lookup = self.lookup(vm, key, hash_value, None)?; match self.pop_inner(lookup) { ControlFlow::Break(entry) => break entry.map(|e| e.value), ControlFlow::Continue(()) => continue, } }; Ok(removed) } pub fn pop_back(&self) -> Option<(PyObjectRef, T)> { let inner = &mut *self.write(); let entry = loop { let entry = inner.entries.pop()?; if let Some(entry) = entry { break entry; } }; inner.used -= 1; *unsafe { // entry.index always refers valid index inner.indices.get_unchecked_mut(entry.index) } = IndexEntry::DUMMY; Some((entry.key, entry.value)) } pub fn sizeof(&self) -> usize { let inner = self.read(); size_of::<Self>() + size_of::<DictInner<T>>() + inner.indices.len() * size_of::<i64>() + inner.entries.len() * size_of::<DictEntry<T>>() } } type LookupResult = (IndexEntry, IndexIndex); /// Types implementing this trait can be used to index /// the dictionary. Typical use-cases are: /// - PyObjectRef -> arbitrary python type used as key /// - str -> string reference used as key, this is often used internally pub trait DictKey { type Owned: ToPyObject; fn _to_owned(&self, vm: &VirtualMachine) -> Self::Owned; fn to_pyobject(&self, vm: &VirtualMachine) -> PyObjectRef { self._to_owned(vm).to_pyobject(vm) } fn key_hash(&self, vm: &VirtualMachine) -> PyResult<HashValue>; fn key_is(&self, other: &PyObject) -> bool; fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObject) -> PyResult<bool>; fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult<isize>; } /// Implement trait for PyObjectRef such that we can use python objects /// to index dictionaries. impl DictKey for PyObject { type Owned = PyObjectRef; #[inline(always)] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { self.to_owned() } #[inline(always)] fn key_hash(&self, vm: &VirtualMachine) -> PyResult<HashValue> { self.hash(vm) } #[inline(always)] fn key_is(&self, other: &PyObject) -> bool { self.is(other) } #[inline(always)] fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObject) -> PyResult<bool> { vm.identical_or_equal(self, other_key) } #[inline] fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult<isize> { self.try_index(vm)?.try_to_primitive(vm) } } impl DictKey for Py<PyStr> { type Owned = PyStrRef; #[inline(always)] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { self.to_owned() } #[inline] fn key_hash(&self, vm: &VirtualMachine) -> PyResult<HashValue> { Ok(self.hash(vm)) } #[inline(always)] fn key_is(&self, other: &PyObject) -> bool { self.is(other) } fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObject) -> PyResult<bool> { if self.is(other_key) { Ok(true) } else if let Some(pystr) = other_key.downcast_ref_if_exact::<PyStr>(vm) { Ok(self.as_wtf8() == pystr.as_wtf8()) } else { vm.bool_eq(self.as_object(), other_key) } } #[inline(always)] fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult<isize> { self.as_object().key_as_isize(vm) } } impl DictKey for PyStrInterned { type Owned = PyRefExact<PyStr>; #[inline] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { let zelf: &'static Self = unsafe { &*(self as *const _) }; zelf.to_exact() } #[inline] fn key_hash(&self, vm: &VirtualMachine) -> PyResult<HashValue> { (**self).key_hash(vm) } #[inline] fn key_is(&self, other: &PyObject) -> bool { (**self).key_is(other) } #[inline] fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObject) -> PyResult<bool> { (**self).key_eq(vm, other_key) } #[inline] fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult<isize> { (**self).key_as_isize(vm) } } impl DictKey for PyExact<PyStr> { type Owned = PyRefExact<PyStr>; #[inline] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { self.to_owned() } #[inline(always)] fn key_hash(&self, vm: &VirtualMachine) -> PyResult<HashValue> { (**self).key_hash(vm) } #[inline(always)] fn key_is(&self, other: &PyObject) -> bool { (**self).key_is(other) } #[inline(always)] fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObject) -> PyResult<bool> { (**self).key_eq(vm, other_key) } #[inline(always)] fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult<isize> { (**self).key_as_isize(vm) } } // AsRef<str> fit this case but not possible in rust 1.46 /// Implement trait for the str type, so that we can use strings /// to index dictionaries. impl DictKey for str { type Owned = String; #[inline(always)] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { self.to_owned() } #[inline] fn key_hash(&self, vm: &VirtualMachine) -> PyResult<HashValue> { // follow a similar route as the hashing of PyStrRef Ok(vm.state.hash_secret.hash_str(self)) } #[inline(always)] fn key_is(&self, _other: &PyObject) -> bool { // No matter who the other pyobject is, we are never the same thing, since // we are a str, not a pyobject. false } fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObject) -> PyResult<bool> { if let Some(pystr) = other_key.downcast_ref_if_exact::<PyStr>(vm) { Ok(pystr.as_wtf8() == self) } else { // Fall back to PyObjectRef implementation. let s = vm.ctx.new_str(self); s.key_eq(vm, other_key) } } fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult<isize> { Err(vm.new_type_error("'str' object cannot be interpreted as an integer")) } } impl DictKey for String { type Owned = Self; #[inline] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { self.clone() } fn key_hash(&self, vm: &VirtualMachine) -> PyResult<HashValue> { self.as_str().key_hash(vm) } fn key_is(&self, other: &PyObject) -> bool { self.as_str().key_is(other) } fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObject) -> PyResult<bool> { self.as_str().key_eq(vm, other_key) } fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult<isize> { self.as_str().key_as_isize(vm) } } impl DictKey for Wtf8 { type Owned = Wtf8Buf; #[inline(always)] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { self.to_owned() } #[inline] fn key_hash(&self, vm: &VirtualMachine) -> PyResult<HashValue> { // follow a similar route as the hashing of PyStrRef Ok(vm.state.hash_secret.hash_bytes(self.as_bytes())) } #[inline(always)] fn key_is(&self, _other: &PyObject) -> bool { // No matter who the other pyobject is, we are never the same thing, since // we are a str, not a pyobject. false } fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObject) -> PyResult<bool> { if let Some(pystr) = other_key.downcast_ref_if_exact::<PyStr>(vm) { Ok(pystr.as_wtf8() == self) } else { // Fall back to PyObjectRef implementation. let s = vm.ctx.new_str(self); s.key_eq(vm, other_key) } } fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult<isize> { Err(vm.new_type_error("'str' object cannot be interpreted as an integer")) } } impl DictKey for Wtf8Buf { type Owned = Self; #[inline] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { self.clone() } fn key_hash(&self, vm: &VirtualMachine) -> PyResult<HashValue> { (**self).key_hash(vm) } fn key_is(&self, other: &PyObject) -> bool { (**self).key_is(other) } fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObject) -> PyResult<bool> { (**self).key_eq(vm, other_key) } fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult<isize> { (**self).key_as_isize(vm) } } impl DictKey for [u8] { type Owned = Vec<u8>; #[inline(always)] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { self.to_owned() } #[inline] fn key_hash(&self, vm: &VirtualMachine) -> PyResult<HashValue> { // follow a similar route as the hashing of PyStrRef Ok(vm.state.hash_secret.hash_bytes(self)) } #[inline(always)] fn key_is(&self, _other: &PyObject) -> bool { // No matter who the other pyobject is, we are never the same thing, since // we are a str, not a pyobject. false } fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObject) -> PyResult<bool> { if let Some(pystr) = other_key.downcast_ref_if_exact::<PyBytes>(vm) { Ok(pystr.as_bytes() == self) } else { // Fall back to PyObjectRef implementation. let s = vm.ctx.new_bytes(self.to_vec()); s.key_eq(vm, other_key) } } fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult<isize> { Err(vm.new_type_error("'str' object cannot be interpreted as an integer")) } } impl DictKey for Vec<u8> { type Owned = Self; #[inline] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { self.clone() } fn key_hash(&self, vm: &VirtualMachine) -> PyResult<HashValue> { self.as_slice().key_hash(vm) } fn key_is(&self, other: &PyObject) -> bool { self.as_slice().key_is(other) } fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObject) -> PyResult<bool> { self.as_slice().key_eq(vm, other_key) } fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult<isize> { self.as_slice().key_as_isize(vm) } } impl DictKey for usize { type Owned = Self; #[inline] fn _to_owned(&self, _vm: &VirtualMachine) -> Self::Owned { *self } fn key_hash(&self, _vm: &VirtualMachine) -> PyResult<HashValue> { Ok(hash::hash_usize(*self)) } fn key_is(&self, _other: &PyObject) -> bool { false } fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObject) -> PyResult<bool> { if let Some(int) = other_key.downcast_ref_if_exact::<PyInt>(vm) { if let Some(i) = int.as_bigint().to_usize() { Ok(i == *self) } else { Ok(false) } } else { let int = vm.ctx.new_int(*self); vm.bool_eq(int.as_ref(), other_key) } } fn key_as_isize(&self, _vm: &VirtualMachine) -> PyResult<isize> { Ok(*self as isize) } } #[cfg(test)] mod tests { use super::*; use crate::{Interpreter, common::ascii}; #[test] fn test_insert() {
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/import.rs
crates/vm/src/import.rs
//! Import mechanics use crate::{ AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, builtins::{PyCode, list, traceback::PyTraceback}, exceptions::types::PyBaseException, scope::Scope, vm::{VirtualMachine, resolve_frozen_alias, thread}, }; pub(crate) fn check_pyc_magic_number_bytes(buf: &[u8]) -> bool { buf.starts_with(&crate::version::PYC_MAGIC_NUMBER_BYTES[..2]) } pub(crate) fn init_importlib_base(vm: &mut VirtualMachine) -> PyResult<PyObjectRef> { flame_guard!("init importlib"); // importlib_bootstrap needs these and it inlines checks to sys.modules before calling into // import machinery, so this should bring some speedup #[cfg(all(feature = "threading", not(target_os = "wasi")))] import_builtin(vm, "_thread")?; import_builtin(vm, "_warnings")?; import_builtin(vm, "_weakref")?; let importlib = thread::enter_vm(vm, || { let bootstrap = import_frozen(vm, "_frozen_importlib")?; let install = bootstrap.get_attr("_install", vm)?; let imp = import_builtin(vm, "_imp")?; install.call((vm.sys_module.clone(), imp), vm)?; Ok(bootstrap) })?; vm.import_func = importlib.get_attr(identifier!(vm, __import__), vm)?; Ok(importlib) } pub(crate) fn init_importlib_package(vm: &VirtualMachine, importlib: PyObjectRef) -> PyResult<()> { thread::enter_vm(vm, || { flame_guard!("install_external"); // same deal as imports above #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] import_builtin(vm, crate::stdlib::os::MODULE_NAME)?; #[cfg(windows)] import_builtin(vm, "winreg")?; import_builtin(vm, "_io")?; import_builtin(vm, "marshal")?; let install_external = importlib.get_attr("_install_external_importers", vm)?; install_external.call((), vm)?; let zipimport_res = (|| -> PyResult<()> { let zipimport = vm.import("zipimport", 0)?; let zipimporter = zipimport.get_attr("zipimporter", vm)?; let path_hooks = vm.sys_module.get_attr("path_hooks", vm)?; let path_hooks = list::PyListRef::try_from_object(vm, path_hooks)?; path_hooks.insert(0, zipimporter); Ok(()) })(); if zipimport_res.is_err() { warn!("couldn't init zipimport") } Ok(()) }) } pub fn make_frozen(vm: &VirtualMachine, name: &str) -> PyResult<PyRef<PyCode>> { let frozen = vm.state.frozen.get(name).ok_or_else(|| { vm.new_import_error( format!("No such frozen object named {name}"), vm.ctx.new_str(name), ) })?; Ok(vm.ctx.new_code(frozen.code)) } pub fn import_frozen(vm: &VirtualMachine, module_name: &str) -> PyResult { let frozen = vm.state.frozen.get(module_name).ok_or_else(|| { vm.new_import_error( format!("No such frozen object named {module_name}"), vm.ctx.new_str(module_name), ) })?; let module = import_code_obj(vm, module_name, vm.ctx.new_code(frozen.code), false)?; debug_assert!(module.get_attr(identifier!(vm, __name__), vm).is_ok()); let origname = resolve_frozen_alias(module_name); module.set_attr("__origname__", vm.ctx.new_str(origname), vm)?; Ok(module) } pub fn import_builtin(vm: &VirtualMachine, module_name: &str) -> PyResult { let make_module_func = vm.state.module_inits.get(module_name).ok_or_else(|| { vm.new_import_error( format!("Cannot import builtin module {module_name}"), vm.ctx.new_str(module_name), ) })?; let module = make_module_func(vm); let sys_modules = vm.sys_module.get_attr("modules", vm)?; sys_modules.set_item(module_name, module.as_object().to_owned(), vm)?; Ok(module.into()) } #[cfg(feature = "rustpython-compiler")] pub fn import_file( vm: &VirtualMachine, module_name: &str, file_path: String, content: &str, ) -> PyResult { let code = vm .compile_with_opts( content, crate::compiler::Mode::Exec, file_path, vm.compile_opts(), ) .map_err(|err| vm.new_syntax_error(&err, Some(content)))?; import_code_obj(vm, module_name, code, true) } #[cfg(feature = "rustpython-compiler")] pub fn import_source(vm: &VirtualMachine, module_name: &str, content: &str) -> PyResult { let code = vm .compile_with_opts( content, crate::compiler::Mode::Exec, "<source>".to_owned(), vm.compile_opts(), ) .map_err(|err| vm.new_syntax_error(&err, Some(content)))?; import_code_obj(vm, module_name, code, false) } pub fn import_code_obj( vm: &VirtualMachine, module_name: &str, code_obj: PyRef<PyCode>, set_file_attr: bool, ) -> PyResult { let attrs = vm.ctx.new_dict(); attrs.set_item( identifier!(vm, __name__), vm.ctx.new_str(module_name).into(), vm, )?; if set_file_attr { attrs.set_item( identifier!(vm, __file__), code_obj.source_path.to_object(), vm, )?; } let module = vm.new_module(module_name, attrs.clone(), None); // Store module in cache to prevent infinite loop with mutual importing libs: let sys_modules = vm.sys_module.get_attr("modules", vm)?; sys_modules.set_item(module_name, module.clone().into(), vm)?; // Execute main code in module: let scope = Scope::with_builtins(None, attrs, vm); vm.run_code_obj(code_obj, scope)?; Ok(module.into()) } fn remove_importlib_frames_inner( vm: &VirtualMachine, tb: Option<PyRef<PyTraceback>>, always_trim: bool, ) -> (Option<PyRef<PyTraceback>>, bool) { let traceback = if let Some(tb) = tb { tb } else { return (None, false); }; let file_name = traceback.frame.code.source_path.as_str(); let (inner_tb, mut now_in_importlib) = remove_importlib_frames_inner(vm, traceback.next.lock().clone(), always_trim); if file_name == "_frozen_importlib" || file_name == "_frozen_importlib_external" { if traceback.frame.code.obj_name.as_str() == "_call_with_frames_removed" { now_in_importlib = true; } if always_trim || now_in_importlib { return (inner_tb, now_in_importlib); } } else { now_in_importlib = false; } ( Some( PyTraceback::new( inner_tb, traceback.frame.clone(), traceback.lasti, traceback.lineno, ) .into_ref(&vm.ctx), ), now_in_importlib, ) } // TODO: This function should do nothing on verbose mode. // TODO: Fix this function after making PyTraceback.next mutable pub fn remove_importlib_frames(vm: &VirtualMachine, exc: &Py<PyBaseException>) { if vm.state.config.settings.verbose != 0 { return; } let always_trim = exc.fast_isinstance(vm.ctx.exceptions.import_error); if let Some(tb) = exc.__traceback__() { let trimmed_tb = remove_importlib_frames_inner(vm, Some(tb), always_trim).0; exc.set_traceback_typed(trimmed_tb); } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/exception_group.rs
crates/vm/src/exception_group.rs
//! ExceptionGroup implementation for Python 3.11+ //! //! This module implements BaseExceptionGroup and ExceptionGroup with multiple inheritance support. use crate::builtins::{PyList, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef}; use crate::function::{ArgIterable, FuncArgs}; use crate::types::{PyTypeFlags, PyTypeSlots}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyRef, PyResult, TryFromObject, VirtualMachine, }; use crate::exceptions::types::PyBaseException; /// Create dynamic ExceptionGroup type with multiple inheritance fn create_exception_group(ctx: &Context) -> PyRef<PyType> { let excs = &ctx.exceptions; let exception_group_slots = PyTypeSlots { flags: PyTypeFlags::heap_type_flags() | PyTypeFlags::HAS_DICT, ..Default::default() }; PyType::new_heap( "ExceptionGroup", vec![ excs.base_exception_group.to_owned(), excs.exception_type.to_owned(), ], Default::default(), exception_group_slots, ctx.types.type_type.to_owned(), ctx, ) .expect("Failed to create ExceptionGroup type with multiple inheritance") } pub fn exception_group() -> &'static Py<PyType> { ::rustpython_vm::common::static_cell! { static CELL: ::rustpython_vm::builtins::PyTypeRef; } CELL.get_or_init(|| create_exception_group(Context::genesis())) } pub(super) mod types { use super::*; use crate::PyPayload; use crate::builtins::PyGenericAlias; use crate::types::{Constructor, Initializer}; #[pyexception(name, base = PyBaseException, ctx = "base_exception_group")] #[derive(Debug)] #[repr(transparent)] pub struct PyBaseExceptionGroup(PyBaseException); #[pyexception(with(Constructor, Initializer))] impl PyBaseExceptionGroup { #[pyclassmethod] fn __class_getitem__( cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine, ) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } #[pymethod] fn derive( zelf: PyRef<PyBaseException>, excs: PyObjectRef, vm: &VirtualMachine, ) -> PyResult { let message = zelf.get_arg(0).unwrap_or_else(|| vm.ctx.new_str("").into()); vm.invoke_exception( vm.ctx.exceptions.base_exception_group.to_owned(), vec![message, excs], ) .map(|e| e.into()) } #[pymethod] fn subgroup( zelf: PyRef<PyBaseException>, condition: PyObjectRef, vm: &VirtualMachine, ) -> PyResult { let matcher = get_condition_matcher(&condition, vm)?; // If self matches the condition entirely, return self let zelf_obj: PyObjectRef = zelf.clone().into(); if matcher.check(&zelf_obj, vm)? { return Ok(zelf_obj); } let exceptions = get_exceptions_tuple(&zelf, vm)?; let mut matching: Vec<PyObjectRef> = Vec::new(); let mut modified = false; for exc in exceptions { if is_base_exception_group(&exc, vm) { // Recursive call for nested groups let subgroup_result = vm.call_method(&exc, "subgroup", (condition.clone(),))?; if !vm.is_none(&subgroup_result) { matching.push(subgroup_result.clone()); } if !subgroup_result.is(&exc) { modified = true; } } else if matcher.check(&exc, vm)? { matching.push(exc); } else { modified = true; } } if !modified { return Ok(zelf.clone().into()); } if matching.is_empty() { return Ok(vm.ctx.none()); } // Create new group with matching exceptions and copy metadata derive_and_copy_attributes(&zelf, matching, vm) } #[pymethod] fn split( zelf: PyRef<PyBaseException>, condition: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyTupleRef> { let matcher = get_condition_matcher(&condition, vm)?; // If self matches the condition entirely let zelf_obj: PyObjectRef = zelf.clone().into(); if matcher.check(&zelf_obj, vm)? { return Ok(vm.ctx.new_tuple(vec![zelf_obj, vm.ctx.none()])); } let exceptions = get_exceptions_tuple(&zelf, vm)?; let mut matching: Vec<PyObjectRef> = Vec::new(); let mut rest: Vec<PyObjectRef> = Vec::new(); for exc in exceptions { if is_base_exception_group(&exc, vm) { let result = vm.call_method(&exc, "split", (condition.clone(),))?; let result_tuple: PyTupleRef = result.try_into_value(vm)?; let match_part = result_tuple .first() .cloned() .unwrap_or_else(|| vm.ctx.none()); let rest_part = result_tuple .get(1) .cloned() .unwrap_or_else(|| vm.ctx.none()); if !vm.is_none(&match_part) { matching.push(match_part); } if !vm.is_none(&rest_part) { rest.push(rest_part); } } else if matcher.check(&exc, vm)? { matching.push(exc); } else { rest.push(exc); } } let match_group = if matching.is_empty() { vm.ctx.none() } else { derive_and_copy_attributes(&zelf, matching, vm)? }; let rest_group = if rest.is_empty() { vm.ctx.none() } else { derive_and_copy_attributes(&zelf, rest, vm)? }; Ok(vm.ctx.new_tuple(vec![match_group, rest_group])) } #[pymethod] fn __str__(zelf: &Py<PyBaseException>, vm: &VirtualMachine) -> PyResult<PyStrRef> { let message = zelf .get_arg(0) .map(|m| m.str(vm)) .transpose()? .map(|s| s.as_str().to_owned()) .unwrap_or_default(); let num_excs = zelf .get_arg(1) .and_then(|obj| obj.downcast_ref::<PyTuple>().map(|t| t.len())) .unwrap_or(0); let suffix = if num_excs == 1 { "" } else { "s" }; Ok(vm.ctx.new_str(format!( "{} ({} sub-exception{})", message, num_excs, suffix ))) } #[pyslot] fn slot_repr(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyStrRef> { let zelf = zelf .downcast_ref::<PyBaseException>() .expect("exception group must be BaseException"); let class_name = zelf.class().name().to_owned(); let message = zelf .get_arg(0) .map(|m| m.repr(vm)) .transpose()? .map(|s| s.as_str().to_owned()) .unwrap_or_else(|| "''".to_owned()); // Format exceptions as list [exc1, exc2, ...] instead of tuple (exc1, exc2, ...) // CPython displays exceptions in list format even though they're stored as tuple let exceptions_str = if let Some(exceptions_obj) = zelf.get_arg(1) { // Get exceptions using ArgIterable for robustness let iter: ArgIterable<PyObjectRef> = ArgIterable::try_from_object(vm, exceptions_obj.clone())?; let mut exc_repr_list = Vec::new(); for exc in iter.iter(vm)? { exc_repr_list.push(exc?.repr(vm)?.as_str().to_owned()); } format!("[{}]", exc_repr_list.join(", ")) } else { "[]".to_owned() }; Ok(vm .ctx .new_str(format!("{}({}, {})", class_name, message, exceptions_str))) } } impl Constructor for PyBaseExceptionGroup { type Args = crate::function::PosArgs; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let args: Self::Args = args.bind(vm)?; let args = args.into_vec(); // Validate exactly 2 positional arguments if args.len() != 2 { return Err(vm.new_type_error(format!( "BaseExceptionGroup.__new__() takes exactly 2 positional arguments ({} given)", args.len() ))); } // Validate message is str let message = args[0].clone(); if !message.fast_isinstance(vm.ctx.types.str_type) { return Err(vm.new_type_error(format!( "argument 1 must be str, not {}", message.class().name() ))); } // Validate exceptions is a sequence (not set or None) let exceptions_arg = &args[1]; // Check for set/frozenset (not a sequence - unordered) if exceptions_arg.fast_isinstance(vm.ctx.types.set_type) || exceptions_arg.fast_isinstance(vm.ctx.types.frozenset_type) { return Err(vm.new_type_error("second argument (exceptions) must be a sequence")); } // Check for None if exceptions_arg.is(&vm.ctx.none) { return Err(vm.new_type_error("second argument (exceptions) must be a sequence")); } let exceptions: Vec<PyObjectRef> = exceptions_arg.try_to_value(vm).map_err(|_| { vm.new_type_error("second argument (exceptions) must be a sequence") })?; // Validate non-empty if exceptions.is_empty() { return Err(vm.new_value_error( "second argument (exceptions) must be a non-empty sequence".to_owned(), )); } // Validate all items are BaseException instances let mut has_non_exception = false; for (i, exc) in exceptions.iter().enumerate() { if !exc.fast_isinstance(vm.ctx.exceptions.base_exception_type) { return Err(vm.new_value_error(format!( "Item {} of second argument (exceptions) is not an exception", i ))); } // Check if any exception is not an Exception subclass // With dynamic ExceptionGroup (inherits from both BaseExceptionGroup and Exception), // ExceptionGroup instances are automatically instances of Exception if !exc.fast_isinstance(vm.ctx.exceptions.exception_type) { has_non_exception = true; } } // Get the dynamic ExceptionGroup type let exception_group_type = crate::exception_group::exception_group(); // Determine the actual class to use let actual_cls = if cls.is(exception_group_type) { // ExceptionGroup cannot contain BaseExceptions that are not Exception if has_non_exception { return Err( vm.new_type_error("Cannot nest BaseExceptions in an ExceptionGroup") ); } cls } else if cls.is(vm.ctx.exceptions.base_exception_group) { // Auto-convert to ExceptionGroup if all are Exception subclasses if !has_non_exception { exception_group_type.to_owned() } else { cls } } else { // User-defined subclass if has_non_exception && cls.fast_issubclass(vm.ctx.exceptions.exception_type) { return Err(vm.new_type_error(format!( "Cannot nest BaseExceptions in '{}'", cls.name() ))); } cls }; // Create the exception with (message, exceptions_tuple) as args let exceptions_tuple = vm.ctx.new_tuple(exceptions); let init_args = vec![message, exceptions_tuple.into()]; PyBaseException::new(init_args, vm) .into_ref_with_type(vm, actual_cls) .map(Into::into) } fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> { unimplemented!("use slot_new") } } impl Initializer for PyBaseExceptionGroup { type Args = FuncArgs; fn slot_init(_zelf: PyObjectRef, _args: FuncArgs, _vm: &VirtualMachine) -> PyResult<()> { // No-op: __new__ already set up the correct args (message, exceptions_tuple) Ok(()) } fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> { unreachable!("slot_init is overridden") } } // Helper functions for ExceptionGroup fn is_base_exception_group(obj: &PyObject, vm: &VirtualMachine) -> bool { obj.fast_isinstance(vm.ctx.exceptions.base_exception_group) } fn get_exceptions_tuple( exc: &Py<PyBaseException>, vm: &VirtualMachine, ) -> PyResult<Vec<PyObjectRef>> { let obj = exc .get_arg(1) .ok_or_else(|| vm.new_type_error("exceptions must be a tuple"))?; let tuple = obj .downcast_ref::<PyTuple>() .ok_or_else(|| vm.new_type_error("exceptions must be a tuple"))?; Ok(tuple.to_vec()) } enum ConditionMatcher { Type(PyTypeRef), Types(Vec<PyTypeRef>), Callable(PyObjectRef), } fn get_condition_matcher( condition: &PyObject, vm: &VirtualMachine, ) -> PyResult<ConditionMatcher> { // If it's a type and subclass of BaseException if let Some(typ) = condition.downcast_ref::<PyType>() && typ.fast_issubclass(vm.ctx.exceptions.base_exception_type) { return Ok(ConditionMatcher::Type(typ.to_owned())); } // If it's a tuple of types if let Some(tuple) = condition.downcast_ref::<PyTuple>() { let mut types = Vec::new(); for item in tuple.iter() { let typ: PyTypeRef = item.clone().try_into_value(vm).map_err(|_| { vm.new_type_error( "expected a function, exception type or tuple of exception types", ) })?; if !typ.fast_issubclass(vm.ctx.exceptions.base_exception_type) { return Err(vm.new_type_error( "expected a function, exception type or tuple of exception types", )); } types.push(typ); } if !types.is_empty() { return Ok(ConditionMatcher::Types(types)); } } // If it's callable (but not a type) if condition.is_callable() && condition.downcast_ref::<PyType>().is_none() { return Ok(ConditionMatcher::Callable(condition.to_owned())); } Err(vm.new_type_error("expected a function, exception type or tuple of exception types")) } impl ConditionMatcher { fn check(&self, exc: &PyObject, vm: &VirtualMachine) -> PyResult<bool> { match self { ConditionMatcher::Type(typ) => Ok(exc.fast_isinstance(typ)), ConditionMatcher::Types(types) => Ok(types.iter().any(|t| exc.fast_isinstance(t))), ConditionMatcher::Callable(func) => { let result = func.call((exc.to_owned(),), vm)?; result.try_to_bool(vm) } } } } fn derive_and_copy_attributes( orig: &Py<PyBaseException>, excs: Vec<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<PyObjectRef> { // Call derive method to create new group let excs_seq = vm.ctx.new_list(excs); let new_group = vm.call_method(orig.as_object(), "derive", (excs_seq,))?; // Verify derive returned a BaseExceptionGroup if !is_base_exception_group(&new_group, vm) { return Err(vm.new_type_error("derive must return an instance of BaseExceptionGroup")); } // Copy traceback if let Some(tb) = orig.__traceback__() { new_group.set_attr("__traceback__", tb, vm)?; } // Copy context if let Some(ctx) = orig.__context__() { new_group.set_attr("__context__", ctx, vm)?; } // Copy cause if let Some(cause) = orig.__cause__() { new_group.set_attr("__cause__", cause, vm)?; } // Copy notes (if present) - make a copy of the list if let Ok(notes) = orig.as_object().get_attr("__notes__", vm) && let Some(notes_list) = notes.downcast_ref::<PyList>() { let notes_copy = vm.ctx.new_list(notes_list.borrow_vec().to_vec()); new_group.set_attr("__notes__", notes_copy, vm)?; } Ok(new_group) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/sliceable.rs
crates/vm/src/sliceable.rs
// export through sliceable module, not slice. use crate::{ PyObject, PyResult, VirtualMachine, builtins::{int::PyInt, slice::PySlice}, }; use core::ops::Range; use malachite_bigint::BigInt; use num_traits::{Signed, ToPrimitive}; pub trait SliceableSequenceMutOp where Self: AsRef<[Self::Item]>, { type Item: Clone; fn do_set(&mut self, index: usize, value: Self::Item); fn do_delete(&mut self, index: usize); /// as CPython, length of range and items could be different, function must act like Vec::splice() fn do_set_range(&mut self, range: Range<usize>, items: &[Self::Item]); fn do_delete_range(&mut self, range: Range<usize>); fn do_set_indexes<I>(&mut self, indexes: I, items: &[Self::Item]) where I: Iterator<Item = usize>; /// indexes must be positive order fn do_delete_indexes<I>(&mut self, range: Range<usize>, indexes: I) where I: Iterator<Item = usize>; fn setitem_by_index( &mut self, vm: &VirtualMachine, index: isize, value: Self::Item, ) -> PyResult<()> { let pos = self .as_ref() .wrap_index(index) .ok_or_else(|| vm.new_index_error("assignment index out of range"))?; self.do_set(pos, value); Ok(()) } fn setitem_by_slice_no_resize( &mut self, vm: &VirtualMachine, slice: SaturatedSlice, items: &[Self::Item], ) -> PyResult<()> { let (range, step, slice_len) = slice.adjust_indices(self.as_ref().len()); if slice_len != items.len() { Err(vm.new_buffer_error("Existing exports of data: object cannot be re-sized")) } else if step == 1 { self.do_set_range(range, items); Ok(()) } else { self.do_set_indexes( SaturatedSliceIter::from_adjust_indices(range, step, slice_len), items, ); Ok(()) } } fn setitem_by_slice( &mut self, vm: &VirtualMachine, slice: SaturatedSlice, items: &[Self::Item], ) -> PyResult<()> { let (range, step, slice_len) = slice.adjust_indices(self.as_ref().len()); if step == 1 { self.do_set_range(range, items); Ok(()) } else if slice_len == items.len() { self.do_set_indexes( SaturatedSliceIter::from_adjust_indices(range, step, slice_len), items, ); Ok(()) } else { Err(vm.new_value_error(format!( "attempt to assign sequence of size {} to extended slice of size {}", items.len(), slice_len ))) } } fn delitem_by_index(&mut self, vm: &VirtualMachine, index: isize) -> PyResult<()> { let pos = self .as_ref() .wrap_index(index) .ok_or_else(|| vm.new_index_error("assignment index out of range"))?; self.do_delete(pos); Ok(()) } fn delitem_by_slice(&mut self, _vm: &VirtualMachine, slice: SaturatedSlice) -> PyResult<()> { let (range, step, slice_len) = slice.adjust_indices(self.as_ref().len()); if slice_len == 0 { Ok(()) } else if step == 1 || step == -1 { self.do_set_range(range, &[]); Ok(()) } else { self.do_delete_indexes( range.clone(), SaturatedSliceIter::from_adjust_indices(range, step, slice_len).positive_order(), ); Ok(()) } } } impl<T: Clone> SliceableSequenceMutOp for Vec<T> { type Item = T; fn do_set(&mut self, index: usize, value: Self::Item) { self[index] = value; } fn do_delete(&mut self, index: usize) { self.remove(index); } fn do_set_range(&mut self, range: Range<usize>, items: &[Self::Item]) { self.splice(range, items.to_vec()); } fn do_delete_range(&mut self, range: Range<usize>) { self.drain(range); } fn do_set_indexes<I>(&mut self, indexes: I, items: &[Self::Item]) where I: Iterator<Item = usize>, { for (i, item) in indexes.zip(items) { self.do_set(i, item.clone()); } } fn do_delete_indexes<I>(&mut self, range: Range<usize>, indexes: I) where I: Iterator<Item = usize>, { let mut indexes = indexes.peekable(); let mut deleted = 0; // passing whole range, swap or overlap for i in range.clone() { if indexes.peek() == Some(&i) { indexes.next(); deleted += 1; } else { self.swap(i - deleted, i); } } // then drain (the values to delete should now be contiguous at the end of the range) self.drain((range.end - deleted)..range.end); } } #[allow(clippy::len_without_is_empty)] pub trait SliceableSequenceOp { type Item; type Sliced; fn do_get(&self, index: usize) -> Self::Item; fn do_slice(&self, range: Range<usize>) -> Self::Sliced; fn do_slice_reverse(&self, range: Range<usize>) -> Self::Sliced; fn do_stepped_slice(&self, range: Range<usize>, step: usize) -> Self::Sliced; fn do_stepped_slice_reverse(&self, range: Range<usize>, step: usize) -> Self::Sliced; fn empty() -> Self::Sliced; fn len(&self) -> usize; fn wrap_index(&self, p: isize) -> Option<usize> { p.wrapped_at(self.len()) } fn saturate_index(&self, p: isize) -> usize { p.saturated_at(self.len()) } fn getitem_by_slice( &self, _vm: &VirtualMachine, slice: SaturatedSlice, ) -> PyResult<Self::Sliced> { let (range, step, slice_len) = slice.adjust_indices(self.len()); let sliced = if slice_len == 0 { Self::empty() } else if step == 1 { self.do_slice(range) } else if step == -1 { self.do_slice_reverse(range) } else if step.is_positive() { self.do_stepped_slice(range, step.unsigned_abs()) } else { self.do_stepped_slice_reverse(range, step.unsigned_abs()) }; Ok(sliced) } fn getitem_by_index(&self, vm: &VirtualMachine, index: isize) -> PyResult<Self::Item> { let pos = self .wrap_index(index) .ok_or_else(|| vm.new_index_error("index out of range"))?; Ok(self.do_get(pos)) } } impl<T: Clone> SliceableSequenceOp for [T] { type Item = T; type Sliced = Vec<T>; #[inline] fn do_get(&self, index: usize) -> Self::Item { self[index].clone() } #[inline] fn do_slice(&self, range: Range<usize>) -> Self::Sliced { self[range].to_vec() } #[inline] fn do_slice_reverse(&self, range: Range<usize>) -> Self::Sliced { let mut slice = self[range].to_vec(); slice.reverse(); slice } #[inline] fn do_stepped_slice(&self, range: Range<usize>, step: usize) -> Self::Sliced { self[range].iter().step_by(step).cloned().collect() } #[inline] fn do_stepped_slice_reverse(&self, range: Range<usize>, step: usize) -> Self::Sliced { self[range].iter().rev().step_by(step).cloned().collect() } #[inline(always)] fn empty() -> Self::Sliced { Vec::new() } #[inline(always)] fn len(&self) -> usize { self.len() } } pub enum SequenceIndex { Int(isize), Slice(SaturatedSlice), } impl SequenceIndex { pub fn try_from_borrowed_object( vm: &VirtualMachine, obj: &PyObject, type_name: &str, ) -> PyResult<Self> { if let Some(i) = obj.downcast_ref::<PyInt>() { // TODO: number protocol i.try_to_primitive(vm) .map_err(|_| vm.new_index_error("cannot fit 'int' into an index-sized integer")) .map(Self::Int) } else if let Some(slice) = obj.downcast_ref::<PySlice>() { slice.to_saturated(vm).map(Self::Slice) } else if let Some(i) = obj.try_index_opt(vm) { // TODO: __index__ for indices is no more supported? i?.try_to_primitive(vm) .map_err(|_| vm.new_index_error("cannot fit 'int' into an index-sized integer")) .map(Self::Int) } else { Err(vm.new_type_error(format!( "{} indices must be integers or slices or classes that override __index__ operator, not '{}'", type_name, obj.class() ))) } } } pub trait SequenceIndexOp { // Saturate p in range [0, len] inclusive fn saturated_at(&self, len: usize) -> usize; // Use PySliceableSequence::wrap_index for implementors fn wrapped_at(&self, len: usize) -> Option<usize>; } impl SequenceIndexOp for isize { fn saturated_at(&self, len: usize) -> usize { let len = len.to_isize().unwrap_or(Self::MAX); let mut p = *self; if p < 0 { p += len; } p.clamp(0, len) as usize } fn wrapped_at(&self, len: usize) -> Option<usize> { let mut p = *self; if p < 0 { // casting to isize is ok because it is used by wrapping_add p = p.wrapping_add(len as Self); } if p < 0 || (p as usize) >= len { None } else { Some(p as usize) } } } impl SequenceIndexOp for BigInt { fn saturated_at(&self, len: usize) -> usize { if self.is_negative() { self.abs() .try_into() .map_or(0, |abs| len.saturating_sub(abs)) } else { self.try_into().unwrap_or(len) } } fn wrapped_at(&self, _len: usize) -> Option<usize> { unimplemented!("please add one once we need it") } } /// A saturated slice with values ranging in [isize::MIN, isize::MAX]. Used for /// sliceable sequences that require indices in the aforementioned range. /// /// Invokes `__index__` on the PySliceRef during construction so as to separate the /// transformation from PyObject into isize and the adjusting of the slice to a given /// sequence length. The reason this is important is due to the fact that an objects /// `__index__` might get a lock on the sequence and cause a deadlock. #[derive(Copy, Clone, Debug)] pub struct SaturatedSlice { start: isize, stop: isize, step: isize, } impl SaturatedSlice { // Equivalent to PySlice_Unpack. pub fn with_slice(slice: &PySlice, vm: &VirtualMachine) -> PyResult<Self> { let step = to_isize_index(vm, slice.step_ref(vm))?.unwrap_or(1); if step == 0 { return Err(vm.new_value_error("slice step cannot be zero")); } let start = to_isize_index(vm, slice.start_ref(vm))? .unwrap_or_else(|| if step.is_negative() { isize::MAX } else { 0 }); let stop = to_isize_index(vm, &slice.stop(vm))?.unwrap_or_else(|| { if step.is_negative() { isize::MIN } else { isize::MAX } }); Ok(Self { start, stop, step }) } // Equivalent to PySlice_AdjustIndices /// Convert for usage in indexing the underlying rust collections. Called *after* /// __index__ has been called on the Slice which might mutate the collection. pub fn adjust_indices(&self, len: usize) -> (Range<usize>, isize, usize) { if len == 0 { return (0..0, self.step, 0); } let range = if self.step.is_negative() { let stop = if self.stop == -1 { len } else { self.stop.saturating_add(1).saturated_at(len) }; let start = if self.start == -1 { len } else { self.start.saturating_add(1).saturated_at(len) }; stop..start } else { self.start.saturated_at(len)..self.stop.saturated_at(len) }; let (range, slice_len) = if range.start >= range.end { (range.start..range.start, 0) } else { let slice_len = (range.end - range.start - 1) / self.step.unsigned_abs() + 1; (range, slice_len) }; (range, self.step, slice_len) } pub fn iter(&self, len: usize) -> SaturatedSliceIter { SaturatedSliceIter::new(self, len) } } pub struct SaturatedSliceIter { index: isize, step: isize, len: usize, } impl SaturatedSliceIter { pub fn new(slice: &SaturatedSlice, seq_len: usize) -> Self { let (range, step, len) = slice.adjust_indices(seq_len); Self::from_adjust_indices(range, step, len) } pub const fn from_adjust_indices(range: Range<usize>, step: isize, len: usize) -> Self { let index = if step.is_negative() { range.end as isize - 1 } else { range.start as isize }; Self { index, step, len } } pub const fn positive_order(mut self) -> Self { if self.step.is_negative() { self.index += self.step * self.len.saturating_sub(1) as isize; self.step = self.step.saturating_abs() } self } } impl Iterator for SaturatedSliceIter { type Item = usize; fn next(&mut self) -> Option<Self::Item> { if self.len == 0 { return None; } self.len -= 1; let ret = self.index as usize; // SAFETY: if index is overflowed, len should be zero self.index = self.index.wrapping_add(self.step); Some(ret) } } // Go from PyObjectRef to isize w/o overflow error, out of range values are substituted by // isize::MIN or isize::MAX depending on type and value of step. // Equivalent to PyEval_SliceIndex. fn to_isize_index(vm: &VirtualMachine, obj: &PyObject) -> PyResult<Option<isize>> { if vm.is_none(obj) { return Ok(None); } let result = obj.try_index_opt(vm).unwrap_or_else(|| { Err(vm.new_type_error("slice indices must be integers or None or have an __index__ method")) })?; let value = result.as_bigint(); let is_negative = value.is_negative(); Ok(Some(value.to_isize().unwrap_or(if is_negative { isize::MIN } else { isize::MAX }))) }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/iter.rs
crates/vm/src/iter.rs
use crate::{PyObjectRef, PyResult, types::PyComparisonOp, vm::VirtualMachine}; use itertools::Itertools; pub trait PyExactSizeIterator<'a>: ExactSizeIterator<Item = &'a PyObjectRef> + Sized { fn eq(self, other: impl PyExactSizeIterator<'a>, vm: &VirtualMachine) -> PyResult<bool> { let lhs = self; let rhs = other; if lhs.len() != rhs.len() { return Ok(false); } for (a, b) in lhs.zip_eq(rhs) { if !vm.identical_or_equal(a, b)? { return Ok(false); } } Ok(true) } fn richcompare( self, other: impl PyExactSizeIterator<'a>, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<bool> { let less = match op { PyComparisonOp::Eq => return PyExactSizeIterator::eq(self, other, vm), PyComparisonOp::Ne => return PyExactSizeIterator::eq(self, other, vm).map(|eq| !eq), PyComparisonOp::Lt | PyComparisonOp::Le => true, PyComparisonOp::Gt | PyComparisonOp::Ge => false, }; let lhs = self; let rhs = other; let lhs_len = lhs.len(); let rhs_len = rhs.len(); for (a, b) in lhs.zip(rhs) { if vm.bool_eq(a, b)? { continue; } let ret = if less { vm.bool_seq_lt(a, b)? } else { vm.bool_seq_gt(a, b)? }; if let Some(v) = ret { return Ok(v); } } Ok(op.eval_ord(lhs_len.cmp(&rhs_len))) } } impl<'a, T> PyExactSizeIterator<'a> for T where T: ExactSizeIterator<Item = &'a PyObjectRef> + Sized {}
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/suggestion.rs
crates/vm/src/suggestion.rs
//! This module provides functionality to suggest similar names for attributes or variables. //! This is used during tracebacks. use crate::{ AsObject, Py, PyObject, PyObjectRef, VirtualMachine, builtins::{PyStr, PyStrRef}, exceptions::types::PyBaseException, sliceable::SliceableSequenceOp, }; use core::iter::ExactSizeIterator; use rustpython_common::str::levenshtein::{MOVE_COST, levenshtein_distance}; const MAX_CANDIDATE_ITEMS: usize = 750; pub fn calculate_suggestions<'a>( dir_iter: impl ExactSizeIterator<Item = &'a PyObjectRef>, name: &PyObject, ) -> Option<PyStrRef> { if dir_iter.len() >= MAX_CANDIDATE_ITEMS { return None; } let mut suggestion: Option<&Py<PyStr>> = None; let mut suggestion_distance = usize::MAX; let name = name.downcast_ref::<PyStr>()?; for item in dir_iter { let item_name = item.downcast_ref::<PyStr>()?; if name.as_bytes() == item_name.as_bytes() { continue; } // No more than 1/3 of the characters should need changed let max_distance = usize::min( (name.len() + item_name.len() + 3) * MOVE_COST / 6, suggestion_distance - 1, ); let current_distance = levenshtein_distance(name.as_bytes(), item_name.as_bytes(), max_distance); if current_distance > max_distance { continue; } if suggestion.is_none() || current_distance < suggestion_distance { suggestion = Some(item_name); suggestion_distance = current_distance; } } suggestion.map(|r| r.to_owned()) } pub fn offer_suggestions(exc: &Py<PyBaseException>, vm: &VirtualMachine) -> Option<PyStrRef> { if exc.class().is(vm.ctx.exceptions.attribute_error) { let name = exc.as_object().get_attr("name", vm).unwrap(); let obj = exc.as_object().get_attr("obj", vm).unwrap(); calculate_suggestions(vm.dir(Some(obj)).ok()?.borrow_vec().iter(), &name) } else if exc.class().is(vm.ctx.exceptions.name_error) { let name = exc.as_object().get_attr("name", vm).unwrap(); let tb = exc.__traceback__()?; let tb = tb.iter().last().unwrap_or(tb); let varnames = tb.frame.code.clone().co_varnames(vm); if let Some(suggestions) = calculate_suggestions(varnames.iter(), &name) { return Some(suggestions); }; let globals: Vec<_> = tb.frame.globals.as_object().try_to_value(vm).ok()?; if let Some(suggestions) = calculate_suggestions(globals.iter(), &name) { return Some(suggestions); }; let builtins: Vec<_> = tb.frame.builtins.as_object().try_to_value(vm).ok()?; calculate_suggestions(builtins.iter(), &name) } else { None } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/exceptions.rs
crates/vm/src/exceptions.rs
use self::types::{PyBaseException, PyBaseExceptionRef}; use crate::common::lock::PyRwLock; use crate::object::{Traverse, TraverseFn}; use crate::{ AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, builtins::{ PyList, PyNone, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, traceback::{PyTraceback, PyTracebackRef}, }, class::{PyClassImpl, StaticType}, convert::{ToPyException, ToPyObject}, function::{ArgIterable, FuncArgs, IntoFuncArgs, PySetterValue}, py_io::{self, Write}, stdlib::sys, suggestion::offer_suggestions, types::{Callable, Constructor, Initializer, Representable}, }; use crossbeam_utils::atomic::AtomicCell; use itertools::Itertools; use std::{ collections::HashSet, io::{self, BufRead, BufReader}, }; pub use super::exception_group::exception_group; unsafe impl Traverse for PyBaseException { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { self.traceback.traverse(tracer_fn); self.cause.traverse(tracer_fn); self.context.traverse(tracer_fn); self.args.traverse(tracer_fn); } } impl core::fmt::Debug for PyBaseException { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { // TODO: implement more detailed, non-recursive Debug formatter f.write_str("PyBaseException") } } impl PyPayload for PyBaseException { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.exceptions.base_exception_type } } impl VirtualMachine { // Why `impl VirtualMachine`? // These functions are natively free function in CPython - not methods of PyException /// Print exception chain by calling sys.excepthook pub fn print_exception(&self, exc: PyBaseExceptionRef) { let vm = self; let write_fallback = |exc, errstr| { if let Ok(stderr) = sys::get_stderr(vm) { let mut stderr = py_io::PyWriter(stderr, vm); // if this fails stderr might be closed -- ignore it let _ = writeln!(stderr, "{errstr}"); let _ = self.write_exception(&mut stderr, exc); } else { eprintln!("{errstr}\nlost sys.stderr"); let _ = self.write_exception(&mut py_io::IoWriter(io::stderr()), exc); } }; if let Ok(excepthook) = vm.sys_module.get_attr("excepthook", vm) { let (exc_type, exc_val, exc_tb) = vm.split_exception(exc.clone()); if let Err(eh_exc) = excepthook.call((exc_type, exc_val, exc_tb), vm) { write_fallback(&eh_exc, "Error in sys.excepthook:"); write_fallback(&exc, "Original exception was:"); } } else { write_fallback(&exc, "missing sys.excepthook"); } } pub fn write_exception<W: Write>( &self, output: &mut W, exc: &Py<PyBaseException>, ) -> Result<(), W::Error> { let seen = &mut HashSet::<usize>::new(); self.write_exception_recursive(output, exc, seen) } fn write_exception_recursive<W: Write>( &self, output: &mut W, exc: &Py<PyBaseException>, seen: &mut HashSet<usize>, ) -> Result<(), W::Error> { // This function should not be called directly, // use `wite_exception` as a public interface. // It is similar to `print_exception_recursive` from `CPython`. seen.insert(exc.get_id()); #[allow(clippy::manual_map)] if let Some((cause_or_context, msg)) = if let Some(cause) = exc.__cause__() { // This can be a special case: `raise e from e`, // we just ignore it and treat like `raise e` without any extra steps. Some(( cause, "\nThe above exception was the direct cause of the following exception:\n", )) } else if let Some(context) = exc.__context__() { // This can be a special case: // e = ValueError('e') // e.__context__ = e // In this case, we just ignore // `__context__` part from going into recursion. Some(( context, "\nDuring handling of the above exception, another exception occurred:\n", )) } else { None } { if !seen.contains(&cause_or_context.get_id()) { self.write_exception_recursive(output, &cause_or_context, seen)?; writeln!(output, "{msg}")?; } else { seen.insert(cause_or_context.get_id()); } } self.write_exception_inner(output, exc) } /// Print exception with traceback pub fn write_exception_inner<W: Write>( &self, output: &mut W, exc: &Py<PyBaseException>, ) -> Result<(), W::Error> { let vm = self; if let Some(tb) = exc.traceback.read().clone() { writeln!(output, "Traceback (most recent call last):")?; for tb in tb.iter() { write_traceback_entry(output, &tb)?; } } let varargs = exc.args(); let args_repr = vm.exception_args_as_string(varargs, true); let exc_class = exc.class(); if exc_class.fast_issubclass(vm.ctx.exceptions.syntax_error) { return self.write_syntaxerror(output, exc, exc_class, &args_repr); } let exc_name = exc_class.name(); match args_repr.len() { 0 => write!(output, "{exc_name}"), 1 => write!(output, "{}: {}", exc_name, args_repr[0]), _ => write!( output, "{}: ({})", exc_name, args_repr.into_iter().format(", "), ), }?; match offer_suggestions(exc, vm) { Some(suggestions) => writeln!(output, ". Did you mean: '{suggestions}'?"), None => writeln!(output), } } /// Format and write a SyntaxError /// This logic is derived from TracebackException._format_syntax_error /// /// The logic has support for `end_offset` to highlight a range in the source code, /// but it looks like `end_offset` is not used yet when SyntaxErrors are created. fn write_syntaxerror<W: Write>( &self, output: &mut W, exc: &Py<PyBaseException>, exc_type: &Py<PyType>, args_repr: &[PyRef<PyStr>], ) -> Result<(), W::Error> { let vm = self; debug_assert!(exc_type.fast_issubclass(vm.ctx.exceptions.syntax_error)); let getattr = |attr: &'static str| exc.as_object().get_attr(attr, vm).ok(); let maybe_lineno = getattr("lineno").map(|obj| { obj.str(vm) .unwrap_or_else(|_| vm.ctx.new_str("<lineno str() failed>")) }); let maybe_filename = getattr("filename").and_then(|obj| obj.str(vm).ok()); let maybe_text = getattr("text").map(|obj| { obj.str(vm) .unwrap_or_else(|_| vm.ctx.new_str("<text str() failed>")) }); let mut filename_suffix = String::new(); if let Some(lineno) = maybe_lineno { let filename = match maybe_filename { Some(filename) => filename, None => vm.ctx.new_str("<string>"), }; writeln!(output, r##" File "{filename}", line {lineno}"##,)?; } else if let Some(filename) = maybe_filename { filename_suffix = format!(" ({filename})"); } if let Some(text) = maybe_text { // if text ends with \n, remove it let r_text = text.as_str().trim_end_matches('\n'); let l_text = r_text.trim_start_matches([' ', '\n', '\x0c']); // \x0c is \f let spaces = (r_text.len() - l_text.len()) as isize; writeln!(output, " {l_text}")?; let maybe_offset: Option<isize> = getattr("offset").and_then(|obj| obj.try_to_value::<isize>(vm).ok()); if let Some(offset) = maybe_offset { let maybe_end_offset: Option<isize> = getattr("end_offset").and_then(|obj| obj.try_to_value::<isize>(vm).ok()); let mut end_offset = match maybe_end_offset { Some(0) | None => offset, Some(end_offset) => end_offset, }; if offset == end_offset || end_offset == -1 { end_offset = offset + 1; } // Convert 1-based column offset to 0-based index into stripped text let colno = offset - 1 - spaces; let end_colno = end_offset - 1 - spaces; if colno >= 0 { let caret_space = l_text .chars() .take(colno as usize) .map(|c| if c.is_whitespace() { c } else { ' ' }) .collect::<String>(); let mut error_width = end_colno - colno; if error_width < 1 { error_width = 1; } writeln!( output, " {}{}", caret_space, "^".repeat(error_width as usize) )?; } } } let exc_name = exc_type.name(); match args_repr.len() { 0 => write!(output, "{exc_name}{filename_suffix}"), 1 => write!(output, "{}: {}{}", exc_name, args_repr[0], filename_suffix), _ => write!( output, "{}: ({}){}", exc_name, args_repr.iter().format(", "), filename_suffix ), }?; match offer_suggestions(exc, vm) { Some(suggestions) => writeln!(output, ". Did you mean: '{suggestions}'?"), None => writeln!(output), } } fn exception_args_as_string(&self, varargs: PyTupleRef, str_single: bool) -> Vec<PyStrRef> { let vm = self; match varargs.len() { 0 => vec![], 1 => { let args0_repr = if str_single { varargs[0] .str(vm) .unwrap_or_else(|_| PyStr::from("<element str() failed>").into_ref(&vm.ctx)) } else { varargs[0].repr(vm).unwrap_or_else(|_| { PyStr::from("<element repr() failed>").into_ref(&vm.ctx) }) }; vec![args0_repr] } _ => varargs .iter() .map(|vararg| { vararg.repr(vm).unwrap_or_else(|_| { PyStr::from("<element repr() failed>").into_ref(&vm.ctx) }) }) .collect(), } } pub fn split_exception( &self, exc: PyBaseExceptionRef, ) -> (PyObjectRef, PyObjectRef, PyObjectRef) { let tb = exc.__traceback__().to_pyobject(self); let class = exc.class().to_owned(); (class.into(), exc.into(), tb) } /// Similar to PyErr_NormalizeException in CPython pub fn normalize_exception( &self, exc_type: PyObjectRef, exc_val: PyObjectRef, exc_tb: PyObjectRef, ) -> PyResult<PyBaseExceptionRef> { let ctor = ExceptionCtor::try_from_object(self, exc_type)?; let exc = ctor.instantiate_value(exc_val, self)?; if let Some(tb) = Option::<PyTracebackRef>::try_from_object(self, exc_tb)? { exc.set_traceback_typed(Some(tb)); } Ok(exc) } pub fn invoke_exception( &self, cls: PyTypeRef, args: Vec<PyObjectRef>, ) -> PyResult<PyBaseExceptionRef> { // TODO: fast-path built-in exceptions by directly instantiating them? Is that really worth it? let res = PyType::call(&cls, args.into_args(self), self)?; PyBaseExceptionRef::try_from_object(self, res) } } fn print_source_line<W: Write>( output: &mut W, filename: &str, lineno: usize, ) -> Result<(), W::Error> { // TODO: use io.open() method instead, when available, according to https://github.com/python/cpython/blob/main/Python/traceback.c#L393 // TODO: support different encodings let file = match std::fs::File::open(filename) { Ok(file) => file, Err(_) => return Ok(()), }; let file = BufReader::new(file); for (i, line) in file.lines().enumerate() { if i + 1 == lineno { if let Ok(line) = line { // Indented with 4 spaces writeln!(output, " {}", line.trim_start())?; } return Ok(()); } } Ok(()) } /// Print exception occurrence location from traceback element fn write_traceback_entry<W: Write>( output: &mut W, tb_entry: &Py<PyTraceback>, ) -> Result<(), W::Error> { let filename = tb_entry.frame.code.source_path.as_str(); writeln!( output, r##" File "{}", line {}, in {}"##, filename.trim_start_matches(r"\\?\"), tb_entry.lineno, tb_entry.frame.code.obj_name )?; print_source_line(output, filename, tb_entry.lineno.get())?; Ok(()) } #[derive(Clone)] pub enum ExceptionCtor { Class(PyTypeRef), Instance(PyBaseExceptionRef), } impl TryFromObject for ExceptionCtor { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { obj.downcast::<PyType>() .and_then(|cls| { if cls.fast_issubclass(vm.ctx.exceptions.base_exception_type) { Ok(Self::Class(cls)) } else { Err(cls.into()) } }) .or_else(|obj| obj.downcast::<PyBaseException>().map(Self::Instance)) .map_err(|obj| { vm.new_type_error(format!( "exceptions must be classes or instances deriving from BaseException, not {}", obj.class().name() )) }) } } impl ExceptionCtor { pub fn instantiate(self, vm: &VirtualMachine) -> PyResult<PyBaseExceptionRef> { match self { Self::Class(cls) => vm.invoke_exception(cls, vec![]), Self::Instance(exc) => Ok(exc), } } pub fn instantiate_value( self, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyBaseExceptionRef> { let exc_inst = value.clone().downcast::<PyBaseException>().ok(); match (self, exc_inst) { // both are instances; which would we choose? (Self::Instance(_exc_a), Some(_exc_b)) => { Err(vm.new_type_error("instance exception may not have a separate value")) } // if the "type" is an instance and the value isn't, use the "type" (Self::Instance(exc), None) => Ok(exc), // if the value is an instance of the type, use the instance value (Self::Class(cls), Some(exc)) if exc.fast_isinstance(&cls) => Ok(exc), // otherwise; construct an exception of the type using the value as args (Self::Class(cls), _) => { let args = match_class!(match value { PyNone => vec![], tup @ PyTuple => tup.to_vec(), exc @ PyBaseException => exc.args().to_vec(), obj => vec![obj], }); vm.invoke_exception(cls, args) } } } } #[derive(Debug)] pub struct ExceptionZoo { pub base_exception_type: &'static Py<PyType>, pub base_exception_group: &'static Py<PyType>, pub system_exit: &'static Py<PyType>, pub keyboard_interrupt: &'static Py<PyType>, pub generator_exit: &'static Py<PyType>, pub exception_type: &'static Py<PyType>, pub stop_iteration: &'static Py<PyType>, pub stop_async_iteration: &'static Py<PyType>, pub arithmetic_error: &'static Py<PyType>, pub floating_point_error: &'static Py<PyType>, pub overflow_error: &'static Py<PyType>, pub zero_division_error: &'static Py<PyType>, pub assertion_error: &'static Py<PyType>, pub attribute_error: &'static Py<PyType>, pub buffer_error: &'static Py<PyType>, pub eof_error: &'static Py<PyType>, pub import_error: &'static Py<PyType>, pub module_not_found_error: &'static Py<PyType>, pub lookup_error: &'static Py<PyType>, pub index_error: &'static Py<PyType>, pub key_error: &'static Py<PyType>, pub memory_error: &'static Py<PyType>, pub name_error: &'static Py<PyType>, pub unbound_local_error: &'static Py<PyType>, pub os_error: &'static Py<PyType>, pub blocking_io_error: &'static Py<PyType>, pub child_process_error: &'static Py<PyType>, pub connection_error: &'static Py<PyType>, pub broken_pipe_error: &'static Py<PyType>, pub connection_aborted_error: &'static Py<PyType>, pub connection_refused_error: &'static Py<PyType>, pub connection_reset_error: &'static Py<PyType>, pub file_exists_error: &'static Py<PyType>, pub file_not_found_error: &'static Py<PyType>, pub interrupted_error: &'static Py<PyType>, pub is_a_directory_error: &'static Py<PyType>, pub not_a_directory_error: &'static Py<PyType>, pub permission_error: &'static Py<PyType>, pub process_lookup_error: &'static Py<PyType>, pub timeout_error: &'static Py<PyType>, pub reference_error: &'static Py<PyType>, pub runtime_error: &'static Py<PyType>, pub not_implemented_error: &'static Py<PyType>, pub recursion_error: &'static Py<PyType>, pub python_finalization_error: &'static Py<PyType>, pub syntax_error: &'static Py<PyType>, pub incomplete_input_error: &'static Py<PyType>, pub indentation_error: &'static Py<PyType>, pub tab_error: &'static Py<PyType>, pub system_error: &'static Py<PyType>, pub type_error: &'static Py<PyType>, pub value_error: &'static Py<PyType>, pub unicode_error: &'static Py<PyType>, pub unicode_decode_error: &'static Py<PyType>, pub unicode_encode_error: &'static Py<PyType>, pub unicode_translate_error: &'static Py<PyType>, #[cfg(feature = "jit")] pub jit_error: &'static Py<PyType>, pub warning: &'static Py<PyType>, pub deprecation_warning: &'static Py<PyType>, pub pending_deprecation_warning: &'static Py<PyType>, pub runtime_warning: &'static Py<PyType>, pub syntax_warning: &'static Py<PyType>, pub user_warning: &'static Py<PyType>, pub future_warning: &'static Py<PyType>, pub import_warning: &'static Py<PyType>, pub unicode_warning: &'static Py<PyType>, pub bytes_warning: &'static Py<PyType>, pub resource_warning: &'static Py<PyType>, pub encoding_warning: &'static Py<PyType>, } macro_rules! extend_exception { ( $exc_struct:ident, $ctx:expr, $class:expr ) => { extend_exception!($exc_struct, $ctx, $class, {}); }; ( $exc_struct:ident, $ctx:expr, $class:expr, { $($name:expr => $value:expr),* $(,)* } ) => { $exc_struct::extend_class($ctx, $class); extend_class!($ctx, $class, { $($name => $value,)* }); }; } impl PyBaseException { pub(crate) fn new(args: Vec<PyObjectRef>, vm: &VirtualMachine) -> Self { Self { traceback: PyRwLock::new(None), cause: PyRwLock::new(None), context: PyRwLock::new(None), suppress_context: AtomicCell::new(false), args: PyRwLock::new(PyTuple::new_ref(args, &vm.ctx)), } } pub fn get_arg(&self, idx: usize) -> Option<PyObjectRef> { self.args.read().get(idx).cloned() } } #[pyclass( with(Py, PyRef, Constructor, Initializer, Representable), flags(BASETYPE, HAS_DICT) )] impl PyBaseException { #[pygetset] pub fn args(&self) -> PyTupleRef { self.args.read().clone() } #[pygetset(setter)] fn set_args(&self, args: ArgIterable, vm: &VirtualMachine) -> PyResult<()> { let args = args.iter(vm)?.collect::<PyResult<Vec<_>>>()?; *self.args.write() = PyTuple::new_ref(args, &vm.ctx); Ok(()) } #[pygetset] pub fn __traceback__(&self) -> Option<PyTracebackRef> { self.traceback.read().clone() } #[pygetset(setter)] pub fn set___traceback__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let traceback = if vm.is_none(&value) { None } else { match value.downcast::<PyTraceback>() { Ok(tb) => Some(tb), Err(_) => { return Err(vm.new_type_error("__traceback__ must be a traceback or None")); } } }; self.set_traceback_typed(traceback); Ok(()) } // Helper method for internal use that doesn't require PyObjectRef pub(crate) fn set_traceback_typed(&self, traceback: Option<PyTracebackRef>) { *self.traceback.write() = traceback; } #[pygetset] pub fn __cause__(&self) -> Option<PyRef<Self>> { self.cause.read().clone() } #[pygetset(setter)] pub fn set___cause__(&self, cause: Option<PyRef<Self>>) { let mut c = self.cause.write(); self.set_suppress_context(true); *c = cause; } #[pygetset] pub fn __context__(&self) -> Option<PyRef<Self>> { self.context.read().clone() } #[pygetset(setter)] pub fn set___context__(&self, context: Option<PyRef<Self>>) { *self.context.write() = context; } #[pygetset] pub(super) fn __suppress_context__(&self) -> bool { self.suppress_context.load() } #[pygetset(name = "__suppress_context__", setter)] fn set_suppress_context(&self, suppress_context: bool) { self.suppress_context.store(suppress_context); } } #[pyclass] impl Py<PyBaseException> { #[pymethod] pub(super) fn __str__(&self, vm: &VirtualMachine) -> PyResult<PyStrRef> { let str_args = vm.exception_args_as_string(self.args(), true); Ok(match str_args.into_iter().exactly_one() { Err(i) if i.len() == 0 => vm.ctx.empty_str.to_owned(), Ok(s) => s, Err(i) => PyStr::from(format!("({})", i.format(", "))).into_ref(&vm.ctx), }) } } #[pyclass] impl PyRef<PyBaseException> { #[pymethod] fn with_traceback(self, tb: Option<PyTracebackRef>) -> PyResult<Self> { *self.traceback.write() = tb; Ok(self) } #[pymethod] fn add_note(self, note: PyStrRef, vm: &VirtualMachine) -> PyResult<()> { let dict = self .as_object() .dict() .ok_or_else(|| vm.new_attribute_error("Exception object has no __dict__"))?; let notes = if let Ok(notes) = dict.get_item("__notes__", vm) { notes } else { let new_notes = vm.ctx.new_list(vec![]); dict.set_item("__notes__", new_notes.clone().into(), vm)?; new_notes.into() }; let notes = notes .downcast::<PyList>() .map_err(|_| vm.new_type_error("__notes__ must be a list"))?; notes.borrow_vec_mut().push(note.into()); Ok(()) } #[pymethod] fn __reduce__(self, vm: &VirtualMachine) -> PyTupleRef { if let Some(dict) = self.as_object().dict().filter(|x| !x.is_empty()) { vm.new_tuple((self.class().to_owned(), self.args(), dict)) } else { vm.new_tuple((self.class().to_owned(), self.args())) } } #[pymethod] fn __setstate__(self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> { if !vm.is_none(&state) { let dict = state .downcast::<crate::builtins::PyDict>() .map_err(|_| vm.new_type_error("state is not a dictionary"))?; for (key, value) in &dict { let key_str = key.str(vm)?; if key_str.as_str().starts_with("__") { continue; } self.as_object().set_attr(&key_str, value.clone(), vm)?; } } Ok(vm.ctx.none()) } } impl Constructor for PyBaseException { type Args = FuncArgs; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { if cls.is(Self::class(&vm.ctx)) && !args.kwargs.is_empty() { return Err(vm.new_type_error("BaseException() takes no keyword arguments")); } Self::new(args.args, vm) .into_ref_with_type(vm, cls) .map(Into::into) } fn py_new(_cls: &Py<PyType>, _args: FuncArgs, _vm: &VirtualMachine) -> PyResult<Self> { unimplemented!("use slot_new") } } impl Initializer for PyBaseException { type Args = FuncArgs; fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { *zelf.args.write() = PyTuple::new_ref(args.args, &vm.ctx); Ok(()) } } impl Representable for PyBaseException { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { let repr_args = vm.exception_args_as_string(zelf.args(), false); let cls = zelf.class(); Ok(format!("{}({})", cls.name(), repr_args.iter().format(", "))) } } impl ExceptionZoo { pub(crate) fn init() -> Self { use self::types::*; let base_exception_type = PyBaseException::init_builtin_type(); // Sorted By Hierarchy then alphabetized. let base_exception_group = PyBaseExceptionGroup::init_builtin_type(); let system_exit = PySystemExit::init_builtin_type(); let keyboard_interrupt = PyKeyboardInterrupt::init_builtin_type(); let generator_exit = PyGeneratorExit::init_builtin_type(); let exception_type = PyException::init_builtin_type(); let stop_iteration = PyStopIteration::init_builtin_type(); let stop_async_iteration = PyStopAsyncIteration::init_builtin_type(); let arithmetic_error = PyArithmeticError::init_builtin_type(); let floating_point_error = PyFloatingPointError::init_builtin_type(); let overflow_error = PyOverflowError::init_builtin_type(); let zero_division_error = PyZeroDivisionError::init_builtin_type(); let assertion_error = PyAssertionError::init_builtin_type(); let attribute_error = PyAttributeError::init_builtin_type(); let buffer_error = PyBufferError::init_builtin_type(); let eof_error = PyEOFError::init_builtin_type(); let import_error = PyImportError::init_builtin_type(); let module_not_found_error = PyModuleNotFoundError::init_builtin_type(); let lookup_error = PyLookupError::init_builtin_type(); let index_error = PyIndexError::init_builtin_type(); let key_error = PyKeyError::init_builtin_type(); let memory_error = PyMemoryError::init_builtin_type(); let name_error = PyNameError::init_builtin_type(); let unbound_local_error = PyUnboundLocalError::init_builtin_type(); // os errors let os_error = PyOSError::init_builtin_type(); let blocking_io_error = PyBlockingIOError::init_builtin_type(); let child_process_error = PyChildProcessError::init_builtin_type(); let connection_error = PyConnectionError::init_builtin_type(); let broken_pipe_error = PyBrokenPipeError::init_builtin_type(); let connection_aborted_error = PyConnectionAbortedError::init_builtin_type(); let connection_refused_error = PyConnectionRefusedError::init_builtin_type(); let connection_reset_error = PyConnectionResetError::init_builtin_type(); let file_exists_error = PyFileExistsError::init_builtin_type(); let file_not_found_error = PyFileNotFoundError::init_builtin_type(); let interrupted_error = PyInterruptedError::init_builtin_type(); let is_a_directory_error = PyIsADirectoryError::init_builtin_type(); let not_a_directory_error = PyNotADirectoryError::init_builtin_type(); let permission_error = PyPermissionError::init_builtin_type(); let process_lookup_error = PyProcessLookupError::init_builtin_type(); let timeout_error = PyTimeoutError::init_builtin_type(); let reference_error = PyReferenceError::init_builtin_type(); let runtime_error = PyRuntimeError::init_builtin_type(); let not_implemented_error = PyNotImplementedError::init_builtin_type(); let recursion_error = PyRecursionError::init_builtin_type(); let python_finalization_error = PyPythonFinalizationError::init_builtin_type(); let syntax_error = PySyntaxError::init_builtin_type(); let incomplete_input_error = PyIncompleteInputError::init_builtin_type(); let indentation_error = PyIndentationError::init_builtin_type(); let tab_error = PyTabError::init_builtin_type(); let system_error = PySystemError::init_builtin_type(); let type_error = PyTypeError::init_builtin_type(); let value_error = PyValueError::init_builtin_type(); let unicode_error = PyUnicodeError::init_builtin_type(); let unicode_decode_error = PyUnicodeDecodeError::init_builtin_type(); let unicode_encode_error = PyUnicodeEncodeError::init_builtin_type(); let unicode_translate_error = PyUnicodeTranslateError::init_builtin_type(); #[cfg(feature = "jit")] let jit_error = PyJitError::init_builtin_type(); let warning = PyWarning::init_builtin_type(); let deprecation_warning = PyDeprecationWarning::init_builtin_type(); let pending_deprecation_warning = PyPendingDeprecationWarning::init_builtin_type(); let runtime_warning = PyRuntimeWarning::init_builtin_type(); let syntax_warning = PySyntaxWarning::init_builtin_type(); let user_warning = PyUserWarning::init_builtin_type(); let future_warning = PyFutureWarning::init_builtin_type(); let import_warning = PyImportWarning::init_builtin_type(); let unicode_warning = PyUnicodeWarning::init_builtin_type(); let bytes_warning = PyBytesWarning::init_builtin_type(); let resource_warning = PyResourceWarning::init_builtin_type(); let encoding_warning = PyEncodingWarning::init_builtin_type(); Self { base_exception_type, base_exception_group, system_exit, keyboard_interrupt, generator_exit, exception_type, stop_iteration, stop_async_iteration, arithmetic_error, floating_point_error, overflow_error, zero_division_error, assertion_error, attribute_error, buffer_error, eof_error, import_error, module_not_found_error, lookup_error, index_error, key_error, memory_error, name_error, unbound_local_error, os_error, blocking_io_error, child_process_error, connection_error, broken_pipe_error, connection_aborted_error, connection_refused_error, connection_reset_error, file_exists_error, file_not_found_error, interrupted_error, is_a_directory_error, not_a_directory_error, permission_error, process_lookup_error, timeout_error, reference_error, runtime_error, not_implemented_error, recursion_error, python_finalization_error, syntax_error, incomplete_input_error, indentation_error, tab_error, system_error, type_error, value_error, unicode_error, unicode_decode_error, unicode_encode_error, unicode_translate_error, #[cfg(feature = "jit")] jit_error, warning, deprecation_warning, pending_deprecation_warning, runtime_warning, syntax_warning, user_warning,
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/compiler.rs
crates/vm/src/compiler.rs
#[cfg(feature = "codegen")] pub use rustpython_codegen::CompileOpts; #[cfg(feature = "compiler")] pub use rustpython_compiler::*; #[cfg(not(feature = "compiler"))] pub use rustpython_compiler_core::Mode; #[cfg(not(feature = "compiler"))] pub use rustpython_compiler_core as core; #[cfg(not(feature = "compiler"))] pub use ruff_python_parser as parser; #[cfg(not(feature = "compiler"))] mod error { #[cfg(all(feature = "parser", feature = "codegen"))] panic!("Use --features=compiler to enable both parser and codegen"); #[derive(Debug, thiserror::Error)] pub enum CompileErrorType { #[cfg(feature = "codegen")] #[error(transparent)] Codegen(#[from] super::codegen::error::CodegenErrorType), #[cfg(feature = "parser")] #[error(transparent)] Parse(#[from] super::parser::ParseErrorType), } #[derive(Debug, thiserror::Error)] pub enum CompileError { #[cfg(feature = "codegen")] #[error(transparent)] Codegen(#[from] super::codegen::error::CodegenError), #[cfg(feature = "parser")] #[error(transparent)] Parse(#[from] super::parser::ParseError), } } #[cfg(not(feature = "compiler"))] pub use error::{CompileError, CompileErrorType}; #[cfg(any(feature = "parser", feature = "codegen"))] impl crate::convert::ToPyException for (CompileError, Option<&str>) { fn to_pyexception(&self, vm: &crate::VirtualMachine) -> crate::builtins::PyBaseExceptionRef { vm.new_syntax_error(&self.0, self.1) } } #[cfg(any(feature = "parser", feature = "codegen"))] impl crate::convert::ToPyException for (CompileError, Option<&str>, bool) { fn to_pyexception(&self, vm: &crate::VirtualMachine) -> crate::builtins::PyBaseExceptionRef { vm.new_syntax_error_maybe_incomplete(&self.0, self.1, self.2) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/coroutine.rs
crates/vm/src/builtins/coroutine.rs
use super::{PyCode, PyGenericAlias, PyStrRef, PyType, PyTypeRef}; use crate::{ AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, class::PyClassImpl, coroutine::{Coro, warn_deprecated_throw_signature}, frame::FrameRef, function::OptionalArg, protocol::PyIterReturn, types::{IterNext, Iterable, Representable, SelfIter}, }; use crossbeam_utils::atomic::AtomicCell; #[pyclass(module = false, name = "coroutine")] #[derive(Debug)] // PyCoro_Type in CPython pub struct PyCoroutine { inner: Coro, } impl PyPayload for PyCoroutine { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.coroutine_type } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(Py, IterNext, Representable))] impl PyCoroutine { pub const fn as_coro(&self) -> &Coro { &self.inner } pub fn new(frame: FrameRef, name: PyStrRef, qualname: PyStrRef) -> Self { Self { inner: Coro::new(frame, name, qualname), } } #[pygetset] fn __name__(&self) -> PyStrRef { self.inner.name() } #[pygetset(setter)] fn set___name__(&self, name: PyStrRef) { self.inner.set_name(name) } #[pygetset] fn __qualname__(&self) -> PyStrRef { self.inner.qualname() } #[pygetset(setter)] fn set___qualname__(&self, qualname: PyStrRef) { self.inner.set_qualname(qualname) } #[pymethod(name = "__await__")] fn r#await(zelf: PyRef<Self>) -> PyCoroutineWrapper { PyCoroutineWrapper { coro: zelf, closed: AtomicCell::new(false), } } #[pygetset] fn cr_await(&self, _vm: &VirtualMachine) -> Option<PyObjectRef> { self.inner.frame().yield_from_target() } #[pygetset] fn cr_frame(&self, _vm: &VirtualMachine) -> FrameRef { self.inner.frame() } #[pygetset] fn cr_running(&self, _vm: &VirtualMachine) -> bool { self.inner.running() } #[pygetset] fn cr_code(&self, _vm: &VirtualMachine) -> PyRef<PyCode> { self.inner.frame().code.clone() } // TODO: coroutine origin tracking: // https://docs.python.org/3/library/sys.html#sys.set_coroutine_origin_tracking_depth #[pygetset] const fn cr_origin(&self, _vm: &VirtualMachine) -> Option<(PyStrRef, usize, PyStrRef)> { None } #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } #[pyclass] impl Py<PyCoroutine> { #[pymethod] fn send(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyIterReturn> { self.inner.send(self.as_object(), value, vm) } #[pymethod] fn throw( &self, exc_type: PyObjectRef, exc_val: OptionalArg, exc_tb: OptionalArg, vm: &VirtualMachine, ) -> PyResult<PyIterReturn> { warn_deprecated_throw_signature(&exc_val, &exc_tb, vm)?; self.inner.throw( self.as_object(), exc_type, exc_val.unwrap_or_none(vm), exc_tb.unwrap_or_none(vm), vm, ) } #[pymethod] fn close(&self, vm: &VirtualMachine) -> PyResult<()> { self.inner.close(self.as_object(), vm) } } impl Representable for PyCoroutine { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { Ok(zelf.inner.repr(zelf.as_object(), zelf.get_id(), vm)) } } impl SelfIter for PyCoroutine {} impl IterNext for PyCoroutine { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { zelf.send(vm.ctx.none(), vm) } } #[pyclass(module = false, name = "coroutine_wrapper")] #[derive(Debug)] // PyCoroWrapper_Type in CPython pub struct PyCoroutineWrapper { coro: PyRef<PyCoroutine>, closed: AtomicCell<bool>, } impl PyPayload for PyCoroutineWrapper { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.coroutine_wrapper_type } } #[pyclass(with(IterNext, Iterable))] impl PyCoroutineWrapper { fn check_closed(&self, vm: &VirtualMachine) -> PyResult<()> { if self.closed.load() { return Err(vm.new_runtime_error("cannot reuse already awaited coroutine")); } Ok(()) } #[pymethod] fn send(&self, val: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyIterReturn> { self.check_closed(vm)?; let result = self.coro.send(val, vm); // Mark as closed if exhausted if let Ok(PyIterReturn::StopIteration(_)) = &result { self.closed.store(true); } result } #[pymethod] fn throw( &self, exc_type: PyObjectRef, exc_val: OptionalArg, exc_tb: OptionalArg, vm: &VirtualMachine, ) -> PyResult<PyIterReturn> { self.check_closed(vm)?; warn_deprecated_throw_signature(&exc_val, &exc_tb, vm)?; let result = self.coro.throw(exc_type, exc_val, exc_tb, vm); // Mark as closed if exhausted if let Ok(PyIterReturn::StopIteration(_)) = &result { self.closed.store(true); } result } #[pymethod] fn close(&self, vm: &VirtualMachine) -> PyResult<()> { self.closed.store(true); self.coro.close(vm) } } impl SelfIter for PyCoroutineWrapper {} impl IterNext for PyCoroutineWrapper { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { Self::send(zelf, vm.ctx.none(), vm) } } pub fn init(ctx: &Context) { PyCoroutine::extend_class(ctx, ctx.types.coroutine_type); PyCoroutineWrapper::extend_class(ctx, ctx.types.coroutine_wrapper_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/slice.rs
crates/vm/src/builtins/slice.rs
// sliceobject.{h,c} in CPython // spell-checker:ignore sliceobject use super::{PyGenericAlias, PyStrRef, PyTupleRef, PyType, PyTypeRef}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, class::PyClassImpl, common::hash::{PyHash, PyUHash}, convert::ToPyObject, function::{ArgIndex, FuncArgs, OptionalArg, PyComparisonValue}, sliceable::SaturatedSlice, types::{Comparable, Constructor, Hashable, PyComparisonOp, Representable}, }; use malachite_bigint::{BigInt, ToBigInt}; use num_traits::{One, Signed, Zero}; #[pyclass(module = false, name = "slice", unhashable = true, traverse)] #[derive(Debug)] pub struct PySlice { pub start: Option<PyObjectRef>, pub stop: PyObjectRef, pub step: Option<PyObjectRef>, } impl PyPayload for PySlice { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.slice_type } } #[pyclass(with(Comparable, Representable, Hashable))] impl PySlice { #[pygetset] fn start(&self, vm: &VirtualMachine) -> PyObjectRef { self.start.clone().to_pyobject(vm) } pub(crate) fn start_ref<'a>(&'a self, vm: &'a VirtualMachine) -> &'a PyObject { match &self.start { Some(v) => v, None => vm.ctx.none.as_object(), } } #[pygetset] pub(crate) fn stop(&self, _vm: &VirtualMachine) -> PyObjectRef { self.stop.clone() } #[pygetset] fn step(&self, vm: &VirtualMachine) -> PyObjectRef { self.step.clone().to_pyobject(vm) } pub(crate) fn step_ref<'a>(&'a self, vm: &'a VirtualMachine) -> &'a PyObject { match &self.step { Some(v) => v, None => vm.ctx.none.as_object(), } } pub fn to_saturated(&self, vm: &VirtualMachine) -> PyResult<SaturatedSlice> { SaturatedSlice::with_slice(self, vm) } #[pyslot] fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let slice: Self = match args.args.len() { 0 => { return Err(vm.new_type_error("slice() must have at least one arguments.")); } 1 => { let stop = args.bind(vm)?; Self { start: None, stop, step: None, } } _ => { let (start, stop, step): (PyObjectRef, PyObjectRef, OptionalArg<PyObjectRef>) = args.bind(vm)?; Self { start: Some(start), stop, step: step.into_option(), } } }; slice.into_ref_with_type(vm, cls).map(Into::into) } pub(crate) fn inner_indices( &self, length: &BigInt, vm: &VirtualMachine, ) -> PyResult<(BigInt, BigInt, BigInt)> { // Calculate step let step: BigInt; if vm.is_none(self.step_ref(vm)) { step = One::one(); } else { // Clone the value, not the reference. let this_step = self.step(vm).try_index(vm)?; step = this_step.as_bigint().clone(); if step.is_zero() { return Err(vm.new_value_error("slice step cannot be zero.")); } } // For convenience let backwards = step.is_negative(); // Each end of the array let lower = if backwards { (-1_i8).to_bigint().unwrap() } else { Zero::zero() }; let upper = if backwards { lower.clone() + length } else { length.clone() }; // Calculate start let mut start: BigInt; if vm.is_none(self.start_ref(vm)) { // Default start = if backwards { upper.clone() } else { lower.clone() }; } else { let this_start = self.start(vm).try_index(vm)?; start = this_start.as_bigint().clone(); if start < Zero::zero() { // From end of array start += length; if start < lower { start = lower.clone(); } } else if start > upper { start = upper.clone(); } } // Calculate Stop let mut stop: BigInt; if vm.is_none(&self.stop) { stop = if backwards { lower } else { upper }; } else { let this_stop = self.stop(vm).try_index(vm)?; stop = this_stop.as_bigint().clone(); if stop < Zero::zero() { // From end of array stop += length; if stop < lower { stop = lower; } } else if stop > upper { stop = upper; } } Ok((start, stop, step)) } #[pymethod] fn indices(&self, length: ArgIndex, vm: &VirtualMachine) -> PyResult<PyTupleRef> { let length = length.into_int_ref(); let length = length.as_bigint(); if length.is_negative() { return Err(vm.new_value_error("length should not be negative.")); } let (start, stop, step) = self.inner_indices(length, vm)?; Ok(vm.new_tuple((start, stop, step))) } #[allow(clippy::type_complexity)] #[pymethod] fn __reduce__( zelf: PyRef<Self>, ) -> PyResult<( PyTypeRef, (Option<PyObjectRef>, PyObjectRef, Option<PyObjectRef>), )> { Ok(( zelf.class().to_owned(), (zelf.start.clone(), zelf.stop.clone(), zelf.step.clone()), )) } // TODO: Uncomment when Python adds __class_getitem__ to slice // #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } impl Hashable for PySlice { #[inline] fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> { const XXPRIME_1: PyUHash = if cfg!(target_pointer_width = "64") { 11400714785074694791 } else { 2654435761 }; const XXPRIME_2: PyUHash = if cfg!(target_pointer_width = "64") { 14029467366897019727 } else { 2246822519 }; const XXPRIME_5: PyUHash = if cfg!(target_pointer_width = "64") { 2870177450012600261 } else { 374761393 }; const ROTATE: u32 = if cfg!(target_pointer_width = "64") { 31 } else { 13 }; let mut acc = XXPRIME_5; for part in &[zelf.start_ref(vm), &zelf.stop, zelf.step_ref(vm)] { let lane = part.hash(vm)? as PyUHash; if lane == u64::MAX as PyUHash { return Ok(-1 as PyHash); } acc = acc.wrapping_add(lane.wrapping_mul(XXPRIME_2)); acc = acc.rotate_left(ROTATE); acc = acc.wrapping_mul(XXPRIME_1); } if acc == u64::MAX as PyUHash { return Ok(1546275796 as PyHash); } Ok(acc as PyHash) } } impl Comparable for PySlice { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { let other = class_or_notimplemented!(Self, other); let ret = match op { PyComparisonOp::Lt | PyComparisonOp::Le => None .or_else(|| { vm.bool_seq_lt(zelf.start_ref(vm), other.start_ref(vm)) .transpose() }) .or_else(|| vm.bool_seq_lt(&zelf.stop, &other.stop).transpose()) .or_else(|| { vm.bool_seq_lt(zelf.step_ref(vm), other.step_ref(vm)) .transpose() }) .unwrap_or_else(|| Ok(op == PyComparisonOp::Le))?, PyComparisonOp::Eq | PyComparisonOp::Ne => { let eq = vm.identical_or_equal(zelf.start_ref(vm), other.start_ref(vm))? && vm.identical_or_equal(&zelf.stop, &other.stop)? && vm.identical_or_equal(zelf.step_ref(vm), other.step_ref(vm))?; if op == PyComparisonOp::Ne { !eq } else { eq } } PyComparisonOp::Gt | PyComparisonOp::Ge => None .or_else(|| { vm.bool_seq_gt(zelf.start_ref(vm), other.start_ref(vm)) .transpose() }) .or_else(|| vm.bool_seq_gt(&zelf.stop, &other.stop).transpose()) .or_else(|| { vm.bool_seq_gt(zelf.step_ref(vm), other.step_ref(vm)) .transpose() }) .unwrap_or_else(|| Ok(op == PyComparisonOp::Ge))?, }; Ok(PyComparisonValue::Implemented(ret)) } } impl Representable for PySlice { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { let start_repr = zelf.start_ref(vm).repr(vm)?; let stop_repr = zelf.stop.repr(vm)?; let step_repr = zelf.step_ref(vm).repr(vm)?; Ok(format!("slice({start_repr}, {stop_repr}, {step_repr})")) } } #[pyclass(module = false, name = "EllipsisType")] #[derive(Debug)] pub struct PyEllipsis; impl PyPayload for PyEllipsis { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.ellipsis_type } } impl Constructor for PyEllipsis { type Args = (); fn slot_new(_cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let _: () = args.bind(vm)?; Ok(vm.ctx.ellipsis.clone().into()) } fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> { unreachable!("Ellipsis is a singleton") } } #[pyclass(with(Constructor, Representable))] impl PyEllipsis { #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyStrRef { vm.ctx.names.Ellipsis.to_owned() } } impl Representable for PyEllipsis { #[inline] fn repr(_zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> { Ok(vm.ctx.names.Ellipsis.to_owned()) } #[cold] fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { unreachable!("use repr instead") } } pub fn init(ctx: &Context) { PySlice::extend_class(ctx, ctx.types.slice_type); PyEllipsis::extend_class(ctx, ctx.types.ellipsis_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/descriptor.rs
crates/vm/src/builtins/descriptor.rs
use super::{PyStr, PyStrInterned, PyType}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::{PyTypeRef, builtin_func::PyNativeMethod, type_}, class::PyClassImpl, common::hash::PyHash, convert::{ToPyObject, ToPyResult}, function::{ArgSize, FuncArgs, PyMethodDef, PyMethodFlags, PySetterValue}, protocol::{PyNumberBinaryFunc, PyNumberTernaryFunc, PyNumberUnaryFunc}, types::{ Callable, Comparable, DelFunc, DescrGetFunc, DescrSetFunc, GenericMethod, GetDescriptor, GetattroFunc, HashFunc, Hashable, InitFunc, IterFunc, IterNextFunc, MapAssSubscriptFunc, MapLenFunc, MapSubscriptFunc, PyComparisonOp, Representable, RichCompareFunc, SeqAssItemFunc, SeqConcatFunc, SeqContainsFunc, SeqItemFunc, SeqLenFunc, SeqRepeatFunc, SetattroFunc, StringifyFunc, }, }; use rustpython_common::lock::PyRwLock; #[derive(Debug)] pub struct PyDescriptor { pub typ: &'static Py<PyType>, pub name: &'static PyStrInterned, pub qualname: PyRwLock<Option<String>>, } #[derive(Debug)] pub struct PyDescriptorOwned { pub typ: PyRef<PyType>, pub name: &'static PyStrInterned, pub qualname: PyRwLock<Option<String>>, } #[pyclass(name = "method_descriptor", module = false)] pub struct PyMethodDescriptor { pub common: PyDescriptor, pub method: &'static PyMethodDef, // vectorcall: vector_call_func, pub objclass: &'static Py<PyType>, // TODO: move to tp_members } impl PyMethodDescriptor { pub fn new(method: &'static PyMethodDef, typ: &'static Py<PyType>, ctx: &Context) -> Self { Self { common: PyDescriptor { typ, name: ctx.intern_str(method.name), qualname: PyRwLock::new(None), }, method, objclass: typ, } } } impl PyPayload for PyMethodDescriptor { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.method_descriptor_type } } impl core::fmt::Debug for PyMethodDescriptor { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "method descriptor for '{}'", self.common.name) } } impl GetDescriptor for PyMethodDescriptor { fn descr_get( zelf: PyObjectRef, obj: Option<PyObjectRef>, cls: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { let descr = Self::_as_pyref(&zelf, vm).unwrap(); let bound = match obj { Some(obj) => { if descr.method.flags.contains(PyMethodFlags::METHOD) { if cls.is_some_and(|c| c.fast_isinstance(vm.ctx.types.type_type)) { obj } else { return Err(vm.new_type_error(format!( "descriptor '{}' needs a type, not '{}', as arg 2", descr.common.name.as_str(), obj.class().name() ))); } } else if descr.method.flags.contains(PyMethodFlags::CLASS) { obj.class().to_owned().into() } else { unimplemented!() } } None if descr.method.flags.contains(PyMethodFlags::CLASS) => cls.unwrap(), None => return Ok(zelf), }; // Ok(descr.method.build_bound_method(&vm.ctx, bound, class).into()) Ok(descr.bind(bound, &vm.ctx).into()) } } impl Callable for PyMethodDescriptor { type Args = FuncArgs; #[inline] fn call(zelf: &Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult { (zelf.method.func)(vm, args) } } impl PyMethodDescriptor { pub fn bind(&self, obj: PyObjectRef, ctx: &Context) -> PyRef<PyNativeMethod> { self.method.build_bound_method(ctx, obj, self.common.typ) } } #[pyclass( with(GetDescriptor, Callable, Representable), flags(METHOD_DESCRIPTOR, DISALLOW_INSTANTIATION) )] impl PyMethodDescriptor { #[pygetset] const fn __name__(&self) -> &'static PyStrInterned { self.common.name } #[pygetset] fn __qualname__(&self) -> String { format!("{}.{}", self.common.typ.name(), &self.common.name) } #[pygetset] const fn __doc__(&self) -> Option<&'static str> { self.method.doc } #[pygetset] fn __text_signature__(&self) -> Option<String> { self.method.doc.and_then(|doc| { type_::get_text_signature_from_internal_doc(self.method.name, doc) .map(|signature| signature.to_string()) }) } #[pygetset] fn __objclass__(&self) -> PyTypeRef { self.objclass.to_owned() } #[pymethod] fn __reduce__( &self, vm: &VirtualMachine, ) -> (Option<PyObjectRef>, (Option<PyObjectRef>, &'static str)) { let builtins_getattr = vm.builtins.get_attr("getattr", vm).ok(); let classname = vm.builtins.get_attr(&self.common.typ.__name__(vm), vm).ok(); (builtins_getattr, (classname, self.method.name)) } } impl Representable for PyMethodDescriptor { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { Ok(format!( "<method '{}' of '{}' objects>", &zelf.method.name, zelf.common.typ.name() )) } } #[derive(Debug)] pub enum MemberKind { Bool = 14, ObjectEx = 16, } pub type MemberSetterFunc = Option<fn(&VirtualMachine, PyObjectRef, PySetterValue) -> PyResult<()>>; pub enum MemberGetter { Getter(fn(&VirtualMachine, PyObjectRef) -> PyResult), Offset(usize), } pub enum MemberSetter { Setter(MemberSetterFunc), Offset(usize), } pub struct PyMemberDef { pub name: String, pub kind: MemberKind, pub getter: MemberGetter, pub setter: MemberSetter, pub doc: Option<String>, } impl PyMemberDef { fn get(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { match self.getter { MemberGetter::Getter(getter) => (getter)(vm, obj), MemberGetter::Offset(offset) => get_slot_from_object(obj, offset, self, vm), } } fn set( &self, obj: PyObjectRef, value: PySetterValue<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<()> { match self.setter { MemberSetter::Setter(setter) => match setter { Some(setter) => (setter)(vm, obj, value), None => Err(vm.new_attribute_error("readonly attribute")), }, MemberSetter::Offset(offset) => set_slot_at_object(obj, offset, self, value, vm), } } } impl core::fmt::Debug for PyMemberDef { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyMemberDef") .field("name", &self.name) .field("kind", &self.kind) .field("doc", &self.doc) .finish() } } // = PyMemberDescrObject #[pyclass(name = "member_descriptor", module = false)] #[derive(Debug)] pub struct PyMemberDescriptor { pub common: PyDescriptorOwned, pub member: PyMemberDef, } impl PyPayload for PyMemberDescriptor { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.member_descriptor_type } } fn calculate_qualname(descr: &PyDescriptorOwned, vm: &VirtualMachine) -> PyResult<Option<String>> { if let Some(qualname) = vm.get_attribute_opt(descr.typ.clone().into(), "__qualname__")? { let str = qualname.downcast::<PyStr>().map_err(|_| { vm.new_type_error("<descriptor>.__objclass__.__qualname__ is not a unicode object") })?; Ok(Some(format!("{}.{}", str, descr.name))) } else { Ok(None) } } #[pyclass( with(GetDescriptor, Representable), flags(BASETYPE, DISALLOW_INSTANTIATION) )] impl PyMemberDescriptor { #[pygetset] fn __doc__(&self) -> Option<String> { self.member.doc.to_owned() } #[pygetset] fn __qualname__(&self, vm: &VirtualMachine) -> PyResult<Option<String>> { let qualname = self.common.qualname.read(); Ok(if qualname.is_none() { drop(qualname); let calculated = calculate_qualname(&self.common, vm)?; calculated.clone_into(&mut self.common.qualname.write()); calculated } else { qualname.to_owned() }) } #[pyslot] fn descr_set( zelf: &PyObject, obj: PyObjectRef, value: PySetterValue<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<()> { let zelf = Self::_as_pyref(zelf, vm)?; if !obj.class().fast_issubclass(&zelf.common.typ) { return Err(vm.new_type_error(format!( "descriptor '{}' for '{}' objects doesn't apply to a '{}' object", zelf.common.name, zelf.common.typ.name(), obj.class().name() ))); } zelf.member.set(obj, value, vm) } } // PyMember_GetOne fn get_slot_from_object( obj: PyObjectRef, offset: usize, member: &PyMemberDef, vm: &VirtualMachine, ) -> PyResult { let slot = match member.kind { MemberKind::Bool => obj .get_slot(offset) .unwrap_or_else(|| vm.ctx.new_bool(false).into()), MemberKind::ObjectEx => obj.get_slot(offset).ok_or_else(|| { vm.new_no_attribute_error(obj.clone(), vm.ctx.new_str(member.name.clone())) })?, }; Ok(slot) } // PyMember_SetOne fn set_slot_at_object( obj: PyObjectRef, offset: usize, member: &PyMemberDef, value: PySetterValue, vm: &VirtualMachine, ) -> PyResult<()> { match member.kind { MemberKind::Bool => { match value { PySetterValue::Assign(v) => { if !v.class().is(vm.ctx.types.bool_type) { return Err(vm.new_type_error("attribute value type must be bool")); } obj.set_slot(offset, Some(v)) } PySetterValue::Delete => obj.set_slot(offset, None), }; } MemberKind::ObjectEx => { let value = match value { PySetterValue::Assign(v) => Some(v), PySetterValue::Delete => None, }; obj.set_slot(offset, value); } } Ok(()) } impl Representable for PyMemberDescriptor { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { Ok(format!( "<member '{}' of '{}' objects>", zelf.common.name, zelf.common.typ.name(), )) } } impl GetDescriptor for PyMemberDescriptor { fn descr_get( zelf: PyObjectRef, obj: Option<PyObjectRef>, cls: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { let descr = Self::_as_pyref(&zelf, vm)?; match obj { Some(x) => descr.member.get(x, vm), None => { // When accessed from class (not instance), for __doc__ member descriptor, // return the class's docstring if available // When accessed from class (not instance), check if the class has // an attribute with the same name as this member descriptor if let Some(cls) = cls && let Ok(cls_type) = cls.downcast::<PyType>() && let Some(interned) = vm.ctx.interned_str(descr.member.name.as_str()) && let Some(attr) = cls_type.attributes.read().get(&interned) { return Ok(attr.clone()); } Ok(zelf) } } } } pub fn init(ctx: &Context) { PyMemberDescriptor::extend_class(ctx, ctx.types.member_descriptor_type); PyMethodDescriptor::extend_class(ctx, ctx.types.method_descriptor_type); PyWrapper::extend_class(ctx, ctx.types.wrapper_descriptor_type); PyMethodWrapper::extend_class(ctx, ctx.types.method_wrapper_type); } // PyWrapper - wrapper_descriptor /// Each variant knows how to call the wrapped function with proper types #[derive(Clone, Copy)] pub enum SlotFunc { // Basic slots Init(InitFunc), Hash(HashFunc), Str(StringifyFunc), Repr(StringifyFunc), Iter(IterFunc), IterNext(IterNextFunc), Call(GenericMethod), Del(DelFunc), // Attribute access slots GetAttro(GetattroFunc), SetAttro(SetattroFunc), // __setattr__ DelAttro(SetattroFunc), // __delattr__ (same func type, different PySetterValue) // Rich comparison slots (with comparison op) RichCompare(RichCompareFunc, PyComparisonOp), // Descriptor slots DescrGet(DescrGetFunc), DescrSet(DescrSetFunc), // __set__ DescrDel(DescrSetFunc), // __delete__ (same func type, different PySetterValue) // Sequence sub-slots (sq_*) SeqLength(SeqLenFunc), SeqConcat(SeqConcatFunc), SeqRepeat(SeqRepeatFunc), SeqItem(SeqItemFunc), SeqSetItem(SeqAssItemFunc), // __setitem__ (same func type, value = Some) SeqDelItem(SeqAssItemFunc), // __delitem__ (same func type, value = None) SeqContains(SeqContainsFunc), // Mapping sub-slots (mp_*) MapLength(MapLenFunc), MapSubscript(MapSubscriptFunc), MapSetSubscript(MapAssSubscriptFunc), // __setitem__ (same func type, value = Some) MapDelSubscript(MapAssSubscriptFunc), // __delitem__ (same func type, value = None) // Number sub-slots (nb_*) - grouped by signature NumBoolean(PyNumberUnaryFunc<bool>), // __bool__ NumUnary(PyNumberUnaryFunc), // __int__, __float__, __index__ NumBinary(PyNumberBinaryFunc), // __add__, __sub__, __mul__, etc. NumBinaryRight(PyNumberBinaryFunc), // __radd__, __rsub__, etc. (swapped args) NumTernary(PyNumberTernaryFunc), // __pow__ NumTernaryRight(PyNumberTernaryFunc), // __rpow__ (swapped first two args) } impl core::fmt::Debug for SlotFunc { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { SlotFunc::Init(_) => write!(f, "SlotFunc::Init(...)"), SlotFunc::Hash(_) => write!(f, "SlotFunc::Hash(...)"), SlotFunc::Str(_) => write!(f, "SlotFunc::Str(...)"), SlotFunc::Repr(_) => write!(f, "SlotFunc::Repr(...)"), SlotFunc::Iter(_) => write!(f, "SlotFunc::Iter(...)"), SlotFunc::IterNext(_) => write!(f, "SlotFunc::IterNext(...)"), SlotFunc::Call(_) => write!(f, "SlotFunc::Call(...)"), SlotFunc::Del(_) => write!(f, "SlotFunc::Del(...)"), SlotFunc::GetAttro(_) => write!(f, "SlotFunc::GetAttro(...)"), SlotFunc::SetAttro(_) => write!(f, "SlotFunc::SetAttro(...)"), SlotFunc::DelAttro(_) => write!(f, "SlotFunc::DelAttro(...)"), SlotFunc::RichCompare(_, op) => write!(f, "SlotFunc::RichCompare(..., {:?})", op), SlotFunc::DescrGet(_) => write!(f, "SlotFunc::DescrGet(...)"), SlotFunc::DescrSet(_) => write!(f, "SlotFunc::DescrSet(...)"), SlotFunc::DescrDel(_) => write!(f, "SlotFunc::DescrDel(...)"), // Sequence sub-slots SlotFunc::SeqLength(_) => write!(f, "SlotFunc::SeqLength(...)"), SlotFunc::SeqConcat(_) => write!(f, "SlotFunc::SeqConcat(...)"), SlotFunc::SeqRepeat(_) => write!(f, "SlotFunc::SeqRepeat(...)"), SlotFunc::SeqItem(_) => write!(f, "SlotFunc::SeqItem(...)"), SlotFunc::SeqSetItem(_) => write!(f, "SlotFunc::SeqSetItem(...)"), SlotFunc::SeqDelItem(_) => write!(f, "SlotFunc::SeqDelItem(...)"), SlotFunc::SeqContains(_) => write!(f, "SlotFunc::SeqContains(...)"), // Mapping sub-slots SlotFunc::MapLength(_) => write!(f, "SlotFunc::MapLength(...)"), SlotFunc::MapSubscript(_) => write!(f, "SlotFunc::MapSubscript(...)"), SlotFunc::MapSetSubscript(_) => write!(f, "SlotFunc::MapSetSubscript(...)"), SlotFunc::MapDelSubscript(_) => write!(f, "SlotFunc::MapDelSubscript(...)"), // Number sub-slots SlotFunc::NumBoolean(_) => write!(f, "SlotFunc::NumBoolean(...)"), SlotFunc::NumUnary(_) => write!(f, "SlotFunc::NumUnary(...)"), SlotFunc::NumBinary(_) => write!(f, "SlotFunc::NumBinary(...)"), SlotFunc::NumBinaryRight(_) => write!(f, "SlotFunc::NumBinaryRight(...)"), SlotFunc::NumTernary(_) => write!(f, "SlotFunc::NumTernary(...)"), SlotFunc::NumTernaryRight(_) => write!(f, "SlotFunc::NumTernaryRight(...)"), } } } impl SlotFunc { /// Call the wrapped slot function with proper type handling pub fn call(&self, obj: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { match self { SlotFunc::Init(func) => { func(obj, args, vm)?; Ok(vm.ctx.none()) } SlotFunc::Hash(func) => { if !args.args.is_empty() || !args.kwargs.is_empty() { return Err( vm.new_type_error("__hash__() takes no arguments (1 given)".to_owned()) ); } let hash = func(&obj, vm)?; Ok(vm.ctx.new_int(hash).into()) } SlotFunc::Repr(func) | SlotFunc::Str(func) => { if !args.args.is_empty() || !args.kwargs.is_empty() { let name = match self { SlotFunc::Repr(_) => "__repr__", SlotFunc::Str(_) => "__str__", _ => unreachable!(), }; return Err(vm.new_type_error(format!("{name}() takes no arguments (1 given)"))); } let s = func(&obj, vm)?; Ok(s.into()) } SlotFunc::Iter(func) => { if !args.args.is_empty() || !args.kwargs.is_empty() { return Err( vm.new_type_error("__iter__() takes no arguments (1 given)".to_owned()) ); } func(obj, vm) } SlotFunc::IterNext(func) => { if !args.args.is_empty() || !args.kwargs.is_empty() { return Err( vm.new_type_error("__next__() takes no arguments (1 given)".to_owned()) ); } func(&obj, vm).to_pyresult(vm) } SlotFunc::Call(func) => func(&obj, args, vm), SlotFunc::Del(func) => { if !args.args.is_empty() || !args.kwargs.is_empty() { return Err( vm.new_type_error("__del__() takes no arguments (1 given)".to_owned()) ); } func(&obj, vm)?; Ok(vm.ctx.none()) } SlotFunc::GetAttro(func) => { let (name,): (PyRef<PyStr>,) = args.bind(vm)?; func(&obj, &name, vm) } SlotFunc::SetAttro(func) => { let (name, value): (PyRef<PyStr>, PyObjectRef) = args.bind(vm)?; func(&obj, &name, PySetterValue::Assign(value), vm)?; Ok(vm.ctx.none()) } SlotFunc::DelAttro(func) => { let (name,): (PyRef<PyStr>,) = args.bind(vm)?; func(&obj, &name, PySetterValue::Delete, vm)?; Ok(vm.ctx.none()) } SlotFunc::RichCompare(func, op) => { let (other,): (PyObjectRef,) = args.bind(vm)?; func(&obj, &other, *op, vm).map(|r| match r { crate::function::Either::A(obj) => obj, crate::function::Either::B(cmp_val) => cmp_val.to_pyobject(vm), }) } SlotFunc::DescrGet(func) => { let (instance, owner): (PyObjectRef, crate::function::OptionalArg<PyObjectRef>) = args.bind(vm)?; let owner = owner.into_option(); let instance_opt = if vm.is_none(&instance) { None } else { Some(instance) }; func(obj, instance_opt, owner, vm) } SlotFunc::DescrSet(func) => { let (instance, value): (PyObjectRef, PyObjectRef) = args.bind(vm)?; func(&obj, instance, PySetterValue::Assign(value), vm)?; Ok(vm.ctx.none()) } SlotFunc::DescrDel(func) => { let (instance,): (PyObjectRef,) = args.bind(vm)?; func(&obj, instance, PySetterValue::Delete, vm)?; Ok(vm.ctx.none()) } // Sequence sub-slots SlotFunc::SeqLength(func) => { args.bind::<()>(vm)?; let len = func(obj.sequence_unchecked(), vm)?; Ok(vm.ctx.new_int(len).into()) } SlotFunc::SeqConcat(func) => { let (other,): (PyObjectRef,) = args.bind(vm)?; func(obj.sequence_unchecked(), &other, vm) } SlotFunc::SeqRepeat(func) => { let (n,): (ArgSize,) = args.bind(vm)?; func(obj.sequence_unchecked(), n.into(), vm) } SlotFunc::SeqItem(func) => { let (index,): (isize,) = args.bind(vm)?; func(obj.sequence_unchecked(), index, vm) } SlotFunc::SeqSetItem(func) => { let (index, value): (isize, PyObjectRef) = args.bind(vm)?; func(obj.sequence_unchecked(), index, Some(value), vm)?; Ok(vm.ctx.none()) } SlotFunc::SeqDelItem(func) => { let (index,): (isize,) = args.bind(vm)?; func(obj.sequence_unchecked(), index, None, vm)?; Ok(vm.ctx.none()) } SlotFunc::SeqContains(func) => { let (item,): (PyObjectRef,) = args.bind(vm)?; let result = func(obj.sequence_unchecked(), &item, vm)?; Ok(vm.ctx.new_bool(result).into()) } // Mapping sub-slots SlotFunc::MapLength(func) => { args.bind::<()>(vm)?; let len = func(obj.mapping_unchecked(), vm)?; Ok(vm.ctx.new_int(len).into()) } SlotFunc::MapSubscript(func) => { let (key,): (PyObjectRef,) = args.bind(vm)?; func(obj.mapping_unchecked(), &key, vm) } SlotFunc::MapSetSubscript(func) => { let (key, value): (PyObjectRef, PyObjectRef) = args.bind(vm)?; func(obj.mapping_unchecked(), &key, Some(value), vm)?; Ok(vm.ctx.none()) } SlotFunc::MapDelSubscript(func) => { let (key,): (PyObjectRef,) = args.bind(vm)?; func(obj.mapping_unchecked(), &key, None, vm)?; Ok(vm.ctx.none()) } // Number sub-slots SlotFunc::NumBoolean(func) => { args.bind::<()>(vm)?; let result = func(obj.number(), vm)?; Ok(vm.ctx.new_bool(result).into()) } SlotFunc::NumUnary(func) => { args.bind::<()>(vm)?; func(obj.number(), vm) } SlotFunc::NumBinary(func) => { let (other,): (PyObjectRef,) = args.bind(vm)?; func(&obj, &other, vm) } SlotFunc::NumBinaryRight(func) => { let (other,): (PyObjectRef,) = args.bind(vm)?; func(&other, &obj, vm) // Swapped: other op obj } SlotFunc::NumTernary(func) => { let (y, z): (PyObjectRef, crate::function::OptionalArg<PyObjectRef>) = args.bind(vm)?; let z = z.unwrap_or_else(|| vm.ctx.none()); func(&obj, &y, &z, vm) } SlotFunc::NumTernaryRight(func) => { let (y, z): (PyObjectRef, crate::function::OptionalArg<PyObjectRef>) = args.bind(vm)?; let z = z.unwrap_or_else(|| vm.ctx.none()); func(&y, &obj, &z, vm) // Swapped: y ** obj % z } } } } /// wrapper_descriptor: wraps a slot function as a Python method // = PyWrapperDescrObject #[pyclass(name = "wrapper_descriptor", module = false)] #[derive(Debug)] pub struct PyWrapper { pub typ: &'static Py<PyType>, pub name: &'static PyStrInterned, pub wrapped: SlotFunc, pub doc: Option<&'static str>, } impl PyPayload for PyWrapper { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.wrapper_descriptor_type } } impl GetDescriptor for PyWrapper { fn descr_get( zelf: PyObjectRef, obj: Option<PyObjectRef>, _cls: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { match obj { None => Ok(zelf), Some(obj) => { let zelf = zelf.downcast::<Self>().unwrap(); Ok(PyMethodWrapper { wrapper: zelf, obj }.into_pyobject(vm)) } } } } impl Callable for PyWrapper { type Args = FuncArgs; fn call(zelf: &Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult { // list.__init__(l, [1,2,3]) form - first arg is self let (obj, rest): (PyObjectRef, FuncArgs) = args.bind(vm)?; if !obj.fast_isinstance(zelf.typ) { return Err(vm.new_type_error(format!( "descriptor '{}' requires a '{}' object but received a '{}'", zelf.name.as_str(), zelf.typ.name(), obj.class().name() ))); } zelf.wrapped.call(obj, rest, vm) } } #[pyclass( with(GetDescriptor, Callable, Representable), flags(DISALLOW_INSTANTIATION) )] impl PyWrapper { #[pygetset] fn __name__(&self) -> &'static PyStrInterned { self.name } #[pygetset] fn __qualname__(&self) -> String { format!("{}.{}", self.typ.name(), self.name) } #[pygetset] fn __objclass__(&self) -> PyTypeRef { self.typ.to_owned() } #[pygetset] fn __doc__(&self) -> Option<&'static str> { self.doc } } impl Representable for PyWrapper { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { Ok(format!( "<slot wrapper '{}' of '{}' objects>", zelf.name.as_str(), zelf.typ.name() )) } } // PyMethodWrapper - method-wrapper /// method-wrapper: a slot wrapper bound to an instance /// Returned when accessing l.__init__ on an instance #[pyclass(name = "method-wrapper", module = false, traverse)] #[derive(Debug)] pub struct PyMethodWrapper { pub wrapper: PyRef<PyWrapper>, #[pytraverse(skip)] pub obj: PyObjectRef, } impl PyPayload for PyMethodWrapper { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.method_wrapper_type } } impl Callable for PyMethodWrapper { type Args = FuncArgs; fn call(zelf: &Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult { // bpo-37619: Check type compatibility before calling wrapped slot if !zelf.obj.fast_isinstance(zelf.wrapper.typ) { return Err(vm.new_type_error(format!( "descriptor '{}' requires a '{}' object but received a '{}'", zelf.wrapper.name.as_str(), zelf.wrapper.typ.name(), zelf.obj.class().name() ))); } zelf.wrapper.wrapped.call(zelf.obj.clone(), args, vm) } } #[pyclass( with(Callable, Representable, Hashable, Comparable), flags(DISALLOW_INSTANTIATION) )] impl PyMethodWrapper { #[pygetset] fn __self__(&self) -> PyObjectRef { self.obj.clone() } #[pygetset] fn __name__(&self) -> &'static PyStrInterned { self.wrapper.name } #[pygetset] fn __objclass__(&self) -> PyTypeRef { self.wrapper.typ.to_owned() } #[pymethod] fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { let builtins_getattr = vm.builtins.get_attr("getattr", vm)?; Ok(vm .ctx .new_tuple(vec![ builtins_getattr, vm.ctx .new_tuple(vec![ zelf.obj.clone(), vm.ctx.new_str(zelf.wrapper.name.as_str()).into(), ]) .into(), ]) .into()) } } impl Representable for PyMethodWrapper { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { Ok(format!( "<method-wrapper '{}' of {} object at {:#x}>", zelf.wrapper.name.as_str(), zelf.obj.class().name(), zelf.obj.get_id() )) } } impl Hashable for PyMethodWrapper { fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> { let obj_hash = zelf.obj.hash(vm)?; let wrapper_hash = zelf.wrapper.as_object().get_id() as PyHash; Ok(obj_hash ^ wrapper_hash) } } impl Comparable for PyMethodWrapper { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<crate::function::PyComparisonValue> { op.eq_only(|| { let other = class_or_notimplemented!(Self, other); let eq = zelf.wrapper.is(&other.wrapper) && vm.bool_eq(&zelf.obj, &other.obj)?; Ok(eq.into()) }) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/object.rs
crates/vm/src/builtins/object.rs
use super::{PyDictRef, PyList, PyStr, PyStrRef, PyType, PyTypeRef}; use crate::common::hash::PyHash; use crate::types::PyTypeFlags; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, class::PyClassImpl, convert::ToPyResult, function::{Either, FuncArgs, PyArithmeticValue, PyComparisonValue, PySetterValue}, types::{Constructor, Initializer, PyComparisonOp}, }; use itertools::Itertools; /// object() /// -- /// /// The base class of the class hierarchy. /// /// When called, it accepts no arguments and returns a new featureless /// instance that has no instance attributes and cannot be given any. #[pyclass(module = false, name = "object")] #[derive(Debug)] pub struct PyBaseObject; impl PyPayload for PyBaseObject { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.object_type } } impl Constructor for PyBaseObject { type Args = FuncArgs; // = object_new fn slot_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult { if !args.args.is_empty() || !args.kwargs.is_empty() { // Check if type's __new__ != object.__new__ let tp_new = cls.get_attr(identifier!(vm, __new__)); let object_new = vm.ctx.types.object_type.get_attr(identifier!(vm, __new__)); if let (Some(tp_new), Some(object_new)) = (tp_new, object_new) { if !tp_new.is(&object_new) { // Type has its own __new__, so object.__new__ is being called // with excess args. This is the first error case in CPython return Err(vm.new_type_error( "object.__new__() takes exactly one argument (the type to instantiate)" .to_owned(), )); } // If we reach here, tp_new == object_new // Now check if type's __init__ == object.__init__ let tp_init = cls.get_attr(identifier!(vm, __init__)); let object_init = vm.ctx.types.object_type.get_attr(identifier!(vm, __init__)); if let (Some(tp_init), Some(object_init)) = (tp_init, object_init) && tp_init.is(&object_init) { // Both __new__ and __init__ are object's versions, // so the type accepts no arguments return Err(vm.new_type_error(format!("{}() takes no arguments", cls.name()))); } // If tp_init != object_init, then the type has custom __init__ // which might accept arguments, so we allow it } } // more or less __new__ operator // Only create dict if the class has HAS_DICT flag (i.e., __slots__ was not defined // or __dict__ is in __slots__) let dict = if cls .slots .flags .has_feature(crate::types::PyTypeFlags::HAS_DICT) { Some(vm.ctx.new_dict()) } else { None }; // Ensure that all abstract methods are implemented before instantiating instance. if let Some(abs_methods) = cls.get_attr(identifier!(vm, __abstractmethods__)) && let Some(unimplemented_abstract_method_count) = abs_methods.length_opt(vm) { let methods: Vec<PyStrRef> = abs_methods.try_to_value(vm)?; let methods: String = Itertools::intersperse(methods.iter().map(|name| name.as_str()), "', '").collect(); let unimplemented_abstract_method_count = unimplemented_abstract_method_count?; let name = cls.name().to_string(); match unimplemented_abstract_method_count { 0 => {} 1 => { return Err(vm.new_type_error(format!( "class {name} without an implementation for abstract method '{methods}'" ))); } 2.. => { return Err(vm.new_type_error(format!( "class {name} without an implementation for abstract methods '{methods}'" ))); } // TODO: remove `allow` when redox build doesn't complain about it #[allow(unreachable_patterns)] _ => unreachable!(), } } Ok(crate::PyRef::new_ref(Self, cls, dict).into()) } fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> { unimplemented!("use slot_new") } } impl Initializer for PyBaseObject { type Args = FuncArgs; // object_init: excess_args validation fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { if args.is_empty() { return Ok(()); } let typ = zelf.class(); let object_type = &vm.ctx.types.object_type; let typ_init = typ.slots.init.load().map(|f| f as usize); let object_init = object_type.slots.init.load().map(|f| f as usize); // if (type->tp_init != object_init) → first error if typ_init != object_init { return Err(vm.new_type_error( "object.__init__() takes exactly one argument (the instance to initialize)" .to_owned(), )); } let typ_new = typ.slots.new.load().map(|f| f as usize); let object_new = object_type.slots.new.load().map(|f| f as usize); // if (type->tp_new == object_new) → second error if typ_new == object_new { return Err(vm.new_type_error(format!( "{}.__init__() takes exactly one argument (the instance to initialize)", typ.name() ))); } // Both conditions false → OK (e.g., tuple, dict with custom __new__) Ok(()) } fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> { unreachable!("slot_init is defined") } } // TODO: implement _PyType_GetSlotNames properly fn type_slot_names(typ: &Py<PyType>, vm: &VirtualMachine) -> PyResult<Option<super::PyListRef>> { // let attributes = typ.attributes.read(); // if let Some(slot_names) = attributes.get(identifier!(vm.ctx, __slotnames__)) { // return match_class!(match slot_names.clone() { // l @ super::PyList => Ok(Some(l)), // _n @ super::PyNone => Ok(None), // _ => Err(vm.new_type_error(format!( // "{:.200}.__slotnames__ should be a list or None, not {:.200}", // typ.name(), // slot_names.class().name() // ))), // }); // } let copyreg = vm.import("copyreg", 0)?; let copyreg_slotnames = copyreg.get_attr("_slotnames", vm)?; let slot_names = copyreg_slotnames.call((typ.to_owned(),), vm)?; let result = match_class!(match slot_names { l @ super::PyList => Some(l), _n @ super::PyNone => None, _ => return Err(vm.new_type_error("copyreg._slotnames didn't return a list or None")), }); Ok(result) } // object_getstate_default in CPython fn object_getstate_default(obj: &PyObject, required: bool, vm: &VirtualMachine) -> PyResult { // TODO: itemsize // if required && obj.class().slots.itemsize > 0 { // return vm.new_type_error(format!( // "cannot pickle {:.200} objects", // obj.class().name() // )); // } let state = if obj.dict().is_none_or(|d| d.is_empty()) { vm.ctx.none() } else { // let state = object_get_dict(obj.clone(), obj.ctx()).unwrap(); let Some(state) = obj.dict() else { return Ok(vm.ctx.none()); }; state.into() }; let slot_names = type_slot_names(obj.class(), vm).map_err(|_| vm.new_type_error("cannot pickle object"))?; if required { let mut basicsize = obj.class().slots.basicsize; // if obj.class().slots.dict_offset > 0 // && !obj.class().slots.flags.has_feature(PyTypeFlags::MANAGED_DICT) // { // basicsize += std::mem::size_of::<PyObjectRef>(); // } // if obj.class().slots.weaklist_offset > 0 { // basicsize += std::mem::size_of::<PyObjectRef>(); // } if let Some(ref slot_names) = slot_names { basicsize += core::mem::size_of::<PyObjectRef>() * slot_names.__len__(); } if obj.class().slots.basicsize > basicsize { return Err( vm.new_type_error(format!("cannot pickle {:.200} object", obj.class().name())) ); } } if let Some(slot_names) = slot_names { let slot_names_len = slot_names.__len__(); if slot_names_len > 0 { let slots = vm.ctx.new_dict(); for i in 0..slot_names_len { let borrowed_names = slot_names.borrow_vec(); let name = borrowed_names[i].downcast_ref::<PyStr>().unwrap(); let Ok(value) = obj.get_attr(name, vm) else { continue; }; slots.set_item(name.as_str(), value, vm).unwrap(); } if !slots.is_empty() { return (state, slots).to_pyresult(vm); } } } Ok(state) } // object_getstate in CPython // fn object_getstate( // obj: &PyObject, // required: bool, // vm: &VirtualMachine, // ) -> PyResult { // let getstate = obj.get_attr(identifier!(vm, __getstate__), vm)?; // if vm.is_none(&getstate) { // return Ok(None); // } // let getstate = match getstate.downcast_exact::<PyNativeFunction>(vm) { // Ok(getstate) // if getstate // .get_self() // .map_or(false, |self_obj| self_obj.is(obj)) // && std::ptr::addr_eq( // getstate.as_func() as *const _, // &PyBaseObject::__getstate__ as &dyn crate::function::PyNativeFn as *const _, // ) => // { // return object_getstate_default(obj, required, vm); // } // Ok(getstate) => getstate.into_pyref().into(), // Err(getstate) => getstate, // }; // getstate.call((), vm) // } #[pyclass(with(Constructor, Initializer), flags(BASETYPE))] impl PyBaseObject { #[pymethod(raw)] fn __getstate__(vm: &VirtualMachine, args: FuncArgs) -> PyResult { let (zelf,): (PyObjectRef,) = args.bind(vm)?; object_getstate_default(&zelf, false, vm) } #[pyslot] fn slot_richcompare( zelf: &PyObject, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<Either<PyObjectRef, PyComparisonValue>> { Self::cmp(zelf, other, op, vm).map(Either::B) } #[inline(always)] fn cmp( zelf: &PyObject, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { let res = match op { PyComparisonOp::Eq => { if zelf.is(other) { PyComparisonValue::Implemented(true) } else { PyComparisonValue::NotImplemented } } PyComparisonOp::Ne => { let cmp = zelf.class().slots.richcompare.load().unwrap(); let value = match cmp(zelf, other, PyComparisonOp::Eq, vm)? { Either::A(obj) => PyArithmeticValue::from_object(vm, obj) .map(|obj| obj.try_to_bool(vm)) .transpose()?, Either::B(value) => value, }; value.map(|v| !v) } _ => PyComparisonValue::NotImplemented, }; Ok(res) } /// Implement setattr(self, name, value). #[pymethod] fn __setattr__( obj: PyObjectRef, name: PyStrRef, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { obj.generic_setattr(&name, PySetterValue::Assign(value), vm) } /// Implement delattr(self, name). #[pymethod] fn __delattr__(obj: PyObjectRef, name: PyStrRef, vm: &VirtualMachine) -> PyResult<()> { obj.generic_setattr(&name, PySetterValue::Delete, vm) } #[pyslot] fn slot_setattro( obj: &PyObject, attr_name: &Py<PyStr>, value: PySetterValue, vm: &VirtualMachine, ) -> PyResult<()> { obj.generic_setattr(attr_name, value, vm) } /// Return str(self). #[pyslot] fn slot_str(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyStrRef> { // FIXME: try tp_repr first and fallback to object.__repr__ zelf.repr(vm) } #[pyslot] fn slot_repr(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyStrRef> { let class = zelf.class(); match ( class .__qualname__(vm) .downcast_ref::<PyStr>() .map(|n| n.as_str()), class .__module__(vm) .downcast_ref::<PyStr>() .map(|m| m.as_str()), ) { (None, _) => Err(vm.new_type_error("Unknown qualified name")), (Some(qualname), Some(module)) if module != "builtins" => Ok(PyStr::from(format!( "<{}.{} object at {:#x}>", module, qualname, zelf.get_id() )) .into_ref(&vm.ctx)), _ => Ok(PyStr::from(format!( "<{} object at {:#x}>", class.slot_name(), zelf.get_id() )) .into_ref(&vm.ctx)), } } #[pyclassmethod] fn __subclasshook__(_args: FuncArgs, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.not_implemented() } #[pyclassmethod] fn __init_subclass__(_cls: PyTypeRef) {} #[pymethod] pub fn __dir__(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyList> { obj.dir(vm) } #[pymethod] fn __format__( obj: PyObjectRef, format_spec: PyStrRef, vm: &VirtualMachine, ) -> PyResult<PyStrRef> { if !format_spec.is_empty() { return Err(vm.new_type_error(format!( "unsupported format string passed to {}.__format__", obj.class().name() ))); } obj.str(vm) } #[pygetset] fn __class__(obj: PyObjectRef) -> PyTypeRef { obj.class().to_owned() } #[pygetset(setter)] fn set___class__( instance: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { match value.downcast::<PyType>() { Ok(cls) => { let current_cls = instance.class(); let both_module = current_cls.fast_issubclass(vm.ctx.types.module_type) && cls.fast_issubclass(vm.ctx.types.module_type); let both_mutable = !current_cls .slots .flags .has_feature(PyTypeFlags::IMMUTABLETYPE) && !cls.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE); // FIXME(#1979) cls instances might have a payload if both_mutable || both_module { let has_dict = |typ: &Py<PyType>| typ.slots.flags.has_feature(PyTypeFlags::HAS_DICT); // Compare slots tuples let slots_equal = match ( current_cls .heaptype_ext .as_ref() .and_then(|e| e.slots.as_ref()), cls.heaptype_ext.as_ref().and_then(|e| e.slots.as_ref()), ) { (Some(a), Some(b)) => { a.len() == b.len() && a.iter() .zip(b.iter()) .all(|(x, y)| x.as_str() == y.as_str()) } (None, None) => true, _ => false, }; if current_cls.slots.basicsize != cls.slots.basicsize || !slots_equal || has_dict(current_cls) != has_dict(&cls) { return Err(vm.new_type_error(format!( "__class__ assignment: '{}' object layout differs from '{}'", cls.name(), current_cls.name() ))); } instance.set_class(cls, vm); Ok(()) } else { Err(vm.new_type_error( "__class__ assignment only supported for mutable types or ModuleType subclasses", )) } } Err(value) => { let value_class = value.class(); let type_repr = &value_class.name(); Err(vm.new_type_error(format!( "__class__ must be set to a class, not '{type_repr}' object" ))) } } } /// Return getattr(self, name). #[pyslot] pub(crate) fn getattro(obj: &PyObject, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult { vm_trace!("object.__getattribute__({:?}, {:?})", obj, name); obj.as_object().generic_getattr(name, vm) } #[pymethod] fn __getattribute__(obj: PyObjectRef, name: PyStrRef, vm: &VirtualMachine) -> PyResult { Self::getattro(&obj, &name, vm) } #[pymethod] fn __reduce__(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { common_reduce(obj, 0, vm) } #[pymethod] fn __reduce_ex__(obj: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResult { let __reduce__ = identifier!(vm, __reduce__); if let Some(reduce) = vm.get_attribute_opt(obj.clone(), __reduce__)? { let object_reduce = vm.ctx.types.object_type.get_attr(__reduce__).unwrap(); let typ_obj: PyObjectRef = obj.class().to_owned().into(); let class_reduce = typ_obj.get_attr(__reduce__, vm)?; if !class_reduce.is(&object_reduce) { return reduce.call((), vm); } } common_reduce(obj, proto, vm) } #[pyslot] fn slot_hash(zelf: &PyObject, _vm: &VirtualMachine) -> PyResult<PyHash> { Ok(zelf.get_id() as _) } #[pymethod] fn __sizeof__(zelf: PyObjectRef) -> usize { zelf.class().slots.basicsize } } pub fn object_get_dict(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyDictRef> { obj.dict() .ok_or_else(|| vm.new_attribute_error("This object has no __dict__")) } pub fn object_set_dict(obj: PyObjectRef, dict: PyDictRef, vm: &VirtualMachine) -> PyResult<()> { obj.set_dict(dict) .map_err(|_| vm.new_attribute_error("This object has no __dict__")) } pub fn init(ctx: &Context) { // Manually set init slot - derive macro doesn't generate extend_slots // for trait impl that overrides #[pyslot] method ctx.types .object_type .slots .init .store(Some(<PyBaseObject as Initializer>::slot_init)); PyBaseObject::extend_class(ctx, ctx.types.object_type); } fn common_reduce(obj: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResult { if proto >= 2 { let reducelib = vm.import("__reducelib", 0)?; let reduce_2 = reducelib.get_attr("reduce_2", vm)?; reduce_2.call((obj,), vm) } else { let copyreg = vm.import("copyreg", 0)?; let reduce_ex = copyreg.get_attr("_reduce_ex", vm)?; reduce_ex.call((obj, proto), vm) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/bytes.rs
crates/vm/src/builtins/bytes.rs
use super::{ PositionIterInternal, PyDictRef, PyGenericAlias, PyIntRef, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine, anystr::{self, AnyStr}, atomic_func, bytes_inner::{ ByteInnerFindOptions, ByteInnerNewOptions, ByteInnerPaddingOptions, ByteInnerSplitOptions, ByteInnerTranslateOptions, DecodeArgs, PyBytesInner, bytes_decode, }, class::PyClassImpl, common::{hash::PyHash, lock::PyMutex}, convert::{ToPyObject, ToPyResult}, function::{ ArgBytesLike, ArgIndex, ArgIterable, Either, FuncArgs, OptionalArg, OptionalOption, PyComparisonValue, }, protocol::{ BufferDescriptor, BufferMethods, PyBuffer, PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods, }, sliceable::{SequenceIndex, SliceableSequenceOp}, types::{ AsBuffer, AsMapping, AsNumber, AsSequence, Callable, Comparable, Constructor, Hashable, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, }, }; use bstr::ByteSlice; use core::{mem::size_of, ops::Deref}; use std::sync::LazyLock; #[pyclass(module = false, name = "bytes")] #[derive(Clone, Debug)] pub struct PyBytes { inner: PyBytesInner, } pub type PyBytesRef = PyRef<PyBytes>; impl From<Vec<u8>> for PyBytes { fn from(elements: Vec<u8>) -> Self { Self { inner: PyBytesInner { elements }, } } } impl From<PyBytesInner> for PyBytes { fn from(inner: PyBytesInner) -> Self { Self { inner } } } impl ToPyObject for Vec<u8> { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.new_bytes(self).into() } } impl Deref for PyBytes { type Target = [u8]; fn deref(&self) -> &[u8] { self.as_bytes() } } impl AsRef<[u8]> for PyBytes { fn as_ref(&self) -> &[u8] { self.as_bytes() } } impl AsRef<[u8]> for PyBytesRef { fn as_ref(&self) -> &[u8] { self.as_bytes() } } impl PyPayload for PyBytes { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.bytes_type } } pub(crate) fn init(context: &Context) { PyBytes::extend_class(context, context.types.bytes_type); PyBytesIterator::extend_class(context, context.types.bytes_iterator_type); } impl Constructor for PyBytes { type Args = Vec<u8>; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let options: ByteInnerNewOptions = args.bind(vm)?; // Optimizations for exact bytes type if cls.is(vm.ctx.types.bytes_type) { // Return empty bytes singleton if options.source.is_missing() && options.encoding.is_missing() && options.errors.is_missing() { return Ok(vm.ctx.empty_bytes.clone().into()); } // Return exact bytes as-is if let OptionalArg::Present(ref obj) = options.source && options.encoding.is_missing() && options.errors.is_missing() && let Ok(b) = obj.clone().downcast_exact::<PyBytes>(vm) { return Ok(b.into_pyref().into()); } } // Handle __bytes__ method - may return PyBytes directly if let OptionalArg::Present(ref obj) = options.source && options.encoding.is_missing() && options.errors.is_missing() && let Some(bytes_method) = vm.get_method(obj.clone(), identifier!(vm, __bytes__)) { let bytes = bytes_method?.call((), vm)?; // If exact bytes type and __bytes__ returns bytes, use it directly if cls.is(vm.ctx.types.bytes_type) && let Ok(b) = bytes.clone().downcast::<PyBytes>() { return Ok(b.into()); } // Otherwise convert to Vec<u8> let inner = PyBytesInner::try_from_borrowed_object(vm, &bytes)?; let payload = Self::py_new(&cls, inner.elements, vm)?; return payload.into_ref_with_type(vm, cls).map(Into::into); } // Fallback to get_bytearray_inner let elements = options.get_bytearray_inner(vm)?.elements; // Return empty bytes singleton for exact bytes types if elements.is_empty() && cls.is(vm.ctx.types.bytes_type) { return Ok(vm.ctx.empty_bytes.clone().into()); } let payload = Self::py_new(&cls, elements, vm)?; payload.into_ref_with_type(vm, cls).map(Into::into) } fn py_new(_cls: &Py<PyType>, elements: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> { Ok(Self::from(elements)) } } impl PyBytes { #[deprecated(note = "use PyBytes::from(...).into_ref() instead")] pub fn new_ref(data: Vec<u8>, ctx: &Context) -> PyRef<Self> { Self::from(data).into_ref(ctx) } fn _getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { match SequenceIndex::try_from_borrowed_object(vm, needle, "byte")? { SequenceIndex::Int(i) => self .getitem_by_index(vm, i) .map(|x| vm.ctx.new_int(x).into()), SequenceIndex::Slice(slice) => self .getitem_by_slice(vm, slice) .map(|x| vm.ctx.new_bytes(x).into()), } } } impl PyRef<PyBytes> { fn repeat(self, count: isize, vm: &VirtualMachine) -> PyResult<Self> { if count == 1 && self.class().is(vm.ctx.types.bytes_type) { // Special case: when some `bytes` is multiplied by `1`, // nothing really happens, we need to return an object itself // with the same `id()` to be compatible with CPython. // This only works for `bytes` itself, not its subclasses. return Ok(self); } self.inner .mul(count, vm) .map(|x| PyBytes::from(x).into_ref(&vm.ctx)) } } #[pyclass( itemsize = 1, flags(BASETYPE, _MATCH_SELF), with( Py, PyRef, AsMapping, AsSequence, Hashable, Comparable, AsBuffer, Iterable, Constructor, AsNumber, Representable, ) )] impl PyBytes { #[inline] pub const fn __len__(&self) -> usize { self.inner.len() } #[inline] pub const fn is_empty(&self) -> bool { self.inner.is_empty() } #[inline] pub fn as_bytes(&self) -> &[u8] { self.inner.as_bytes() } #[pymethod] fn __sizeof__(&self) -> usize { size_of::<Self>() + self.len() * size_of::<u8>() } fn __add__(&self, other: ArgBytesLike) -> Vec<u8> { self.inner.add(&other.borrow_buf()) } fn __contains__( &self, needle: Either<PyBytesInner, PyIntRef>, vm: &VirtualMachine, ) -> PyResult<bool> { self.inner.contains(needle, vm) } #[pystaticmethod] fn maketrans(from: PyBytesInner, to: PyBytesInner, vm: &VirtualMachine) -> PyResult<Vec<u8>> { PyBytesInner::maketrans(from, to, vm) } fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { self._getitem(&needle, vm) } #[pymethod] fn isalnum(&self) -> bool { self.inner.isalnum() } #[pymethod] fn isalpha(&self) -> bool { self.inner.isalpha() } #[pymethod] fn isascii(&self) -> bool { self.inner.isascii() } #[pymethod] fn isdigit(&self) -> bool { self.inner.isdigit() } #[pymethod] fn islower(&self) -> bool { self.inner.islower() } #[pymethod] fn isspace(&self) -> bool { self.inner.isspace() } #[pymethod] fn isupper(&self) -> bool { self.inner.isupper() } #[pymethod] fn istitle(&self) -> bool { self.inner.istitle() } #[pymethod] fn lower(&self) -> Self { self.inner.lower().into() } #[pymethod] fn upper(&self) -> Self { self.inner.upper().into() } #[pymethod] fn capitalize(&self) -> Self { self.inner.capitalize().into() } #[pymethod] fn swapcase(&self) -> Self { self.inner.swapcase().into() } #[pymethod] pub(crate) fn hex( &self, sep: OptionalArg<Either<PyStrRef, PyBytesRef>>, bytes_per_sep: OptionalArg<isize>, vm: &VirtualMachine, ) -> PyResult<String> { self.inner.hex(sep, bytes_per_sep, vm) } #[pyclassmethod] fn fromhex(cls: PyTypeRef, string: PyStrRef, vm: &VirtualMachine) -> PyResult { let bytes = PyBytesInner::fromhex(string.as_bytes(), vm)?; let bytes = vm.ctx.new_bytes(bytes).into(); PyType::call(&cls, vec![bytes].into(), vm) } #[pymethod] fn center(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<Self> { Ok(self.inner.center(options, vm)?.into()) } #[pymethod] fn ljust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<Self> { Ok(self.inner.ljust(options, vm)?.into()) } #[pymethod] fn rjust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<Self> { Ok(self.inner.rjust(options, vm)?.into()) } #[pymethod] fn count(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> { self.inner.count(options, vm) } #[pymethod] fn join(&self, iter: ArgIterable<PyBytesInner>, vm: &VirtualMachine) -> PyResult<Self> { Ok(self.inner.join(iter, vm)?.into()) } #[pymethod] fn endswith(&self, options: anystr::StartsEndsWithArgs, vm: &VirtualMachine) -> PyResult<bool> { let (affix, substr) = match options.prepare(self.as_bytes(), self.len(), |s, r| s.get_bytes(r)) { Some(x) => x, None => return Ok(false), }; substr.py_starts_ends_with( &affix, "endswith", "bytes", |s, x: PyBytesInner| s.ends_with(x.as_bytes()), vm, ) } #[pymethod] fn startswith( &self, options: anystr::StartsEndsWithArgs, vm: &VirtualMachine, ) -> PyResult<bool> { let (affix, substr) = match options.prepare(self.as_bytes(), self.len(), |s, r| s.get_bytes(r)) { Some(x) => x, None => return Ok(false), }; substr.py_starts_ends_with( &affix, "startswith", "bytes", |s, x: PyBytesInner| s.starts_with(x.as_bytes()), vm, ) } #[pymethod] fn find(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<isize> { let index = self.inner.find(options, |h, n| h.find(n), vm)?; Ok(index.map_or(-1, |v| v as isize)) } #[pymethod] fn index(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> { let index = self.inner.find(options, |h, n| h.find(n), vm)?; index.ok_or_else(|| vm.new_value_error("substring not found")) } #[pymethod] fn rfind(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<isize> { let index = self.inner.find(options, |h, n| h.rfind(n), vm)?; Ok(index.map_or(-1, |v| v as isize)) } #[pymethod] fn rindex(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> { let index = self.inner.find(options, |h, n| h.rfind(n), vm)?; index.ok_or_else(|| vm.new_value_error("substring not found")) } #[pymethod] fn translate(&self, options: ByteInnerTranslateOptions, vm: &VirtualMachine) -> PyResult<Self> { Ok(self.inner.translate(options, vm)?.into()) } #[pymethod] fn strip(&self, chars: OptionalOption<PyBytesInner>) -> Self { self.inner.strip(chars).into() } #[pymethod] fn removeprefix(&self, prefix: PyBytesInner) -> Self { self.inner.removeprefix(prefix).into() } #[pymethod] fn removesuffix(&self, suffix: PyBytesInner) -> Self { self.inner.removesuffix(suffix).into() } #[pymethod] fn split( &self, options: ByteInnerSplitOptions, vm: &VirtualMachine, ) -> PyResult<Vec<PyObjectRef>> { self.inner .split(options, |s, vm| vm.ctx.new_bytes(s.to_vec()).into(), vm) } #[pymethod] fn rsplit( &self, options: ByteInnerSplitOptions, vm: &VirtualMachine, ) -> PyResult<Vec<PyObjectRef>> { self.inner .rsplit(options, |s, vm| vm.ctx.new_bytes(s.to_vec()).into(), vm) } #[pymethod] fn partition(&self, sep: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyTupleRef> { let sub = PyBytesInner::try_from_borrowed_object(vm, &sep)?; let (front, has_mid, back) = self.inner.partition(&sub, vm)?; Ok(vm.new_tuple(( vm.ctx.new_bytes(front), if has_mid { sep } else { vm.ctx.new_bytes(Vec::new()).into() }, vm.ctx.new_bytes(back), ))) } #[pymethod] fn rpartition(&self, sep: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyTupleRef> { let sub = PyBytesInner::try_from_borrowed_object(vm, &sep)?; let (back, has_mid, front) = self.inner.rpartition(&sub, vm)?; Ok(vm.new_tuple(( vm.ctx.new_bytes(front), if has_mid { sep } else { vm.ctx.new_bytes(Vec::new()).into() }, vm.ctx.new_bytes(back), ))) } #[pymethod] fn expandtabs(&self, options: anystr::ExpandTabsArgs) -> Self { self.inner.expandtabs(options).into() } #[pymethod] fn splitlines(&self, options: anystr::SplitLinesArgs, vm: &VirtualMachine) -> Vec<PyObjectRef> { self.inner .splitlines(options, |x| vm.ctx.new_bytes(x.to_vec()).into()) } #[pymethod] fn zfill(&self, width: isize) -> Self { self.inner.zfill(width).into() } #[pymethod] fn replace( &self, old: PyBytesInner, new: PyBytesInner, count: OptionalArg<isize>, vm: &VirtualMachine, ) -> PyResult<Self> { Ok(self.inner.replace(old, new, count, vm)?.into()) } #[pymethod] fn title(&self) -> Self { self.inner.title().into() } fn __mul__(zelf: PyRef<Self>, value: ArgIndex, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { zelf.repeat(value.into_int_ref().try_to_primitive(vm)?, vm) } fn __mod__(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> { let formatted = self.inner.cformat(values, vm)?; Ok(formatted.into()) } #[pymethod] fn __getnewargs__(&self, vm: &VirtualMachine) -> PyTupleRef { let param: Vec<PyObjectRef> = self.elements().map(|x| x.to_pyobject(vm)).collect(); PyTuple::new_ref(param, &vm.ctx) } // TODO: Uncomment when Python adds __class_getitem__ to bytes // #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } #[pyclass] impl Py<PyBytes> { #[pymethod] fn __reduce_ex__( &self, _proto: usize, vm: &VirtualMachine, ) -> (PyTypeRef, PyTupleRef, Option<PyDictRef>) { self.__reduce__(vm) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef, Option<PyDictRef>) { let bytes = PyBytes::from(self.to_vec()).to_pyobject(vm); ( self.class().to_owned(), PyTuple::new_ref(vec![bytes], &vm.ctx), self.as_object().dict(), ) } } #[pyclass] impl PyRef<PyBytes> { #[pymethod] fn __bytes__(self, vm: &VirtualMachine) -> Self { if self.is(vm.ctx.types.bytes_type) { self } else { PyBytes::from(self.inner.clone()).into_ref(&vm.ctx) } } #[pymethod] fn lstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self { let stripped = self.inner.lstrip(chars); if stripped == self.as_bytes() { self } else { vm.ctx.new_bytes(stripped.to_vec()) } } #[pymethod] fn rstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self { let stripped = self.inner.rstrip(chars); if stripped == self.as_bytes() { self } else { vm.ctx.new_bytes(stripped.to_vec()) } } /// Return a string decoded from the given bytes. /// Default encoding is 'utf-8'. /// Default errors is 'strict', meaning that encoding errors raise a UnicodeError. /// Other possible values are 'ignore', 'replace' /// For a list of possible encodings, /// see https://docs.python.org/3/library/codecs.html#standard-encodings /// currently, only 'utf-8' and 'ascii' implemented #[pymethod] fn decode(self, args: DecodeArgs, vm: &VirtualMachine) -> PyResult<PyStrRef> { bytes_decode(self.into(), args, vm) } } static BUFFER_METHODS: BufferMethods = BufferMethods { obj_bytes: |buffer| buffer.obj_as::<PyBytes>().as_bytes().into(), obj_bytes_mut: |_| panic!(), release: |_| {}, retain: |_| {}, }; impl AsBuffer for PyBytes { fn as_buffer(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyBuffer> { let buf = PyBuffer::new( zelf.to_owned().into(), BufferDescriptor::simple(zelf.len(), true), &BUFFER_METHODS, ); Ok(buf) } } impl AsMapping for PyBytes { fn as_mapping() -> &'static PyMappingMethods { static AS_MAPPING: LazyLock<PyMappingMethods> = LazyLock::new(|| PyMappingMethods { length: atomic_func!(|mapping, _vm| Ok(PyBytes::mapping_downcast(mapping).len())), subscript: atomic_func!( |mapping, needle, vm| PyBytes::mapping_downcast(mapping)._getitem(needle, vm) ), ..PyMappingMethods::NOT_IMPLEMENTED }); &AS_MAPPING } } impl AsSequence for PyBytes { fn as_sequence() -> &'static PySequenceMethods { static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods { length: atomic_func!(|seq, _vm| Ok(PyBytes::sequence_downcast(seq).len())), concat: atomic_func!(|seq, other, vm| { PyBytes::sequence_downcast(seq) .inner .concat(other, vm) .map(|x| vm.ctx.new_bytes(x).into()) }), repeat: atomic_func!(|seq, n, vm| { let zelf = seq.obj.to_owned().downcast::<PyBytes>().map_err(|_| { vm.new_type_error("bad argument type for built-in operation".to_owned()) })?; zelf.repeat(n, vm).to_pyresult(vm) }), item: atomic_func!(|seq, i, vm| { PyBytes::sequence_downcast(seq) .as_bytes() .getitem_by_index(vm, i) .map(|x| vm.ctx.new_bytes(vec![x]).into()) }), contains: atomic_func!(|seq, other, vm| { let other = <Either<PyBytesInner, PyIntRef>>::try_from_object(vm, other.to_owned())?; PyBytes::sequence_downcast(seq).__contains__(other, vm) }), ..PySequenceMethods::NOT_IMPLEMENTED }); &AS_SEQUENCE } } impl AsNumber for PyBytes { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { remainder: Some(|a, b, vm| { if let Some(a) = a.downcast_ref::<PyBytes>() { a.__mod__(b.to_owned(), vm).to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } }), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } } impl Hashable for PyBytes { #[inline] fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> { Ok(zelf.inner.hash(vm)) } } impl Comparable for PyBytes { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { Ok(if let Some(res) = op.identical_optimization(zelf, other) { res.into() } else if other.fast_isinstance(vm.ctx.types.memoryview_type) && op != PyComparisonOp::Eq && op != PyComparisonOp::Ne { return Err(vm.new_type_error(format!( "'{}' not supported between instances of '{}' and '{}'", op.operator_token(), zelf.class().name(), other.class().name() ))); } else { zelf.inner.cmp(other, op, vm) }) } } impl Iterable for PyBytes { fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { Ok(PyBytesIterator { internal: PyMutex::new(PositionIterInternal::new(zelf, 0)), } .into_pyobject(vm)) } } impl Representable for PyBytes { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { zelf.inner.repr_bytes(vm) } } #[pyclass(module = false, name = "bytes_iterator")] #[derive(Debug)] pub struct PyBytesIterator { internal: PyMutex<PositionIterInternal<PyBytesRef>>, } impl PyPayload for PyBytesIterator { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.bytes_iterator_type } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] impl PyBytesIterator { #[pymethod] fn __length_hint__(&self) -> usize { self.internal.lock().length_hint(|obj| obj.len()) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef { self.internal .lock() .builtins_iter_reduce(|x| x.clone().into(), vm) } #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal .lock() .set_state(state, |obj, pos| pos.min(obj.len()), vm) } } impl SelfIter for PyBytesIterator {} impl IterNext for PyBytesIterator { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { zelf.internal.lock().next(|bytes, pos| { Ok(PyIterReturn::from_result( bytes .as_bytes() .get(pos) .map(|&x| vm.new_pyobj(x)) .ok_or(None), )) }) } } impl<'a> TryFromBorrowedObject<'a> for PyBytes { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> { PyBytesInner::try_from_borrowed_object(vm, obj).map(|x| x.into()) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/complex.rs
crates/vm/src/builtins/complex.rs
use super::{PyStr, PyType, PyTypeRef, float}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::PyStrRef, class::PyClassImpl, common::format::FormatSpec, convert::{IntoPyException, ToPyObject, ToPyResult}, function::{FuncArgs, OptionalArg, PyComparisonValue}, protocol::PyNumberMethods, stdlib::warnings, types::{AsNumber, Comparable, Constructor, Hashable, PyComparisonOp, Representable}, }; use core::num::Wrapping; use num_complex::Complex64; use num_traits::Zero; use rustpython_common::hash; /// Create a complex number from a real part and an optional imaginary part. /// /// This is equivalent to (real + imag*1j) where imag defaults to 0. #[pyclass(module = false, name = "complex")] #[derive(Debug, Copy, Clone, PartialEq)] pub struct PyComplex { value: Complex64, } impl PyPayload for PyComplex { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.complex_type } } impl ToPyObject for Complex64 { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { PyComplex::from(self).to_pyobject(vm) } } impl From<Complex64> for PyComplex { fn from(value: Complex64) -> Self { Self { value } } } impl PyObjectRef { /// Tries converting a python object into a complex, returns an option of whether the complex /// and whether the object was a complex originally or coerced into one pub fn try_complex(&self, vm: &VirtualMachine) -> PyResult<Option<(Complex64, bool)>> { if let Some(complex) = self.downcast_ref_if_exact::<PyComplex>(vm) { return Ok(Some((complex.value, true))); } if let Some(method) = vm.get_method(self.clone(), identifier!(vm, __complex__)) { let result = method?.call((), vm)?; let ret_class = result.class().to_owned(); if let Some(ret) = result.downcast_ref::<PyComplex>() { warnings::warn( vm.ctx.exceptions.deprecation_warning, format!( "__complex__ returned non-complex (type {ret_class}). \ The ability to return an instance of a strict subclass of complex \ is deprecated, and may be removed in a future version of Python." ), 1, vm, )?; return Ok(Some((ret.value, true))); } else { return match result.downcast_ref::<PyComplex>() { Some(complex_obj) => Ok(Some((complex_obj.value, true))), None => Err(vm.new_type_error(format!( "__complex__ returned non-complex (type '{}')", result.class().name() ))), }; } } // `complex` does not have a `__complex__` by default, so subclasses might not either, // use the actual stored value in this case if let Some(complex) = self.downcast_ref::<PyComplex>() { return Ok(Some((complex.value, true))); } if let Some(float) = self.try_float_opt(vm) { return Ok(Some((Complex64::new(float?.to_f64(), 0.0), false))); } Ok(None) } } pub fn init(context: &Context) { PyComplex::extend_class(context, context.types.complex_type); } fn to_op_complex(value: &PyObject, vm: &VirtualMachine) -> PyResult<Option<Complex64>> { let r = if let Some(complex) = value.downcast_ref::<PyComplex>() { Some(complex.value) } else { float::to_op_float(value, vm)?.map(|float| Complex64::new(float, 0.0)) }; Ok(r) } fn inner_div(v1: Complex64, v2: Complex64, vm: &VirtualMachine) -> PyResult<Complex64> { if v2.is_zero() { return Err(vm.new_zero_division_error("complex division by zero")); } Ok(v1.fdiv(v2)) } fn inner_pow(v1: Complex64, v2: Complex64, vm: &VirtualMachine) -> PyResult<Complex64> { if v1.is_zero() { return if v2.re < 0.0 || v2.im != 0.0 { let msg = format!("{v1} cannot be raised to a negative or complex power"); Err(vm.new_zero_division_error(msg)) } else if v2.is_zero() { Ok(Complex64::new(1.0, 0.0)) } else { Ok(Complex64::new(0.0, 0.0)) }; } let ans = powc(v1, v2); if ans.is_infinite() && !(v1.is_infinite() || v2.is_infinite()) { Err(vm.new_overflow_error("complex exponentiation overflow")) } else { Ok(ans) } } // num-complex changed their powc() implementation in 0.4.4, making it incompatible // with what the regression tests expect. this is that old formula. fn powc(a: Complex64, exp: Complex64) -> Complex64 { let (r, theta) = a.to_polar(); if r.is_zero() { return Complex64::new(r, r); } Complex64::from_polar( r.powf(exp.re) * (-exp.im * theta).exp(), exp.re * theta + exp.im * r.ln(), ) } impl Constructor for PyComplex { type Args = ComplexArgs; fn slot_new(cls: PyTypeRef, func_args: FuncArgs, vm: &VirtualMachine) -> PyResult { // Optimization: return exact complex as-is (only when imag is not provided) if cls.is(vm.ctx.types.complex_type) && func_args.args.len() == 1 && func_args.kwargs.is_empty() && func_args.args[0].class().is(vm.ctx.types.complex_type) { return Ok(func_args.args[0].clone()); } let args: Self::Args = func_args.bind(vm)?; let payload = Self::py_new(&cls, args, vm)?; payload.into_ref_with_type(vm, cls).map(Into::into) } fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> { let imag_missing = args.imag.is_missing(); let (real, real_was_complex) = match args.real { OptionalArg::Missing => (Complex64::new(0.0, 0.0), false), OptionalArg::Present(val) => { if let Some(c) = val.try_complex(vm)? { c } else if let Some(s) = val.downcast_ref::<PyStr>() { if args.imag.is_present() { return Err(vm.new_type_error( "complex() can't take second arg if first is a string", )); } let (re, im) = s .to_str() .and_then(rustpython_literal::complex::parse_str) .ok_or_else(|| vm.new_value_error("complex() arg is a malformed string"))?; return Ok(Self::from(Complex64 { re, im })); } else { return Err(vm.new_type_error(format!( "complex() first argument must be a string or a number, not '{}'", val.class().name() ))); } } }; let (imag, imag_was_complex) = match args.imag { // Copy the imaginary from the real to the real of the imaginary // if an imaginary argument is not passed in OptionalArg::Missing => (Complex64::new(real.im, 0.0), false), OptionalArg::Present(obj) => { if let Some(c) = obj.try_complex(vm)? { c } else if obj.class().fast_issubclass(vm.ctx.types.str_type) { return Err(vm.new_type_error("complex() second arg can't be a string")); } else { return Err(vm.new_type_error(format!( "complex() second argument must be a number, not '{}'", obj.class().name() ))); } } }; let final_real = if imag_was_complex { real.re - imag.im } else { real.re }; let final_imag = if real_was_complex && !imag_missing { imag.re + real.im } else { imag.re }; let value = Complex64::new(final_real, final_imag); Ok(Self::from(value)) } } impl PyComplex { #[deprecated(note = "use PyComplex::from(...).into_ref() instead")] pub fn new_ref(value: Complex64, ctx: &Context) -> PyRef<Self> { Self::from(value).into_ref(ctx) } pub const fn to_complex64(self) -> Complex64 { self.value } pub const fn to_complex(&self) -> Complex64 { self.value } fn number_op<F, R>(a: &PyObject, b: &PyObject, op: F, vm: &VirtualMachine) -> PyResult where F: FnOnce(Complex64, Complex64, &VirtualMachine) -> R, R: ToPyResult, { if let (Some(a), Some(b)) = (to_op_complex(a, vm)?, to_op_complex(b, vm)?) { op(a, b, vm).to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } } } #[pyclass( flags(BASETYPE), with(PyRef, Comparable, Hashable, Constructor, AsNumber, Representable) )] impl PyComplex { #[pygetset] const fn real(&self) -> f64 { self.value.re } #[pygetset] const fn imag(&self) -> f64 { self.value.im } #[pymethod] fn conjugate(&self) -> Complex64 { self.value.conj() } #[pymethod] const fn __getnewargs__(&self) -> (f64, f64) { let Complex64 { re, im } = self.value; (re, im) } #[pymethod] fn __format__(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> { FormatSpec::parse(spec.as_str()) .and_then(|format_spec| format_spec.format_complex(&self.value)) .map_err(|err| err.into_pyexception(vm)) } } #[pyclass] impl PyRef<PyComplex> { #[pymethod] fn __complex__(self, vm: &VirtualMachine) -> Self { if self.is(vm.ctx.types.complex_type) { self } else { PyComplex::from(self.value).into_ref(&vm.ctx) } } } impl Comparable for PyComplex { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { op.eq_only(|| { let result = if let Some(other) = other.downcast_ref::<Self>() { if zelf.value.re.is_nan() && zelf.value.im.is_nan() && other.value.re.is_nan() && other.value.im.is_nan() { true } else { zelf.value == other.value } } else { match float::to_op_float(other, vm) { Ok(Some(other)) => zelf.value == other.into(), Err(_) => false, Ok(None) => return Ok(PyComparisonValue::NotImplemented), } }; Ok(PyComparisonValue::Implemented(result)) }) } } impl Hashable for PyComplex { #[inline] fn hash(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<hash::PyHash> { let value = zelf.value; let re_hash = hash::hash_float(value.re).unwrap_or_else(|| hash::hash_object_id(zelf.get_id())); let im_hash = hash::hash_float(value.im).unwrap_or_else(|| hash::hash_object_id(zelf.get_id())); let Wrapping(ret) = Wrapping(re_hash) + Wrapping(im_hash) * Wrapping(hash::IMAG); Ok(hash::fix_sentinel(ret)) } } impl AsNumber for PyComplex { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { add: Some(|a, b, vm| PyComplex::number_op(a, b, |a, b, _vm| a + b, vm)), subtract: Some(|a, b, vm| PyComplex::number_op(a, b, |a, b, _vm| a - b, vm)), multiply: Some(|a, b, vm| PyComplex::number_op(a, b, |a, b, _vm| a * b, vm)), power: Some(|a, b, c, vm| { if vm.is_none(c) { PyComplex::number_op(a, b, inner_pow, vm) } else { Err(vm.new_value_error(String::from("complex modulo"))) } }), negative: Some(|number, vm| { let value = PyComplex::number_downcast(number).value; (-value).to_pyresult(vm) }), positive: Some(|number, vm| { PyComplex::number_downcast_exact(number, vm).to_pyresult(vm) }), absolute: Some(|number, vm| { let value = PyComplex::number_downcast(number).value; let result = value.norm(); // Check for overflow: hypot returns inf for finite inputs that overflow if result.is_infinite() && value.re.is_finite() && value.im.is_finite() { return Err(vm.new_overflow_error("absolute value too large".to_owned())); } result.to_pyresult(vm) }), boolean: Some(|number, _vm| Ok(!PyComplex::number_downcast(number).value.is_zero())), true_divide: Some(|a, b, vm| PyComplex::number_op(a, b, inner_div, vm)), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } fn clone_exact(zelf: &Py<Self>, vm: &VirtualMachine) -> PyRef<Self> { vm.ctx.new_complex(zelf.value) } } impl Representable for PyComplex { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { // TODO: when you fix this, move it to rustpython_common::complex::repr and update // ast/src/unparse.rs + impl Display for Constant in ast/src/constant.rs let Complex64 { re, im } = zelf.value; Ok(rustpython_literal::complex::to_string(re, im)) } } #[derive(FromArgs)] pub struct ComplexArgs { #[pyarg(any, optional)] real: OptionalArg<PyObjectRef>, #[pyarg(any, optional)] imag: OptionalArg<PyObjectRef>, }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/range.rs
crates/vm/src/builtins/range.rs
use super::{ PyGenericAlias, PyInt, PyIntRef, PySlice, PyTupleRef, PyType, PyTypeRef, builtins_iter, tuple::tuple_hash, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, atomic_func, class::PyClassImpl, common::hash::PyHash, function::{ArgIndex, FuncArgs, OptionalArg, PyComparisonValue}, protocol::{PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods}, types::{ AsMapping, AsNumber, AsSequence, Comparable, Hashable, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, }, }; use core::cmp::max; use crossbeam_utils::atomic::AtomicCell; use malachite_bigint::{BigInt, Sign}; use num_integer::Integer; use num_traits::{One, Signed, ToPrimitive, Zero}; use std::sync::LazyLock; // Search flag passed to iter_search enum SearchType { Count, Contains, Index, } #[inline] fn iter_search( obj: &PyObject, item: &PyObject, flag: SearchType, vm: &VirtualMachine, ) -> PyResult<usize> { let mut count = 0; let iter = obj.get_iter(vm)?; for element in iter.iter_without_hint::<PyObjectRef>(vm)? { if vm.bool_eq(item, &*element?)? { match flag { SearchType::Index => return Ok(count), SearchType::Contains => return Ok(1), SearchType::Count => count += 1, } } } match flag { SearchType::Count => Ok(count), SearchType::Contains => Ok(0), SearchType::Index => Err(vm.new_value_error(format!( "{} not in range", item.repr(vm) .map(|v| v.as_str().to_owned()) .unwrap_or_else(|_| "value".to_owned()) ))), } } #[pyclass(module = false, name = "range")] #[derive(Debug, Clone)] pub struct PyRange { pub start: PyIntRef, pub stop: PyIntRef, pub step: PyIntRef, } impl PyPayload for PyRange { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.range_type } } impl PyRange { #[inline] fn offset(&self, value: &BigInt) -> Option<BigInt> { let start = self.start.as_bigint(); let stop = self.stop.as_bigint(); let step = self.step.as_bigint(); match step.sign() { Sign::Plus if value >= start && value < stop => Some(value - start), Sign::Minus if value <= self.start.as_bigint() && value > stop => Some(start - value), _ => None, } } #[inline] pub fn index_of(&self, value: &BigInt) -> Option<BigInt> { let step = self.step.as_bigint(); match self.offset(value) { Some(ref offset) if offset.is_multiple_of(step) => Some((offset / step).abs()), Some(_) | None => None, } } #[inline] pub fn is_empty(&self) -> bool { self.compute_length().is_zero() } #[inline] pub fn forward(&self) -> bool { self.start.as_bigint() < self.stop.as_bigint() } #[inline] pub fn get(&self, index: &BigInt) -> Option<BigInt> { let start = self.start.as_bigint(); let step = self.step.as_bigint(); let stop = self.stop.as_bigint(); if self.is_empty() { return None; } if index.is_negative() { let length = self.compute_length(); let index: BigInt = &length + index; if index.is_negative() { return None; } Some(if step.is_one() { start + index } else { start + step * index }) } else { let index = if step.is_one() { start + index } else { start + step * index }; if (step.is_positive() && stop > &index) || (step.is_negative() && stop < &index) { Some(index) } else { None } } } #[inline] fn compute_length(&self) -> BigInt { let start = self.start.as_bigint(); let stop = self.stop.as_bigint(); let step = self.step.as_bigint(); match step.sign() { Sign::Plus if start < stop => { if step.is_one() { stop - start } else { (stop - start - 1usize) / step + 1 } } Sign::Minus if start > stop => (start - stop - 1usize) / (-step) + 1, Sign::Plus | Sign::Minus => BigInt::zero(), Sign::NoSign => unreachable!(), } } } // pub fn get_value(obj: &PyObject) -> PyRange { // obj.downcast_ref::<PyRange>().unwrap().clone() // } pub fn init(context: &Context) { PyRange::extend_class(context, context.types.range_type); PyLongRangeIterator::extend_class(context, context.types.long_range_iterator_type); PyRangeIterator::extend_class(context, context.types.range_iterator_type); } #[pyclass( with( Py, AsMapping, AsNumber, AsSequence, Hashable, Comparable, Iterable, Representable ), flags(SEQUENCE) )] impl PyRange { fn new(cls: PyTypeRef, stop: ArgIndex, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { Self { start: vm.ctx.new_pyref(0), stop: stop.into(), step: vm.ctx.new_pyref(1), } .into_ref_with_type(vm, cls) } fn new_from( cls: PyTypeRef, start: PyObjectRef, stop: PyObjectRef, step: OptionalArg<ArgIndex>, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let step = step.map_or_else(|| vm.ctx.new_int(1), |step| step.into()); if step.as_bigint().is_zero() { return Err(vm.new_value_error("range() arg 3 must not be zero")); } Self { start: start.try_index(vm)?, stop: stop.try_index(vm)?, step, } .into_ref_with_type(vm, cls) } #[pygetset] fn start(&self) -> PyIntRef { self.start.clone() } #[pygetset] fn stop(&self) -> PyIntRef { self.stop.clone() } #[pygetset] fn step(&self) -> PyIntRef { self.step.clone() } #[pymethod] fn __reversed__(&self, vm: &VirtualMachine) -> PyResult { let start = self.start.as_bigint(); let step = self.step.as_bigint(); // Use CPython calculation for this: let length = self.__len__(); let new_stop = start - step; let start = &new_stop + length.clone() * step; let step = -step; Ok( if let (Some(start), Some(step), Some(_)) = (start.to_isize(), step.to_isize(), new_stop.to_isize()) { PyRangeIterator { index: AtomicCell::new(0), start, step, // Cannot fail. If start, stop and step all successfully convert to isize, then result of zelf.len will // always fit in a usize. length: length.to_usize().unwrap_or(0), } .into_pyobject(vm) } else { PyLongRangeIterator { index: AtomicCell::new(0), start, step, length, } .into_pyobject(vm) }, ) } fn __len__(&self) -> BigInt { self.compute_length() } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef) { let range_parameters: Vec<PyObjectRef> = [&self.start, &self.stop, &self.step] .iter() .map(|x| x.as_object().to_owned()) .collect(); let range_parameters_tuple = vm.ctx.new_tuple(range_parameters); (vm.ctx.types.range_type.to_owned(), range_parameters_tuple) } fn __getitem__(&self, subscript: PyObjectRef, vm: &VirtualMachine) -> PyResult { match RangeIndex::try_from_object(vm, subscript)? { RangeIndex::Slice(slice) => { let (mut sub_start, mut sub_stop, mut sub_step) = slice.inner_indices(&self.compute_length(), vm)?; let range_step = &self.step; let range_start = &self.start; sub_step *= range_step.as_bigint(); sub_start = (sub_start * range_step.as_bigint()) + range_start.as_bigint(); sub_stop = (sub_stop * range_step.as_bigint()) + range_start.as_bigint(); Ok(Self { start: vm.ctx.new_pyref(sub_start), stop: vm.ctx.new_pyref(sub_stop), step: vm.ctx.new_pyref(sub_step), } .into_ref(&vm.ctx) .into()) } RangeIndex::Int(index) => match self.get(index.as_bigint()) { Some(value) => Ok(vm.ctx.new_int(value).into()), None => Err(vm.new_index_error("range object index out of range")), }, } } #[pyslot] fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let range = if args.args.len() <= 1 { let stop = args.bind(vm)?; Self::new(cls, stop, vm) } else { let (start, stop, step) = args.bind(vm)?; Self::new_from(cls, start, stop, step, vm) }?; Ok(range.into()) } // TODO: Uncomment when Python adds __class_getitem__ to range // #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } #[pyclass] impl Py<PyRange> { fn contains_inner(&self, needle: &PyObject, vm: &VirtualMachine) -> bool { // Only accept ints, not subclasses. if let Some(int) = needle.downcast_ref_if_exact::<PyInt>(vm) { match self.offset(int.as_bigint()) { Some(ref offset) => offset.is_multiple_of(self.step.as_bigint()), None => false, } } else { iter_search(self.as_object(), needle, SearchType::Contains, vm).unwrap_or(0) != 0 } } fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> bool { self.contains_inner(&needle, vm) } #[pymethod] fn index(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<BigInt> { if let Ok(int) = needle.clone().downcast::<PyInt>() { match self.index_of(int.as_bigint()) { Some(idx) => Ok(idx), None => Err(vm.new_value_error(format!("{int} is not in range"))), } } else { // Fallback to iteration. Ok(BigInt::from_bytes_be( Sign::Plus, &iter_search(self.as_object(), &needle, SearchType::Index, vm)?.to_be_bytes(), )) } } #[pymethod] fn count(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> { if let Ok(int) = item.clone().downcast::<PyInt>() { let count = if self.index_of(int.as_bigint()).is_some() { 1 } else { 0 }; Ok(count) } else { // Dealing with classes who might compare equal with ints in their // __eq__, slow search. iter_search(self.as_object(), &item, SearchType::Count, vm) } } } impl PyRange { fn protocol_length(&self, vm: &VirtualMachine) -> PyResult<usize> { PyInt::from(self.__len__()) .try_to_primitive::<isize>(vm) .map(|x| x as usize) } } impl AsMapping for PyRange { fn as_mapping() -> &'static PyMappingMethods { static AS_MAPPING: LazyLock<PyMappingMethods> = LazyLock::new(|| PyMappingMethods { length: atomic_func!( |mapping, vm| PyRange::mapping_downcast(mapping).protocol_length(vm) ), subscript: atomic_func!(|mapping, needle, vm| { PyRange::mapping_downcast(mapping).__getitem__(needle.to_owned(), vm) }), ..PyMappingMethods::NOT_IMPLEMENTED }); &AS_MAPPING } } impl AsSequence for PyRange { fn as_sequence() -> &'static PySequenceMethods { static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods { length: atomic_func!(|seq, vm| PyRange::sequence_downcast(seq).protocol_length(vm)), item: atomic_func!(|seq, i, vm| { PyRange::sequence_downcast(seq) .get(&i.into()) .map(|x| PyInt::from(x).into_ref(&vm.ctx).into()) .ok_or_else(|| vm.new_index_error("index out of range")) }), contains: atomic_func!(|seq, needle, vm| { Ok(PyRange::sequence_downcast(seq).contains_inner(needle, vm)) }), ..PySequenceMethods::NOT_IMPLEMENTED }); &AS_SEQUENCE } } impl AsNumber for PyRange { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { boolean: Some(|number, _vm| { let zelf = number.obj.downcast_ref::<PyRange>().unwrap(); Ok(!zelf.is_empty()) }), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } } impl Hashable for PyRange { fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> { let length = zelf.compute_length(); let elements = if length.is_zero() { [vm.ctx.new_int(length).into(), vm.ctx.none(), vm.ctx.none()] } else if length.is_one() { [ vm.ctx.new_int(length).into(), zelf.start().into(), vm.ctx.none(), ] } else { [ vm.ctx.new_int(length).into(), zelf.start().into(), zelf.step().into(), ] }; tuple_hash(&elements, vm) } } impl Comparable for PyRange { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, _vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { op.eq_only(|| { if zelf.is(other) { return Ok(true.into()); } let rhs = class_or_notimplemented!(Self, other); let lhs_len = zelf.compute_length(); let eq = if lhs_len != rhs.compute_length() { false } else if lhs_len.is_zero() { true } else if zelf.start.as_bigint() != rhs.start.as_bigint() { false } else if lhs_len.is_one() { true } else { zelf.step.as_bigint() == rhs.step.as_bigint() }; Ok(eq.into()) }) } } impl Iterable for PyRange { fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { let (start, stop, step, length) = ( zelf.start.as_bigint(), zelf.stop.as_bigint(), zelf.step.as_bigint(), zelf.__len__(), ); if let (Some(start), Some(step), Some(_), Some(_)) = ( start.to_isize(), step.to_isize(), stop.to_isize(), (start + step).to_isize(), ) { Ok(PyRangeIterator { index: AtomicCell::new(0), start, step, // Cannot fail. If start, stop and step all successfully convert to isize, then result of zelf.len will // always fit in a usize. length: length.to_usize().unwrap_or(0), } .into_pyobject(vm)) } else { Ok(PyLongRangeIterator { index: AtomicCell::new(0), start: start.clone(), step: step.clone(), length, } .into_pyobject(vm)) } } } impl Representable for PyRange { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { let repr = if zelf.step.as_bigint().is_one() { format!("range({}, {})", zelf.start, zelf.stop) } else { format!("range({}, {}, {})", zelf.start, zelf.stop, zelf.step) }; Ok(repr) } } // Semantically, this is the same as the previous representation. // // Unfortunately, since AtomicCell requires a Copy type, no BigInt implementations can // generally be used. As such, usize::MAX is the upper bound on number of elements (length) // the range can contain in RustPython. // // This doesn't preclude the range from containing large values, since start and step // can be BigInts, we can store any arbitrary range of values. #[pyclass(module = false, name = "longrange_iterator")] #[derive(Debug)] pub struct PyLongRangeIterator { index: AtomicCell<usize>, start: BigInt, step: BigInt, length: BigInt, } impl PyPayload for PyLongRangeIterator { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.long_range_iterator_type } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] impl PyLongRangeIterator { #[pymethod] fn __length_hint__(&self) -> BigInt { let index = BigInt::from(self.index.load()); if index < self.length { self.length.clone() - index } else { BigInt::zero() } } #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.index.store(range_state(&self.length, state, vm)?); Ok(()) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> { range_iter_reduce( self.start.clone(), self.length.clone(), self.step.clone(), self.index.load(), vm, ) } } impl SelfIter for PyLongRangeIterator {} impl IterNext for PyLongRangeIterator { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { // TODO: In pathological case (index == usize::MAX) this can wrap around // (since fetch_add wraps). This would result in the iterator spinning again // from the beginning. let index = BigInt::from(zelf.index.fetch_add(1)); let r = if index < zelf.length { let value = zelf.start.clone() + index * zelf.step.clone(); PyIterReturn::Return(vm.ctx.new_int(value).into()) } else { PyIterReturn::StopIteration(None) }; Ok(r) } } // When start, stop, step are isize, we can use a faster more compact representation // that only operates using isize to track values. #[pyclass(module = false, name = "range_iterator")] #[derive(Debug)] pub struct PyRangeIterator { index: AtomicCell<usize>, start: isize, step: isize, length: usize, } impl PyPayload for PyRangeIterator { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.range_iterator_type } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] impl PyRangeIterator { #[pymethod] fn __length_hint__(&self) -> usize { let index = self.index.load(); self.length.saturating_sub(index) } #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.index .store(range_state(&BigInt::from(self.length), state, vm)?); Ok(()) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> { range_iter_reduce( BigInt::from(self.start), BigInt::from(self.length), BigInt::from(self.step), self.index.load(), vm, ) } } impl SelfIter for PyRangeIterator {} impl IterNext for PyRangeIterator { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { // TODO: In pathological case (index == usize::MAX) this can wrap around // (since fetch_add wraps). This would result in the iterator spinning again // from the beginning. let index = zelf.index.fetch_add(1); let r = if index < zelf.length { let value = zelf.start + (index as isize) * zelf.step; PyIterReturn::Return(vm.ctx.new_int(value).into()) } else { PyIterReturn::StopIteration(None) }; Ok(r) } } fn range_iter_reduce( start: BigInt, length: BigInt, step: BigInt, index: usize, vm: &VirtualMachine, ) -> PyResult<PyTupleRef> { let iter = builtins_iter(vm).to_owned(); let stop = start.clone() + length * step.clone(); let range = PyRange { start: PyInt::from(start).into_ref(&vm.ctx), stop: PyInt::from(stop).into_ref(&vm.ctx), step: PyInt::from(step).into_ref(&vm.ctx), }; Ok(vm.new_tuple((iter, (range,), index))) } // Silently clips state (i.e index) in range [0, usize::MAX]. fn range_state(length: &BigInt, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> { if let Some(i) = state.downcast_ref::<PyInt>() { let mut index = i.as_bigint(); let max_usize = BigInt::from(usize::MAX); if index > length { index = max(length, &max_usize); } Ok(index.to_usize().unwrap_or(0)) } else { Err(vm.new_type_error("an integer is required.")) } } pub enum RangeIndex { Int(PyIntRef), Slice(PyRef<PySlice>), } impl TryFromObject for RangeIndex { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { match_class!(match obj { i @ PyInt => Ok(Self::Int(i)), s @ PySlice => Ok(Self::Slice(s)), obj => { let val = obj.try_index(vm).map_err(|_| vm.new_type_error(format!( "sequence indices be integers or slices or classes that override __index__ operator, not '{}'", obj.class().name() )))?; Ok(Self::Int(val)) } }) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/union.rs
crates/vm/src/builtins/union.rs
use super::{genericalias, type_}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, atomic_func, builtins::{PyFrozenSet, PyGenericAlias, PyStr, PyTuple, PyTupleRef, PyType}, class::PyClassImpl, common::hash, convert::{ToPyObject, ToPyResult}, function::PyComparisonValue, protocol::{PyMappingMethods, PyNumberMethods}, stdlib::typing::TypeAliasType, types::{AsMapping, AsNumber, Comparable, GetAttr, Hashable, PyComparisonOp, Representable}, }; use alloc::fmt; use std::sync::LazyLock; const CLS_ATTRS: &[&str] = &["__module__"]; #[pyclass(module = "types", name = "UnionType", traverse)] pub struct PyUnion { args: PyTupleRef, parameters: PyTupleRef, } impl fmt::Debug for PyUnion { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("UnionObject") } } impl PyPayload for PyUnion { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.union_type } } impl PyUnion { pub fn new(args: PyTupleRef, vm: &VirtualMachine) -> Self { let parameters = make_parameters(&args, vm); Self { args, parameters } } /// Direct access to args field, matching CPython's _Py_union_args #[inline] pub fn args(&self) -> &Py<PyTuple> { &self.args } fn repr(&self, vm: &VirtualMachine) -> PyResult<String> { fn repr_item(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<String> { if obj.is(vm.ctx.types.none_type) { return Ok("None".to_string()); } if vm .get_attribute_opt(obj.clone(), identifier!(vm, __origin__))? .is_some() && vm .get_attribute_opt(obj.clone(), identifier!(vm, __args__))? .is_some() { return Ok(obj.repr(vm)?.to_string()); } match ( vm.get_attribute_opt(obj.clone(), identifier!(vm, __qualname__))? .and_then(|o| o.downcast_ref::<PyStr>().map(|n| n.to_string())), vm.get_attribute_opt(obj.clone(), identifier!(vm, __module__))? .and_then(|o| o.downcast_ref::<PyStr>().map(|m| m.to_string())), ) { (None, _) | (_, None) => Ok(obj.repr(vm)?.to_string()), (Some(qualname), Some(module)) => Ok(if module == "builtins" { qualname } else { format!("{module}.{qualname}") }), } } Ok(self .args .iter() .map(|o| repr_item(o.clone(), vm)) .collect::<PyResult<Vec<_>>>()? .join(" | ")) } } #[pyclass( flags(BASETYPE), with(Hashable, Comparable, AsMapping, AsNumber, Representable) )] impl PyUnion { #[pygetset] fn __parameters__(&self) -> PyObjectRef { self.parameters.clone().into() } #[pygetset] fn __args__(&self) -> PyObjectRef { self.args.clone().into() } #[pymethod] fn __instancecheck__( zelf: PyRef<Self>, obj: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<bool> { if zelf .args .iter() .any(|x| x.class().is(vm.ctx.types.generic_alias_type)) { Err(vm.new_type_error("isinstance() argument 2 cannot be a parameterized generic")) } else { obj.is_instance(zelf.__args__().as_object(), vm) } } #[pymethod] fn __subclasscheck__( zelf: PyRef<Self>, obj: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<bool> { if zelf .args .iter() .any(|x| x.class().is(vm.ctx.types.generic_alias_type)) { Err(vm.new_type_error("issubclass() argument 2 cannot be a parameterized generic")) } else { obj.is_subclass(zelf.__args__().as_object(), vm) } } fn __or__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { type_::or_(zelf, other, vm) } #[pyclassmethod] fn __class_getitem__( cls: crate::builtins::PyTypeRef, args: PyObjectRef, vm: &VirtualMachine, ) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } pub fn is_unionable(obj: PyObjectRef, vm: &VirtualMachine) -> bool { let cls = obj.class(); cls.is(vm.ctx.types.none_type) || obj.downcastable::<PyType>() || cls.fast_issubclass(vm.ctx.types.generic_alias_type) || cls.is(vm.ctx.types.union_type) || obj.downcast_ref::<TypeAliasType>().is_some() } fn make_parameters(args: &Py<PyTuple>, vm: &VirtualMachine) -> PyTupleRef { let parameters = genericalias::make_parameters(args, vm); dedup_and_flatten_args(&parameters, vm) } fn flatten_args(args: &Py<PyTuple>, vm: &VirtualMachine) -> PyTupleRef { let mut total_args = 0; for arg in args { if let Some(pyref) = arg.downcast_ref::<PyUnion>() { total_args += pyref.args.len(); } else { total_args += 1; }; } let mut flattened_args = Vec::with_capacity(total_args); for arg in args { if let Some(pyref) = arg.downcast_ref::<PyUnion>() { flattened_args.extend(pyref.args.iter().cloned()); } else if vm.is_none(arg) { flattened_args.push(vm.ctx.types.none_type.to_owned().into()); } else { flattened_args.push(arg.clone()); }; } PyTuple::new_ref(flattened_args, &vm.ctx) } fn dedup_and_flatten_args(args: &Py<PyTuple>, vm: &VirtualMachine) -> PyTupleRef { let args = flatten_args(args, vm); let mut new_args: Vec<PyObjectRef> = Vec::with_capacity(args.len()); for arg in &*args { if !new_args.iter().any(|param| { param .rich_compare_bool(arg, PyComparisonOp::Eq, vm) .unwrap_or_default() }) { new_args.push(arg.clone()); } } new_args.shrink_to_fit(); PyTuple::new_ref(new_args, &vm.ctx) } pub fn make_union(args: &Py<PyTuple>, vm: &VirtualMachine) -> PyObjectRef { let args = dedup_and_flatten_args(args, vm); match args.len() { 1 => args[0].to_owned(), _ => PyUnion::new(args, vm).to_pyobject(vm), } } impl PyUnion { fn getitem(zelf: PyRef<Self>, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { let new_args = genericalias::subs_parameters( zelf.to_owned().into(), zelf.args.clone(), zelf.parameters.clone(), needle, vm, )?; let mut res; if new_args.is_empty() { res = make_union(&new_args, vm); } else { res = new_args[0].to_owned(); for arg in new_args.iter().skip(1) { res = vm._or(&res, arg)?; } } Ok(res) } } impl AsMapping for PyUnion { fn as_mapping() -> &'static PyMappingMethods { static AS_MAPPING: LazyLock<PyMappingMethods> = LazyLock::new(|| PyMappingMethods { subscript: atomic_func!(|mapping, needle, vm| { let zelf = PyUnion::mapping_downcast(mapping); PyUnion::getitem(zelf.to_owned(), needle.to_owned(), vm) }), ..PyMappingMethods::NOT_IMPLEMENTED }); &AS_MAPPING } } impl AsNumber for PyUnion { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { or: Some(|a, b, vm| PyUnion::__or__(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } } impl Comparable for PyUnion { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { op.eq_only(|| { let other = class_or_notimplemented!(Self, other); let a = PyFrozenSet::from_iter(vm, zelf.args.into_iter().cloned())?; let b = PyFrozenSet::from_iter(vm, other.args.into_iter().cloned())?; Ok(PyComparisonValue::Implemented( a.into_pyobject(vm).as_object().rich_compare_bool( b.into_pyobject(vm).as_object(), PyComparisonOp::Eq, vm, )?, )) }) } } impl Hashable for PyUnion { #[inline] fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<hash::PyHash> { let set = PyFrozenSet::from_iter(vm, zelf.args.into_iter().cloned())?; PyFrozenSet::hash(&set.into_ref(&vm.ctx), vm) } } impl GetAttr for PyUnion { fn getattro(zelf: &Py<Self>, attr: &Py<PyStr>, vm: &VirtualMachine) -> PyResult { for &exc in CLS_ATTRS { if *exc == attr.to_string() { return zelf.as_object().generic_getattr(attr, vm); } } zelf.as_object().get_attr(attr, vm) } } impl Representable for PyUnion { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { zelf.repr(vm) } } pub fn init(context: &Context) { let union_type = &context.types.union_type; PyUnion::extend_class(context, union_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/classmethod.rs
crates/vm/src/builtins/classmethod.rs
use super::{PyBoundMethod, PyGenericAlias, PyStr, PyType, PyTypeRef}; use crate::{ AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, class::PyClassImpl, common::lock::PyMutex, function::FuncArgs, types::{Constructor, GetDescriptor, Initializer, Representable}, }; /// classmethod(function) -> method /// /// Convert a function to be a class method. /// /// A class method receives the class as implicit first argument, /// just like an instance method receives the instance. /// To declare a class method, use this idiom: /// /// class C: /// @classmethod /// def f(cls, arg1, arg2, ...): /// ... /// /// It can be called either on the class (e.g. C.f()) or on an instance /// (e.g. C().f()). The instance is ignored except for its class. /// If a class method is called for a derived class, the derived class /// object is passed as the implied first argument. /// /// Class methods are different than C++ or Java static methods. /// If you want those, see the staticmethod builtin. #[pyclass(module = false, name = "classmethod")] #[derive(Debug)] pub struct PyClassMethod { callable: PyMutex<PyObjectRef>, } impl From<PyObjectRef> for PyClassMethod { fn from(callable: PyObjectRef) -> Self { Self { callable: PyMutex::new(callable), } } } impl PyPayload for PyClassMethod { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.classmethod_type } } impl GetDescriptor for PyClassMethod { fn descr_get( zelf: PyObjectRef, obj: Option<PyObjectRef>, cls: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { let (zelf, _obj) = Self::_unwrap(&zelf, obj, vm)?; let cls = cls.unwrap_or_else(|| _obj.class().to_owned().into()); // Clone and release lock before calling Python code to prevent deadlock let callable = zelf.callable.lock().clone(); let call_descr_get: PyResult<PyObjectRef> = callable.get_attr("__get__", vm); match call_descr_get { Err(_) => Ok(PyBoundMethod::new(cls, callable).into_ref(&vm.ctx).into()), Ok(call_descr_get) => call_descr_get.call((cls.clone(), cls), vm), } } } impl Constructor for PyClassMethod { type Args = PyObjectRef; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let callable: Self::Args = args.bind(vm)?; // Create a dictionary to hold copied attributes let dict = vm.ctx.new_dict(); // Copy attributes from the callable to the dict // This is similar to functools.wraps in CPython if let Ok(doc) = callable.get_attr("__doc__", vm) { dict.set_item(identifier!(vm.ctx, __doc__), doc, vm)?; } if let Ok(name) = callable.get_attr("__name__", vm) { dict.set_item(identifier!(vm.ctx, __name__), name, vm)?; } if let Ok(qualname) = callable.get_attr("__qualname__", vm) { dict.set_item(identifier!(vm.ctx, __qualname__), qualname, vm)?; } if let Ok(module) = callable.get_attr("__module__", vm) { dict.set_item(identifier!(vm.ctx, __module__), module, vm)?; } if let Ok(annotations) = callable.get_attr("__annotations__", vm) { dict.set_item(identifier!(vm.ctx, __annotations__), annotations, vm)?; } // Create PyClassMethod instance with the pre-populated dict let classmethod = Self { callable: PyMutex::new(callable), }; let result = PyRef::new_ref(classmethod, cls, Some(dict)); Ok(PyObjectRef::from(result)) } fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> { unimplemented!("use slot_new") } } impl Initializer for PyClassMethod { type Args = PyObjectRef; fn init(zelf: PyRef<Self>, callable: Self::Args, _vm: &VirtualMachine) -> PyResult<()> { *zelf.callable.lock() = callable; Ok(()) } } impl PyClassMethod { #[deprecated(note = "use PyClassMethod::from(...).into_ref() instead")] pub fn new_ref(callable: PyObjectRef, ctx: &Context) -> PyRef<Self> { Self::from(callable).into_ref(ctx) } } #[pyclass( with(GetDescriptor, Constructor, Initializer, Representable), flags(BASETYPE, HAS_DICT) )] impl PyClassMethod { #[pygetset] fn __func__(&self) -> PyObjectRef { self.callable.lock().clone() } #[pygetset] fn __wrapped__(&self) -> PyObjectRef { self.callable.lock().clone() } #[pygetset] fn __module__(&self, vm: &VirtualMachine) -> PyResult { self.callable.lock().get_attr("__module__", vm) } #[pygetset] fn __qualname__(&self, vm: &VirtualMachine) -> PyResult { self.callable.lock().get_attr("__qualname__", vm) } #[pygetset] fn __name__(&self, vm: &VirtualMachine) -> PyResult { self.callable.lock().get_attr("__name__", vm) } #[pygetset] fn __annotations__(&self, vm: &VirtualMachine) -> PyResult { self.callable.lock().get_attr("__annotations__", vm) } #[pygetset] fn __isabstractmethod__(&self, vm: &VirtualMachine) -> PyObjectRef { match vm.get_attribute_opt(self.callable.lock().clone(), "__isabstractmethod__") { Ok(Some(is_abstract)) => is_abstract, _ => vm.ctx.new_bool(false).into(), } } #[pygetset(setter)] fn set___isabstractmethod__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.callable .lock() .set_attr("__isabstractmethod__", value, vm)?; Ok(()) } #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } impl Representable for PyClassMethod { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { let callable = zelf.callable.lock().repr(vm).unwrap(); let class = Self::class(&vm.ctx); let repr = match ( class .__qualname__(vm) .downcast_ref::<PyStr>() .map(|n| n.as_str()), class .__module__(vm) .downcast_ref::<PyStr>() .map(|m| m.as_str()), ) { (None, _) => return Err(vm.new_type_error("Unknown qualified name")), (Some(qualname), Some(module)) if module != "builtins" => { format!("<{module}.{qualname}({callable})>") } _ => format!("<{}({})>", class.slot_name(), callable), }; Ok(repr) } } pub(crate) fn init(context: &Context) { PyClassMethod::extend_class(context, context.types.classmethod_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/filter.rs
crates/vm/src/builtins/filter.rs
use super::{PyType, PyTypeRef}; use crate::{ Context, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, class::PyClassImpl, protocol::{PyIter, PyIterReturn}, raise_if_stop, types::{Constructor, IterNext, Iterable, SelfIter}, }; #[pyclass(module = false, name = "filter", traverse)] #[derive(Debug)] pub struct PyFilter { predicate: PyObjectRef, iterator: PyIter, } impl PyPayload for PyFilter { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.filter_type } } impl Constructor for PyFilter { type Args = (PyObjectRef, PyIter); fn py_new( _cls: &Py<PyType>, (function, iterator): Self::Args, _vm: &VirtualMachine, ) -> PyResult<Self> { Ok(Self { predicate: function, iterator, }) } } #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyFilter { #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, (PyObjectRef, PyIter)) { ( vm.ctx.types.filter_type.to_owned(), (self.predicate.clone(), self.iterator.clone()), ) } } impl SelfIter for PyFilter {} impl IterNext for PyFilter { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let predicate = &zelf.predicate; loop { let next_obj = raise_if_stop!(zelf.iterator.next(vm)?); let predicate_value = if vm.is_none(predicate) { next_obj.clone() } else { // the predicate itself can raise StopIteration which does stop the filter iteration raise_if_stop!(PyIterReturn::from_pyresult( predicate.call((next_obj.clone(),), vm), vm )?) }; if predicate_value.try_to_bool(vm)? { return Ok(PyIterReturn::Return(next_obj)); } } } } pub fn init(context: &Context) { PyFilter::extend_class(context, context.types.filter_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/module.rs
crates/vm/src/builtins/module.rs
use super::{PyDict, PyDictRef, PyStr, PyStrRef, PyType, PyTypeRef}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::{PyStrInterned, pystr::AsPyStr}, class::PyClassImpl, convert::ToPyObject, function::{FuncArgs, PyMethodDef}, types::{GetAttr, Initializer, Representable}, }; #[pyclass(module = false, name = "module")] #[derive(Debug)] pub struct PyModuleDef { // pub index: usize, pub name: &'static PyStrInterned, pub doc: Option<&'static PyStrInterned>, // pub size: isize, pub methods: &'static [PyMethodDef], pub slots: PyModuleSlots, // traverse: traverse_proc // clear: inquiry // free: free_func } pub type ModuleCreate = fn(&VirtualMachine, &PyObject, &'static PyModuleDef) -> PyResult<PyRef<PyModule>>; pub type ModuleExec = fn(&VirtualMachine, &Py<PyModule>) -> PyResult<()>; #[derive(Default)] pub struct PyModuleSlots { pub create: Option<ModuleCreate>, pub exec: Option<ModuleExec>, } impl core::fmt::Debug for PyModuleSlots { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyModuleSlots") .field("create", &self.create.is_some()) .field("exec", &self.exec.is_some()) .finish() } } #[allow(clippy::new_without_default)] // avoid Default implementation #[pyclass(module = false, name = "module")] #[derive(Debug)] pub struct PyModule { // PyObject *md_dict; pub def: Option<&'static PyModuleDef>, // state: Any // weaklist // for logging purposes after md_dict is cleared pub name: Option<&'static PyStrInterned>, } impl PyPayload for PyModule { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.module_type } } #[derive(FromArgs)] pub struct ModuleInitArgs { name: PyStrRef, #[pyarg(any, default)] doc: Option<PyStrRef>, } impl PyModule { #[allow(clippy::new_without_default)] pub const fn new() -> Self { Self { def: None, name: None, } } pub const fn from_def(def: &'static PyModuleDef) -> Self { Self { def: Some(def), name: Some(def.name), } } pub fn __init_dict_from_def(vm: &VirtualMachine, module: &Py<Self>) { let doc = module.def.unwrap().doc.map(|doc| doc.to_owned()); module.init_dict(module.name.unwrap(), doc, vm); } } impl Py<PyModule> { pub fn __init_methods(&self, vm: &VirtualMachine) -> PyResult<()> { debug_assert!(self.def.is_some()); for method in self.def.unwrap().methods { let func = method .to_function() .with_module(self.name.unwrap()) .into_ref(&vm.ctx); vm.__module_set_attr(self, vm.ctx.intern_str(method.name), func)?; } Ok(()) } fn getattr_inner(&self, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult { if let Some(attr) = self.as_object().generic_getattr_opt(name, None, vm)? { return Ok(attr); } if let Ok(getattr) = self.dict().get_item(identifier!(vm, __getattr__), vm) { return getattr.call((name.to_owned(),), vm); } let module_name = if let Some(name) = self.name(vm) { format!(" '{name}'") } else { "".to_owned() }; Err(vm.new_attribute_error(format!("module{module_name} has no attribute '{name}'"))) } fn name(&self, vm: &VirtualMachine) -> Option<PyStrRef> { let name = self .as_object() .generic_getattr_opt(identifier!(vm, __name__), None, vm) .unwrap_or_default()?; name.downcast::<PyStr>().ok() } // TODO: to be replaced by the commented-out dict method above once dictoffset land pub fn dict(&self) -> PyDictRef { self.as_object().dict().unwrap() } // TODO: should be on PyModule, not Py<PyModule> pub(crate) fn init_dict( &self, name: &'static PyStrInterned, doc: Option<PyStrRef>, vm: &VirtualMachine, ) { let dict = self.dict(); dict.set_item(identifier!(vm, __name__), name.to_object(), vm) .expect("Failed to set __name__ on module"); dict.set_item(identifier!(vm, __doc__), doc.to_pyobject(vm), vm) .expect("Failed to set __doc__ on module"); dict.set_item("__package__", vm.ctx.none(), vm) .expect("Failed to set __package__ on module"); dict.set_item("__loader__", vm.ctx.none(), vm) .expect("Failed to set __loader__ on module"); dict.set_item("__spec__", vm.ctx.none(), vm) .expect("Failed to set __spec__ on module"); } pub fn get_attr<'a>(&self, attr_name: impl AsPyStr<'a>, vm: &VirtualMachine) -> PyResult { let attr_name = attr_name.as_pystr(&vm.ctx); self.getattr_inner(attr_name, vm) } pub fn set_attr<'a>( &self, attr_name: impl AsPyStr<'a>, attr_value: impl Into<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<()> { self.as_object().set_attr(attr_name, attr_value, vm) } } #[pyclass(with(GetAttr, Initializer, Representable), flags(BASETYPE, HAS_DICT))] impl PyModule { #[pyslot] fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { Self::new().into_ref_with_type(vm, cls).map(Into::into) } #[pymethod] fn __dir__(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<Vec<PyObjectRef>> { // First check if __dict__ attribute exists and is actually a dictionary let dict_attr = zelf.as_object().get_attr(identifier!(vm, __dict__), vm)?; let dict = dict_attr .downcast::<PyDict>() .map_err(|_| vm.new_type_error("<module>.__dict__ is not a dictionary"))?; let attrs = dict.into_iter().map(|(k, _v)| k).collect(); Ok(attrs) } } impl Initializer for PyModule { type Args = ModuleInitArgs; fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { debug_assert!( zelf.class() .slots .flags .has_feature(crate::types::PyTypeFlags::HAS_DICT) ); zelf.init_dict(vm.ctx.intern_str(args.name.as_str()), args.doc, vm); Ok(()) } } impl GetAttr for PyModule { fn getattro(zelf: &Py<Self>, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult { zelf.getattr_inner(name, vm) } } impl Representable for PyModule { #[inline] fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> { let importlib = vm.import("_frozen_importlib", 0)?; let module_repr = importlib.get_attr("_module_repr", vm)?; let repr = module_repr.call((zelf.to_owned(),), vm)?; repr.downcast() .map_err(|_| vm.new_type_error("_module_repr did not return a string")) } #[cold] fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { unreachable!("use repr instead") } } pub(crate) fn init(context: &Context) { PyModule::extend_class(context, context.types.module_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/list.rs
crates/vm/src/builtins/list.rs
use super::{PositionIterInternal, PyGenericAlias, PyTupleRef, PyType, PyTypeRef}; use crate::atomic_func; use crate::common::lock::{ PyMappedRwLockReadGuard, PyMutex, PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, class::PyClassImpl, convert::ToPyObject, function::{ArgSize, FuncArgs, OptionalArg, PyComparisonValue}, iter::PyExactSizeIterator, protocol::{PyIterReturn, PyMappingMethods, PySequenceMethods}, recursion::ReprGuard, sequence::{MutObjectSequenceOp, OptionalRangeArgs, SequenceExt, SequenceMutExt}, sliceable::{SequenceIndex, SliceableSequenceMutOp, SliceableSequenceOp}, types::{ AsMapping, AsSequence, Comparable, Constructor, Initializer, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, }, utils::collection_repr, vm::VirtualMachine, }; use alloc::fmt; use core::ops::DerefMut; #[pyclass(module = false, name = "list", unhashable = true, traverse)] #[derive(Default)] pub struct PyList { elements: PyRwLock<Vec<PyObjectRef>>, } impl fmt::Debug for PyList { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // TODO: implement more detailed, non-recursive Debug formatter f.write_str("list") } } impl From<Vec<PyObjectRef>> for PyList { fn from(elements: Vec<PyObjectRef>) -> Self { Self { elements: PyRwLock::new(elements), } } } impl FromIterator<PyObjectRef> for PyList { fn from_iter<T: IntoIterator<Item = PyObjectRef>>(iter: T) -> Self { Vec::from_iter(iter).into() } } impl PyPayload for PyList { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.list_type } } impl ToPyObject for Vec<PyObjectRef> { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { PyList::from(self).into_ref(&vm.ctx).into() } } impl PyList { #[deprecated(note = "use PyList::from(...).into_ref() instead")] pub fn new_ref(elements: Vec<PyObjectRef>, ctx: &Context) -> PyRef<Self> { Self::from(elements).into_ref(ctx) } pub fn borrow_vec(&self) -> PyMappedRwLockReadGuard<'_, [PyObjectRef]> { PyRwLockReadGuard::map(self.elements.read(), |v| &**v) } pub fn borrow_vec_mut(&self) -> PyRwLockWriteGuard<'_, Vec<PyObjectRef>> { self.elements.write() } fn repeat(&self, n: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { let elements = &*self.borrow_vec(); let v = elements.mul(vm, n)?; Ok(Self::from(v).into_ref(&vm.ctx)) } fn irepeat(zelf: PyRef<Self>, n: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { zelf.borrow_vec_mut().imul(vm, n)?; Ok(zelf) } } #[derive(FromArgs, Default, Traverse)] pub(crate) struct SortOptions { #[pyarg(named, default)] key: Option<PyObjectRef>, #[pytraverse(skip)] #[pyarg(named, default = false)] reverse: bool, } pub type PyListRef = PyRef<PyList>; #[pyclass( with( Constructor, Initializer, AsMapping, Iterable, Comparable, AsSequence, Representable ), flags(BASETYPE, SEQUENCE, _MATCH_SELF) )] impl PyList { #[pymethod] pub(crate) fn append(&self, x: PyObjectRef) { self.borrow_vec_mut().push(x); } #[pymethod] pub(crate) fn extend(&self, x: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let mut new_elements = x.try_to_value(vm)?; self.borrow_vec_mut().append(&mut new_elements); Ok(()) } #[pymethod] pub(crate) fn insert(&self, position: isize, element: PyObjectRef) { let mut elements = self.borrow_vec_mut(); let position = elements.saturate_index(position); elements.insert(position, element); } fn concat(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { let other = other.downcast_ref::<Self>().ok_or_else(|| { vm.new_type_error(format!( "Cannot add {} and {}", Self::class(&vm.ctx).name(), other.class().name() )) })?; let mut elements = self.borrow_vec().to_vec(); elements.extend(other.borrow_vec().iter().cloned()); Ok(Self::from(elements).into_ref(&vm.ctx)) } fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { self.concat(&other, vm) } fn inplace_concat( zelf: &Py<Self>, other: &PyObject, vm: &VirtualMachine, ) -> PyResult<PyObjectRef> { let mut seq = extract_cloned(other, Ok, vm)?; zelf.borrow_vec_mut().append(&mut seq); Ok(zelf.to_owned().into()) } fn __iadd__( zelf: PyRef<Self>, other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let mut seq = extract_cloned(&other, Ok, vm)?; zelf.borrow_vec_mut().append(&mut seq); Ok(zelf) } #[pymethod] fn clear(&self) { let _removed = core::mem::take(self.borrow_vec_mut().deref_mut()); } #[pymethod] fn copy(&self, vm: &VirtualMachine) -> PyRef<Self> { Self::from(self.borrow_vec().to_vec()).into_ref(&vm.ctx) } #[allow(clippy::len_without_is_empty)] pub fn __len__(&self) -> usize { self.borrow_vec().len() } #[pymethod] fn __sizeof__(&self) -> usize { core::mem::size_of::<Self>() + self.elements.read().capacity() * core::mem::size_of::<PyObjectRef>() } #[pymethod] fn reverse(&self) { self.borrow_vec_mut().reverse(); } #[pymethod] fn __reversed__(zelf: PyRef<Self>) -> PyListReverseIterator { let position = zelf.__len__().saturating_sub(1); PyListReverseIterator { internal: PyMutex::new(PositionIterInternal::new(zelf, position)), } } fn _getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { match SequenceIndex::try_from_borrowed_object(vm, needle, "list")? { SequenceIndex::Int(i) => self.borrow_vec().getitem_by_index(vm, i), SequenceIndex::Slice(slice) => self .borrow_vec() .getitem_by_slice(vm, slice) .map(|x| vm.ctx.new_list(x).into()), } } fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { self._getitem(&needle, vm) } fn _setitem(&self, needle: &PyObject, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { match SequenceIndex::try_from_borrowed_object(vm, needle, "list")? { SequenceIndex::Int(index) => self.borrow_vec_mut().setitem_by_index(vm, index, value), SequenceIndex::Slice(slice) => { let sec = extract_cloned(&value, Ok, vm)?; self.borrow_vec_mut().setitem_by_slice(vm, slice, &sec) } } } fn __setitem__( &self, needle: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { self._setitem(&needle, value, vm) } fn __mul__(&self, n: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { self.repeat(n.into(), vm) } fn __imul__(zelf: PyRef<Self>, n: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { Self::irepeat(zelf, n.into(), vm) } #[pymethod] fn count(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> { self.mut_count(vm, &needle) } pub(crate) fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> { self.mut_contains(vm, &needle) } #[pymethod] fn index( &self, needle: PyObjectRef, range: OptionalRangeArgs, vm: &VirtualMachine, ) -> PyResult<usize> { let (start, stop) = range.saturate(self.__len__(), vm)?; let index = self.mut_index_range(vm, &needle, start..stop)?; if let Some(index) = index.into() { Ok(index) } else { Err(vm.new_value_error(format!("'{}' is not in list", needle.str(vm)?))) } } #[pymethod] fn pop(&self, i: OptionalArg<isize>, vm: &VirtualMachine) -> PyResult { let mut i = i.into_option().unwrap_or(-1); let mut elements = self.borrow_vec_mut(); if i < 0 { i += elements.len() as isize; } if elements.is_empty() { Err(vm.new_index_error("pop from empty list")) } else if i < 0 || i as usize >= elements.len() { Err(vm.new_index_error("pop index out of range")) } else { Ok(elements.remove(i as usize)) } } #[pymethod] fn remove(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let index = self.mut_index(vm, &needle)?; if let Some(index) = index.into() { // defer delete out of borrow let is_inside_range = index < self.borrow_vec().len(); Ok(is_inside_range.then(|| self.borrow_vec_mut().remove(index))) } else { Err(vm.new_value_error(format!("'{}' is not in list", needle.str(vm)?))) } .map(drop) } fn _delitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<()> { match SequenceIndex::try_from_borrowed_object(vm, needle, "list")? { SequenceIndex::Int(i) => self.borrow_vec_mut().delitem_by_index(vm, i), SequenceIndex::Slice(slice) => self.borrow_vec_mut().delitem_by_slice(vm, slice), } } fn __delitem__(&self, subscript: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self._delitem(&subscript, vm) } #[pymethod] pub(crate) fn sort(&self, options: SortOptions, vm: &VirtualMachine) -> PyResult<()> { // replace list contents with [] for duration of sort. // this prevents keyfunc from messing with the list and makes it easy to // check if it tries to append elements to it. let mut elements = core::mem::take(self.borrow_vec_mut().deref_mut()); let res = do_sort(vm, &mut elements, options.key, options.reverse); core::mem::swap(self.borrow_vec_mut().deref_mut(), &mut elements); res?; if !elements.is_empty() { return Err(vm.new_value_error("list modified during sort")); } Ok(()) } #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } fn extract_cloned<F, R>(obj: &PyObject, mut f: F, vm: &VirtualMachine) -> PyResult<Vec<R>> where F: FnMut(PyObjectRef) -> PyResult<R>, { use crate::builtins::PyTuple; if let Some(tuple) = obj.downcast_ref_if_exact::<PyTuple>(vm) { tuple.iter().map(|x| f(x.clone())).collect() } else if let Some(list) = obj.downcast_ref_if_exact::<PyList>(vm) { list.borrow_vec().iter().map(|x| f(x.clone())).collect() } else { let iter = obj.to_owned().get_iter(vm)?; let iter = iter.iter::<PyObjectRef>(vm)?; let len = obj .sequence_unchecked() .length_opt(vm) .transpose()? .unwrap_or(0); let mut v = Vec::with_capacity(len); for x in iter { v.push(f(x?)?); } v.shrink_to_fit(); Ok(v) } } impl MutObjectSequenceOp for PyList { type Inner = [PyObjectRef]; fn do_get(index: usize, inner: &[PyObjectRef]) -> Option<&PyObject> { inner.get(index).map(|r| r.as_ref()) } fn do_lock(&self) -> impl core::ops::Deref<Target = [PyObjectRef]> { self.borrow_vec() } } impl Constructor for PyList { type Args = FuncArgs; fn py_new(_cls: &Py<PyType>, _args: FuncArgs, _vm: &VirtualMachine) -> PyResult<Self> { Ok(Self::default()) } } impl Initializer for PyList { type Args = OptionalArg<PyObjectRef>; fn init(zelf: PyRef<Self>, iterable: Self::Args, vm: &VirtualMachine) -> PyResult<()> { let mut elements = if let OptionalArg::Present(iterable) = iterable { iterable.try_to_value(vm)? } else { vec![] }; core::mem::swap(zelf.borrow_vec_mut().deref_mut(), &mut elements); Ok(()) } } impl AsMapping for PyList { fn as_mapping() -> &'static PyMappingMethods { static AS_MAPPING: PyMappingMethods = PyMappingMethods { length: atomic_func!(|mapping, _vm| Ok(PyList::mapping_downcast(mapping).__len__())), subscript: atomic_func!( |mapping, needle, vm| PyList::mapping_downcast(mapping)._getitem(needle, vm) ), ass_subscript: atomic_func!(|mapping, needle, value, vm| { let zelf = PyList::mapping_downcast(mapping); if let Some(value) = value { zelf._setitem(needle, value, vm) } else { zelf._delitem(needle, vm) } }), }; &AS_MAPPING } } impl AsSequence for PyList { fn as_sequence() -> &'static PySequenceMethods { static AS_SEQUENCE: PySequenceMethods = PySequenceMethods { length: atomic_func!(|seq, _vm| Ok(PyList::sequence_downcast(seq).__len__())), concat: atomic_func!(|seq, other, vm| { PyList::sequence_downcast(seq) .concat(other, vm) .map(|x| x.into()) }), repeat: atomic_func!(|seq, n, vm| { PyList::sequence_downcast(seq) .repeat(n, vm) .map(|x| x.into()) }), item: atomic_func!(|seq, i, vm| { PyList::sequence_downcast(seq) .borrow_vec() .getitem_by_index(vm, i) }), ass_item: atomic_func!(|seq, i, value, vm| { let zelf = PyList::sequence_downcast(seq); if let Some(value) = value { zelf.borrow_vec_mut().setitem_by_index(vm, i, value) } else { zelf.borrow_vec_mut().delitem_by_index(vm, i) } }), contains: atomic_func!(|seq, target, vm| { let zelf = PyList::sequence_downcast(seq); zelf.mut_contains(vm, target) }), inplace_concat: atomic_func!(|seq, other, vm| { let zelf = PyList::sequence_downcast(seq); PyList::inplace_concat(zelf, other, vm) }), inplace_repeat: atomic_func!(|seq, n, vm| { let zelf = PyList::sequence_downcast(seq); Ok(PyList::irepeat(zelf.to_owned(), n, vm)?.into()) }), }; &AS_SEQUENCE } } impl Iterable for PyList { fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { Ok(PyListIterator { internal: PyMutex::new(PositionIterInternal::new(zelf, 0)), } .into_pyobject(vm)) } } impl Comparable for PyList { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { if let Some(res) = op.identical_optimization(zelf, other) { return Ok(res.into()); } let other = class_or_notimplemented!(Self, other); let a = &*zelf.borrow_vec(); let b = &*other.borrow_vec(); a.iter() .richcompare(b.iter(), op, vm) .map(PyComparisonValue::Implemented) } } impl Representable for PyList { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { let s = if zelf.__len__() == 0 { "[]".to_owned() } else if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { collection_repr(None, "[", "]", zelf.borrow_vec().iter(), vm)? } else { "[...]".to_owned() }; Ok(s) } } fn do_sort( vm: &VirtualMachine, values: &mut Vec<PyObjectRef>, key_func: Option<PyObjectRef>, reverse: bool, ) -> PyResult<()> { let op = if reverse { PyComparisonOp::Lt } else { PyComparisonOp::Gt }; let cmp = |a: &PyObjectRef, b: &PyObjectRef| a.rich_compare_bool(b, op, vm); if let Some(ref key_func) = key_func { let mut items = values .iter() .map(|x| Ok((x.clone(), key_func.call((x.clone(),), vm)?))) .collect::<Result<Vec<_>, _>>()?; timsort::try_sort_by_gt(&mut items, |a, b| cmp(&a.1, &b.1))?; *values = items.into_iter().map(|(val, _)| val).collect(); } else { timsort::try_sort_by_gt(values, cmp)?; } Ok(()) } #[pyclass(module = false, name = "list_iterator", traverse)] #[derive(Debug)] pub struct PyListIterator { internal: PyMutex<PositionIterInternal<PyListRef>>, } impl PyPayload for PyListIterator { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.list_iterator_type } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] impl PyListIterator { #[pymethod] fn __length_hint__(&self) -> usize { self.internal.lock().length_hint(|obj| obj.__len__()) } #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal .lock() .set_state(state, |obj, pos| pos.min(obj.__len__()), vm) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef { self.internal .lock() .builtins_iter_reduce(|x| x.clone().into(), vm) } } impl SelfIter for PyListIterator {} impl IterNext for PyListIterator { fn next(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyIterReturn> { zelf.internal.lock().next(|list, pos| { let vec = list.borrow_vec(); Ok(PyIterReturn::from_result(vec.get(pos).cloned().ok_or(None))) }) } } #[pyclass(module = false, name = "list_reverseiterator", traverse)] #[derive(Debug)] pub struct PyListReverseIterator { internal: PyMutex<PositionIterInternal<PyListRef>>, } impl PyPayload for PyListReverseIterator { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.list_reverseiterator_type } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] impl PyListReverseIterator { #[pymethod] fn __length_hint__(&self) -> usize { self.internal.lock().rev_length_hint(|obj| obj.__len__()) } #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal .lock() .set_state(state, |obj, pos| pos.min(obj.__len__()), vm) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef { self.internal .lock() .builtins_reversed_reduce(|x| x.clone().into(), vm) } } impl SelfIter for PyListReverseIterator {} impl IterNext for PyListReverseIterator { fn next(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyIterReturn> { zelf.internal.lock().rev_next(|list, pos| { let vec = list.borrow_vec(); Ok(PyIterReturn::from_result(vec.get(pos).cloned().ok_or(None))) }) } } pub fn init(context: &Context) { let list_type = &context.types.list_type; PyList::extend_class(context, list_type); PyListIterator::extend_class(context, context.types.list_iterator_type); PyListReverseIterator::extend_class(context, context.types.list_reverseiterator_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/asyncgenerator.rs
crates/vm/src/builtins/asyncgenerator.rs
use super::{PyCode, PyGenericAlias, PyStrRef, PyType, PyTypeRef}; use crate::{ AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::PyBaseExceptionRef, class::PyClassImpl, common::lock::PyMutex, coroutine::{Coro, warn_deprecated_throw_signature}, frame::FrameRef, function::OptionalArg, protocol::PyIterReturn, types::{Destructor, IterNext, Iterable, Representable, SelfIter}, }; use crossbeam_utils::atomic::AtomicCell; #[pyclass(name = "async_generator", module = false)] #[derive(Debug)] pub struct PyAsyncGen { inner: Coro, running_async: AtomicCell<bool>, // whether hooks have been initialized ag_hooks_inited: AtomicCell<bool>, // ag_origin_or_finalizer - stores the finalizer callback ag_finalizer: PyMutex<Option<PyObjectRef>>, } type PyAsyncGenRef = PyRef<PyAsyncGen>; impl PyPayload for PyAsyncGen { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.async_generator } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(PyRef, Representable, Destructor))] impl PyAsyncGen { pub const fn as_coro(&self) -> &Coro { &self.inner } pub fn new(frame: FrameRef, name: PyStrRef, qualname: PyStrRef) -> Self { Self { inner: Coro::new(frame, name, qualname), running_async: AtomicCell::new(false), ag_hooks_inited: AtomicCell::new(false), ag_finalizer: PyMutex::new(None), } } /// Initialize async generator hooks. /// Returns Ok(()) if successful, Err if firstiter hook raised an exception. fn init_hooks(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<()> { // = async_gen_init_hooks if zelf.ag_hooks_inited.load() { return Ok(()); } zelf.ag_hooks_inited.store(true); // Get and store finalizer from thread-local storage let finalizer = crate::vm::thread::ASYNC_GEN_FINALIZER.with_borrow(|f| f.as_ref().cloned()); if let Some(finalizer) = finalizer { *zelf.ag_finalizer.lock() = Some(finalizer); } // Call firstiter hook let firstiter = crate::vm::thread::ASYNC_GEN_FIRSTITER.with_borrow(|f| f.as_ref().cloned()); if let Some(firstiter) = firstiter { let obj: PyObjectRef = zelf.to_owned().into(); firstiter.call((obj,), vm)?; } Ok(()) } /// Call finalizer hook if set. fn call_finalizer(zelf: &Py<Self>, vm: &VirtualMachine) { let finalizer = zelf.ag_finalizer.lock().clone(); if let Some(finalizer) = finalizer && !zelf.inner.closed.load() { // Ignore any errors (PyErr_WriteUnraisable) let obj: PyObjectRef = zelf.to_owned().into(); let _ = finalizer.call((obj,), vm); } } #[pygetset] fn __name__(&self) -> PyStrRef { self.inner.name() } #[pygetset(setter)] fn set___name__(&self, name: PyStrRef) { self.inner.set_name(name) } #[pygetset] fn __qualname__(&self) -> PyStrRef { self.inner.qualname() } #[pygetset(setter)] fn set___qualname__(&self, qualname: PyStrRef) { self.inner.set_qualname(qualname) } #[pygetset] fn ag_await(&self, _vm: &VirtualMachine) -> Option<PyObjectRef> { self.inner.frame().yield_from_target() } #[pygetset] fn ag_frame(&self, _vm: &VirtualMachine) -> FrameRef { self.inner.frame() } #[pygetset] fn ag_running(&self, _vm: &VirtualMachine) -> bool { self.inner.running() } #[pygetset] fn ag_code(&self, _vm: &VirtualMachine) -> PyRef<PyCode> { self.inner.frame().code.clone() } #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } #[pyclass] impl PyRef<PyAsyncGen> { #[pymethod] const fn __aiter__(self, _vm: &VirtualMachine) -> Self { self } #[pymethod] fn __anext__(self, vm: &VirtualMachine) -> PyResult<PyAsyncGenASend> { PyAsyncGen::init_hooks(&self, vm)?; Ok(PyAsyncGenASend { ag: self, state: AtomicCell::new(AwaitableState::Init), value: vm.ctx.none(), }) } #[pymethod] fn asend(self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyAsyncGenASend> { PyAsyncGen::init_hooks(&self, vm)?; Ok(PyAsyncGenASend { ag: self, state: AtomicCell::new(AwaitableState::Init), value, }) } #[pymethod] fn athrow( self, exc_type: PyObjectRef, exc_val: OptionalArg, exc_tb: OptionalArg, vm: &VirtualMachine, ) -> PyResult<PyAsyncGenAThrow> { PyAsyncGen::init_hooks(&self, vm)?; Ok(PyAsyncGenAThrow { ag: self, aclose: false, state: AtomicCell::new(AwaitableState::Init), value: ( exc_type, exc_val.unwrap_or_none(vm), exc_tb.unwrap_or_none(vm), ), }) } #[pymethod] fn aclose(self, vm: &VirtualMachine) -> PyResult<PyAsyncGenAThrow> { PyAsyncGen::init_hooks(&self, vm)?; Ok(PyAsyncGenAThrow { ag: self, aclose: true, state: AtomicCell::new(AwaitableState::Init), value: ( vm.ctx.exceptions.generator_exit.to_owned().into(), vm.ctx.none(), vm.ctx.none(), ), }) } } impl Representable for PyAsyncGen { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { Ok(zelf.inner.repr(zelf.as_object(), zelf.get_id(), vm)) } } #[pyclass(module = false, name = "async_generator_wrapped_value")] #[derive(Debug)] pub(crate) struct PyAsyncGenWrappedValue(pub PyObjectRef); impl PyPayload for PyAsyncGenWrappedValue { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.async_generator_wrapped_value } } #[pyclass] impl PyAsyncGenWrappedValue {} impl PyAsyncGenWrappedValue { fn unbox(ag: &PyAsyncGen, val: PyResult<PyIterReturn>, vm: &VirtualMachine) -> PyResult { let (closed, async_done) = match &val { Ok(PyIterReturn::StopIteration(_)) => (true, true), Err(e) if e.fast_isinstance(vm.ctx.exceptions.generator_exit) => (true, true), Err(_) => (false, true), _ => (false, false), }; if closed { ag.inner.closed.store(true); } if async_done { ag.running_async.store(false); } let val = val?.into_async_pyresult(vm)?; match_class!(match val { val @ Self => { ag.running_async.store(false); Err(vm.new_stop_iteration(Some(val.0.clone()))) } val => Ok(val), }) } } #[derive(Debug, Clone, Copy)] enum AwaitableState { Init, Iter, Closed, } #[pyclass(module = false, name = "async_generator_asend")] #[derive(Debug)] pub(crate) struct PyAsyncGenASend { ag: PyAsyncGenRef, state: AtomicCell<AwaitableState>, value: PyObjectRef, } impl PyPayload for PyAsyncGenASend { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.async_generator_asend } } #[pyclass(with(IterNext, Iterable))] impl PyAsyncGenASend { #[pymethod(name = "__await__")] const fn r#await(zelf: PyRef<Self>, _vm: &VirtualMachine) -> PyRef<Self> { zelf } #[pymethod] fn send(&self, val: PyObjectRef, vm: &VirtualMachine) -> PyResult { let val = match self.state.load() { AwaitableState::Closed => { return Err( vm.new_runtime_error("cannot reuse already awaited __anext__()/asend()") ); } AwaitableState::Iter => val, // already running, all good AwaitableState::Init => { if self.ag.running_async.load() { return Err( vm.new_runtime_error("anext(): asynchronous generator is already running") ); } self.ag.running_async.store(true); self.state.store(AwaitableState::Iter); if vm.is_none(&val) { self.value.clone() } else { val } } }; let res = self.ag.inner.send(self.ag.as_object(), val, vm); let res = PyAsyncGenWrappedValue::unbox(&self.ag, res, vm); if res.is_err() { self.close(); } res } #[pymethod] fn throw( &self, exc_type: PyObjectRef, exc_val: OptionalArg, exc_tb: OptionalArg, vm: &VirtualMachine, ) -> PyResult { if let AwaitableState::Closed = self.state.load() { return Err(vm.new_runtime_error("cannot reuse already awaited __anext__()/asend()")); } warn_deprecated_throw_signature(&exc_val, &exc_tb, vm)?; let res = self.ag.inner.throw( self.ag.as_object(), exc_type, exc_val.unwrap_or_none(vm), exc_tb.unwrap_or_none(vm), vm, ); let res = PyAsyncGenWrappedValue::unbox(&self.ag, res, vm); if res.is_err() { self.close(); } res } #[pymethod] fn close(&self) { self.state.store(AwaitableState::Closed); } } impl SelfIter for PyAsyncGenASend {} impl IterNext for PyAsyncGenASend { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { PyIterReturn::from_pyresult(zelf.send(vm.ctx.none(), vm), vm) } } #[pyclass(module = false, name = "async_generator_athrow")] #[derive(Debug)] pub(crate) struct PyAsyncGenAThrow { ag: PyAsyncGenRef, aclose: bool, state: AtomicCell<AwaitableState>, value: (PyObjectRef, PyObjectRef, PyObjectRef), } impl PyPayload for PyAsyncGenAThrow { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.async_generator_athrow } } #[pyclass(with(IterNext, Iterable))] impl PyAsyncGenAThrow { #[pymethod(name = "__await__")] const fn r#await(zelf: PyRef<Self>, _vm: &VirtualMachine) -> PyRef<Self> { zelf } #[pymethod] fn send(&self, val: PyObjectRef, vm: &VirtualMachine) -> PyResult { match self.state.load() { AwaitableState::Closed => { Err(vm.new_runtime_error("cannot reuse already awaited aclose()/athrow()")) } AwaitableState::Init => { if self.ag.running_async.load() { self.state.store(AwaitableState::Closed); let msg = if self.aclose { "aclose(): asynchronous generator is already running" } else { "athrow(): asynchronous generator is already running" }; return Err(vm.new_runtime_error(msg.to_owned())); } if self.ag.inner.closed() { self.state.store(AwaitableState::Closed); return Err(vm.new_stop_iteration(None)); } if !vm.is_none(&val) { return Err(vm.new_runtime_error( "can't send non-None value to a just-started async generator", )); } self.state.store(AwaitableState::Iter); self.ag.running_async.store(true); let (ty, val, tb) = self.value.clone(); let ret = self.ag.inner.throw(self.ag.as_object(), ty, val, tb, vm); let ret = if self.aclose { if self.ignored_close(&ret) { Err(self.yield_close(vm)) } else { ret.and_then(|o| o.into_async_pyresult(vm)) } } else { PyAsyncGenWrappedValue::unbox(&self.ag, ret, vm) }; ret.map_err(|e| self.check_error(e, vm)) } AwaitableState::Iter => { let ret = self.ag.inner.send(self.ag.as_object(), val, vm); if self.aclose { match ret { Ok(PyIterReturn::Return(v)) if v.downcastable::<PyAsyncGenWrappedValue>() => { Err(self.yield_close(vm)) } other => other .and_then(|o| o.into_async_pyresult(vm)) .map_err(|e| self.check_error(e, vm)), } } else { PyAsyncGenWrappedValue::unbox(&self.ag, ret, vm) } } } } #[pymethod] fn throw( &self, exc_type: PyObjectRef, exc_val: OptionalArg, exc_tb: OptionalArg, vm: &VirtualMachine, ) -> PyResult { warn_deprecated_throw_signature(&exc_val, &exc_tb, vm)?; let ret = self.ag.inner.throw( self.ag.as_object(), exc_type, exc_val.unwrap_or_none(vm), exc_tb.unwrap_or_none(vm), vm, ); let res = if self.aclose { if self.ignored_close(&ret) { Err(self.yield_close(vm)) } else { ret.and_then(|o| o.into_async_pyresult(vm)) } } else { PyAsyncGenWrappedValue::unbox(&self.ag, ret, vm) }; res.map_err(|e| self.check_error(e, vm)) } #[pymethod] fn close(&self) { self.state.store(AwaitableState::Closed); } fn ignored_close(&self, res: &PyResult<PyIterReturn>) -> bool { res.as_ref().is_ok_and(|v| match v { PyIterReturn::Return(obj) => obj.downcastable::<PyAsyncGenWrappedValue>(), PyIterReturn::StopIteration(_) => false, }) } fn yield_close(&self, vm: &VirtualMachine) -> PyBaseExceptionRef { self.ag.running_async.store(false); self.state.store(AwaitableState::Closed); vm.new_runtime_error("async generator ignored GeneratorExit") } fn check_error(&self, exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyBaseExceptionRef { self.ag.running_async.store(false); self.state.store(AwaitableState::Closed); if self.aclose && (exc.fast_isinstance(vm.ctx.exceptions.stop_async_iteration) || exc.fast_isinstance(vm.ctx.exceptions.generator_exit)) { vm.new_stop_iteration(None) } else { exc } } } impl SelfIter for PyAsyncGenAThrow {} impl IterNext for PyAsyncGenAThrow { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { PyIterReturn::from_pyresult(zelf.send(vm.ctx.none(), vm), vm) } } /// Awaitable wrapper for anext() builtin with default value. /// When StopAsyncIteration is raised, it converts it to StopIteration(default). #[pyclass(module = false, name = "anext_awaitable")] #[derive(Debug)] pub struct PyAnextAwaitable { wrapped: PyObjectRef, default_value: PyObjectRef, state: AtomicCell<AwaitableState>, } impl PyPayload for PyAnextAwaitable { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.anext_awaitable } } #[pyclass(with(IterNext, Iterable))] impl PyAnextAwaitable { pub fn new(wrapped: PyObjectRef, default_value: PyObjectRef) -> Self { Self { wrapped, default_value, state: AtomicCell::new(AwaitableState::Init), } } #[pymethod(name = "__await__")] fn r#await(zelf: PyRef<Self>, _vm: &VirtualMachine) -> PyRef<Self> { zelf } fn check_closed(&self, vm: &VirtualMachine) -> PyResult<()> { if let AwaitableState::Closed = self.state.load() { return Err(vm.new_runtime_error("cannot reuse already awaited __anext__()/asend()")); } Ok(()) } /// Get the awaitable iterator from wrapped object. // = anextawaitable_getiter. fn get_awaitable_iter(&self, vm: &VirtualMachine) -> PyResult { use crate::builtins::PyCoroutine; use crate::protocol::PyIter; let wrapped = &self.wrapped; // If wrapped is already an async_generator_asend, it's an iterator if wrapped.class().is(vm.ctx.types.async_generator_asend) || wrapped.class().is(vm.ctx.types.async_generator_athrow) { return Ok(wrapped.clone()); } // _PyCoro_GetAwaitableIter equivalent let awaitable = if wrapped.class().is(vm.ctx.types.coroutine_type) { // Coroutine - get __await__ later wrapped.clone() } else { // Try to get __await__ method if let Some(await_method) = vm.get_method(wrapped.clone(), identifier!(vm, __await__)) { await_method?.call((), vm)? } else { return Err(vm.new_type_error(format!( "object {} can't be used in 'await' expression", wrapped.class().name() ))); } }; // If awaitable is a coroutine, get its __await__ if awaitable.class().is(vm.ctx.types.coroutine_type) { let coro_await = vm.call_method(&awaitable, "__await__", ())?; // Check that __await__ returned an iterator if !PyIter::check(&coro_await) { return Err(vm.new_type_error("__await__ returned a non-iterable")); } return Ok(coro_await); } // Check the result is an iterator, not a coroutine if awaitable.downcast_ref::<PyCoroutine>().is_some() { return Err(vm.new_type_error("__await__() returned a coroutine")); } // Check that the result is an iterator if !PyIter::check(&awaitable) { return Err(vm.new_type_error(format!( "__await__() returned non-iterator of type '{}'", awaitable.class().name() ))); } Ok(awaitable) } #[pymethod] fn send(&self, val: PyObjectRef, vm: &VirtualMachine) -> PyResult { self.check_closed(vm)?; self.state.store(AwaitableState::Iter); let awaitable = self.get_awaitable_iter(vm)?; let result = vm.call_method(&awaitable, "send", (val,)); self.handle_result(result, vm) } #[pymethod] fn throw( &self, exc_type: PyObjectRef, exc_val: OptionalArg, exc_tb: OptionalArg, vm: &VirtualMachine, ) -> PyResult { self.check_closed(vm)?; warn_deprecated_throw_signature(&exc_val, &exc_tb, vm)?; self.state.store(AwaitableState::Iter); let awaitable = self.get_awaitable_iter(vm)?; let result = vm.call_method( &awaitable, "throw", ( exc_type, exc_val.unwrap_or_none(vm), exc_tb.unwrap_or_none(vm), ), ); self.handle_result(result, vm) } #[pymethod] fn close(&self, vm: &VirtualMachine) -> PyResult<()> { self.state.store(AwaitableState::Closed); if let Ok(awaitable) = self.get_awaitable_iter(vm) { let _ = vm.call_method(&awaitable, "close", ()); } Ok(()) } /// Convert StopAsyncIteration to StopIteration(default_value) fn handle_result(&self, result: PyResult, vm: &VirtualMachine) -> PyResult { match result { Ok(value) => Ok(value), Err(exc) if exc.fast_isinstance(vm.ctx.exceptions.stop_async_iteration) => { Err(vm.new_stop_iteration(Some(self.default_value.clone()))) } Err(exc) => Err(exc), } } } impl SelfIter for PyAnextAwaitable {} impl IterNext for PyAnextAwaitable { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { PyIterReturn::from_pyresult(zelf.send(vm.ctx.none(), vm), vm) } } /// _PyGen_Finalize for async generators impl Destructor for PyAsyncGen { fn del(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<()> { // Generator isn't paused, so no need to close if zelf.inner.closed.load() { return Ok(()); } Self::call_finalizer(zelf, vm); Ok(()) } } pub fn init(ctx: &Context) { PyAsyncGen::extend_class(ctx, ctx.types.async_generator); PyAsyncGenASend::extend_class(ctx, ctx.types.async_generator_asend); PyAsyncGenAThrow::extend_class(ctx, ctx.types.async_generator_athrow); PyAnextAwaitable::extend_class(ctx, ctx.types.anext_awaitable); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/singletons.rs
crates/vm/src/builtins/singletons.rs
use super::{PyStrRef, PyType, PyTypeRef}; use crate::{ Context, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, class::PyClassImpl, convert::ToPyObject, function::FuncArgs, protocol::PyNumberMethods, types::{AsNumber, Constructor, Representable}, }; #[pyclass(module = false, name = "NoneType")] #[derive(Debug)] pub struct PyNone; impl PyPayload for PyNone { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.none_type } } // This allows a built-in function to not return a value, mapping to // Python's behavior of returning `None` in this situation. impl ToPyObject for () { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.none() } } impl<T: ToPyObject> ToPyObject for Option<T> { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { match self { Some(x) => x.to_pyobject(vm), None => vm.ctx.none(), } } } impl Constructor for PyNone { type Args = (); fn slot_new(_cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let _: () = args.bind(vm)?; Ok(vm.ctx.none.clone().into()) } fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> { unreachable!("None is a singleton") } } #[pyclass(with(Constructor, AsNumber, Representable))] impl PyNone {} impl Representable for PyNone { #[inline] fn repr(_zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> { Ok(vm.ctx.names.None.to_owned()) } #[cold] fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { unreachable!("use repr instead") } } impl AsNumber for PyNone { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { boolean: Some(|_number, _vm| Ok(false)), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } } #[pyclass(module = false, name = "NotImplementedType")] #[derive(Debug)] pub struct PyNotImplemented; impl PyPayload for PyNotImplemented { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.not_implemented_type } } impl Constructor for PyNotImplemented { type Args = (); fn slot_new(_cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let _: () = args.bind(vm)?; Ok(vm.ctx.not_implemented.clone().into()) } fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> { unreachable!("PyNotImplemented is a singleton") } } #[pyclass(with(Constructor, AsNumber, Representable))] impl PyNotImplemented { #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyStrRef { vm.ctx.names.NotImplemented.to_owned() } } impl AsNumber for PyNotImplemented { fn as_number() -> &'static PyNumberMethods { // TODO: As per https://bugs.python.org/issue35712, using NotImplemented // in boolean contexts will need to raise a DeprecationWarning in 3.9 // and, eventually, a TypeError. static AS_NUMBER: PyNumberMethods = PyNumberMethods { boolean: Some(|_number, _vm| Ok(true)), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } } impl Representable for PyNotImplemented { #[inline] fn repr(_zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> { Ok(vm.ctx.names.NotImplemented.to_owned()) } #[cold] fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { unreachable!("use repr instead") } } pub fn init(context: &Context) { PyNone::extend_class(context, context.types.none_type); PyNotImplemented::extend_class(context, context.types.not_implemented_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/bytearray.rs
crates/vm/src/builtins/bytearray.rs
//! Implementation of the python bytearray object. use super::{ PositionIterInternal, PyBytes, PyBytesRef, PyDictRef, PyGenericAlias, PyIntRef, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, anystr::{self, AnyStr}, atomic_func, byte::{bytes_from_object, value_from_object}, bytes_inner::{ ByteInnerFindOptions, ByteInnerNewOptions, ByteInnerPaddingOptions, ByteInnerSplitOptions, ByteInnerTranslateOptions, DecodeArgs, PyBytesInner, bytes_decode, }, class::PyClassImpl, common::{ atomic::{AtomicUsize, Ordering}, lock::{ PyMappedRwLockReadGuard, PyMappedRwLockWriteGuard, PyMutex, PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard, }, }, convert::{ToPyObject, ToPyResult}, function::{ ArgBytesLike, ArgIterable, ArgSize, Either, OptionalArg, OptionalOption, PyComparisonValue, }, protocol::{ BufferDescriptor, BufferMethods, BufferResizeGuard, PyBuffer, PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods, }, sliceable::{SequenceIndex, SliceableSequenceMutOp, SliceableSequenceOp}, types::{ AsBuffer, AsMapping, AsNumber, AsSequence, Callable, Comparable, Constructor, DefaultConstructor, Initializer, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, }, }; use bstr::ByteSlice; use core::mem::size_of; #[pyclass(module = false, name = "bytearray", unhashable = true)] #[derive(Debug, Default)] pub struct PyByteArray { inner: PyRwLock<PyBytesInner>, exports: AtomicUsize, } pub type PyByteArrayRef = PyRef<PyByteArray>; impl From<PyBytesInner> for PyByteArray { fn from(inner: PyBytesInner) -> Self { Self::from_inner(inner) } } impl From<Vec<u8>> for PyByteArray { fn from(elements: Vec<u8>) -> Self { Self::from(PyBytesInner { elements }) } } impl PyPayload for PyByteArray { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.bytearray_type } } /// Fill bytearray class methods dictionary. pub(crate) fn init(context: &Context) { PyByteArray::extend_class(context, context.types.bytearray_type); PyByteArrayIterator::extend_class(context, context.types.bytearray_iterator_type); } impl PyByteArray { #[deprecated(note = "use PyByteArray::from(...).into_ref() instead")] pub fn new_ref(data: Vec<u8>, ctx: &Context) -> PyRef<Self> { Self::from(data).into_ref(ctx) } const fn from_inner(inner: PyBytesInner) -> Self { Self { inner: PyRwLock::new(inner), exports: AtomicUsize::new(0), } } pub fn borrow_buf(&self) -> PyMappedRwLockReadGuard<'_, [u8]> { PyRwLockReadGuard::map(self.inner.read(), |inner| &*inner.elements) } pub fn borrow_buf_mut(&self) -> PyMappedRwLockWriteGuard<'_, Vec<u8>> { PyRwLockWriteGuard::map(self.inner.write(), |inner| &mut inner.elements) } fn repeat(&self, value: isize, vm: &VirtualMachine) -> PyResult<Self> { self.inner().mul(value, vm).map(|x| x.into()) } fn _setitem_by_index(&self, i: isize, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let value = value_from_object(vm, &value)?; self.borrow_buf_mut().setitem_by_index(vm, i, value) } fn _setitem( zelf: &Py<Self>, needle: &PyObject, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { match SequenceIndex::try_from_borrowed_object(vm, needle, "bytearray")? { SequenceIndex::Int(i) => zelf._setitem_by_index(i, value, vm), SequenceIndex::Slice(slice) => { let items = if zelf.is(&value) { zelf.borrow_buf().to_vec() } else { bytes_from_object(vm, &value)? }; if let Some(mut w) = zelf.try_resizable_opt() { w.elements.setitem_by_slice(vm, slice, &items) } else { zelf.borrow_buf_mut() .setitem_by_slice_no_resize(vm, slice, &items) } } } } fn _getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { match SequenceIndex::try_from_borrowed_object(vm, needle, "bytearray")? { SequenceIndex::Int(i) => self .borrow_buf() .getitem_by_index(vm, i) .map(|x| vm.ctx.new_int(x).into()), SequenceIndex::Slice(slice) => self .borrow_buf() .getitem_by_slice(vm, slice) .map(|x| vm.ctx.new_bytearray(x).into()), } } pub fn _delitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<()> { match SequenceIndex::try_from_borrowed_object(vm, needle, "bytearray")? { SequenceIndex::Int(i) => self.try_resizable(vm)?.elements.delitem_by_index(vm, i), SequenceIndex::Slice(slice) => { // TODO: delete 0 elements don't need resizable self.try_resizable(vm)?.elements.delitem_by_slice(vm, slice) } } } fn irepeat(zelf: &Py<Self>, n: isize, vm: &VirtualMachine) -> PyResult<()> { if n == 1 { return Ok(()); } let mut w = match zelf.try_resizable(vm) { Ok(w) => w, Err(err) => { return if zelf.borrow_buf().is_empty() { // We can multiple an empty vector by any integer Ok(()) } else { Err(err) }; } }; w.imul(n, vm) } } #[pyclass( flags(BASETYPE, _MATCH_SELF), with( Py, PyRef, Constructor, Initializer, Comparable, AsBuffer, AsMapping, AsSequence, AsNumber, Iterable, Representable ) )] impl PyByteArray { #[cfg(debug_assertions)] #[pygetset] fn exports(&self) -> usize { self.exports.load(Ordering::Relaxed) } #[inline] fn inner(&self) -> PyRwLockReadGuard<'_, PyBytesInner> { self.inner.read() } #[inline] fn inner_mut(&self) -> PyRwLockWriteGuard<'_, PyBytesInner> { self.inner.write() } #[pymethod] fn __alloc__(&self) -> usize { self.inner().capacity() } fn __len__(&self) -> usize { self.borrow_buf().len() } #[pymethod] fn __sizeof__(&self) -> usize { size_of::<Self>() + self.borrow_buf().len() * size_of::<u8>() } fn __add__(&self, other: ArgBytesLike) -> Self { self.inner().add(&other.borrow_buf()).into() } fn __contains__( &self, needle: Either<PyBytesInner, PyIntRef>, vm: &VirtualMachine, ) -> PyResult<bool> { self.inner().contains(needle, vm) } fn __iadd__( zelf: PyRef<Self>, other: ArgBytesLike, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { zelf.try_resizable(vm)? .elements .extend(&*other.borrow_buf()); Ok(zelf) } fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { self._getitem(&needle, vm) } pub fn __delitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self._delitem(&needle, vm) } #[pystaticmethod] fn maketrans(from: PyBytesInner, to: PyBytesInner, vm: &VirtualMachine) -> PyResult<Vec<u8>> { PyBytesInner::maketrans(from, to, vm) } #[pymethod] fn isalnum(&self) -> bool { self.inner().isalnum() } #[pymethod] fn isalpha(&self) -> bool { self.inner().isalpha() } #[pymethod] fn isascii(&self) -> bool { self.inner().isascii() } #[pymethod] fn isdigit(&self) -> bool { self.inner().isdigit() } #[pymethod] fn islower(&self) -> bool { self.inner().islower() } #[pymethod] fn isspace(&self) -> bool { self.inner().isspace() } #[pymethod] fn isupper(&self) -> bool { self.inner().isupper() } #[pymethod] fn istitle(&self) -> bool { self.inner().istitle() } #[pymethod] fn lower(&self) -> Self { self.inner().lower().into() } #[pymethod] fn upper(&self) -> Self { self.inner().upper().into() } #[pymethod] fn capitalize(&self) -> Self { self.inner().capitalize().into() } #[pymethod] fn swapcase(&self) -> Self { self.inner().swapcase().into() } #[pymethod] fn hex( &self, sep: OptionalArg<Either<PyStrRef, PyBytesRef>>, bytes_per_sep: OptionalArg<isize>, vm: &VirtualMachine, ) -> PyResult<String> { self.inner().hex(sep, bytes_per_sep, vm) } #[pyclassmethod] fn fromhex(cls: PyTypeRef, string: PyStrRef, vm: &VirtualMachine) -> PyResult { let bytes = PyBytesInner::fromhex(string.as_bytes(), vm)?; let bytes = vm.ctx.new_bytes(bytes); let args = vec![bytes.into()].into(); PyType::call(&cls, args, vm) } #[pymethod] fn center(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<Self> { Ok(self.inner().center(options, vm)?.into()) } #[pymethod] fn ljust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<Self> { Ok(self.inner().ljust(options, vm)?.into()) } #[pymethod] fn rjust(&self, options: ByteInnerPaddingOptions, vm: &VirtualMachine) -> PyResult<Self> { Ok(self.inner().rjust(options, vm)?.into()) } #[pymethod] fn count(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> { self.inner().count(options, vm) } #[pymethod] fn join(&self, iter: ArgIterable<PyBytesInner>, vm: &VirtualMachine) -> PyResult<Self> { Ok(self.inner().join(iter, vm)?.into()) } #[pymethod] fn endswith(&self, options: anystr::StartsEndsWithArgs, vm: &VirtualMachine) -> PyResult<bool> { let borrowed = self.borrow_buf(); let (affix, substr) = match options.prepare(&*borrowed, borrowed.len(), |s, r| s.get_bytes(r)) { Some(x) => x, None => return Ok(false), }; substr.py_starts_ends_with( &affix, "endswith", "bytes", |s, x: PyBytesInner| s.ends_with(x.as_bytes()), vm, ) } #[pymethod] fn startswith( &self, options: anystr::StartsEndsWithArgs, vm: &VirtualMachine, ) -> PyResult<bool> { let borrowed = self.borrow_buf(); let (affix, substr) = match options.prepare(&*borrowed, borrowed.len(), |s, r| s.get_bytes(r)) { Some(x) => x, None => return Ok(false), }; substr.py_starts_ends_with( &affix, "startswith", "bytes", |s, x: PyBytesInner| s.starts_with(x.as_bytes()), vm, ) } #[pymethod] fn find(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<isize> { let index = self.inner().find(options, |h, n| h.find(n), vm)?; Ok(index.map_or(-1, |v| v as isize)) } #[pymethod] fn index(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> { let index = self.inner().find(options, |h, n| h.find(n), vm)?; index.ok_or_else(|| vm.new_value_error("substring not found")) } #[pymethod] fn rfind(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<isize> { let index = self.inner().find(options, |h, n| h.rfind(n), vm)?; Ok(index.map_or(-1, |v| v as isize)) } #[pymethod] fn rindex(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult<usize> { let index = self.inner().find(options, |h, n| h.rfind(n), vm)?; index.ok_or_else(|| vm.new_value_error("substring not found")) } #[pymethod] fn translate(&self, options: ByteInnerTranslateOptions, vm: &VirtualMachine) -> PyResult<Self> { Ok(self.inner().translate(options, vm)?.into()) } #[pymethod] fn strip(&self, chars: OptionalOption<PyBytesInner>) -> Self { self.inner().strip(chars).into() } #[pymethod] fn removeprefix(&self, prefix: PyBytesInner) -> Self { self.inner().removeprefix(prefix).into() } #[pymethod] fn removesuffix(&self, suffix: PyBytesInner) -> Self { self.inner().removesuffix(suffix).to_vec().into() } #[pymethod] fn split( &self, options: ByteInnerSplitOptions, vm: &VirtualMachine, ) -> PyResult<Vec<PyObjectRef>> { self.inner() .split(options, |s, vm| vm.ctx.new_bytearray(s.to_vec()).into(), vm) } #[pymethod] fn rsplit( &self, options: ByteInnerSplitOptions, vm: &VirtualMachine, ) -> PyResult<Vec<PyObjectRef>> { self.inner() .rsplit(options, |s, vm| vm.ctx.new_bytearray(s.to_vec()).into(), vm) } #[pymethod] fn partition(&self, sep: PyBytesInner, vm: &VirtualMachine) -> PyResult<PyTupleRef> { // sep ALWAYS converted to bytearray even it's bytes or memoryview // so its ok to accept PyBytesInner let value = self.inner(); let (front, has_mid, back) = value.partition(&sep, vm)?; Ok(vm.new_tuple(( vm.ctx.new_bytearray(front.to_vec()), vm.ctx .new_bytearray(if has_mid { sep.elements } else { Vec::new() }), vm.ctx.new_bytearray(back.to_vec()), ))) } #[pymethod] fn rpartition(&self, sep: PyBytesInner, vm: &VirtualMachine) -> PyResult<PyTupleRef> { let value = self.inner(); let (back, has_mid, front) = value.rpartition(&sep, vm)?; Ok(vm.new_tuple(( vm.ctx.new_bytearray(front.to_vec()), vm.ctx .new_bytearray(if has_mid { sep.elements } else { Vec::new() }), vm.ctx.new_bytearray(back.to_vec()), ))) } #[pymethod] fn expandtabs(&self, options: anystr::ExpandTabsArgs) -> Self { self.inner().expandtabs(options).into() } #[pymethod] fn splitlines(&self, options: anystr::SplitLinesArgs, vm: &VirtualMachine) -> Vec<PyObjectRef> { self.inner() .splitlines(options, |x| vm.ctx.new_bytearray(x.to_vec()).into()) } #[pymethod] fn zfill(&self, width: isize) -> Self { self.inner().zfill(width).into() } #[pymethod] fn replace( &self, old: PyBytesInner, new: PyBytesInner, count: OptionalArg<isize>, vm: &VirtualMachine, ) -> PyResult<Self> { Ok(self.inner().replace(old, new, count, vm)?.into()) } #[pymethod] fn copy(&self) -> Self { self.borrow_buf().to_vec().into() } #[pymethod] fn title(&self) -> Self { self.inner().title().into() } fn __mul__(&self, value: ArgSize, vm: &VirtualMachine) -> PyResult<Self> { self.repeat(value.into(), vm) } fn __imul__(zelf: PyRef<Self>, value: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { Self::irepeat(&zelf, value.into(), vm)?; Ok(zelf) } fn __mod__(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> { let formatted = self.inner().cformat(values, vm)?; Ok(formatted.into()) } #[pymethod] fn reverse(&self) { self.borrow_buf_mut().reverse(); } // TODO: Uncomment when Python adds __class_getitem__ to bytearray // #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } #[pyclass] impl Py<PyByteArray> { fn __setitem__( &self, needle: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { PyByteArray::_setitem(self, &needle, value, vm) } #[pymethod] fn pop(&self, index: OptionalArg<isize>, vm: &VirtualMachine) -> PyResult<u8> { let elements = &mut self.try_resizable(vm)?.elements; let index = elements .wrap_index(index.unwrap_or(-1)) .ok_or_else(|| vm.new_index_error("index out of range"))?; Ok(elements.remove(index)) } #[pymethod] fn insert(&self, index: isize, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let value = value_from_object(vm, &object)?; let elements = &mut self.try_resizable(vm)?.elements; let index = elements.saturate_index(index); elements.insert(index, value); Ok(()) } #[pymethod] fn append(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let value = value_from_object(vm, &object)?; self.try_resizable(vm)?.elements.push(value); Ok(()) } #[pymethod] fn remove(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let value = value_from_object(vm, &object)?; let elements = &mut self.try_resizable(vm)?.elements; let index = elements .find_byte(value) .ok_or_else(|| vm.new_value_error("value not found in bytearray"))?; elements.remove(index); Ok(()) } #[pymethod] fn extend(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { if self.is(&object) { PyByteArray::irepeat(self, 2, vm) } else { let items = bytes_from_object(vm, &object)?; self.try_resizable(vm)?.elements.extend(items); Ok(()) } } #[pymethod] fn clear(&self, vm: &VirtualMachine) -> PyResult<()> { self.try_resizable(vm)?.elements.clear(); Ok(()) } #[pymethod] fn __reduce_ex__( &self, _proto: usize, vm: &VirtualMachine, ) -> (PyTypeRef, PyTupleRef, Option<PyDictRef>) { self.__reduce__(vm) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef, Option<PyDictRef>) { let bytes = PyBytes::from(self.borrow_buf().to_vec()).to_pyobject(vm); ( self.class().to_owned(), PyTuple::new_ref(vec![bytes], &vm.ctx), self.as_object().dict(), ) } } #[pyclass] impl PyRef<PyByteArray> { #[pymethod] fn lstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self { let inner = self.inner(); let stripped = inner.lstrip(chars); let elements = &inner.elements; if stripped == elements { drop(inner); self } else { vm.ctx.new_pyref(PyByteArray::from(stripped.to_vec())) } } #[pymethod] fn rstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self { let inner = self.inner(); let stripped = inner.rstrip(chars); let elements = &inner.elements; if stripped == elements { drop(inner); self } else { vm.ctx.new_pyref(PyByteArray::from(stripped.to_vec())) } } #[pymethod] fn decode(self, args: DecodeArgs, vm: &VirtualMachine) -> PyResult<PyStrRef> { bytes_decode(self.into(), args, vm) } } impl DefaultConstructor for PyByteArray {} impl Initializer for PyByteArray { type Args = ByteInnerNewOptions; fn init(zelf: PyRef<Self>, options: Self::Args, vm: &VirtualMachine) -> PyResult<()> { // First unpack bytearray and *then* get a lock to set it. let mut inner = options.get_bytearray_inner(vm)?; core::mem::swap(&mut *zelf.inner_mut(), &mut inner); Ok(()) } } impl Comparable for PyByteArray { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { if let Some(res) = op.identical_optimization(zelf, other) { return Ok(res.into()); } Ok(zelf.inner().cmp(other, op, vm)) } } static BUFFER_METHODS: BufferMethods = BufferMethods { obj_bytes: |buffer| buffer.obj_as::<PyByteArray>().borrow_buf().into(), obj_bytes_mut: |buffer| { PyMappedRwLockWriteGuard::map(buffer.obj_as::<PyByteArray>().borrow_buf_mut(), |x| { x.as_mut_slice() }) .into() }, release: |buffer| { buffer .obj_as::<PyByteArray>() .exports .fetch_sub(1, Ordering::Release); }, retain: |buffer| { buffer .obj_as::<PyByteArray>() .exports .fetch_add(1, Ordering::Release); }, }; impl AsBuffer for PyByteArray { fn as_buffer(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyBuffer> { Ok(PyBuffer::new( zelf.to_owned().into(), BufferDescriptor::simple(zelf.__len__(), false), &BUFFER_METHODS, )) } } impl BufferResizeGuard for PyByteArray { type Resizable<'a> = PyRwLockWriteGuard<'a, PyBytesInner>; fn try_resizable_opt(&self) -> Option<Self::Resizable<'_>> { let w = self.inner.write(); (self.exports.load(Ordering::SeqCst) == 0).then_some(w) } } impl AsMapping for PyByteArray { fn as_mapping() -> &'static PyMappingMethods { static AS_MAPPING: PyMappingMethods = PyMappingMethods { length: atomic_func!(|mapping, _vm| Ok( PyByteArray::mapping_downcast(mapping).__len__() )), subscript: atomic_func!(|mapping, needle, vm| { PyByteArray::mapping_downcast(mapping).__getitem__(needle.to_owned(), vm) }), ass_subscript: atomic_func!(|mapping, needle, value, vm| { let zelf = PyByteArray::mapping_downcast(mapping); if let Some(value) = value { zelf.__setitem__(needle.to_owned(), value, vm) } else { zelf.__delitem__(needle.to_owned(), vm) } }), }; &AS_MAPPING } } impl AsSequence for PyByteArray { fn as_sequence() -> &'static PySequenceMethods { static AS_SEQUENCE: PySequenceMethods = PySequenceMethods { length: atomic_func!(|seq, _vm| Ok(PyByteArray::sequence_downcast(seq).__len__())), concat: atomic_func!(|seq, other, vm| { PyByteArray::sequence_downcast(seq) .inner() .concat(other, vm) .map(|x| PyByteArray::from(x).into_pyobject(vm)) }), repeat: atomic_func!(|seq, n, vm| { PyByteArray::sequence_downcast(seq) .repeat(n, vm) .map(|x| x.into_pyobject(vm)) }), item: atomic_func!(|seq, i, vm| { PyByteArray::sequence_downcast(seq) .borrow_buf() .getitem_by_index(vm, i) .map(|x| vm.ctx.new_bytes(vec![x]).into()) }), ass_item: atomic_func!(|seq, i, value, vm| { let zelf = PyByteArray::sequence_downcast(seq); if let Some(value) = value { zelf._setitem_by_index(i, value, vm) } else { zelf.borrow_buf_mut().delitem_by_index(vm, i) } }), contains: atomic_func!(|seq, other, vm| { let other = <Either<PyBytesInner, PyIntRef>>::try_from_object(vm, other.to_owned())?; PyByteArray::sequence_downcast(seq).__contains__(other, vm) }), inplace_concat: atomic_func!(|seq, other, vm| { let other = ArgBytesLike::try_from_object(vm, other.to_owned())?; let zelf = PyByteArray::sequence_downcast(seq).to_owned(); PyByteArray::__iadd__(zelf, other, vm).map(|x| x.into()) }), inplace_repeat: atomic_func!(|seq, n, vm| { let zelf = PyByteArray::sequence_downcast(seq).to_owned(); PyByteArray::irepeat(&zelf, n, vm)?; Ok(zelf.into()) }), }; &AS_SEQUENCE } } impl AsNumber for PyByteArray { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { remainder: Some(|a, b, vm| { if let Some(a) = a.downcast_ref::<PyByteArray>() { a.__mod__(b.to_owned(), vm).to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } }), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } } impl Iterable for PyByteArray { fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { Ok(PyByteArrayIterator { internal: PyMutex::new(PositionIterInternal::new(zelf, 0)), } .into_pyobject(vm)) } } impl Representable for PyByteArray { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { let class = zelf.class(); let class_name = class.name(); zelf.inner().repr_with_name(&class_name, vm) } } #[pyclass(module = false, name = "bytearray_iterator")] #[derive(Debug)] pub struct PyByteArrayIterator { internal: PyMutex<PositionIterInternal<PyByteArrayRef>>, } impl PyPayload for PyByteArrayIterator { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.bytearray_iterator_type } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] impl PyByteArrayIterator { #[pymethod] fn __length_hint__(&self) -> usize { self.internal.lock().length_hint(|obj| obj.__len__()) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef { self.internal .lock() .builtins_iter_reduce(|x| x.clone().into(), vm) } #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal .lock() .set_state(state, |obj, pos| pos.min(obj.__len__()), vm) } } impl SelfIter for PyByteArrayIterator {} impl IterNext for PyByteArrayIterator { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { zelf.internal.lock().next(|bytearray, pos| { let buf = bytearray.borrow_buf(); Ok(PyIterReturn::from_result( buf.get(pos).map(|&x| vm.new_pyobj(x)).ok_or(None), )) }) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/mappingproxy.rs
crates/vm/src/builtins/mappingproxy.rs
use super::{PyDict, PyDictRef, PyGenericAlias, PyList, PyTuple, PyType, PyTypeRef}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, atomic_func, class::PyClassImpl, convert::ToPyObject, function::{ArgMapping, OptionalArg, PyComparisonValue}, object::{Traverse, TraverseFn}, protocol::{PyMappingMethods, PyNumberMethods, PySequenceMethods}, types::{ AsMapping, AsNumber, AsSequence, Comparable, Constructor, Iterable, PyComparisonOp, Representable, }, }; use std::sync::LazyLock; #[pyclass(module = false, name = "mappingproxy", traverse)] #[derive(Debug)] pub struct PyMappingProxy { mapping: MappingProxyInner, } #[derive(Debug)] enum MappingProxyInner { Class(PyTypeRef), Mapping(ArgMapping), } unsafe impl Traverse for MappingProxyInner { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { match self { Self::Class(r) => r.traverse(tracer_fn), Self::Mapping(arg) => arg.traverse(tracer_fn), } } } impl PyPayload for PyMappingProxy { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.mappingproxy_type } } impl From<PyTypeRef> for PyMappingProxy { fn from(dict: PyTypeRef) -> Self { Self { mapping: MappingProxyInner::Class(dict), } } } impl From<PyDictRef> for PyMappingProxy { fn from(dict: PyDictRef) -> Self { Self { mapping: MappingProxyInner::Mapping(ArgMapping::from_dict_exact(dict)), } } } impl Constructor for PyMappingProxy { type Args = PyObjectRef; fn py_new(_cls: &Py<PyType>, mapping: Self::Args, vm: &VirtualMachine) -> PyResult<Self> { if mapping.mapping_unchecked().check() && !mapping.downcastable::<PyList>() && !mapping.downcastable::<PyTuple>() { return Ok(Self { mapping: MappingProxyInner::Mapping(ArgMapping::new(mapping)), }); } Err(vm.new_type_error(format!( "mappingproxy() argument must be a mapping, not {}", mapping.class() ))) } } #[pyclass(with( AsMapping, Iterable, Constructor, AsSequence, Comparable, AsNumber, Representable ))] impl PyMappingProxy { fn get_inner(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<Option<PyObjectRef>> { match &self.mapping { MappingProxyInner::Class(class) => Ok(key .as_interned_str(vm) .and_then(|key| class.attributes.read().get(key).cloned())), MappingProxyInner::Mapping(mapping) => mapping.mapping().subscript(&*key, vm).map(Some), } } #[pymethod] fn get( &self, key: PyObjectRef, default: OptionalArg, vm: &VirtualMachine, ) -> PyResult<Option<PyObjectRef>> { let obj = self.to_object(vm)?; Ok(Some(vm.call_method( &obj, "get", (key, default.unwrap_or_none(vm)), )?)) } pub fn __getitem__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { self.get_inner(key.clone(), vm)? .ok_or_else(|| vm.new_key_error(key)) } fn _contains(&self, key: &PyObject, vm: &VirtualMachine) -> PyResult<bool> { match &self.mapping { MappingProxyInner::Class(class) => Ok(key .as_interned_str(vm) .is_some_and(|key| class.attributes.read().contains_key(key))), MappingProxyInner::Mapping(mapping) => { mapping.obj().sequence_unchecked().contains(key, vm) } } } pub fn __contains__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> { self._contains(&key, vm) } fn to_object(&self, vm: &VirtualMachine) -> PyResult { Ok(match &self.mapping { MappingProxyInner::Mapping(d) => d.as_ref().to_owned(), MappingProxyInner::Class(c) => { PyDict::from_attributes(c.attributes.read().clone(), vm)?.to_pyobject(vm) } }) } #[pymethod] pub fn items(&self, vm: &VirtualMachine) -> PyResult { let obj = self.to_object(vm)?; vm.call_method(&obj, identifier!(vm, items).as_str(), ()) } #[pymethod] pub fn keys(&self, vm: &VirtualMachine) -> PyResult { let obj = self.to_object(vm)?; vm.call_method(&obj, identifier!(vm, keys).as_str(), ()) } #[pymethod] pub fn values(&self, vm: &VirtualMachine) -> PyResult { let obj = self.to_object(vm)?; vm.call_method(&obj, identifier!(vm, values).as_str(), ()) } #[pymethod] pub fn copy(&self, vm: &VirtualMachine) -> PyResult { match &self.mapping { MappingProxyInner::Mapping(d) => { vm.call_method(d.obj(), identifier!(vm, copy).as_str(), ()) } MappingProxyInner::Class(c) => { Ok(PyDict::from_attributes(c.attributes.read().clone(), vm)?.to_pyobject(vm)) } } } #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } fn __len__(&self, vm: &VirtualMachine) -> PyResult<usize> { let obj = self.to_object(vm)?; obj.length(vm) } #[pymethod] fn __reversed__(&self, vm: &VirtualMachine) -> PyResult { vm.call_method( self.to_object(vm)?.as_object(), identifier!(vm, __reversed__).as_str(), (), ) } fn __ior__(&self, _args: PyObjectRef, vm: &VirtualMachine) -> PyResult { Err(vm.new_type_error(format!( r#""'|=' is not supported by {}; use '|' instead""#, Self::class(&vm.ctx) ))) } fn __or__(&self, args: PyObjectRef, vm: &VirtualMachine) -> PyResult { vm._or(self.copy(vm)?.as_ref(), args.as_ref()) } } impl Comparable for PyMappingProxy { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { let obj = zelf.to_object(vm)?; Ok(PyComparisonValue::Implemented( obj.rich_compare_bool(other, op, vm)?, )) } } impl AsMapping for PyMappingProxy { fn as_mapping() -> &'static PyMappingMethods { static AS_MAPPING: LazyLock<PyMappingMethods> = LazyLock::new(|| PyMappingMethods { length: atomic_func!( |mapping, vm| PyMappingProxy::mapping_downcast(mapping).__len__(vm) ), subscript: atomic_func!(|mapping, needle, vm| { PyMappingProxy::mapping_downcast(mapping).__getitem__(needle.to_owned(), vm) }), ..PyMappingMethods::NOT_IMPLEMENTED }); &AS_MAPPING } } impl AsSequence for PyMappingProxy { fn as_sequence() -> &'static PySequenceMethods { static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods { length: atomic_func!(|seq, vm| PyMappingProxy::sequence_downcast(seq).__len__(vm)), contains: atomic_func!( |seq, target, vm| PyMappingProxy::sequence_downcast(seq)._contains(target, vm) ), ..PySequenceMethods::NOT_IMPLEMENTED }); &AS_SEQUENCE } } impl AsNumber for PyMappingProxy { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { or: Some(|a, b, vm| { if let Some(a) = a.downcast_ref::<PyMappingProxy>() { a.__or__(b.to_pyobject(vm), vm) } else { Ok(vm.ctx.not_implemented()) } }), inplace_or: Some(|a, b, vm| { if let Some(a) = a.downcast_ref::<PyMappingProxy>() { a.__ior__(b.to_pyobject(vm), vm) } else { Ok(vm.ctx.not_implemented()) } }), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } } impl Iterable for PyMappingProxy { fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { let obj = zelf.to_object(vm)?; let iter = obj.get_iter(vm)?; Ok(iter.into()) } } impl Representable for PyMappingProxy { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { let obj = zelf.to_object(vm)?; Ok(format!("mappingproxy({})", obj.repr(vm)?)) } } pub fn init(context: &Context) { PyMappingProxy::extend_class(context, context.types.mappingproxy_type) }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/memory.rs
crates/vm/src/builtins/memory.rs
use super::{ PositionIterInternal, PyBytes, PyBytesRef, PyGenericAlias, PyInt, PyListRef, PySlice, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine, atomic_func, buffer::FormatSpec, bytes_inner::bytes_to_hex, class::PyClassImpl, common::{ borrow::{BorrowedValue, BorrowedValueMut}, hash::PyHash, lock::OnceCell, }, convert::ToPyObject, function::Either, function::{FuncArgs, OptionalArg, PyComparisonValue}, protocol::{ BufferDescriptor, BufferMethods, PyBuffer, PyIterReturn, PyMappingMethods, PySequenceMethods, VecBuffer, }, sliceable::SequenceIndexOp, types::{ AsBuffer, AsMapping, AsSequence, Comparable, Constructor, Hashable, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, }, }; use core::{cmp::Ordering, fmt::Debug, mem::ManuallyDrop, ops::Range}; use crossbeam_utils::atomic::AtomicCell; use itertools::Itertools; use rustpython_common::lock::PyMutex; use std::sync::LazyLock; #[derive(FromArgs)] pub struct PyMemoryViewNewArgs { object: PyObjectRef, } #[pyclass(module = false, name = "memoryview")] #[derive(Debug)] pub struct PyMemoryView { // avoid double release when memoryview had released the buffer before drop buffer: ManuallyDrop<PyBuffer>, // the released memoryview does not mean the buffer is destroyed // because the possible another memoryview is viewing from it released: AtomicCell<bool>, // start does NOT mean the bytes before start will not be visited, // it means the point we starting to get the absolute position via // the needle start: usize, format_spec: FormatSpec, // memoryview's options could be different from buffer's options desc: BufferDescriptor, hash: OnceCell<PyHash>, // exports // memoryview has no exports count by itself // instead it relay on the buffer it viewing to maintain the count } impl Constructor for PyMemoryView { type Args = PyMemoryViewNewArgs; fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> { Self::from_object(&args.object, vm) } } impl PyMemoryView { fn parse_format(format: &str, vm: &VirtualMachine) -> PyResult<FormatSpec> { FormatSpec::parse(format.as_bytes(), vm) } /// this should be the main entrance to create the memoryview /// to avoid the chained memoryview pub fn from_object(obj: &PyObject, vm: &VirtualMachine) -> PyResult<Self> { if let Some(other) = obj.downcast_ref::<Self>() { Ok(other.new_view()) } else { let buffer = PyBuffer::try_from_borrowed_object(vm, obj)?; Self::from_buffer(buffer, vm) } } /// don't use this function to create the memoryview if the buffer is exporting /// via another memoryview, use PyMemoryView::new_view() or PyMemoryView::from_object /// to reduce the chain pub fn from_buffer(buffer: PyBuffer, vm: &VirtualMachine) -> PyResult<Self> { // when we get a buffer means the buffered object is size locked // so we can assume the buffer's options will never change as long // as memoryview is still alive let format_spec = Self::parse_format(&buffer.desc.format, vm)?; let desc = buffer.desc.clone(); Ok(Self { buffer: ManuallyDrop::new(buffer), released: AtomicCell::new(false), start: 0, format_spec, desc, hash: OnceCell::new(), }) } /// don't use this function to create the memoryview if the buffer is exporting /// via another memoryview, use PyMemoryView::new_view() or PyMemoryView::from_object /// to reduce the chain pub fn from_buffer_range( buffer: PyBuffer, range: Range<usize>, vm: &VirtualMachine, ) -> PyResult<Self> { let mut zelf = Self::from_buffer(buffer, vm)?; zelf.init_range(range, 0); zelf.init_len(); Ok(zelf) } /// this should be the only way to create a memoryview from another memoryview pub fn new_view(&self) -> Self { let zelf = Self { buffer: self.buffer.clone(), released: AtomicCell::new(false), start: self.start, format_spec: self.format_spec.clone(), desc: self.desc.clone(), hash: OnceCell::new(), }; zelf.buffer.retain(); zelf } fn try_not_released(&self, vm: &VirtualMachine) -> PyResult<()> { if self.released.load() { Err(vm.new_value_error("operation forbidden on released memoryview object")) } else { Ok(()) } } fn getitem_by_idx(&self, i: isize, vm: &VirtualMachine) -> PyResult { if self.desc.ndim() != 1 { return Err( vm.new_not_implemented_error("multi-dimensional sub-views are not implemented") ); } let (shape, stride, suboffset) = self.desc.dim_desc[0]; let index = i .wrapped_at(shape) .ok_or_else(|| vm.new_index_error("index out of range"))?; let index = index as isize * stride + suboffset; let pos = (index + self.start as isize) as usize; self.unpack_single(pos, vm) } fn getitem_by_slice(&self, slice: &PySlice, vm: &VirtualMachine) -> PyResult { let mut other = self.new_view(); other.init_slice(slice, 0, vm)?; other.init_len(); Ok(other.into_ref(&vm.ctx).into()) } fn getitem_by_multi_idx(&self, indexes: &[isize], vm: &VirtualMachine) -> PyResult { let pos = self.pos_from_multi_index(indexes, vm)?; let bytes = self.buffer.obj_bytes(); format_unpack(&self.format_spec, &bytes[pos..pos + self.desc.itemsize], vm) } fn setitem_by_idx(&self, i: isize, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { if self.desc.ndim() != 1 { return Err(vm.new_not_implemented_error("sub-views are not implemented")); } let (shape, stride, suboffset) = self.desc.dim_desc[0]; let index = i .wrapped_at(shape) .ok_or_else(|| vm.new_index_error("index out of range"))?; let index = index as isize * stride + suboffset; let pos = (index + self.start as isize) as usize; self.pack_single(pos, value, vm) } fn setitem_by_multi_idx( &self, indexes: &[isize], value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { let pos = self.pos_from_multi_index(indexes, vm)?; self.pack_single(pos, value, vm) } fn pack_single(&self, pos: usize, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let mut bytes = self.buffer.obj_bytes_mut(); // TODO: Optimize let data = self.format_spec.pack(vec![value], vm).map_err(|_| { vm.new_type_error(format!( "memoryview: invalid type for format '{}'", &self.desc.format )) })?; bytes[pos..pos + self.desc.itemsize].copy_from_slice(&data); Ok(()) } fn unpack_single(&self, pos: usize, vm: &VirtualMachine) -> PyResult { let bytes = self.buffer.obj_bytes(); // TODO: Optimize self.format_spec .unpack(&bytes[pos..pos + self.desc.itemsize], vm) .map(|x| { if x.len() == 1 { x[0].to_owned() } else { x.into() } }) } fn pos_from_multi_index(&self, indexes: &[isize], vm: &VirtualMachine) -> PyResult<usize> { match indexes.len().cmp(&self.desc.ndim()) { Ordering::Less => { return Err(vm.new_not_implemented_error("sub-views are not implemented")); } Ordering::Greater => { return Err(vm.new_type_error(format!( "cannot index {}-dimension view with {}-element tuple", self.desc.ndim(), indexes.len() ))); } Ordering::Equal => (), } let pos = self.desc.position(indexes, vm)?; let pos = (pos + self.start as isize) as usize; Ok(pos) } fn init_len(&mut self) { let product: usize = self.desc.dim_desc.iter().map(|x| x.0).product(); self.desc.len = product * self.desc.itemsize; } fn init_range(&mut self, range: Range<usize>, dim: usize) { let (shape, stride, _) = self.desc.dim_desc[dim]; debug_assert!(shape >= range.len()); let mut is_adjusted = false; for (_, _, suboffset) in self.desc.dim_desc.iter_mut().rev() { if *suboffset != 0 { *suboffset += stride * range.start as isize; is_adjusted = true; break; } } if !is_adjusted { // no suboffset set, stride must be positive self.start += stride as usize * range.start; } let new_len = range.len(); self.desc.dim_desc[dim].0 = new_len; } fn init_slice(&mut self, slice: &PySlice, dim: usize, vm: &VirtualMachine) -> PyResult<()> { let (shape, stride, _) = self.desc.dim_desc[dim]; let slice = slice.to_saturated(vm)?; let (range, step, slice_len) = slice.adjust_indices(shape); let mut is_adjusted_suboffset = false; for (_, _, suboffset) in self.desc.dim_desc.iter_mut().rev() { if *suboffset != 0 { *suboffset += stride * range.start as isize; is_adjusted_suboffset = true; break; } } if !is_adjusted_suboffset { // no suboffset set, stride must be positive self.start += stride as usize * if step.is_negative() { range.end - 1 } else { range.start }; } self.desc.dim_desc[dim].0 = slice_len; self.desc.dim_desc[dim].1 *= step; Ok(()) } fn _to_list( &self, bytes: &[u8], mut index: isize, dim: usize, vm: &VirtualMachine, ) -> PyResult<PyListRef> { let (shape, stride, suboffset) = self.desc.dim_desc[dim]; if dim + 1 == self.desc.ndim() { let mut v = Vec::with_capacity(shape); for _ in 0..shape { let pos = index + suboffset; let pos = (pos + self.start as isize) as usize; let obj = format_unpack(&self.format_spec, &bytes[pos..pos + self.desc.itemsize], vm)?; v.push(obj); index += stride; } return Ok(vm.ctx.new_list(v)); } let mut v = Vec::with_capacity(shape); for _ in 0..shape { let obj = self._to_list(bytes, index + suboffset, dim + 1, vm)?.into(); v.push(obj); index += stride; } Ok(vm.ctx.new_list(v)) } fn eq(zelf: &Py<Self>, other: &PyObject, vm: &VirtualMachine) -> PyResult<bool> { if zelf.is(other) { return Ok(true); } if zelf.released.load() { return Ok(false); } if let Some(other) = other.downcast_ref::<Self>() && other.released.load() { return Ok(false); } let other = match PyBuffer::try_from_borrowed_object(vm, other) { Ok(buf) => buf, Err(_) => return Ok(false), }; if !is_equiv_shape(&zelf.desc, &other.desc) { return Ok(false); } let a_itemsize = zelf.desc.itemsize; let b_itemsize = other.desc.itemsize; let a_format_spec = &zelf.format_spec; let b_format_spec = &Self::parse_format(&other.desc.format, vm)?; if zelf.desc.ndim() == 0 { let a_val = format_unpack(a_format_spec, &zelf.buffer.obj_bytes()[..a_itemsize], vm)?; let b_val = format_unpack(b_format_spec, &other.obj_bytes()[..b_itemsize], vm)?; return vm.bool_eq(&a_val, &b_val); } // TODO: optimize cmp by format let mut ret = Ok(true); let a_bytes = zelf.buffer.obj_bytes(); let b_bytes = other.obj_bytes(); zelf.desc.zip_eq(&other.desc, false, |a_range, b_range| { let a_range = (a_range.start + zelf.start as isize) as usize ..(a_range.end + zelf.start as isize) as usize; let b_range = b_range.start as usize..b_range.end as usize; let a_val = match format_unpack(a_format_spec, &a_bytes[a_range], vm) { Ok(val) => val, Err(e) => { ret = Err(e); return true; } }; let b_val = match format_unpack(b_format_spec, &b_bytes[b_range], vm) { Ok(val) => val, Err(e) => { ret = Err(e); return true; } }; ret = vm.bool_eq(&a_val, &b_val); if let Ok(b) = ret { !b } else { true } }); ret } fn obj_bytes(&self) -> BorrowedValue<'_, [u8]> { if self.desc.is_contiguous() { BorrowedValue::map(self.buffer.obj_bytes(), |x| { &x[self.start..self.start + self.desc.len] }) } else { BorrowedValue::map(self.buffer.obj_bytes(), |x| &x[self.start..]) } } fn obj_bytes_mut(&self) -> BorrowedValueMut<'_, [u8]> { if self.desc.is_contiguous() { BorrowedValueMut::map(self.buffer.obj_bytes_mut(), |x| { &mut x[self.start..self.start + self.desc.len] }) } else { BorrowedValueMut::map(self.buffer.obj_bytes_mut(), |x| &mut x[self.start..]) } } fn as_contiguous(&self) -> Option<BorrowedValue<'_, [u8]>> { self.desc.is_contiguous().then(|| { BorrowedValue::map(self.buffer.obj_bytes(), |x| { &x[self.start..self.start + self.desc.len] }) }) } fn _as_contiguous_mut(&self) -> Option<BorrowedValueMut<'_, [u8]>> { self.desc.is_contiguous().then(|| { BorrowedValueMut::map(self.buffer.obj_bytes_mut(), |x| { &mut x[self.start..self.start + self.desc.len] }) }) } fn append_to(&self, buf: &mut Vec<u8>) { if let Some(bytes) = self.as_contiguous() { buf.extend_from_slice(&bytes); } else { buf.reserve(self.desc.len); let bytes = &*self.buffer.obj_bytes(); self.desc.for_each_segment(true, |range| { let start = (range.start + self.start as isize) as usize; let end = (range.end + self.start as isize) as usize; buf.extend_from_slice(&bytes[start..end]); }) } } fn contiguous_or_collect<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R { let borrowed; let mut collected; let v = if let Some(bytes) = self.as_contiguous() { borrowed = bytes; &*borrowed } else { collected = vec![]; self.append_to(&mut collected); &collected }; f(v) } /// clone data from memoryview /// keep the shape, convert to contiguous pub fn to_contiguous(&self, vm: &VirtualMachine) -> PyBuffer { let mut data = vec![]; self.append_to(&mut data); if self.desc.ndim() == 0 { return VecBuffer::from(data) .into_ref(&vm.ctx) .into_pybuffer_with_descriptor(self.desc.clone()); } let mut dim_desc = self.desc.dim_desc.clone(); dim_desc.last_mut().unwrap().1 = self.desc.itemsize as isize; dim_desc.last_mut().unwrap().2 = 0; for i in (0..dim_desc.len() - 1).rev() { dim_desc[i].1 = dim_desc[i + 1].1 * dim_desc[i + 1].0 as isize; dim_desc[i].2 = 0; } let desc = BufferDescriptor { len: self.desc.len, readonly: self.desc.readonly, itemsize: self.desc.itemsize, format: self.desc.format.clone(), dim_desc, }; VecBuffer::from(data) .into_ref(&vm.ctx) .into_pybuffer_with_descriptor(desc) } } impl Py<PyMemoryView> { fn setitem_by_slice( &self, slice: &PySlice, src: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { if self.desc.ndim() != 1 { return Err(vm.new_not_implemented_error("sub-view are not implemented")); } let mut dest = self.new_view(); dest.init_slice(slice, 0, vm)?; dest.init_len(); if self.is(&src) { return if !is_equiv_structure(&self.desc, &dest.desc) { Err(vm.new_value_error( "memoryview assignment: lvalue and rvalue have different structures", )) } else { // assign self[:] to self Ok(()) }; }; let src = if let Some(src) = src.downcast_ref::<PyMemoryView>() { if self.buffer.obj.is(&src.buffer.obj) { src.to_contiguous(vm) } else { AsBuffer::as_buffer(src, vm)? } } else { PyBuffer::try_from_object(vm, src)? }; if !is_equiv_structure(&src.desc, &dest.desc) { return Err(vm.new_value_error( "memoryview assignment: lvalue and rvalue have different structures", )); } let mut bytes_mut = dest.buffer.obj_bytes_mut(); let src_bytes = src.obj_bytes(); dest.desc.zip_eq(&src.desc, true, |a_range, b_range| { let a_range = (a_range.start + dest.start as isize) as usize ..(a_range.end + dest.start as isize) as usize; let b_range = b_range.start as usize..b_range.end as usize; bytes_mut[a_range].copy_from_slice(&src_bytes[b_range]); false }); Ok(()) } } #[pyclass( with( Py, Hashable, Comparable, AsBuffer, AsMapping, AsSequence, Constructor, Iterable, Representable ), flags(SEQUENCE) )] impl PyMemoryView { // TODO: Uncomment when Python adds __class_getitem__ to memoryview // #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } #[pymethod] pub fn release(&self) { if self.released.compare_exchange(false, true).is_ok() { self.buffer.release(); } } #[pygetset] fn obj(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> { self.try_not_released(vm).map(|_| self.buffer.obj.clone()) } #[pygetset] fn nbytes(&self, vm: &VirtualMachine) -> PyResult<usize> { self.try_not_released(vm).map(|_| self.desc.len) } #[pygetset] fn readonly(&self, vm: &VirtualMachine) -> PyResult<bool> { self.try_not_released(vm).map(|_| self.desc.readonly) } #[pygetset] fn itemsize(&self, vm: &VirtualMachine) -> PyResult<usize> { self.try_not_released(vm).map(|_| self.desc.itemsize) } #[pygetset] fn ndim(&self, vm: &VirtualMachine) -> PyResult<usize> { self.try_not_released(vm).map(|_| self.desc.ndim()) } #[pygetset] fn shape(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> { self.try_not_released(vm)?; Ok(vm.ctx.new_tuple( self.desc .dim_desc .iter() .map(|(shape, _, _)| shape.to_pyobject(vm)) .collect(), )) } #[pygetset] fn strides(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> { self.try_not_released(vm)?; Ok(vm.ctx.new_tuple( self.desc .dim_desc .iter() .map(|(_, stride, _)| stride.to_pyobject(vm)) .collect(), )) } #[pygetset] fn suboffsets(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> { self.try_not_released(vm)?; Ok(vm.ctx.new_tuple( self.desc .dim_desc .iter() .map(|(_, _, suboffset)| suboffset.to_pyobject(vm)) .collect(), )) } #[pygetset] fn format(&self, vm: &VirtualMachine) -> PyResult<PyStr> { self.try_not_released(vm) .map(|_| PyStr::from(self.desc.format.clone())) } #[pygetset] fn contiguous(&self, vm: &VirtualMachine) -> PyResult<bool> { self.try_not_released(vm).map(|_| self.desc.is_contiguous()) } #[pygetset] fn c_contiguous(&self, vm: &VirtualMachine) -> PyResult<bool> { self.try_not_released(vm).map(|_| self.desc.is_contiguous()) } #[pygetset] fn f_contiguous(&self, vm: &VirtualMachine) -> PyResult<bool> { // TODO: column-major order self.try_not_released(vm) .map(|_| self.desc.ndim() <= 1 && self.desc.is_contiguous()) } #[pymethod] fn __enter__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { zelf.try_not_released(vm).map(|_| zelf) } #[pymethod] fn __exit__(&self, _args: FuncArgs) { self.release(); } fn __getitem__(zelf: PyRef<Self>, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { zelf.try_not_released(vm)?; if zelf.desc.ndim() == 0 { // 0-d memoryview can be referenced using mv[...] or mv[()] only if needle.is(&vm.ctx.ellipsis) { return Ok(zelf.into()); } if let Some(tuple) = needle.downcast_ref::<PyTuple>() && tuple.is_empty() { return zelf.unpack_single(0, vm); } return Err(vm.new_type_error("invalid indexing of 0-dim memory")); } match SubscriptNeedle::try_from_object(vm, needle)? { SubscriptNeedle::Index(i) => zelf.getitem_by_idx(i, vm), SubscriptNeedle::Slice(slice) => zelf.getitem_by_slice(&slice, vm), SubscriptNeedle::MultiIndex(indices) => zelf.getitem_by_multi_idx(&indices, vm), } } fn __delitem__(&self, _needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { if self.desc.readonly { return Err(vm.new_type_error("cannot modify read-only memory")); } Err(vm.new_type_error("cannot delete memory")) } fn __len__(&self, vm: &VirtualMachine) -> PyResult<usize> { self.try_not_released(vm)?; if self.desc.ndim() == 0 { // 0-dimensional memoryview has no length Err(vm.new_type_error("0-dim memory has no length".to_owned())) } else { // shape for dim[0] Ok(self.desc.dim_desc[0].0) } } #[pymethod] fn tobytes(&self, vm: &VirtualMachine) -> PyResult<PyBytesRef> { self.try_not_released(vm)?; let mut v = vec![]; self.append_to(&mut v); Ok(PyBytes::from(v).into_ref(&vm.ctx)) } #[pymethod] fn tolist(&self, vm: &VirtualMachine) -> PyResult<PyListRef> { self.try_not_released(vm)?; let bytes = self.buffer.obj_bytes(); if self.desc.ndim() == 0 { return Ok(vm.ctx.new_list(vec![format_unpack( &self.format_spec, &bytes[..self.desc.itemsize], vm, )?])); } self._to_list(&bytes, 0, 0, vm) } #[pymethod] fn toreadonly(&self, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { self.try_not_released(vm)?; let mut other = self.new_view(); other.desc.readonly = true; Ok(other.into_ref(&vm.ctx)) } #[pymethod] fn hex( &self, sep: OptionalArg<Either<PyStrRef, PyBytesRef>>, bytes_per_sep: OptionalArg<isize>, vm: &VirtualMachine, ) -> PyResult<String> { self.try_not_released(vm)?; self.contiguous_or_collect(|x| bytes_to_hex(x, sep, bytes_per_sep, vm)) } fn cast_to_1d(&self, format: PyStrRef, vm: &VirtualMachine) -> PyResult<Self> { let format_spec = Self::parse_format(format.as_str(), vm)?; let itemsize = format_spec.size(); if !self.desc.len.is_multiple_of(itemsize) { return Err(vm.new_type_error("memoryview: length is not a multiple of itemsize")); } Ok(Self { buffer: self.buffer.clone(), released: AtomicCell::new(false), start: self.start, format_spec, desc: BufferDescriptor { len: self.desc.len, readonly: self.desc.readonly, itemsize, format: format.to_string().into(), dim_desc: vec![(self.desc.len / itemsize, itemsize as isize, 0)], }, hash: OnceCell::new(), }) } #[pymethod] fn cast(&self, args: CastArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { self.try_not_released(vm)?; if !self.desc.is_contiguous() { return Err(vm.new_type_error("memoryview: casts are restricted to C-contiguous views")); } let CastArgs { format, shape } = args; if let OptionalArg::Present(shape) = shape { if self.desc.is_zero_in_shape() { return Err(vm.new_type_error( "memoryview: cannot cast view with zeros in shape or strides", )); } let tup; let list; let list_borrow; let shape = match shape { Either::A(shape) => { tup = shape; tup.as_slice() } Either::B(shape) => { list = shape; list_borrow = list.borrow_vec(); &list_borrow } }; let shape_ndim = shape.len(); // TODO: MAX_NDIM if self.desc.ndim() != 1 && shape_ndim != 1 { return Err(vm.new_type_error("memoryview: cast must be 1D -> ND or ND -> 1D")); } let mut other = self.cast_to_1d(format, vm)?; let itemsize = other.desc.itemsize; // 0 ndim is single item if shape_ndim == 0 { other.desc.dim_desc = vec![]; other.desc.len = itemsize; return Ok(other.into_ref(&vm.ctx)); } let mut product_shape = itemsize; let mut dim_descriptor = Vec::with_capacity(shape_ndim); for x in shape { let x = usize::try_from_borrowed_object(vm, x)?; if x > isize::MAX as usize / product_shape { return Err(vm.new_value_error("memoryview.cast(): product(shape) > SSIZE_MAX")); } product_shape *= x; dim_descriptor.push((x, 0, 0)); } dim_descriptor.last_mut().unwrap().1 = itemsize as isize; for i in (0..dim_descriptor.len() - 1).rev() { dim_descriptor[i].1 = dim_descriptor[i + 1].1 * dim_descriptor[i + 1].0 as isize; } if product_shape != other.desc.len { return Err( vm.new_type_error("memoryview: product(shape) * itemsize != buffer size") ); } other.desc.dim_desc = dim_descriptor; Ok(other.into_ref(&vm.ctx)) } else { Ok(self.cast_to_1d(format, vm)?.into_ref(&vm.ctx)) } } } #[pyclass] impl Py<PyMemoryView> { fn __setitem__( &self, needle: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { self.try_not_released(vm)?; if self.desc.readonly { return Err(vm.new_type_error("cannot modify read-only memory")); } if value.is(&vm.ctx.none) { return Err(vm.new_type_error("cannot delete memory")); } if self.desc.ndim() == 0 { // TODO: merge branches when we got conditional if let if needle.is(&vm.ctx.ellipsis) { return self.pack_single(0, value, vm); } else if let Some(tuple) = needle.downcast_ref::<PyTuple>() && tuple.is_empty() { return self.pack_single(0, value, vm); } return Err(vm.new_type_error("invalid indexing of 0-dim memory")); } match SubscriptNeedle::try_from_object(vm, needle)? { SubscriptNeedle::Index(i) => self.setitem_by_idx(i, value, vm), SubscriptNeedle::Slice(slice) => self.setitem_by_slice(&slice, value, vm), SubscriptNeedle::MultiIndex(indices) => self.setitem_by_multi_idx(&indices, value, vm), } } #[pymethod] fn __reduce_ex__(&self, _proto: usize, vm: &VirtualMachine) -> PyResult { self.__reduce__(vm) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { Err(vm.new_type_error("cannot pickle 'memoryview' object")) } } #[derive(FromArgs)] struct CastArgs { #[pyarg(any)] format: PyStrRef, #[pyarg(any, optional)] shape: OptionalArg<Either<PyTupleRef, PyListRef>>, } enum SubscriptNeedle { Index(isize), Slice(PyRef<PySlice>), MultiIndex(Vec<isize>), // MultiSlice(Vec<PySliceRef>), } impl TryFromObject for SubscriptNeedle { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { // TODO: number protocol if let Some(i) = obj.downcast_ref::<PyInt>() { Ok(Self::Index(i.try_to_primitive(vm)?)) } else if obj.downcastable::<PySlice>() { Ok(Self::Slice(unsafe { obj.downcast_unchecked::<PySlice>() })) } else if let Ok(i) = obj.try_index(vm) { Ok(Self::Index(i.try_to_primitive(vm)?)) } else { if let Some(tuple) = obj.downcast_ref::<PyTuple>() { if tuple.iter().all(|x| x.downcastable::<PyInt>()) { let v = tuple .iter() .map(|x| { unsafe { x.downcast_unchecked_ref::<PyInt>() } .try_to_primitive::<isize>(vm) }) .try_collect()?; return Ok(Self::MultiIndex(v)); } else if tuple.iter().all(|x| x.downcastable::<PySlice>()) { return Err(vm.new_not_implemented_error( "multi-dimensional slicing is not implemented", )); } } Err(vm.new_type_error("memoryview: invalid slice key")) } } } static BUFFER_METHODS: BufferMethods = BufferMethods { obj_bytes: |buffer| buffer.obj_as::<PyMemoryView>().obj_bytes(), obj_bytes_mut: |buffer| buffer.obj_as::<PyMemoryView>().obj_bytes_mut(), release: |buffer| buffer.obj_as::<PyMemoryView>().buffer.release(), retain: |buffer| buffer.obj_as::<PyMemoryView>().buffer.retain(), }; impl AsBuffer for PyMemoryView { fn as_buffer(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyBuffer> { if zelf.released.load() { Err(vm.new_value_error("operation forbidden on released memoryview object")) } else { Ok(PyBuffer::new( zelf.to_owned().into(), zelf.desc.clone(), &BUFFER_METHODS, )) } } } impl Drop for PyMemoryView { fn drop(&mut self) { if self.released.load() { unsafe { self.buffer.drop_without_release() }; } else { unsafe { ManuallyDrop::drop(&mut self.buffer) }; } } } impl AsMapping for PyMemoryView { fn as_mapping() -> &'static PyMappingMethods { static AS_MAPPING: PyMappingMethods = PyMappingMethods {
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/code.rs
crates/vm/src/builtins/code.rs
//! Infamous code object. The python class `code` use super::{PyBytesRef, PyStrRef, PyTupleRef, PyType}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::PyStrInterned, bytecode::{self, AsBag, BorrowedConstant, CodeFlags, Constant, ConstantBag}, class::{PyClassImpl, StaticType}, convert::{ToPyException, ToPyObject}, frozen, function::OptionalArg, types::{Constructor, Representable}, }; use alloc::fmt; use core::{borrow::Borrow, ops::Deref}; use malachite_bigint::BigInt; use num_traits::Zero; use rustpython_compiler_core::{OneIndexed, bytecode::CodeUnits, bytecode::PyCodeLocationInfoKind}; /// State for iterating through code address ranges struct PyCodeAddressRange<'a> { ar_start: i32, ar_end: i32, ar_line: i32, computed_line: i32, reader: LineTableReader<'a>, } impl<'a> PyCodeAddressRange<'a> { fn new(linetable: &'a [u8], first_line: i32) -> Self { PyCodeAddressRange { ar_start: 0, ar_end: 0, ar_line: -1, computed_line: first_line, reader: LineTableReader::new(linetable), } } /// Check if this is a NO_LINE marker (code 15) fn is_no_line_marker(byte: u8) -> bool { (byte >> 3) == 0x1f } /// Advance to next address range fn advance(&mut self) -> bool { if self.reader.at_end() { return false; } let first_byte = match self.reader.read_byte() { Some(b) => b, None => return false, }; if (first_byte & 0x80) == 0 { return false; // Invalid linetable } let code = (first_byte >> 3) & 0x0f; let length = ((first_byte & 0x07) + 1) as i32; // Get line delta for this entry let line_delta = self.get_line_delta(code); // Update computed line self.computed_line += line_delta; // Check for NO_LINE marker if Self::is_no_line_marker(first_byte) { self.ar_line = -1; } else { self.ar_line = self.computed_line; } // Update address range self.ar_start = self.ar_end; self.ar_end += length * 2; // sizeof(_Py_CODEUNIT) = 2 // Skip remaining bytes for this entry while !self.reader.at_end() { if let Some(b) = self.reader.peek_byte() { if (b & 0x80) != 0 { break; } self.reader.read_byte(); } else { break; } } true } fn get_line_delta(&mut self, code: u8) -> i32 { let kind = match PyCodeLocationInfoKind::from_code(code) { Some(k) => k, None => return 0, }; match kind { PyCodeLocationInfoKind::None => 0, // NO_LINE marker PyCodeLocationInfoKind::Long => { let delta = self.reader.read_signed_varint(); // Skip end_line, col, end_col self.reader.read_varint(); self.reader.read_varint(); self.reader.read_varint(); delta } PyCodeLocationInfoKind::NoColumns => self.reader.read_signed_varint(), PyCodeLocationInfoKind::OneLine0 => { self.reader.read_byte(); // Skip column self.reader.read_byte(); // Skip end column 0 } PyCodeLocationInfoKind::OneLine1 => { self.reader.read_byte(); // Skip column self.reader.read_byte(); // Skip end column 1 } PyCodeLocationInfoKind::OneLine2 => { self.reader.read_byte(); // Skip column self.reader.read_byte(); // Skip end column 2 } _ if kind.is_short() => { self.reader.read_byte(); // Skip column byte 0 } _ => 0, } } } #[derive(FromArgs)] pub struct ReplaceArgs { #[pyarg(named, optional)] co_posonlyargcount: OptionalArg<u32>, #[pyarg(named, optional)] co_argcount: OptionalArg<u32>, #[pyarg(named, optional)] co_kwonlyargcount: OptionalArg<u32>, #[pyarg(named, optional)] co_filename: OptionalArg<PyStrRef>, #[pyarg(named, optional)] co_firstlineno: OptionalArg<u32>, #[pyarg(named, optional)] co_consts: OptionalArg<Vec<PyObjectRef>>, #[pyarg(named, optional)] co_name: OptionalArg<PyStrRef>, #[pyarg(named, optional)] co_names: OptionalArg<Vec<PyObjectRef>>, #[pyarg(named, optional)] co_flags: OptionalArg<u16>, #[pyarg(named, optional)] co_varnames: OptionalArg<Vec<PyObjectRef>>, #[pyarg(named, optional)] co_nlocals: OptionalArg<u32>, #[pyarg(named, optional)] co_stacksize: OptionalArg<u32>, #[pyarg(named, optional)] co_code: OptionalArg<crate::builtins::PyBytesRef>, #[pyarg(named, optional)] co_linetable: OptionalArg<crate::builtins::PyBytesRef>, #[pyarg(named, optional)] co_exceptiontable: OptionalArg<crate::builtins::PyBytesRef>, #[pyarg(named, optional)] co_freevars: OptionalArg<Vec<PyObjectRef>>, #[pyarg(named, optional)] co_cellvars: OptionalArg<Vec<PyObjectRef>>, #[pyarg(named, optional)] co_qualname: OptionalArg<PyStrRef>, } #[derive(Clone)] #[repr(transparent)] pub struct Literal(PyObjectRef); impl Borrow<PyObject> for Literal { fn borrow(&self) -> &PyObject { &self.0 } } impl From<Literal> for PyObjectRef { fn from(obj: Literal) -> Self { obj.0 } } fn borrow_obj_constant(obj: &PyObject) -> BorrowedConstant<'_, Literal> { match_class!(match obj { ref i @ super::int::PyInt => { let value = i.as_bigint(); if obj.class().is(super::bool_::PyBool::static_type()) { BorrowedConstant::Boolean { value: !value.is_zero(), } } else { BorrowedConstant::Integer { value } } } ref f @ super::float::PyFloat => BorrowedConstant::Float { value: f.to_f64() }, ref c @ super::complex::PyComplex => BorrowedConstant::Complex { value: c.to_complex() }, ref s @ super::pystr::PyStr => BorrowedConstant::Str { value: s.as_wtf8() }, ref b @ super::bytes::PyBytes => BorrowedConstant::Bytes { value: b.as_bytes() }, ref c @ PyCode => { BorrowedConstant::Code { code: &c.code } } ref t @ super::tuple::PyTuple => { let elements = t.as_slice(); // SAFETY: Literal is repr(transparent) over PyObjectRef, and a Literal tuple only ever // has other literals as elements let elements = unsafe { &*(elements as *const [PyObjectRef] as *const [Literal]) }; BorrowedConstant::Tuple { elements } } super::singletons::PyNone => BorrowedConstant::None, super::slice::PyEllipsis => BorrowedConstant::Ellipsis, _ => panic!("unexpected payload for constant python value"), }) } impl Constant for Literal { type Name = &'static PyStrInterned; fn borrow_constant(&self) -> BorrowedConstant<'_, Self> { borrow_obj_constant(&self.0) } } impl<'a> AsBag for &'a Context { type Bag = PyObjBag<'a>; fn as_bag(self) -> PyObjBag<'a> { PyObjBag(self) } } impl<'a> AsBag for &'a VirtualMachine { type Bag = PyObjBag<'a>; fn as_bag(self) -> PyObjBag<'a> { PyObjBag(&self.ctx) } } #[derive(Clone, Copy)] pub struct PyObjBag<'a>(pub &'a Context); impl ConstantBag for PyObjBag<'_> { type Constant = Literal; fn make_constant<C: Constant>(&self, constant: BorrowedConstant<'_, C>) -> Self::Constant { let ctx = self.0; let obj = match constant { BorrowedConstant::Integer { value } => ctx.new_bigint(value).into(), BorrowedConstant::Float { value } => ctx.new_float(value).into(), BorrowedConstant::Complex { value } => ctx.new_complex(value).into(), BorrowedConstant::Str { value } if value.len() <= 20 => { ctx.intern_str(value).to_object() } BorrowedConstant::Str { value } => ctx.new_str(value).into(), BorrowedConstant::Bytes { value } => ctx.new_bytes(value.to_vec()).into(), BorrowedConstant::Boolean { value } => ctx.new_bool(value).into(), BorrowedConstant::Code { code } => ctx.new_code(code.map_clone_bag(self)).into(), BorrowedConstant::Tuple { elements } => { let elements = elements .iter() .map(|constant| self.make_constant(constant.borrow_constant()).0) .collect(); ctx.new_tuple(elements).into() } BorrowedConstant::None => ctx.none(), BorrowedConstant::Ellipsis => ctx.ellipsis.clone().into(), }; Literal(obj) } fn make_name(&self, name: &str) -> &'static PyStrInterned { self.0.intern_str(name) } fn make_int(&self, value: BigInt) -> Self::Constant { Literal(self.0.new_int(value).into()) } fn make_tuple(&self, elements: impl Iterator<Item = Self::Constant>) -> Self::Constant { Literal(self.0.new_tuple(elements.map(|lit| lit.0).collect()).into()) } fn make_code(&self, code: CodeObject) -> Self::Constant { Literal(self.0.new_code(code).into()) } } pub type CodeObject = bytecode::CodeObject<Literal>; pub trait IntoCodeObject { fn into_code_object(self, ctx: &Context) -> CodeObject; } impl IntoCodeObject for CodeObject { fn into_code_object(self, _ctx: &Context) -> Self { self } } impl IntoCodeObject for bytecode::CodeObject { fn into_code_object(self, ctx: &Context) -> CodeObject { self.map_bag(PyObjBag(ctx)) } } impl<B: AsRef<[u8]>> IntoCodeObject for frozen::FrozenCodeObject<B> { fn into_code_object(self, ctx: &Context) -> CodeObject { self.decode(ctx) } } #[pyclass(module = false, name = "code")] pub struct PyCode { pub code: CodeObject, } impl Deref for PyCode { type Target = CodeObject; fn deref(&self) -> &Self::Target { &self.code } } impl PyCode { pub const fn new(code: CodeObject) -> Self { Self { code } } pub fn from_pyc_path(path: &std::path::Path, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { let name = match path.file_stem() { Some(stem) => stem.display().to_string(), None => "".to_owned(), }; let content = std::fs::read(path).map_err(|e| e.to_pyexception(vm))?; Self::from_pyc( &content, Some(&name), Some(&path.display().to_string()), Some("<source>"), vm, ) } pub fn from_pyc( pyc_bytes: &[u8], name: Option<&str>, bytecode_path: Option<&str>, source_path: Option<&str>, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { if !crate::import::check_pyc_magic_number_bytes(pyc_bytes) { return Err(vm.new_value_error("pyc bytes has wrong MAGIC")); } let bootstrap_external = vm.import("_frozen_importlib_external", 0)?; let compile_bytecode = bootstrap_external.get_attr("_compile_bytecode", vm)?; // 16 is the pyc header length let Some((_, code_bytes)) = pyc_bytes.split_at_checked(16) else { return Err(vm.new_value_error(format!( "pyc_bytes header is broken. 16 bytes expected but {} bytes given.", pyc_bytes.len() ))); }; let code_bytes_obj = vm.ctx.new_bytes(code_bytes.to_vec()); let compiled = compile_bytecode.call((code_bytes_obj, name, bytecode_path, source_path), vm)?; compiled.try_downcast(vm) } } impl fmt::Debug for PyCode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "code: {:?}", self.code) } } impl PyPayload for PyCode { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.code_type } } impl Representable for PyCode { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { let code = &zelf.code; Ok(format!( "<code object {} at {:#x} file {:?}, line {}>", code.obj_name, zelf.get_id(), code.source_path.as_str(), code.first_line_number.map_or(-1, |n| n.get() as i32) )) } } // Arguments for code object constructor #[derive(FromArgs)] pub struct PyCodeNewArgs { argcount: u32, posonlyargcount: u32, kwonlyargcount: u32, nlocals: u32, stacksize: u32, flags: u16, co_code: PyBytesRef, consts: PyTupleRef, names: PyTupleRef, varnames: PyTupleRef, filename: PyStrRef, name: PyStrRef, qualname: PyStrRef, firstlineno: i32, linetable: PyBytesRef, exceptiontable: PyBytesRef, freevars: PyTupleRef, cellvars: PyTupleRef, } impl Constructor for PyCode { type Args = PyCodeNewArgs; fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> { // Convert names tuple to vector of interned strings let names: Box<[&'static PyStrInterned]> = args .names .iter() .map(|obj| { let s = obj.downcast_ref::<super::pystr::PyStr>().ok_or_else(|| { vm.new_type_error("names must be tuple of strings".to_owned()) })?; Ok(vm.ctx.intern_str(s.as_str())) }) .collect::<PyResult<Vec<_>>>()? .into_boxed_slice(); let varnames: Box<[&'static PyStrInterned]> = args .varnames .iter() .map(|obj| { let s = obj.downcast_ref::<super::pystr::PyStr>().ok_or_else(|| { vm.new_type_error("varnames must be tuple of strings".to_owned()) })?; Ok(vm.ctx.intern_str(s.as_str())) }) .collect::<PyResult<Vec<_>>>()? .into_boxed_slice(); let cellvars: Box<[&'static PyStrInterned]> = args .cellvars .iter() .map(|obj| { let s = obj.downcast_ref::<super::pystr::PyStr>().ok_or_else(|| { vm.new_type_error("cellvars must be tuple of strings".to_owned()) })?; Ok(vm.ctx.intern_str(s.as_str())) }) .collect::<PyResult<Vec<_>>>()? .into_boxed_slice(); let freevars: Box<[&'static PyStrInterned]> = args .freevars .iter() .map(|obj| { let s = obj.downcast_ref::<super::pystr::PyStr>().ok_or_else(|| { vm.new_type_error("freevars must be tuple of strings".to_owned()) })?; Ok(vm.ctx.intern_str(s.as_str())) }) .collect::<PyResult<Vec<_>>>()? .into_boxed_slice(); // Check nlocals matches varnames length if args.nlocals as usize != varnames.len() { return Err(vm.new_value_error(format!( "nlocals ({}) != len(varnames) ({})", args.nlocals, varnames.len() ))); } // Parse and validate bytecode from bytes let bytecode_bytes = args.co_code.as_bytes(); let instructions = CodeUnits::try_from(bytecode_bytes) .map_err(|e| vm.new_value_error(format!("invalid bytecode: {}", e)))?; // Convert constants let constants: Box<[Literal]> = args .consts .iter() .map(|obj| { // Convert PyObject to Literal constant // For now, just wrap it Literal(obj.clone()) }) .collect::<Vec<_>>() .into_boxed_slice(); // Create locations (start and end pairs) let row = if args.firstlineno > 0 { OneIndexed::new(args.firstlineno as usize).unwrap_or(OneIndexed::MIN) } else { OneIndexed::MIN }; let loc = rustpython_compiler_core::SourceLocation { line: row, character_offset: OneIndexed::from_zero_indexed(0), }; let locations: Box< [( rustpython_compiler_core::SourceLocation, rustpython_compiler_core::SourceLocation, )], > = vec![(loc, loc); instructions.len()].into_boxed_slice(); // Build the CodeObject let code = CodeObject { instructions, locations, flags: CodeFlags::from_bits_truncate(args.flags), posonlyarg_count: args.posonlyargcount, arg_count: args.argcount, kwonlyarg_count: args.kwonlyargcount, source_path: vm.ctx.intern_str(args.filename.as_str()), first_line_number: if args.firstlineno > 0 { OneIndexed::new(args.firstlineno as usize) } else { None }, max_stackdepth: args.stacksize, obj_name: vm.ctx.intern_str(args.name.as_str()), qualname: vm.ctx.intern_str(args.qualname.as_str()), cell2arg: None, // TODO: reuse `fn cell2arg` constants, names, varnames, cellvars, freevars, linetable: args.linetable.as_bytes().to_vec().into_boxed_slice(), exceptiontable: args.exceptiontable.as_bytes().to_vec().into_boxed_slice(), }; Ok(PyCode::new(code)) } } #[pyclass(with(Representable, Constructor))] impl PyCode { #[pygetset] const fn co_posonlyargcount(&self) -> usize { self.code.posonlyarg_count as usize } #[pygetset] const fn co_argcount(&self) -> usize { self.code.arg_count as usize } #[pygetset] const fn co_stacksize(&self) -> u32 { self.code.max_stackdepth } #[pygetset] pub fn co_filename(&self) -> PyStrRef { self.code.source_path.to_owned() } #[pygetset] pub fn co_cellvars(&self, vm: &VirtualMachine) -> PyTupleRef { let cellvars = self .cellvars .iter() .map(|name| name.to_pyobject(vm)) .collect(); vm.ctx.new_tuple(cellvars) } #[pygetset] fn co_nlocals(&self) -> usize { self.code.varnames.len() } #[pygetset] fn co_firstlineno(&self) -> u32 { self.code.first_line_number.map_or(0, |n| n.get() as _) } #[pygetset] const fn co_kwonlyargcount(&self) -> usize { self.code.kwonlyarg_count as usize } #[pygetset] fn co_consts(&self, vm: &VirtualMachine) -> PyTupleRef { let consts = self.code.constants.iter().map(|x| x.0.clone()).collect(); vm.ctx.new_tuple(consts) } #[pygetset] fn co_name(&self) -> PyStrRef { self.code.obj_name.to_owned() } #[pygetset] fn co_qualname(&self) -> PyStrRef { self.code.qualname.to_owned() } #[pygetset] fn co_names(&self, vm: &VirtualMachine) -> PyTupleRef { let names = self .code .names .deref() .iter() .map(|name| name.to_pyobject(vm)) .collect(); vm.ctx.new_tuple(names) } #[pygetset] const fn co_flags(&self) -> u16 { self.code.flags.bits() } #[pygetset] pub fn co_varnames(&self, vm: &VirtualMachine) -> PyTupleRef { let varnames = self.code.varnames.iter().map(|s| s.to_object()).collect(); vm.ctx.new_tuple(varnames) } #[pygetset] pub fn co_code(&self, vm: &VirtualMachine) -> crate::builtins::PyBytesRef { // SAFETY: CodeUnit is #[repr(C)] with size 2, so we can safely transmute to bytes let bytes = unsafe { core::slice::from_raw_parts( self.code.instructions.as_ptr() as *const u8, self.code.instructions.len() * 2, ) }; vm.ctx.new_bytes(bytes.to_vec()) } #[pygetset] pub fn co_freevars(&self, vm: &VirtualMachine) -> PyTupleRef { let names = self .code .freevars .deref() .iter() .map(|name| name.to_pyobject(vm)) .collect(); vm.ctx.new_tuple(names) } #[pygetset] pub fn co_linetable(&self, vm: &VirtualMachine) -> crate::builtins::PyBytesRef { // Return the actual linetable from the code object vm.ctx.new_bytes(self.code.linetable.to_vec()) } #[pygetset] pub fn co_exceptiontable(&self, vm: &VirtualMachine) -> crate::builtins::PyBytesRef { // Return the actual exception table from the code object vm.ctx.new_bytes(self.code.exceptiontable.to_vec()) } #[pymethod] pub fn co_lines(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> { // TODO: Implement lazy iterator (lineiterator) like CPython for better performance // Currently returns eager list for simplicity // Return an iterator over (start_offset, end_offset, lineno) tuples let linetable = self.code.linetable.as_ref(); let mut lines = Vec::new(); if !linetable.is_empty() { let first_line = self.code.first_line_number.map_or(0, |n| n.get() as i32); let mut range = PyCodeAddressRange::new(linetable, first_line); // Process all address ranges and merge consecutive entries with same line let mut pending_entry: Option<(i32, i32, i32)> = None; while range.advance() { let start = range.ar_start; let end = range.ar_end; let line = range.ar_line; if let Some((prev_start, _, prev_line)) = pending_entry { if prev_line == line { // Same line, extend the range pending_entry = Some((prev_start, end, prev_line)); } else { // Different line, emit the previous entry let tuple = if prev_line == -1 { vm.ctx.new_tuple(vec![ vm.ctx.new_int(prev_start).into(), vm.ctx.new_int(start).into(), vm.ctx.none(), ]) } else { vm.ctx.new_tuple(vec![ vm.ctx.new_int(prev_start).into(), vm.ctx.new_int(start).into(), vm.ctx.new_int(prev_line).into(), ]) }; lines.push(tuple.into()); pending_entry = Some((start, end, line)); } } else { // First entry pending_entry = Some((start, end, line)); } } // Emit the last pending entry if let Some((start, end, line)) = pending_entry { let tuple = if line == -1 { vm.ctx.new_tuple(vec![ vm.ctx.new_int(start).into(), vm.ctx.new_int(end).into(), vm.ctx.none(), ]) } else { vm.ctx.new_tuple(vec![ vm.ctx.new_int(start).into(), vm.ctx.new_int(end).into(), vm.ctx.new_int(line).into(), ]) }; lines.push(tuple.into()); } } let list = vm.ctx.new_list(lines); vm.call_method(list.as_object(), "__iter__", ()) } #[pymethod] pub fn co_positions(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> { // Return an iterator over (line, end_line, column, end_column) tuples for each instruction let linetable = self.code.linetable.as_ref(); let mut positions = Vec::new(); if !linetable.is_empty() { let mut reader = LineTableReader::new(linetable); let mut line = self.code.first_line_number.map_or(0, |n| n.get() as i32); while !reader.at_end() { let first_byte = match reader.read_byte() { Some(b) => b, None => break, }; if (first_byte & 0x80) == 0 { break; // Invalid linetable } let code = (first_byte >> 3) & 0x0f; let length = ((first_byte & 0x07) + 1) as i32; let kind = match PyCodeLocationInfoKind::from_code(code) { Some(k) => k, None => break, // Invalid code }; let (line_delta, end_line_delta, column, end_column): ( i32, i32, Option<i32>, Option<i32>, ) = match kind { PyCodeLocationInfoKind::None => { // No location - all values are None (0, 0, None, None) } PyCodeLocationInfoKind::Long => { // Long form let delta = reader.read_signed_varint(); let end_line_delta = reader.read_varint() as i32; let col = reader.read_varint(); let column = if col == 0 { None } else { Some((col - 1) as i32) }; let end_col = reader.read_varint(); let end_column = if end_col == 0 { None } else { Some((end_col - 1) as i32) }; // endline = line + end_line_delta (will be computed after line update) (delta, end_line_delta, column, end_column) } PyCodeLocationInfoKind::NoColumns => { // No column form let delta = reader.read_signed_varint(); (delta, 0, None, None) // endline will be same as line (delta = 0) } PyCodeLocationInfoKind::OneLine0 | PyCodeLocationInfoKind::OneLine1 | PyCodeLocationInfoKind::OneLine2 => { // One-line form - endline = line let col = reader.read_byte().unwrap_or(0) as i32; let end_col = reader.read_byte().unwrap_or(0) as i32; let delta = kind.one_line_delta().unwrap_or(0); (delta, 0, Some(col), Some(end_col)) // endline = line (delta = 0) } _ if kind.is_short() => { // Short form - endline = line let col_data = reader.read_byte().unwrap_or(0); let col_group = kind.short_column_group().unwrap_or(0); let col = ((col_group as i32) << 3) | ((col_data >> 4) as i32); let end_col = col + (col_data & 0x0f) as i32; (0, 0, Some(col), Some(end_col)) // endline = line (delta = 0) } _ => (0, 0, None, None), }; // Update line number line += line_delta; // Generate position tuples for each instruction covered by this entry for _ in 0..length { // Handle special case for no location (code 15) let final_line = if kind == PyCodeLocationInfoKind::None { None } else { Some(line) }; let final_endline = if kind == PyCodeLocationInfoKind::None { None } else { Some(line + end_line_delta) }; let line_obj = final_line.to_pyobject(vm); let end_line_obj = final_endline.to_pyobject(vm); let column_obj = column.to_pyobject(vm); let end_column_obj = end_column.to_pyobject(vm); let tuple = vm.ctx .new_tuple(vec![line_obj, end_line_obj, column_obj, end_column_obj]); positions.push(tuple.into()); } } } let list = vm.ctx.new_list(positions); vm.call_method(list.as_object(), "__iter__", ()) } #[pymethod] pub fn replace(&self, args: ReplaceArgs, vm: &VirtualMachine) -> PyResult<Self> { let ReplaceArgs { co_posonlyargcount, co_argcount, co_kwonlyargcount, co_filename, co_firstlineno, co_consts, co_name, co_names, co_flags, co_varnames, co_nlocals, co_stacksize, co_code, co_linetable, co_exceptiontable, co_freevars, co_cellvars, co_qualname, } = args; let posonlyarg_count = match co_posonlyargcount { OptionalArg::Present(posonlyarg_count) => posonlyarg_count, OptionalArg::Missing => self.code.posonlyarg_count, }; let arg_count = match co_argcount { OptionalArg::Present(arg_count) => arg_count, OptionalArg::Missing => self.code.arg_count, }; let source_path = match co_filename { OptionalArg::Present(source_path) => source_path, OptionalArg::Missing => self.code.source_path.to_owned(), }; let first_line_number = match co_firstlineno { OptionalArg::Present(first_line_number) => OneIndexed::new(first_line_number as _), OptionalArg::Missing => self.code.first_line_number, }; let kwonlyarg_count = match co_kwonlyargcount { OptionalArg::Present(kwonlyarg_count) => kwonlyarg_count, OptionalArg::Missing => self.code.kwonlyarg_count, }; let constants = match co_consts { OptionalArg::Present(constants) => constants, OptionalArg::Missing => self.code.constants.iter().map(|x| x.0.clone()).collect(), }; let obj_name = match co_name { OptionalArg::Present(obj_name) => obj_name, OptionalArg::Missing => self.code.obj_name.to_owned(), }; let names = match co_names { OptionalArg::Present(names) => names, OptionalArg::Missing => self .code .names .deref() .iter() .map(|name| name.to_pyobject(vm)) .collect(), }; let flags = match co_flags { OptionalArg::Present(flags) => flags, OptionalArg::Missing => self.code.flags.bits(), }; let varnames = match co_varnames { OptionalArg::Present(varnames) => varnames, OptionalArg::Missing => self.code.varnames.iter().map(|s| s.to_object()).collect(), }; let qualname = match co_qualname { OptionalArg::Present(qualname) => qualname, OptionalArg::Missing => self.code.qualname.to_owned(), }; let max_stackdepth = match co_stacksize { OptionalArg::Present(stacksize) => stacksize, OptionalArg::Missing => self.code.max_stackdepth, }; let instructions = match co_code { OptionalArg::Present(code_bytes) => { // Parse and validate bytecode from bytes CodeUnits::try_from(code_bytes.as_bytes()) .map_err(|e| vm.new_value_error(format!("invalid bytecode: {}", e)))?
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/weakproxy.rs
crates/vm/src/builtins/weakproxy.rs
use super::{PyStr, PyStrRef, PyType, PyTypeRef, PyWeak}; use crate::{ Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, atomic_func, class::PyClassImpl, common::hash::PyHash, function::{OptionalArg, PyComparisonValue, PySetterValue}, protocol::{PyIter, PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods}, stdlib::builtins::reversed, types::{ AsMapping, AsNumber, AsSequence, Comparable, Constructor, GetAttr, Hashable, IterNext, Iterable, PyComparisonOp, Representable, SetAttr, }, }; use std::sync::LazyLock; #[pyclass(module = false, name = "weakproxy", unhashable = true, traverse)] #[derive(Debug)] pub struct PyWeakProxy { weak: PyRef<PyWeak>, } impl PyPayload for PyWeakProxy { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.weakproxy_type } } #[derive(FromArgs)] pub struct WeakProxyNewArgs { #[pyarg(positional)] referent: PyObjectRef, #[pyarg(positional, optional)] callback: OptionalArg<PyObjectRef>, } impl Constructor for PyWeakProxy { type Args = WeakProxyNewArgs; fn py_new( _cls: &Py<PyType>, Self::Args { referent, callback }: Self::Args, vm: &VirtualMachine, ) -> PyResult<Self> { // using an internal subclass as the class prevents us from getting the generic weakref, // which would mess up the weakref count let weak_cls = WEAK_SUBCLASS.get_or_init(|| { vm.ctx.new_class( None, "__weakproxy", vm.ctx.types.weakref_type.to_owned(), super::PyWeak::make_slots(), ) }); // TODO: PyWeakProxy should use the same payload as PyWeak Ok(Self { weak: referent.downgrade_with_typ(callback.into_option(), weak_cls.clone(), vm)?, }) } } crate::common::static_cell! { static WEAK_SUBCLASS: PyTypeRef; } #[pyclass(with( GetAttr, SetAttr, Constructor, Comparable, AsNumber, AsSequence, AsMapping, Representable, IterNext ))] impl PyWeakProxy { fn try_upgrade(&self, vm: &VirtualMachine) -> PyResult { self.weak.upgrade().ok_or_else(|| new_reference_error(vm)) } #[pymethod] fn __str__(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> { zelf.try_upgrade(vm)?.str(vm) } fn len(&self, vm: &VirtualMachine) -> PyResult<usize> { self.try_upgrade(vm)?.length(vm) } #[pymethod] fn __bytes__(&self, vm: &VirtualMachine) -> PyResult { self.try_upgrade(vm)?.bytes(vm) } #[pymethod] fn __reversed__(&self, vm: &VirtualMachine) -> PyResult { let obj = self.try_upgrade(vm)?; reversed(obj, vm) } fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> { self.try_upgrade(vm)? .sequence_unchecked() .contains(&needle, vm) } fn getitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { let obj = self.try_upgrade(vm)?; obj.get_item(&*needle, vm) } fn setitem( &self, needle: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { let obj = self.try_upgrade(vm)?; obj.set_item(&*needle, value, vm) } fn delitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let obj = self.try_upgrade(vm)?; obj.del_item(&*needle, vm) } } impl Iterable for PyWeakProxy { fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { let obj = zelf.try_upgrade(vm)?; Ok(obj.get_iter(vm)?.into()) } } impl IterNext for PyWeakProxy { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let obj = zelf.try_upgrade(vm)?; PyIter::new(obj).next(vm) } } fn new_reference_error(vm: &VirtualMachine) -> PyRef<super::PyBaseException> { vm.new_exception_msg( vm.ctx.exceptions.reference_error.to_owned(), "weakly-referenced object no longer exists".to_owned(), ) } impl GetAttr for PyWeakProxy { // TODO: callbacks fn getattro(zelf: &Py<Self>, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult { let obj = zelf.try_upgrade(vm)?; obj.get_attr(name, vm) } } impl SetAttr for PyWeakProxy { fn setattro( zelf: &Py<Self>, attr_name: &Py<PyStr>, value: PySetterValue, vm: &VirtualMachine, ) -> PyResult<()> { let obj = zelf.try_upgrade(vm)?; obj.call_set_attr(vm, attr_name, value) } } impl AsNumber for PyWeakProxy { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: LazyLock<PyNumberMethods> = LazyLock::new(|| PyNumberMethods { boolean: Some(|number, vm| { let zelf = number.obj.downcast_ref::<PyWeakProxy>().unwrap(); zelf.try_upgrade(vm)?.is_true(vm) }), ..PyNumberMethods::NOT_IMPLEMENTED }); &AS_NUMBER } } impl Comparable for PyWeakProxy { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { let obj = zelf.try_upgrade(vm)?; Ok(PyComparisonValue::Implemented( obj.rich_compare_bool(other, op, vm)?, )) } } impl AsSequence for PyWeakProxy { fn as_sequence() -> &'static PySequenceMethods { static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods { length: atomic_func!(|seq, vm| PyWeakProxy::sequence_downcast(seq).len(vm)), contains: atomic_func!(|seq, needle, vm| { PyWeakProxy::sequence_downcast(seq).__contains__(needle.to_owned(), vm) }), ..PySequenceMethods::NOT_IMPLEMENTED }); &AS_SEQUENCE } } impl AsMapping for PyWeakProxy { fn as_mapping() -> &'static PyMappingMethods { static AS_MAPPING: PyMappingMethods = PyMappingMethods { length: atomic_func!(|mapping, vm| PyWeakProxy::mapping_downcast(mapping).len(vm)), subscript: atomic_func!(|mapping, needle, vm| { PyWeakProxy::mapping_downcast(mapping).getitem(needle.to_owned(), vm) }), ass_subscript: atomic_func!(|mapping, needle, value, vm| { let zelf = PyWeakProxy::mapping_downcast(mapping); if let Some(value) = value { zelf.setitem(needle.to_owned(), value, vm) } else { zelf.delitem(needle.to_owned(), vm) } }), }; &AS_MAPPING } } impl Representable for PyWeakProxy { #[inline] fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> { zelf.try_upgrade(vm)?.repr(vm) } #[cold] fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { unreachable!("use repr instead") } } pub fn init(context: &Context) { PyWeakProxy::extend_class(context, context.types.weakproxy_type); } impl Hashable for PyWeakProxy { fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> { zelf.try_upgrade(vm)?.hash(vm) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/bool.rs
crates/vm/src/builtins/bool.rs
use super::{PyInt, PyStrRef, PyType, PyTypeRef}; use crate::common::format::FormatSpec; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, VirtualMachine, class::PyClassImpl, convert::{IntoPyException, ToPyObject, ToPyResult}, function::{FuncArgs, OptionalArg}, protocol::PyNumberMethods, types::{AsNumber, Constructor, Representable}, }; use core::fmt::{Debug, Formatter}; use num_traits::Zero; impl ToPyObject for bool { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.new_bool(self).into() } } impl<'a> TryFromBorrowedObject<'a> for bool { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> { // Python takes integers as a legit bool value match obj.downcast_ref::<PyInt>() { Some(int_obj) => { let int_val = int_obj.as_bigint(); Ok(!int_val.is_zero()) } None => { Err(vm.new_type_error(format!("Expected type bool, not {}", obj.class().name()))) } } } } impl PyObjectRef { /// Convert Python bool into Rust bool. pub fn try_to_bool(self, vm: &VirtualMachine) -> PyResult<bool> { if self.is(&vm.ctx.true_value) { return Ok(true); } if self.is(&vm.ctx.false_value) { return Ok(false); } let slots = &self.class().slots; // 1. Try nb_bool slot first if let Some(nb_bool) = slots.as_number.boolean.load() { return nb_bool(self.as_object().number(), vm); } // 2. Try mp_length slot (mapping protocol) if let Some(mp_length) = slots.as_mapping.length.load() { let len = mp_length(self.as_object().mapping_unchecked(), vm)?; return Ok(len != 0); } // 3. Try sq_length slot (sequence protocol) if let Some(sq_length) = slots.as_sequence.length.load() { let len = sq_length(self.as_object().sequence_unchecked(), vm)?; return Ok(len != 0); } // 4. Default: objects without __bool__ or __len__ are truthy Ok(true) } } #[pyclass(name = "bool", module = false, base = PyInt, ctx = "bool_type")] #[repr(transparent)] pub struct PyBool(pub PyInt); impl Debug for PyBool { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { let value = !self.0.as_bigint().is_zero(); write!(f, "PyBool({})", value) } } impl Constructor for PyBool { type Args = OptionalArg<PyObjectRef>; fn slot_new(zelf: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let x: Self::Args = args.bind(vm)?; if !zelf.fast_isinstance(vm.ctx.types.type_type) { let actual_class = zelf.class(); let actual_type = &actual_class.name(); return Err(vm.new_type_error(format!( "requires a 'type' object but received a '{actual_type}'" ))); } let val = x.map_or(Ok(false), |val| val.try_to_bool(vm))?; Ok(vm.ctx.new_bool(val).into()) } fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> { unimplemented!("use slot_new") } } #[pyclass(with(Constructor, AsNumber, Representable), flags(_MATCH_SELF))] impl PyBool { #[pymethod] fn __format__(obj: PyObjectRef, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> { let new_bool = obj.try_to_bool(vm)?; FormatSpec::parse(spec.as_str()) .and_then(|format_spec| format_spec.format_bool(new_bool)) .map_err(|err| err.into_pyexception(vm)) } } impl PyBool { pub(crate) fn __or__(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if lhs.fast_isinstance(vm.ctx.types.bool_type) && rhs.fast_isinstance(vm.ctx.types.bool_type) { let lhs = get_value(&lhs); let rhs = get_value(&rhs); (lhs || rhs).to_pyobject(vm) } else if let Some(lhs) = lhs.downcast_ref::<PyInt>() { lhs.__or__(rhs).to_pyobject(vm) } else { vm.ctx.not_implemented() } } pub(crate) fn __and__(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if lhs.fast_isinstance(vm.ctx.types.bool_type) && rhs.fast_isinstance(vm.ctx.types.bool_type) { let lhs = get_value(&lhs); let rhs = get_value(&rhs); (lhs && rhs).to_pyobject(vm) } else if let Some(lhs) = lhs.downcast_ref::<PyInt>() { lhs.__and__(rhs).to_pyobject(vm) } else { vm.ctx.not_implemented() } } pub(crate) fn __xor__(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if lhs.fast_isinstance(vm.ctx.types.bool_type) && rhs.fast_isinstance(vm.ctx.types.bool_type) { let lhs = get_value(&lhs); let rhs = get_value(&rhs); (lhs ^ rhs).to_pyobject(vm) } else if let Some(lhs) = lhs.downcast_ref::<PyInt>() { lhs.__xor__(rhs).to_pyobject(vm) } else { vm.ctx.not_implemented() } } } impl AsNumber for PyBool { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { and: Some(|a, b, vm| PyBool::__and__(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)), xor: Some(|a, b, vm| PyBool::__xor__(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)), or: Some(|a, b, vm| PyBool::__or__(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)), ..PyInt::AS_NUMBER }; &AS_NUMBER } } impl Representable for PyBool { #[inline] fn slot_repr(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyStrRef> { let name = if get_value(zelf.as_object()) { vm.ctx.names.True } else { vm.ctx.names.False }; Ok(name.to_owned()) } #[cold] fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { unreachable!("use slot_repr instead") } } pub(crate) fn init(context: &Context) { PyBool::extend_class(context, context.types.bool_type); } // pub fn not(vm: &VirtualMachine, obj: &PyObject) -> PyResult<bool> { // if obj.fast_isinstance(vm.ctx.types.bool_type) { // let value = get_value(obj); // Ok(!value) // } else { // Err(vm.new_type_error(format!("Can only invert a bool, on {:?}", obj))) // } // } // Retrieve inner int value: pub(crate) fn get_value(obj: &PyObject) -> bool { !obj.downcast_ref::<PyBool>() .unwrap() .0 .as_bigint() .is_zero() }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/type.rs
crates/vm/src/builtins/type.rs
use super::{ PyClassMethod, PyDictRef, PyList, PyStr, PyStrInterned, PyStrRef, PyTupleRef, PyWeak, mappingproxy::PyMappingProxy, object, union_, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, builtins::{ PyBaseExceptionRef, descriptor::{ MemberGetter, MemberKind, MemberSetter, PyDescriptorOwned, PyMemberDef, PyMemberDescriptor, }, function::PyCellRef, tuple::{IntoPyTuple, PyTuple}, }, class::{PyClassImpl, StaticType}, common::{ ascii, borrow::BorrowedValue, lock::{PyRwLock, PyRwLockReadGuard}, }, convert::ToPyResult, function::{FuncArgs, KwArgs, OptionalArg, PyMethodDef, PySetterValue}, object::{Traverse, TraverseFn}, protocol::{PyIterReturn, PyNumberMethods}, types::{ AsNumber, Callable, Constructor, GetAttr, Initializer, PyTypeFlags, PyTypeSlots, Representable, SLOT_DEFS, SetAttr, TypeDataRef, TypeDataRefMut, TypeDataSlot, }, }; use core::{any::Any, borrow::Borrow, ops::Deref, pin::Pin, ptr::NonNull}; use indexmap::{IndexMap, map::Entry}; use itertools::Itertools; use num_traits::ToPrimitive; use std::collections::HashSet; #[pyclass(module = false, name = "type", traverse = "manual")] pub struct PyType { pub base: Option<PyTypeRef>, pub bases: PyRwLock<Vec<PyTypeRef>>, pub mro: PyRwLock<Vec<PyTypeRef>>, pub subclasses: PyRwLock<Vec<PyRef<PyWeak>>>, pub attributes: PyRwLock<PyAttributes>, pub slots: PyTypeSlots, pub heaptype_ext: Option<Pin<Box<HeapTypeExt>>>, } unsafe impl crate::object::Traverse for PyType { fn traverse(&self, tracer_fn: &mut crate::object::TraverseFn<'_>) { self.base.traverse(tracer_fn); self.bases.traverse(tracer_fn); // mro contains self as mro[0], so skip traversing to avoid circular reference // self.mro.traverse(tracer_fn); self.subclasses.traverse(tracer_fn); self.attributes .read_recursive() .iter() .map(|(_, v)| v.traverse(tracer_fn)) .count(); } } // PyHeapTypeObject in CPython pub struct HeapTypeExt { pub name: PyRwLock<PyStrRef>, pub qualname: PyRwLock<PyStrRef>, pub slots: Option<PyRef<PyTuple<PyStrRef>>>, pub type_data: PyRwLock<Option<TypeDataSlot>>, } pub struct PointerSlot<T>(NonNull<T>); unsafe impl<T> Sync for PointerSlot<T> {} unsafe impl<T> Send for PointerSlot<T> {} impl<T> PointerSlot<T> { pub const unsafe fn borrow_static(&self) -> &'static T { unsafe { self.0.as_ref() } } } impl<T> Clone for PointerSlot<T> { fn clone(&self) -> Self { *self } } impl<T> Copy for PointerSlot<T> {} impl<T> From<&'static T> for PointerSlot<T> { fn from(x: &'static T) -> Self { Self(NonNull::from(x)) } } impl<T> AsRef<T> for PointerSlot<T> { fn as_ref(&self) -> &T { unsafe { self.0.as_ref() } } } pub type PyTypeRef = PyRef<PyType>; cfg_if::cfg_if! { if #[cfg(feature = "threading")] { unsafe impl Send for PyType {} unsafe impl Sync for PyType {} } } /// For attributes we do not use a dict, but an IndexMap, which is an Hash Table /// that maintains order and is compatible with the standard HashMap This is probably /// faster and only supports strings as keys. pub type PyAttributes = IndexMap<&'static PyStrInterned, PyObjectRef, ahash::RandomState>; unsafe impl Traverse for PyAttributes { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { self.values().for_each(|v| v.traverse(tracer_fn)); } } impl core::fmt::Display for PyType { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { core::fmt::Display::fmt(&self.name(), f) } } impl core::fmt::Debug for PyType { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "[PyType {}]", &self.name()) } } impl PyPayload for PyType { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.type_type } } fn downcast_qualname(value: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<PyStr>> { match value.downcast::<PyStr>() { Ok(value) => Ok(value), Err(value) => Err(vm.new_type_error(format!( "can only assign string to __qualname__, not '{}'", value.class().name() ))), } } fn is_subtype_with_mro(a_mro: &[PyTypeRef], a: &Py<PyType>, b: &Py<PyType>) -> bool { if a.is(b) { return true; } for item in a_mro { if item.is(b) { return true; } } false } impl PyType { pub fn new_simple_heap( name: &str, base: &Py<PyType>, ctx: &Context, ) -> Result<PyRef<Self>, String> { Self::new_heap( name, vec![base.to_owned()], Default::default(), Default::default(), Self::static_type().to_owned(), ctx, ) } pub fn new_heap( name: &str, bases: Vec<PyRef<Self>>, attrs: PyAttributes, mut slots: PyTypeSlots, metaclass: PyRef<Self>, ctx: &Context, ) -> Result<PyRef<Self>, String> { // TODO: ensure clean slot name // assert_eq!(slots.name.borrow(), ""); // Set HEAPTYPE flag for heap-allocated types slots.flags |= PyTypeFlags::HEAPTYPE; let name = ctx.new_str(name); let heaptype_ext = HeapTypeExt { name: PyRwLock::new(name.clone()), qualname: PyRwLock::new(name), slots: None, type_data: PyRwLock::new(None), }; let base = bases[0].clone(); Self::new_heap_inner(base, bases, attrs, slots, heaptype_ext, metaclass, ctx) } /// Equivalent to CPython's PyType_Check macro /// Checks if obj is an instance of type (or its subclass) pub(crate) fn check(obj: &PyObject) -> Option<&Py<Self>> { obj.downcast_ref::<Self>() } fn resolve_mro(bases: &[PyRef<Self>]) -> Result<Vec<PyTypeRef>, String> { // Check for duplicates in bases. let mut unique_bases = HashSet::new(); for base in bases { if !unique_bases.insert(base.get_id()) { return Err(format!("duplicate base class {}", base.name())); } } let mros = bases .iter() .map(|base| base.mro_map_collect(|t| t.to_owned())) .collect(); linearise_mro(mros) } /// Inherit SEQUENCE and MAPPING flags from base classes /// Check all bases in order and inherit the first SEQUENCE or MAPPING flag found fn inherit_patma_flags(slots: &mut PyTypeSlots, bases: &[PyRef<Self>]) { const COLLECTION_FLAGS: PyTypeFlags = PyTypeFlags::from_bits_truncate( PyTypeFlags::SEQUENCE.bits() | PyTypeFlags::MAPPING.bits(), ); // If flags are already set, don't override if slots.flags.intersects(COLLECTION_FLAGS) { return; } // Check each base in order and inherit the first collection flag found for base in bases { let base_flags = base.slots.flags & COLLECTION_FLAGS; if !base_flags.is_empty() { slots.flags |= base_flags; return; } } } /// Check for __abc_tpflags__ and set the appropriate flags /// This checks in attrs and all base classes for __abc_tpflags__ fn check_abc_tpflags( slots: &mut PyTypeSlots, attrs: &PyAttributes, bases: &[PyRef<Self>], ctx: &Context, ) { const COLLECTION_FLAGS: PyTypeFlags = PyTypeFlags::from_bits_truncate( PyTypeFlags::SEQUENCE.bits() | PyTypeFlags::MAPPING.bits(), ); // Don't override if flags are already set if slots.flags.intersects(COLLECTION_FLAGS) { return; } // First check in our own attributes let abc_tpflags_name = ctx.intern_str("__abc_tpflags__"); if let Some(abc_tpflags_obj) = attrs.get(abc_tpflags_name) && let Some(int_obj) = abc_tpflags_obj.downcast_ref::<crate::builtins::int::PyInt>() { let flags_val = int_obj.as_bigint().to_i64().unwrap_or(0); let abc_flags = PyTypeFlags::from_bits_truncate(flags_val as u64); slots.flags |= abc_flags & COLLECTION_FLAGS; return; } // Then check in base classes for base in bases { if let Some(abc_tpflags_obj) = base.find_name_in_mro(abc_tpflags_name) && let Some(int_obj) = abc_tpflags_obj.downcast_ref::<crate::builtins::int::PyInt>() { let flags_val = int_obj.as_bigint().to_i64().unwrap_or(0); let abc_flags = PyTypeFlags::from_bits_truncate(flags_val as u64); slots.flags |= abc_flags & COLLECTION_FLAGS; return; } } } #[allow(clippy::too_many_arguments)] fn new_heap_inner( base: PyRef<Self>, bases: Vec<PyRef<Self>>, attrs: PyAttributes, mut slots: PyTypeSlots, heaptype_ext: HeapTypeExt, metaclass: PyRef<Self>, ctx: &Context, ) -> Result<PyRef<Self>, String> { let mro = Self::resolve_mro(&bases)?; // Inherit HAS_DICT from any base in MRO that has it // (not just the first base, as any base with __dict__ means subclass needs it too) if mro .iter() .any(|b| b.slots.flags.has_feature(PyTypeFlags::HAS_DICT)) { slots.flags |= PyTypeFlags::HAS_DICT } // Inherit SEQUENCE and MAPPING flags from base classes Self::inherit_patma_flags(&mut slots, &bases); // Check for __abc_tpflags__ from ABCMeta (for collections.abc.Sequence, Mapping, etc.) Self::check_abc_tpflags(&mut slots, &attrs, &bases, ctx); if slots.basicsize == 0 { slots.basicsize = base.slots.basicsize; } Self::inherit_readonly_slots(&mut slots, &base); if let Some(qualname) = attrs.get(identifier!(ctx, __qualname__)) && !qualname.fast_isinstance(ctx.types.str_type) { return Err(format!( "type __qualname__ must be a str, not {}", qualname.class().name() )); } let new_type = PyRef::new_ref( Self { base: Some(base), bases: PyRwLock::new(bases), mro: PyRwLock::new(mro), subclasses: PyRwLock::default(), attributes: PyRwLock::new(attrs), slots, heaptype_ext: Some(Pin::new(Box::new(heaptype_ext))), }, metaclass, None, ); new_type.mro.write().insert(0, new_type.clone()); new_type.init_slots(ctx); let weakref_type = super::PyWeak::static_type(); for base in new_type.bases.read().iter() { base.subclasses.write().push( new_type .as_object() .downgrade_with_weakref_typ_opt(None, weakref_type.to_owned()) .unwrap(), ); } Ok(new_type) } pub fn new_static( base: PyRef<Self>, attrs: PyAttributes, mut slots: PyTypeSlots, metaclass: PyRef<Self>, ) -> Result<PyRef<Self>, String> { if base.slots.flags.has_feature(PyTypeFlags::HAS_DICT) { slots.flags |= PyTypeFlags::HAS_DICT } // Inherit SEQUENCE and MAPPING flags from base class // For static types, we only have a single base Self::inherit_patma_flags(&mut slots, core::slice::from_ref(&base)); if slots.basicsize == 0 { slots.basicsize = base.slots.basicsize; } Self::inherit_readonly_slots(&mut slots, &base); let bases = PyRwLock::new(vec![base.clone()]); let mro = base.mro_map_collect(|x| x.to_owned()); let new_type = PyRef::new_ref( Self { base: Some(base), bases, mro: PyRwLock::new(mro), subclasses: PyRwLock::default(), attributes: PyRwLock::new(attrs), slots, heaptype_ext: None, }, metaclass, None, ); new_type.mro.write().insert(0, new_type.clone()); // Note: inherit_slots is called in PyClassImpl::init_class after // slots are fully initialized by make_slots() Self::set_new(&new_type.slots, &new_type.base); let weakref_type = super::PyWeak::static_type(); for base in new_type.bases.read().iter() { base.subclasses.write().push( new_type .as_object() .downgrade_with_weakref_typ_opt(None, weakref_type.to_owned()) .unwrap(), ); } Ok(new_type) } pub(crate) fn init_slots(&self, ctx: &Context) { // Inherit slots from MRO (mro[0] is self, so skip it) let mro: Vec<_> = self.mro.read()[1..].to_vec(); for base in mro.iter() { self.inherit_slots(base); } // Wire dunder methods to slots #[allow(clippy::mutable_key_type)] let mut slot_name_set = std::collections::HashSet::new(); // mro[0] is self, so skip it; self.attributes is checked separately below for cls in self.mro.read()[1..].iter() { for &name in cls.attributes.read().keys() { if name.as_bytes().starts_with(b"__") && name.as_bytes().ends_with(b"__") { slot_name_set.insert(name); } } } for &name in self.attributes.read().keys() { if name.as_bytes().starts_with(b"__") && name.as_bytes().ends_with(b"__") { slot_name_set.insert(name); } } // Sort for deterministic iteration order (important for slot processing) let mut slot_names: Vec<_> = slot_name_set.into_iter().collect(); slot_names.sort_by_key(|name| name.as_str()); for attr_name in slot_names { self.update_slot::<true>(attr_name, ctx); } Self::set_new(&self.slots, &self.base); } fn set_new(slots: &PyTypeSlots, base: &Option<PyTypeRef>) { if slots.flags.contains(PyTypeFlags::DISALLOW_INSTANTIATION) { slots.new.store(None) } else if slots.new.load().is_none() { slots.new.store( base.as_ref() .map(|base| base.slots.new.load()) .unwrap_or(None), ) } } /// Inherit readonly slots from base type at creation time. /// These slots are not AtomicCell and must be set before the type is used. fn inherit_readonly_slots(slots: &mut PyTypeSlots, base: &Self) { if slots.as_buffer.is_none() { slots.as_buffer = base.slots.as_buffer; } } /// Inherit slots from base type. inherit_slots pub(crate) fn inherit_slots(&self, base: &Self) { // Use SLOT_DEFS to iterate all slots // Note: as_buffer is handled in inherit_readonly_slots (not AtomicCell) for def in SLOT_DEFS { def.accessor.copyslot_if_none(self, base); } } // This is used for class initialization where the vm is not yet available. pub fn set_str_attr<V: Into<PyObjectRef>>( &self, attr_name: &str, value: V, ctx: impl AsRef<Context>, ) { let ctx = ctx.as_ref(); let attr_name = ctx.intern_str(attr_name); self.set_attr(attr_name, value.into()) } pub fn set_attr(&self, attr_name: &'static PyStrInterned, value: PyObjectRef) { self.attributes.write().insert(attr_name, value); } /// This is the internal get_attr implementation for fast lookup on a class. pub fn get_attr(&self, attr_name: &'static PyStrInterned) -> Option<PyObjectRef> { flame_guard!(format!("class_get_attr({:?})", attr_name)); self.get_direct_attr(attr_name) .or_else(|| self.get_super_attr(attr_name)) } pub fn get_direct_attr(&self, attr_name: &'static PyStrInterned) -> Option<PyObjectRef> { self.attributes.read().get(attr_name).cloned() } /// Equivalent to CPython's find_name_in_mro /// Look in tp_dict of types in MRO - bypasses descriptors and other attribute access machinery fn find_name_in_mro(&self, name: &'static PyStrInterned) -> Option<PyObjectRef> { // mro[0] is self, so we just iterate through the entire MRO for cls in self.mro.read().iter() { if let Some(value) = cls.attributes.read().get(name) { return Some(value.clone()); } } None } /// Equivalent to CPython's _PyType_LookupRef /// Looks up a name through the MRO without setting an exception pub fn lookup_ref(&self, name: &Py<PyStr>, vm: &VirtualMachine) -> Option<PyObjectRef> { // Get interned name for efficient lookup let interned_name = vm.ctx.interned_str(name)?; // Use find_name_in_mro which matches CPython's behavior // This bypasses descriptors and other attribute access machinery self.find_name_in_mro(interned_name) } pub fn get_super_attr(&self, attr_name: &'static PyStrInterned) -> Option<PyObjectRef> { self.mro.read()[1..] .iter() .find_map(|class| class.attributes.read().get(attr_name).cloned()) } // This is the internal has_attr implementation for fast lookup on a class. pub fn has_attr(&self, attr_name: &'static PyStrInterned) -> bool { self.attributes.read().contains_key(attr_name) || self.mro.read()[1..] .iter() .any(|c| c.attributes.read().contains_key(attr_name)) } pub fn get_attributes(&self) -> PyAttributes { // Gather all members here: let mut attributes = PyAttributes::default(); // mro[0] is self, so we iterate through the entire MRO in reverse for bc in self.mro.read().iter().map(|cls| -> &Self { cls }).rev() { for (name, value) in bc.attributes.read().iter() { attributes.insert(name.to_owned(), value.clone()); } } attributes } // bound method for every type pub(crate) fn __new__(zelf: PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let (subtype, args): (PyRef<Self>, FuncArgs) = args.bind(vm)?; if !subtype.fast_issubclass(&zelf) { return Err(vm.new_type_error(format!( "{zelf}.__new__({subtype}): {subtype} is not a subtype of {zelf}", zelf = zelf.name(), subtype = subtype.name(), ))); } call_slot_new(zelf, subtype, args, vm) } fn name_inner<'a, R: 'a>( &'a self, static_f: impl FnOnce(&'static str) -> R, heap_f: impl FnOnce(&'a HeapTypeExt) -> R, ) -> R { if !self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) { static_f(self.slots.name) } else { heap_f(self.heaptype_ext.as_ref().unwrap()) } } pub fn slot_name(&self) -> BorrowedValue<'_, str> { self.name_inner( |name| name.into(), |ext| PyRwLockReadGuard::map(ext.name.read(), |name| name.as_str()).into(), ) } pub fn name(&self) -> BorrowedValue<'_, str> { self.name_inner( |name| name.rsplit_once('.').map_or(name, |(_, name)| name).into(), |ext| PyRwLockReadGuard::map(ext.name.read(), |name| name.as_str()).into(), ) } // Type Data Slot API - CPython's PyObject_GetTypeData equivalent /// Initialize type data for this type. Can only be called once. /// Returns an error if the type is not a heap type or if data is already initialized. pub fn init_type_data<T: Any + Send + Sync + 'static>(&self, data: T) -> Result<(), String> { let ext = self .heaptype_ext .as_ref() .ok_or_else(|| "Cannot set type data on non-heap types".to_string())?; let mut type_data = ext.type_data.write(); if type_data.is_some() { return Err("Type data already initialized".to_string()); } *type_data = Some(TypeDataSlot::new(data)); Ok(()) } /// Get a read guard to the type data. /// Returns None if the type is not a heap type, has no data, or the data type doesn't match. pub fn get_type_data<T: Any + 'static>(&self) -> Option<TypeDataRef<'_, T>> { self.heaptype_ext .as_ref() .and_then(|ext| TypeDataRef::try_new(ext.type_data.read())) } /// Get a write guard to the type data. /// Returns None if the type is not a heap type, has no data, or the data type doesn't match. pub fn get_type_data_mut<T: Any + 'static>(&self) -> Option<TypeDataRefMut<'_, T>> { self.heaptype_ext .as_ref() .and_then(|ext| TypeDataRefMut::try_new(ext.type_data.write())) } /// Check if this type has type data of the given type. pub fn has_type_data<T: Any + 'static>(&self) -> bool { self.heaptype_ext.as_ref().is_some_and(|ext| { ext.type_data .read() .as_ref() .is_some_and(|slot| slot.get::<T>().is_some()) }) } } impl Py<PyType> { pub(crate) fn is_subtype(&self, other: &Self) -> bool { is_subtype_with_mro(&self.mro.read(), self, other) } /// Equivalent to CPython's PyType_CheckExact macro /// Checks if obj is exactly a type (not a subclass) pub fn check_exact<'a>(obj: &'a PyObject, vm: &VirtualMachine) -> Option<&'a Self> { obj.downcast_ref_if_exact::<PyType>(vm) } /// Determines if `subclass` is actually a subclass of `cls`, this doesn't call __subclasscheck__, /// so only use this if `cls` is known to have not overridden the base __subclasscheck__ magic /// method. pub fn fast_issubclass(&self, cls: &impl Borrow<PyObject>) -> bool { self.as_object().is(cls.borrow()) || self.mro.read()[1..].iter().any(|c| c.is(cls.borrow())) } pub fn mro_map_collect<F, R>(&self, f: F) -> Vec<R> where F: Fn(&Self) -> R, { self.mro.read().iter().map(|x| x.deref()).map(f).collect() } pub fn mro_collect(&self) -> Vec<PyRef<PyType>> { self.mro .read() .iter() .map(|x| x.deref()) .map(|x| x.to_owned()) .collect() } pub fn iter_base_chain(&self) -> impl Iterator<Item = &Self> { core::iter::successors(Some(self), |cls| cls.base.as_deref()) } pub fn extend_methods(&'static self, method_defs: &'static [PyMethodDef], ctx: &Context) { for method_def in method_defs { let method = method_def.to_proper_method(self, ctx); self.set_attr(ctx.intern_str(method_def.name), method); } } } #[pyclass( with( Py, Constructor, Initializer, GetAttr, SetAttr, Callable, AsNumber, Representable ), flags(BASETYPE) )] impl PyType { #[pygetset] fn __bases__(&self, vm: &VirtualMachine) -> PyTupleRef { vm.ctx.new_tuple( self.bases .read() .iter() .map(|x| x.as_object().to_owned()) .collect(), ) } #[pygetset(setter, name = "__bases__")] fn set_bases(zelf: &Py<Self>, bases: Vec<PyTypeRef>, vm: &VirtualMachine) -> PyResult<()> { // TODO: Assigning to __bases__ is only used in typing.NamedTupleMeta.__new__ // Rather than correctly re-initializing the class, we are skipping a few steps for now if zelf.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) { return Err(vm.new_type_error(format!( "cannot set '__bases__' attribute of immutable type '{}'", zelf.name() ))); } if bases.is_empty() { return Err(vm.new_type_error(format!( "can only assign non-empty tuple to %s.__bases__, not {}", zelf.name() ))); } // TODO: check for mro cycles // TODO: Remove this class from all subclass lists // for base in self.bases.read().iter() { // let subclasses = base.subclasses.write(); // // TODO: how to uniquely identify the subclasses to remove? // } *zelf.bases.write() = bases; // Recursively update the mros of this class and all subclasses fn update_mro_recursively(cls: &PyType, vm: &VirtualMachine) -> PyResult<()> { let mut mro = PyType::resolve_mro(&cls.bases.read()).map_err(|msg| vm.new_type_error(msg))?; // Preserve self (mro[0]) when updating MRO mro.insert(0, cls.mro.read()[0].to_owned()); *cls.mro.write() = mro; for subclass in cls.subclasses.write().iter() { let subclass = subclass.upgrade().unwrap(); let subclass: &Py<PyType> = subclass.downcast_ref().unwrap(); update_mro_recursively(subclass, vm)?; } Ok(()) } update_mro_recursively(zelf, vm)?; // TODO: do any old slots need to be cleaned up first? zelf.init_slots(&vm.ctx); // Register this type as a subclass of its new bases let weakref_type = super::PyWeak::static_type(); for base in zelf.bases.read().iter() { base.subclasses.write().push( zelf.as_object() .downgrade_with_weakref_typ_opt(None, weakref_type.to_owned()) .unwrap(), ); } Ok(()) } #[pygetset] fn __base__(&self) -> Option<PyTypeRef> { self.base.clone() } #[pygetset] const fn __flags__(&self) -> u64 { self.slots.flags.bits() } #[pygetset] fn __basicsize__(&self) -> usize { crate::object::SIZEOF_PYOBJECT_HEAD + self.slots.basicsize } #[pygetset] fn __itemsize__(&self) -> usize { self.slots.itemsize } #[pygetset] pub fn __name__(&self, vm: &VirtualMachine) -> PyStrRef { self.name_inner( |name| { vm.ctx .interned_str(name.rsplit_once('.').map_or(name, |(_, name)| name)) .unwrap_or_else(|| { panic!( "static type name must be already interned but {} is not", self.slot_name() ) }) .to_owned() }, |ext| ext.name.read().clone(), ) } #[pygetset] pub fn __qualname__(&self, vm: &VirtualMachine) -> PyObjectRef { if let Some(ref heap_type) = self.heaptype_ext { heap_type.qualname.read().clone().into() } else { // For static types, return the name vm.ctx.new_str(self.name().deref()).into() } } #[pygetset(setter)] fn set___qualname__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { // TODO: we should replace heaptype flag check to immutable flag check if !self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) { return Err(vm.new_type_error(format!( "cannot set '__qualname__' attribute of immutable type '{}'", self.name() ))); }; let value = value.ok_or_else(|| { vm.new_type_error(format!( "cannot delete '__qualname__' attribute of immutable type '{}'", self.name() )) })?; let str_value = downcast_qualname(value, vm)?; let heap_type = self .heaptype_ext .as_ref() .expect("HEAPTYPE should have heaptype_ext"); // Use std::mem::replace to swap the new value in and get the old value out, // then drop the old value after releasing the lock let _old_qualname = { let mut qualname_guard = heap_type.qualname.write(); core::mem::replace(&mut *qualname_guard, str_value) }; // old_qualname is dropped here, outside the lock scope Ok(()) } #[pygetset] fn __annotations__(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> { if !self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) { return Err(vm.new_attribute_error(format!( "type object '{}' has no attribute '__annotations__'", self.name() ))); } let __annotations__ = identifier!(vm, __annotations__); let annotations = self.attributes.read().get(__annotations__).cloned(); let annotations = if let Some(annotations) = annotations { annotations } else { let annotations: PyObjectRef = vm.ctx.new_dict().into(); let removed = self .attributes .write() .insert(__annotations__, annotations.clone()); debug_assert!(removed.is_none()); annotations }; Ok(annotations) } #[pygetset(setter)] fn set___annotations__(&self, value: Option<PyObjectRef>, vm: &VirtualMachine) -> PyResult<()> { if self.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) { return Err(vm.new_type_error(format!( "cannot set '__annotations__' attribute of immutable type '{}'", self.name() ))); } let __annotations__ = identifier!(vm, __annotations__); if let Some(value) = value { self.attributes.write().insert(__annotations__, value); } else { self.attributes .read() .get(__annotations__) .cloned() .ok_or_else(|| { vm.new_attribute_error(format!( "'{}' object has no attribute '__annotations__'", self.name() )) })?; } Ok(()) } #[pygetset] pub fn __module__(&self, vm: &VirtualMachine) -> PyObjectRef { self.attributes .read() .get(identifier!(vm, __module__)) .cloned() // We need to exclude this method from going into recursion: .and_then(|found| { if found.fast_isinstance(vm.ctx.types.getset_type) { None } else { Some(found) } }) .unwrap_or_else(|| vm.ctx.new_str(ascii!("builtins")).into()) } #[pygetset(setter)] fn set___module__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.check_set_special_type_attr(identifier!(vm, __module__), vm)?; self.attributes .write() .insert(identifier!(vm, __module__), value); Ok(()) } #[pyclassmethod] fn __prepare__( _cls: PyTypeRef, _name: OptionalArg<PyObjectRef>, _bases: OptionalArg<PyObjectRef>, _kwargs: KwArgs, vm: &VirtualMachine, ) -> PyDictRef { vm.ctx.new_dict() } #[pymethod] fn __subclasses__(&self) -> PyList { let mut subclasses = self.subclasses.write(); subclasses.retain(|x| x.upgrade().is_some()); PyList::from( subclasses .iter() .map(|x| x.upgrade().unwrap()) .collect::<Vec<_>>(), ) } pub fn __ror__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { or_(other, zelf, vm) } pub fn __or__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { or_(zelf, other, vm) } #[pygetset] fn __dict__(zelf: PyRef<Self>) -> PyMappingProxy { PyMappingProxy::from(zelf) } #[pygetset(setter)] fn set___dict__(&self, _value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/enumerate.rs
crates/vm/src/builtins/enumerate.rs
use super::{ IterStatus, PositionIterInternal, PyGenericAlias, PyIntRef, PyTupleRef, PyType, PyTypeRef, }; use crate::common::lock::{PyMutex, PyRwLock}; use crate::{ AsObject, Context, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, class::PyClassImpl, convert::ToPyObject, function::OptionalArg, protocol::{PyIter, PyIterReturn}, raise_if_stop, types::{Constructor, IterNext, Iterable, SelfIter}, }; use malachite_bigint::BigInt; use num_traits::Zero; #[pyclass(module = false, name = "enumerate", traverse)] #[derive(Debug)] pub struct PyEnumerate { #[pytraverse(skip)] counter: PyRwLock<BigInt>, iterable: PyIter, } impl PyPayload for PyEnumerate { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.enumerate_type } } #[derive(FromArgs)] pub struct EnumerateArgs { #[pyarg(any)] iterable: PyIter, #[pyarg(any, optional)] start: OptionalArg<PyIntRef>, } impl Constructor for PyEnumerate { type Args = EnumerateArgs; fn py_new( _cls: &Py<PyType>, Self::Args { iterable, start }: Self::Args, _vm: &VirtualMachine, ) -> PyResult<Self> { let counter = start.map_or_else(BigInt::zero, |start| start.as_bigint().clone()); Ok(Self { counter: PyRwLock::new(counter), iterable, }) } } #[pyclass(with(Py, IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyEnumerate { #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } #[pyclass] impl Py<PyEnumerate> { #[pymethod] fn __reduce__(&self) -> (PyTypeRef, (PyIter, BigInt)) { ( self.class().to_owned(), (self.iterable.clone(), self.counter.read().clone()), ) } } impl SelfIter for PyEnumerate {} impl IterNext for PyEnumerate { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let next_obj = raise_if_stop!(zelf.iterable.next(vm)?); let mut counter = zelf.counter.write(); let position = counter.clone(); *counter += 1; Ok(PyIterReturn::Return((position, next_obj).to_pyobject(vm))) } } #[pyclass(module = false, name = "reversed", traverse)] #[derive(Debug)] pub struct PyReverseSequenceIterator { internal: PyMutex<PositionIterInternal<PyObjectRef>>, } impl PyPayload for PyReverseSequenceIterator { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.reverse_iter_type } } #[pyclass(with(IterNext, Iterable))] impl PyReverseSequenceIterator { pub const fn new(obj: PyObjectRef, len: usize) -> Self { let position = len.saturating_sub(1); Self { internal: PyMutex::new(PositionIterInternal::new(obj, position)), } } #[pymethod] fn __length_hint__(&self, vm: &VirtualMachine) -> PyResult<usize> { let internal = self.internal.lock(); if let IterStatus::Active(obj) = &internal.status && internal.position <= obj.length(vm)? { return Ok(internal.position + 1); } Ok(0) } #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal.lock().set_state(state, |_, pos| pos, vm) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef { self.internal .lock() .builtins_reversed_reduce(|x| x.clone(), vm) } } impl SelfIter for PyReverseSequenceIterator {} impl IterNext for PyReverseSequenceIterator { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { zelf.internal .lock() .rev_next(|obj, pos| PyIterReturn::from_getitem_result(obj.get_item(&pos, vm), vm)) } } pub fn init(context: &Context) { PyEnumerate::extend_class(context, context.types.enumerate_type); PyReverseSequenceIterator::extend_class(context, context.types.reverse_iter_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/function.rs
crates/vm/src/builtins/function.rs
#[cfg(feature = "jit")] mod jit; use super::{ PyAsyncGen, PyCode, PyCoroutine, PyDictRef, PyGenerator, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType, }; #[cfg(feature = "jit")] use crate::common::lock::OnceCell; use crate::common::lock::PyMutex; use crate::function::ArgMapping; use crate::object::{Traverse, TraverseFn}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, bytecode, class::PyClassImpl, frame::Frame, function::{FuncArgs, OptionalArg, PyComparisonValue, PySetterValue}, scope::Scope, types::{ Callable, Comparable, Constructor, GetAttr, GetDescriptor, PyComparisonOp, Representable, }, }; use itertools::Itertools; #[cfg(feature = "jit")] use rustpython_jit::CompiledCode; #[pyclass(module = false, name = "function", traverse = "manual")] #[derive(Debug)] pub struct PyFunction { code: PyMutex<PyRef<PyCode>>, globals: PyDictRef, builtins: PyObjectRef, closure: Option<PyRef<PyTuple<PyCellRef>>>, defaults_and_kwdefaults: PyMutex<(Option<PyTupleRef>, Option<PyDictRef>)>, name: PyMutex<PyStrRef>, qualname: PyMutex<PyStrRef>, type_params: PyMutex<PyTupleRef>, annotations: PyMutex<PyDictRef>, module: PyMutex<PyObjectRef>, doc: PyMutex<PyObjectRef>, #[cfg(feature = "jit")] jitted_code: OnceCell<CompiledCode>, } unsafe impl Traverse for PyFunction { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { self.globals.traverse(tracer_fn); if let Some(closure) = self.closure.as_ref() { closure.as_untyped().traverse(tracer_fn); } self.defaults_and_kwdefaults.traverse(tracer_fn); } } impl PyFunction { #[inline] pub(crate) fn new( code: PyRef<PyCode>, globals: PyDictRef, vm: &VirtualMachine, ) -> PyResult<Self> { let name = PyMutex::new(code.obj_name.to_owned()); let module = vm.unwrap_or_none(globals.get_item_opt(identifier!(vm, __name__), vm)?); let builtins = globals.get_item("__builtins__", vm).unwrap_or_else(|_| { // If not in globals, inherit from current execution context if let Some(frame) = vm.current_frame() { frame.builtins.clone().into() } else { vm.builtins.clone().into() } }); let qualname = vm.ctx.new_str(code.qualname.as_str()); let func = Self { code: PyMutex::new(code.clone()), globals, builtins, closure: None, defaults_and_kwdefaults: PyMutex::new((None, None)), name, qualname: PyMutex::new(qualname), type_params: PyMutex::new(vm.ctx.empty_tuple.clone()), annotations: PyMutex::new(vm.ctx.new_dict()), module: PyMutex::new(module), doc: PyMutex::new(vm.ctx.none()), #[cfg(feature = "jit")] jitted_code: OnceCell::new(), }; Ok(func) } fn fill_locals_from_args( &self, frame: &Frame, func_args: FuncArgs, vm: &VirtualMachine, ) -> PyResult<()> { let code = &*self.code.lock(); let nargs = func_args.args.len(); let n_expected_args = code.arg_count as usize; let total_args = code.arg_count as usize + code.kwonlyarg_count as usize; // let arg_names = self.code.arg_names(); // This parses the arguments from args and kwargs into // the proper variables keeping into account default values // and star-args and kwargs. // See also: PyEval_EvalCodeWithName in cpython: // https://github.com/python/cpython/blob/main/Python/ceval.c#L3681 let mut fastlocals = frame.fastlocals.lock(); let mut args_iter = func_args.args.into_iter(); // Copy positional arguments into local variables // zip short-circuits if either iterator returns None, which is the behavior we want -- // only fill as much as there is to fill with as much as we have for (local, arg) in Iterator::zip( fastlocals.iter_mut().take(n_expected_args), args_iter.by_ref().take(nargs), ) { *local = Some(arg); } let mut vararg_offset = total_args; // Pack other positional arguments in to *args: if code.flags.contains(bytecode::CodeFlags::HAS_VARARGS) { let vararg_value = vm.ctx.new_tuple(args_iter.collect()); fastlocals[vararg_offset] = Some(vararg_value.into()); vararg_offset += 1; } else { // Check the number of positional arguments if nargs > n_expected_args { let n_defaults = self .defaults_and_kwdefaults .lock() .0 .as_ref() .map_or(0, |d| d.len()); let n_required = n_expected_args - n_defaults; let takes_msg = if n_defaults > 0 { format!("from {} to {}", n_required, n_expected_args) } else { n_expected_args.to_string() }; return Err(vm.new_type_error(format!( "{}() takes {} positional argument{} but {} {} given", self.__qualname__(), takes_msg, if n_expected_args == 1 { "" } else { "s" }, nargs, if nargs == 1 { "was" } else { "were" } ))); } } // Do we support `**kwargs` ? let kwargs = if code.flags.contains(bytecode::CodeFlags::HAS_VARKEYWORDS) { let d = vm.ctx.new_dict(); fastlocals[vararg_offset] = Some(d.clone().into()); Some(d) } else { None }; let arg_pos = |range: core::ops::Range<_>, name: &str| { code.varnames .iter() .enumerate() .skip(range.start) .take(range.end - range.start) .find(|(_, s)| s.as_str() == name) .map(|(p, _)| p) }; let mut posonly_passed_as_kwarg = Vec::new(); // Handle keyword arguments for (name, value) in func_args.kwargs { // Check if we have a parameter with this name: if let Some(pos) = arg_pos(code.posonlyarg_count as usize..total_args, &name) { let slot = &mut fastlocals[pos]; if slot.is_some() { return Err(vm.new_type_error(format!( "{}() got multiple values for argument '{}'", self.__qualname__(), name ))); } *slot = Some(value); } else if let Some(kwargs) = kwargs.as_ref() { kwargs.set_item(&name, value, vm)?; } else if arg_pos(0..code.posonlyarg_count as usize, &name).is_some() { posonly_passed_as_kwarg.push(name); } else { return Err(vm.new_type_error(format!( "{}() got an unexpected keyword argument '{}'", self.__qualname__(), name ))); } } if !posonly_passed_as_kwarg.is_empty() { return Err(vm.new_type_error(format!( "{}() got some positional-only arguments passed as keyword arguments: '{}'", self.__qualname__(), posonly_passed_as_kwarg.into_iter().format(", "), ))); } let mut defaults_and_kwdefaults = None; // can't be a closure cause it returns a reference to a captured variable :/ macro_rules! get_defaults { () => {{ defaults_and_kwdefaults .get_or_insert_with(|| self.defaults_and_kwdefaults.lock().clone()) }}; } // Add missing positional arguments, if we have fewer positional arguments than the // function definition calls for if nargs < n_expected_args { let defaults = get_defaults!().0.as_ref().map(|tup| tup.as_slice()); let n_defs = defaults.map_or(0, |d| d.len()); let n_required = code.arg_count as usize - n_defs; // Given the number of defaults available, check all the arguments for which we // _don't_ have defaults; if any are missing, raise an exception let mut missing: Vec<_> = (nargs..n_required) .filter_map(|i| { if fastlocals[i].is_none() { Some(&code.varnames[i]) } else { None } }) .collect(); let missing_args_len = missing.len(); if !missing.is_empty() { let last = if missing.len() > 1 { missing.pop() } else { None }; let (and, right) = if let Some(last) = last { ( if missing.len() == 1 { "' and '" } else { "', and '" }, last.as_str(), ) } else { ("", "") }; return Err(vm.new_type_error(format!( "{}() missing {} required positional argument{}: '{}{}{}'", self.__qualname__(), missing_args_len, if missing_args_len == 1 { "" } else { "s" }, missing.iter().join("', '"), and, right, ))); } if let Some(defaults) = defaults { let n = core::cmp::min(nargs, n_expected_args); let i = n.saturating_sub(n_required); // We have sufficient defaults, so iterate over the corresponding names and use // the default if we don't already have a value for i in i..defaults.len() { let slot = &mut fastlocals[n_required + i]; if slot.is_none() { *slot = Some(defaults[i].clone()); } } } }; if code.kwonlyarg_count > 0 { // TODO: compile a list of missing arguments // let mut missing = vec![]; // Check if kw only arguments are all present: for (slot, kwarg) in fastlocals .iter_mut() .zip(&*code.varnames) .skip(code.arg_count as usize) .take(code.kwonlyarg_count as usize) .filter(|(slot, _)| slot.is_none()) { if let Some(defaults) = &get_defaults!().1 && let Some(default) = defaults.get_item_opt(&**kwarg, vm)? { *slot = Some(default); continue; } // No default value and not specified. return Err( vm.new_type_error(format!("Missing required kw only argument: '{kwarg}'")) ); } } if let Some(cell2arg) = code.cell2arg.as_deref() { for (cell_idx, arg_idx) in cell2arg.iter().enumerate().filter(|(_, i)| **i != -1) { let x = fastlocals[*arg_idx as usize].take(); frame.cells_frees[cell_idx].set(x); } } Ok(()) } /// Set function attribute based on MakeFunctionFlags pub(crate) fn set_function_attribute( &mut self, attr: bytecode::MakeFunctionFlags, attr_value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { use crate::builtins::PyDict; if attr == bytecode::MakeFunctionFlags::DEFAULTS { let defaults = match attr_value.downcast::<PyTuple>() { Ok(tuple) => tuple, Err(obj) => { return Err(vm.new_type_error(format!( "__defaults__ must be a tuple, not {}", obj.class().name() ))); } }; self.defaults_and_kwdefaults.lock().0 = Some(defaults); } else if attr == bytecode::MakeFunctionFlags::KW_ONLY_DEFAULTS { let kwdefaults = match attr_value.downcast::<PyDict>() { Ok(dict) => dict, Err(obj) => { return Err(vm.new_type_error(format!( "__kwdefaults__ must be a dict, not {}", obj.class().name() ))); } }; self.defaults_and_kwdefaults.lock().1 = Some(kwdefaults); } else if attr == bytecode::MakeFunctionFlags::ANNOTATIONS { let annotations = match attr_value.downcast::<PyDict>() { Ok(dict) => dict, Err(obj) => { return Err(vm.new_type_error(format!( "__annotations__ must be a dict, not {}", obj.class().name() ))); } }; *self.annotations.lock() = annotations; } else if attr == bytecode::MakeFunctionFlags::CLOSURE { // For closure, we need special handling // The closure tuple contains cell objects let closure_tuple = attr_value .clone() .downcast_exact::<PyTuple>(vm) .map_err(|obj| { vm.new_type_error(format!( "closure must be a tuple, not {}", obj.class().name() )) })? .into_pyref(); self.closure = Some(closure_tuple.try_into_typed::<PyCell>(vm)?); } else if attr == bytecode::MakeFunctionFlags::TYPE_PARAMS { let type_params = attr_value.clone().downcast::<PyTuple>().map_err(|_| { vm.new_type_error(format!( "__type_params__ must be a tuple, not {}", attr_value.class().name() )) })?; *self.type_params.lock() = type_params; } else { unreachable!("This is a compiler bug"); } Ok(()) } } impl Py<PyFunction> { pub fn invoke_with_locals( &self, func_args: FuncArgs, locals: Option<ArgMapping>, vm: &VirtualMachine, ) -> PyResult { #[cfg(feature = "jit")] if let Some(jitted_code) = self.jitted_code.get() { use crate::convert::ToPyObject; match jit::get_jit_args(self, &func_args, jitted_code, vm) { Ok(args) => { return Ok(args.invoke().to_pyobject(vm)); } Err(err) => info!( "jit: function `{}` is falling back to being interpreted because of the \ error: {}", self.code.lock().obj_name, err ), } } let code = self.code.lock().clone(); let locals = if code.flags.contains(bytecode::CodeFlags::NEW_LOCALS) { ArgMapping::from_dict_exact(vm.ctx.new_dict()) } else if let Some(locals) = locals { locals } else { ArgMapping::from_dict_exact(self.globals.clone()) }; // Construct frame: let frame = Frame::new( code.clone(), Scope::new(Some(locals), self.globals.clone()), vm.builtins.dict(), self.closure.as_ref().map_or(&[], |c| c.as_slice()), Some(self.to_owned().into()), vm, ) .into_ref(&vm.ctx); self.fill_locals_from_args(&frame, func_args, vm)?; // If we have a generator, create a new generator let is_gen = code.flags.contains(bytecode::CodeFlags::IS_GENERATOR); let is_coro = code.flags.contains(bytecode::CodeFlags::IS_COROUTINE); match (is_gen, is_coro) { (true, false) => { Ok(PyGenerator::new(frame, self.__name__(), self.__qualname__()).into_pyobject(vm)) } (false, true) => { Ok(PyCoroutine::new(frame, self.__name__(), self.__qualname__()).into_pyobject(vm)) } (true, true) => { Ok(PyAsyncGen::new(frame, self.__name__(), self.__qualname__()).into_pyobject(vm)) } (false, false) => vm.run_frame(frame), } } #[inline(always)] pub fn invoke(&self, func_args: FuncArgs, vm: &VirtualMachine) -> PyResult { self.invoke_with_locals(func_args, None, vm) } } impl PyPayload for PyFunction { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.function_type } } #[pyclass( with(GetDescriptor, Callable, Representable, Constructor), flags(HAS_DICT, METHOD_DESCRIPTOR) )] impl PyFunction { #[pygetset] fn __code__(&self) -> PyRef<PyCode> { self.code.lock().clone() } #[pygetset(setter)] fn set___code__(&self, code: PyRef<PyCode>) { *self.code.lock() = code; // TODO: jit support // #[cfg(feature = "jit")] // { // // If available, clear cached compiled code. // let _ = self.jitted_code.take(); // } } #[pygetset] fn __defaults__(&self) -> Option<PyTupleRef> { self.defaults_and_kwdefaults.lock().0.clone() } #[pygetset(setter)] fn set___defaults__(&self, defaults: Option<PyTupleRef>) { self.defaults_and_kwdefaults.lock().0 = defaults } #[pygetset] fn __kwdefaults__(&self) -> Option<PyDictRef> { self.defaults_and_kwdefaults.lock().1.clone() } #[pygetset(setter)] fn set___kwdefaults__(&self, kwdefaults: Option<PyDictRef>) { self.defaults_and_kwdefaults.lock().1 = kwdefaults } // {"__closure__", T_OBJECT, OFF(func_closure), READONLY}, // {"__doc__", T_OBJECT, OFF(func_doc), 0}, // {"__globals__", T_OBJECT, OFF(func_globals), READONLY}, // {"__module__", T_OBJECT, OFF(func_module), 0}, // {"__builtins__", T_OBJECT, OFF(func_builtins), READONLY}, #[pymember] fn __globals__(vm: &VirtualMachine, zelf: PyObjectRef) -> PyResult { let zelf = Self::_as_pyref(&zelf, vm)?; Ok(zelf.globals.clone().into()) } #[pymember] fn __closure__(vm: &VirtualMachine, zelf: PyObjectRef) -> PyResult { let zelf = Self::_as_pyref(&zelf, vm)?; Ok(vm.unwrap_or_none(zelf.closure.clone().map(|x| x.into()))) } #[pymember] fn __builtins__(vm: &VirtualMachine, zelf: PyObjectRef) -> PyResult { let zelf = Self::_as_pyref(&zelf, vm)?; Ok(zelf.builtins.clone()) } #[pygetset] fn __name__(&self) -> PyStrRef { self.name.lock().clone() } #[pygetset(setter)] fn set___name__(&self, name: PyStrRef) { *self.name.lock() = name; } #[pymember] fn __doc__(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { // When accessed from instance, obj is the PyFunction instance if let Ok(func) = obj.downcast::<Self>() { let doc = func.doc.lock(); Ok(doc.clone()) } else { // When accessed from class, return None as there's no instance Ok(vm.ctx.none()) } } #[pymember(setter)] fn set___doc__(vm: &VirtualMachine, zelf: PyObjectRef, value: PySetterValue) -> PyResult<()> { let zelf: PyRef<Self> = zelf.downcast().unwrap_or_else(|_| unreachable!()); let value = value.unwrap_or_none(vm); *zelf.doc.lock() = value; Ok(()) } #[pygetset] fn __module__(&self) -> PyObjectRef { self.module.lock().clone() } #[pygetset(setter)] fn set___module__(&self, module: PySetterValue<PyObjectRef>, vm: &VirtualMachine) { *self.module.lock() = module.unwrap_or_none(vm); } #[pygetset] fn __annotations__(&self) -> PyDictRef { self.annotations.lock().clone() } #[pygetset(setter)] fn set___annotations__(&self, annotations: PyDictRef) { *self.annotations.lock() = annotations } #[pygetset] fn __qualname__(&self) -> PyStrRef { self.qualname.lock().clone() } #[pygetset(setter)] fn set___qualname__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { match value { PySetterValue::Assign(value) => { let Ok(qualname) = value.downcast::<PyStr>() else { return Err(vm.new_type_error("__qualname__ must be set to a string object")); }; *self.qualname.lock() = qualname; } PySetterValue::Delete => { return Err(vm.new_type_error("__qualname__ must be set to a string object")); } } Ok(()) } #[pygetset] fn __type_params__(&self) -> PyTupleRef { self.type_params.lock().clone() } #[pygetset(setter)] fn set___type_params__( &self, value: PySetterValue<PyTupleRef>, vm: &VirtualMachine, ) -> PyResult<()> { match value { PySetterValue::Assign(value) => { *self.type_params.lock() = value; } PySetterValue::Delete => { return Err(vm.new_type_error("__type_params__ must be set to a tuple object")); } } Ok(()) } #[cfg(feature = "jit")] #[pymethod] fn __jit__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<()> { zelf.jitted_code .get_or_try_init(|| { let arg_types = jit::get_jit_arg_types(&zelf, vm)?; let ret_type = jit::jit_ret_type(&zelf, vm)?; let code = zelf.code.lock(); rustpython_jit::compile(&code.code, &arg_types, ret_type) .map_err(|err| jit::new_jit_error(err.to_string(), vm)) }) .map(drop) } } impl GetDescriptor for PyFunction { fn descr_get( zelf: PyObjectRef, obj: Option<PyObjectRef>, cls: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { let (_zelf, obj) = Self::_unwrap(&zelf, obj, vm)?; Ok(if vm.is_none(&obj) && !Self::_cls_is(&cls, obj.class()) { zelf } else { PyBoundMethod::new(obj, zelf).into_ref(&vm.ctx).into() }) } } impl Callable for PyFunction { type Args = FuncArgs; #[inline] fn call(zelf: &Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult { zelf.invoke(args, vm) } } impl Representable for PyFunction { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { Ok(format!( "<function {} at {:#x}>", zelf.__qualname__(), zelf.get_id() )) } } #[derive(FromArgs)] pub struct PyFunctionNewArgs { #[pyarg(positional)] code: PyRef<PyCode>, #[pyarg(positional)] globals: PyDictRef, #[pyarg(any, optional)] name: OptionalArg<PyStrRef>, #[pyarg(any, optional)] defaults: OptionalArg<PyTupleRef>, #[pyarg(any, optional)] closure: OptionalArg<PyTupleRef>, #[pyarg(any, optional)] kwdefaults: OptionalArg<PyDictRef>, } impl Constructor for PyFunction { type Args = PyFunctionNewArgs; fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> { // Handle closure - must be a tuple of cells let closure = if let Some(closure_tuple) = args.closure.into_option() { // Check that closure length matches code's free variables if closure_tuple.len() != args.code.freevars.len() { return Err(vm.new_value_error(format!( "{} requires closure of length {}, not {}", args.code.obj_name, args.code.freevars.len(), closure_tuple.len() ))); } // Validate that all items are cells and create typed tuple let typed_closure = closure_tuple.try_into_typed::<PyCell>(vm)?; Some(typed_closure) } else if !args.code.freevars.is_empty() { return Err(vm.new_type_error("arg 5 (closure) must be tuple")); } else { None }; let mut func = Self::new(args.code.clone(), args.globals.clone(), vm)?; // Set function name if provided if let Some(name) = args.name.into_option() { *func.name.lock() = name.clone(); // Also update qualname to match the name *func.qualname.lock() = name; } // Now set additional attributes directly if let Some(closure_tuple) = closure { func.closure = Some(closure_tuple); } if let Some(defaults) = args.defaults.into_option() { func.defaults_and_kwdefaults.lock().0 = Some(defaults); } if let Some(kwdefaults) = args.kwdefaults.into_option() { func.defaults_and_kwdefaults.lock().1 = Some(kwdefaults); } Ok(func) } } #[pyclass(module = false, name = "method", traverse)] #[derive(Debug)] pub struct PyBoundMethod { object: PyObjectRef, function: PyObjectRef, } impl Callable for PyBoundMethod { type Args = FuncArgs; #[inline] fn call(zelf: &Py<Self>, mut args: FuncArgs, vm: &VirtualMachine) -> PyResult { args.prepend_arg(zelf.object.clone()); zelf.function.call(args, vm) } } impl Comparable for PyBoundMethod { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, _vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { op.eq_only(|| { let other = class_or_notimplemented!(Self, other); Ok(PyComparisonValue::Implemented( zelf.function.is(&other.function) && zelf.object.is(&other.object), )) }) } } impl GetAttr for PyBoundMethod { fn getattro(zelf: &Py<Self>, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult { let class_attr = vm .ctx .interned_str(name) .and_then(|attr_name| zelf.get_class_attr(attr_name)); if let Some(obj) = class_attr { return vm.call_if_get_descriptor(&obj, zelf.to_owned().into()); } zelf.function.get_attr(name, vm) } } #[derive(FromArgs)] pub struct PyBoundMethodNewArgs { #[pyarg(positional)] function: PyObjectRef, #[pyarg(positional)] object: PyObjectRef, } impl Constructor for PyBoundMethod { type Args = PyBoundMethodNewArgs; fn py_new( _cls: &Py<PyType>, Self::Args { function, object }: Self::Args, _vm: &VirtualMachine, ) -> PyResult<Self> { Ok(Self::new(object, function)) } } impl PyBoundMethod { pub const fn new(object: PyObjectRef, function: PyObjectRef) -> Self { Self { object, function } } #[deprecated(note = "Use `Self::new(object, function).into_ref(ctx)` instead")] pub fn new_ref(object: PyObjectRef, function: PyObjectRef, ctx: &Context) -> PyRef<Self> { Self::new(object, function).into_ref(ctx) } } #[pyclass( with(Callable, Comparable, GetAttr, Constructor, Representable), flags(IMMUTABLETYPE) )] impl PyBoundMethod { #[pymethod] fn __reduce__( &self, vm: &VirtualMachine, ) -> (Option<PyObjectRef>, (PyObjectRef, Option<PyObjectRef>)) { let builtins_getattr = vm.builtins.get_attr("getattr", vm).ok(); let func_self = self.object.clone(); let func_name = self.function.get_attr("__name__", vm).ok(); (builtins_getattr, (func_self, func_name)) } #[pygetset] fn __doc__(&self, vm: &VirtualMachine) -> PyResult { self.function.get_attr("__doc__", vm) } #[pygetset] fn __func__(&self) -> PyObjectRef { self.function.clone() } #[pygetset(name = "__self__")] fn get_self(&self) -> PyObjectRef { self.object.clone() } #[pygetset] fn __module__(&self, vm: &VirtualMachine) -> Option<PyObjectRef> { self.function.get_attr("__module__", vm).ok() } #[pygetset] fn __qualname__(&self, vm: &VirtualMachine) -> PyResult { if self .function .fast_isinstance(vm.ctx.types.builtin_function_or_method_type) { // Special case: we work with `__new__`, which is not really a method. // It is a function, so its `__qualname__` is just `__new__`. // We need to add object's part manually. let obj_name = vm.get_attribute_opt(self.object.clone(), "__qualname__")?; let obj_name: Option<PyStrRef> = obj_name.and_then(|o| o.downcast().ok()); return Ok(vm .ctx .new_str(format!( "{}.__new__", obj_name.as_ref().map_or("?", |s| s.as_str()) )) .into()); } self.function.get_attr("__qualname__", vm) } } impl PyPayload for PyBoundMethod { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.bound_method_type } } impl Representable for PyBoundMethod { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { #[allow(clippy::needless_match)] // False positive on nightly let func_name = if let Some(qname) = vm.get_attribute_opt(zelf.function.clone(), "__qualname__")? { Some(qname) } else { vm.get_attribute_opt(zelf.function.clone(), "__name__")? }; let func_name: Option<PyStrRef> = func_name.and_then(|o| o.downcast().ok()); let formatted_func_name = match func_name { Some(name) => name.to_string(), None => "?".to_string(), }; let object_repr = zelf.object.repr(vm)?; Ok(format!( "<bound method {formatted_func_name} of {object_repr}>", )) } } #[pyclass(module = false, name = "cell", traverse)] #[derive(Debug, Default)] pub(crate) struct PyCell { contents: PyMutex<Option<PyObjectRef>>, } pub(crate) type PyCellRef = PyRef<PyCell>; impl PyPayload for PyCell { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.cell_type } } impl Constructor for PyCell { type Args = OptionalArg; fn py_new(_cls: &Py<PyType>, value: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> { Ok(Self::new(value.into_option())) } } #[pyclass(with(Constructor))] impl PyCell { pub const fn new(contents: Option<PyObjectRef>) -> Self { Self { contents: PyMutex::new(contents), } } pub fn get(&self) -> Option<PyObjectRef> { self.contents.lock().clone() } pub fn set(&self, x: Option<PyObjectRef>) { *self.contents.lock() = x; } #[pygetset] fn cell_contents(&self, vm: &VirtualMachine) -> PyResult { self.get() .ok_or_else(|| vm.new_value_error("Cell is empty")) } #[pygetset(setter)] fn set_cell_contents(&self, x: PySetterValue) { match x { PySetterValue::Assign(value) => self.set(Some(value)), PySetterValue::Delete => self.set(None), } } } pub fn init(context: &Context) { PyFunction::extend_class(context, context.types.function_type); PyBoundMethod::extend_class(context, context.types.bound_method_type); PyCell::extend_class(context, context.types.cell_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/map.rs
crates/vm/src/builtins/map.rs
use super::{PyType, PyTypeRef}; use crate::{ Context, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, builtins::PyTupleRef, class::PyClassImpl, function::PosArgs, protocol::{PyIter, PyIterReturn}, raise_if_stop, types::{Constructor, IterNext, Iterable, SelfIter}, }; #[pyclass(module = false, name = "map", traverse)] #[derive(Debug)] pub struct PyMap { mapper: PyObjectRef, iterators: Vec<PyIter>, } impl PyPayload for PyMap { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.map_type } } impl Constructor for PyMap { type Args = (PyObjectRef, PosArgs<PyIter>); fn py_new( _cls: &Py<PyType>, (mapper, iterators): Self::Args, _vm: &VirtualMachine, ) -> PyResult<Self> { let iterators = iterators.into_vec(); Ok(Self { mapper, iterators }) } } #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyMap { #[pymethod] fn __length_hint__(&self, vm: &VirtualMachine) -> PyResult<usize> { self.iterators.iter().try_fold(0, |prev, cur| { let cur = cur.as_ref().to_owned().length_hint(0, vm)?; let max = core::cmp::max(prev, cur); Ok(max) }) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef) { let mut vec = vec![self.mapper.clone()]; vec.extend(self.iterators.iter().map(|o| o.clone().into())); (vm.ctx.types.map_type.to_owned(), vm.new_tuple(vec)) } } impl SelfIter for PyMap {} impl IterNext for PyMap { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let mut next_objs = Vec::new(); for iterator in &zelf.iterators { let item = raise_if_stop!(iterator.next(vm)?); next_objs.push(item); } // the mapper itself can raise StopIteration which does stop the map iteration PyIterReturn::from_pyresult(zelf.mapper.call(next_objs, vm), vm) } } pub fn init(context: &Context) { PyMap::extend_class(context, context.types.map_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/getset.rs
crates/vm/src/builtins/getset.rs
/*! Python `attribute` descriptor class. (PyGetSet) */ use super::PyType; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, builtins::type_::PointerSlot, class::PyClassImpl, function::{IntoPyGetterFunc, IntoPySetterFunc, PyGetterFunc, PySetterFunc, PySetterValue}, types::{GetDescriptor, Representable}, }; #[pyclass(module = false, name = "getset_descriptor")] pub struct PyGetSet { name: String, class: PointerSlot<Py<PyType>>, // A class type freed before getset is non-sense. getter: Option<PyGetterFunc>, setter: Option<PySetterFunc>, // doc: Option<String>, } impl core::fmt::Debug for PyGetSet { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!( f, "PyGetSet {{ name: {}, getter: {}, setter: {} }}", self.name, if self.getter.is_some() { "Some" } else { "None" }, if self.setter.is_some() { "Some" } else { "None" }, ) } } impl PyPayload for PyGetSet { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.getset_type } } impl GetDescriptor for PyGetSet { fn descr_get( zelf: PyObjectRef, obj: Option<PyObjectRef>, _cls: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { let (zelf, obj) = match Self::_check(&zelf, obj, vm) { Some(obj) => obj, None => return Ok(zelf), }; if let Some(ref f) = zelf.getter { f(vm, obj) } else { Err(vm.new_attribute_error(format!( "attribute '{}' of '{}' objects is not readable", zelf.name, Self::class(&vm.ctx).name() ))) } } } impl PyGetSet { pub fn new(name: String, class: &'static Py<PyType>) -> Self { Self { name, class: PointerSlot::from(class), getter: None, setter: None, } } pub fn with_get<G, X>(mut self, getter: G) -> Self where G: IntoPyGetterFunc<X>, { self.getter = Some(getter.into_getter()); self } pub fn with_set<S, X>(mut self, setter: S) -> Self where S: IntoPySetterFunc<X>, { self.setter = Some(setter.into_setter()); self } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(GetDescriptor, Representable))] impl PyGetSet { // Descriptor methods #[pyslot] fn descr_set( zelf: &PyObject, obj: PyObjectRef, value: PySetterValue<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<()> { let zelf = zelf.try_to_ref::<Self>(vm)?; if let Some(ref f) = zelf.setter { f(vm, obj, value) } else { Err(vm.new_attribute_error(format!( "attribute '{}' of '{}' objects is not writable", zelf.name, obj.class().name() ))) } } #[pygetset] fn __name__(&self) -> String { self.name.clone() } #[pygetset] fn __qualname__(&self) -> String { format!( "{}.{}", unsafe { self.class.borrow_static() }.slot_name(), self.name.clone() ) } #[pymember] fn __objclass__(vm: &VirtualMachine, zelf: PyObjectRef) -> PyResult { let zelf: &Py<Self> = zelf.try_to_value(vm)?; Ok(unsafe { zelf.class.borrow_static() }.to_owned().into()) } } impl Representable for PyGetSet { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { let class = unsafe { zelf.class.borrow_static() }; // Special case for object type if core::ptr::eq(class, vm.ctx.types.object_type) { Ok(format!("<attribute '{}'>", zelf.name)) } else { Ok(format!( "<attribute '{}' of '{}' objects>", zelf.name, class.name() )) } } } pub(crate) fn init(context: &Context) { PyGetSet::extend_class(context, context.types.getset_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/tuple.rs
crates/vm/src/builtins/tuple.rs
use super::{PositionIterInternal, PyGenericAlias, PyStrRef, PyType, PyTypeRef}; use crate::common::{ hash::{PyHash, PyUHash}, lock::PyMutex, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, atomic_func, class::PyClassImpl, convert::{ToPyObject, TransmuteFromObject}, function::{ArgSize, FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue}, iter::PyExactSizeIterator, protocol::{PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods}, recursion::ReprGuard, sequence::{OptionalRangeArgs, SequenceExt}, sliceable::{SequenceIndex, SliceableSequenceOp}, types::{ AsMapping, AsNumber, AsSequence, Comparable, Constructor, Hashable, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, }, utils::collection_repr, vm::VirtualMachine, }; use alloc::fmt; use std::sync::LazyLock; #[pyclass(module = false, name = "tuple", traverse)] pub struct PyTuple<R = PyObjectRef> { elements: Box<[R]>, } impl<R> fmt::Debug for PyTuple<R> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // TODO: implement more informational, non-recursive Debug formatter f.write_str("tuple") } } impl PyPayload for PyTuple { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.tuple_type } } pub trait IntoPyTuple { fn into_pytuple(self, vm: &VirtualMachine) -> PyTupleRef; } impl IntoPyTuple for () { fn into_pytuple(self, vm: &VirtualMachine) -> PyTupleRef { vm.ctx.empty_tuple.clone() } } impl IntoPyTuple for Vec<PyObjectRef> { fn into_pytuple(self, vm: &VirtualMachine) -> PyTupleRef { PyTuple::new_ref(self, &vm.ctx) } } pub trait FromPyTuple<'a>: Sized { fn from_pytuple(tuple: &'a PyTuple, vm: &VirtualMachine) -> PyResult<Self>; } macro_rules! impl_from_into_pytuple { ($($T:ident),+) => { impl<$($T: ToPyObject),*> IntoPyTuple for ($($T,)*) { fn into_pytuple(self, vm: &VirtualMachine) -> PyTupleRef { #[allow(non_snake_case)] let ($($T,)*) = self; PyTuple::new_ref(vec![$($T.to_pyobject(vm)),*], &vm.ctx) } } // TODO: figure out a way to let PyObjectRef implement TryFromBorrowedObject, and // have this be a TryFromBorrowedObject bound impl<'a, $($T: TryFromObject),*> FromPyTuple<'a> for ($($T,)*) { fn from_pytuple(tuple: &'a PyTuple, vm: &VirtualMachine) -> PyResult<Self> { #[allow(non_snake_case)] let &[$(ref $T),+] = tuple.as_slice().try_into().map_err(|_| { vm.new_type_error(format!("expected tuple with {} elements", impl_from_into_pytuple!(@count $($T)+))) })?; Ok(($($T::try_from_object(vm, $T.clone())?,)+)) } } impl<$($T: ToPyObject),*> ToPyObject for ($($T,)*) { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { self.into_pytuple(vm).into() } } }; (@count $($T:ident)+) => { 0 $(+ impl_from_into_pytuple!(@discard $T))+ }; (@discard $T:ident) => { 1 }; } impl_from_into_pytuple!(A); impl_from_into_pytuple!(A, B); impl_from_into_pytuple!(A, B, C); impl_from_into_pytuple!(A, B, C, D); impl_from_into_pytuple!(A, B, C, D, E); impl_from_into_pytuple!(A, B, C, D, E, F); impl_from_into_pytuple!(A, B, C, D, E, F, G); pub type PyTupleRef = PyRef<PyTuple>; impl Constructor for PyTuple { type Args = Vec<PyObjectRef>; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let iterable: OptionalArg<PyObjectRef> = args.bind(vm)?; // Optimizations for exact tuple type if cls.is(vm.ctx.types.tuple_type) { // Return exact tuple as-is if let OptionalArg::Present(ref input) = iterable && let Ok(tuple) = input.clone().downcast_exact::<PyTuple>(vm) { return Ok(tuple.into_pyref().into()); } // Return empty tuple singleton if iterable.is_missing() { return Ok(vm.ctx.empty_tuple.clone().into()); } } let elements = if let OptionalArg::Present(iterable) = iterable { iterable.try_to_value(vm)? } else { vec![] }; // Return empty tuple singleton for exact tuple types (when iterable was empty) if elements.is_empty() && cls.is(vm.ctx.types.tuple_type) { return Ok(vm.ctx.empty_tuple.clone().into()); } let payload = Self::py_new(&cls, elements, vm)?; payload.into_ref_with_type(vm, cls).map(Into::into) } fn py_new(_cls: &Py<PyType>, elements: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> { Ok(Self { elements: elements.into_boxed_slice(), }) } } impl<R> AsRef<[R]> for PyTuple<R> { fn as_ref(&self) -> &[R] { &self.elements } } impl<R> core::ops::Deref for PyTuple<R> { type Target = [R]; fn deref(&self) -> &[R] { &self.elements } } impl<'a, R> core::iter::IntoIterator for &'a PyTuple<R> { type Item = &'a R; type IntoIter = core::slice::Iter<'a, R>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl<'a, R> core::iter::IntoIterator for &'a Py<PyTuple<R>> { type Item = &'a R; type IntoIter = core::slice::Iter<'a, R>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl<R> PyTuple<R> { pub const fn as_slice(&self) -> &[R] { &self.elements } #[inline] pub fn len(&self) -> usize { self.elements.len() } #[inline] pub fn is_empty(&self) -> bool { self.elements.is_empty() } #[inline] pub fn iter(&self) -> core::slice::Iter<'_, R> { self.elements.iter() } } impl PyTuple<PyObjectRef> { // Do not deprecate this. empty_tuple must be checked. pub fn new_ref(elements: Vec<PyObjectRef>, ctx: &Context) -> PyRef<Self> { if elements.is_empty() { ctx.empty_tuple.clone() } else { let elements = elements.into_boxed_slice(); PyRef::new_ref(Self { elements }, ctx.types.tuple_type.to_owned(), None) } } /// Creating a new tuple with given boxed slice. /// NOTE: for usual case, you probably want to use PyTuple::new_ref. /// Calling this function implies trying micro optimization for non-zero-sized tuple. pub const fn new_unchecked(elements: Box<[PyObjectRef]>) -> Self { Self { elements } } fn repeat(zelf: PyRef<Self>, value: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { Ok(if zelf.elements.is_empty() || value == 0 { vm.ctx.empty_tuple.clone() } else if value == 1 && zelf.class().is(vm.ctx.types.tuple_type) { // Special case: when some `tuple` is multiplied by `1`, // nothing really happens, we need to return an object itself // with the same `id()` to be compatible with CPython. // This only works for `tuple` itself, not its subclasses. zelf } else { let v = zelf.elements.mul(vm, value)?; let elements = v.into_boxed_slice(); Self { elements }.into_ref(&vm.ctx) }) } pub fn extract_tuple<'a, T: FromPyTuple<'a>>(&'a self, vm: &VirtualMachine) -> PyResult<T> { T::from_pytuple(self, vm) } } impl<T> PyTuple<PyRef<T>> { pub fn new_ref_typed(elements: Vec<PyRef<T>>, ctx: &Context) -> PyRef<Self> { // SAFETY: PyRef<T> has the same layout as PyObjectRef unsafe { let elements: Vec<PyObjectRef> = core::mem::transmute::<Vec<PyRef<T>>, Vec<PyObjectRef>>(elements); let tuple = PyTuple::<PyObjectRef>::new_ref(elements, ctx); core::mem::transmute::<PyRef<PyTuple>, PyRef<Self>>(tuple) } } } #[pyclass( itemsize = core::mem::size_of::<crate::PyObjectRef>(), flags(BASETYPE, SEQUENCE, _MATCH_SELF), with(AsMapping, AsNumber, AsSequence, Hashable, Comparable, Iterable, Constructor, Representable) )] impl PyTuple { fn __add__( zelf: PyRef<Self>, other: PyObjectRef, vm: &VirtualMachine, ) -> PyArithmeticValue<PyRef<Self>> { let added = other.downcast::<Self>().map(|other| { if other.elements.is_empty() && zelf.class().is(vm.ctx.types.tuple_type) { zelf } else if zelf.elements.is_empty() && other.class().is(vm.ctx.types.tuple_type) { other } else { let elements = zelf .iter() .chain(other.as_slice()) .cloned() .collect::<Box<[_]>>(); Self { elements }.into_ref(&vm.ctx) } }); PyArithmeticValue::from_option(added.ok()) } #[pymethod] fn count(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> { let mut count: usize = 0; for element in self { if vm.identical_or_equal(element, &needle)? { count += 1; } } Ok(count) } #[inline] pub const fn __len__(&self) -> usize { self.elements.len() } fn __mul__(zelf: PyRef<Self>, value: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { Self::repeat(zelf, value.into(), vm) } fn _getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { match SequenceIndex::try_from_borrowed_object(vm, needle, "tuple")? { SequenceIndex::Int(i) => self.elements.getitem_by_index(vm, i), SequenceIndex::Slice(slice) => self .elements .getitem_by_slice(vm, slice) .map(|x| vm.ctx.new_tuple(x).into()), } } fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { self._getitem(&needle, vm) } #[pymethod] fn index( &self, needle: PyObjectRef, range: OptionalRangeArgs, vm: &VirtualMachine, ) -> PyResult<usize> { let (start, stop) = range.saturate(self.len(), vm)?; for (index, element) in self.elements.iter().enumerate().take(stop).skip(start) { if vm.identical_or_equal(element, &needle)? { return Ok(index); } } Err(vm.new_value_error("tuple.index(x): x not in tuple")) } fn _contains(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<bool> { for element in &self.elements { if vm.identical_or_equal(element, needle)? { return Ok(true); } } Ok(false) } fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> { self._contains(&needle, vm) } #[pymethod] fn __getnewargs__(zelf: PyRef<Self>, vm: &VirtualMachine) -> (PyTupleRef,) { // the arguments to pass to tuple() is just one tuple - so we'll be doing tuple(tup), which // should just return tup, or tuple_subclass(tup), which'll copy/validate (e.g. for a // structseq) let tup_arg = if zelf.class().is(vm.ctx.types.tuple_type) { zelf } else { Self::new_ref(zelf.elements.clone().into_vec(), &vm.ctx) }; (tup_arg,) } #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } impl AsMapping for PyTuple { fn as_mapping() -> &'static PyMappingMethods { static AS_MAPPING: LazyLock<PyMappingMethods> = LazyLock::new(|| PyMappingMethods { length: atomic_func!(|mapping, _vm| Ok(PyTuple::mapping_downcast(mapping).len())), subscript: atomic_func!( |mapping, needle, vm| PyTuple::mapping_downcast(mapping)._getitem(needle, vm) ), ..PyMappingMethods::NOT_IMPLEMENTED }); &AS_MAPPING } } impl AsSequence for PyTuple { fn as_sequence() -> &'static PySequenceMethods { static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods { length: atomic_func!(|seq, _vm| Ok(PyTuple::sequence_downcast(seq).__len__())), concat: atomic_func!(|seq, other, vm| { let zelf = PyTuple::sequence_downcast(seq); match PyTuple::__add__(zelf.to_owned(), other.to_owned(), vm) { PyArithmeticValue::Implemented(tuple) => Ok(tuple.into()), PyArithmeticValue::NotImplemented => Err(vm.new_type_error(format!( "can only concatenate tuple (not '{}') to tuple", other.class().name() ))), } }), repeat: atomic_func!(|seq, n, vm| { let zelf = PyTuple::sequence_downcast(seq); PyTuple::repeat(zelf.to_owned(), n, vm).map(|x| x.into()) }), item: atomic_func!(|seq, i, vm| { let zelf = PyTuple::sequence_downcast(seq); zelf.elements.getitem_by_index(vm, i) }), contains: atomic_func!(|seq, needle, vm| { let zelf = PyTuple::sequence_downcast(seq); zelf._contains(needle, vm) }), ..PySequenceMethods::NOT_IMPLEMENTED }); &AS_SEQUENCE } } impl AsNumber for PyTuple { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { boolean: Some(|number, _vm| { let zelf = number.obj.downcast_ref::<PyTuple>().unwrap(); Ok(!zelf.elements.is_empty()) }), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } } impl Hashable for PyTuple { #[inline] fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> { tuple_hash(zelf.as_slice(), vm) } } impl Comparable for PyTuple { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { if let Some(res) = op.identical_optimization(zelf, other) { return Ok(res.into()); } let other = class_or_notimplemented!(Self, other); zelf.iter() .richcompare(other.iter(), op, vm) .map(PyComparisonValue::Implemented) } } impl Iterable for PyTuple { fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { Ok(PyTupleIterator { internal: PyMutex::new(PositionIterInternal::new(zelf, 0)), } .into_pyobject(vm)) } } impl Representable for PyTuple { #[inline] fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> { let s = if zelf.is_empty() { vm.ctx.intern_str("()").to_owned() } else if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { let s = if zelf.len() == 1 { format!("({},)", zelf.elements[0].repr(vm)?) } else { collection_repr(None, "(", ")", zelf.elements.iter(), vm)? }; vm.ctx.new_str(s) } else { vm.ctx.intern_str("(...)").to_owned() }; Ok(s) } #[cold] fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { unreachable!("use repr instead") } } impl PyRef<PyTuple<PyObjectRef>> { pub fn try_into_typed<T: PyPayload>( self, vm: &VirtualMachine, ) -> PyResult<PyRef<PyTuple<PyRef<T>>>> { // Check that all elements are of the correct type for elem in self.as_slice() { <PyRef<T> as TransmuteFromObject>::check(vm, elem)?; } // SAFETY: We just verified all elements are of type T Ok(unsafe { core::mem::transmute::<Self, PyRef<PyTuple<PyRef<T>>>>(self) }) } } impl<T: PyPayload> PyRef<PyTuple<PyRef<T>>> { pub fn into_untyped(self) -> PyRef<PyTuple> { // SAFETY: PyTuple<PyRef<T>> has the same layout as PyTuple unsafe { core::mem::transmute::<Self, PyRef<PyTuple>>(self) } } } impl<T: PyPayload> Py<PyTuple<PyRef<T>>> { pub fn as_untyped(&self) -> &Py<PyTuple> { // SAFETY: PyTuple<PyRef<T>> has the same layout as PyTuple unsafe { core::mem::transmute::<&Self, &Py<PyTuple>>(self) } } } impl<T: PyPayload> From<PyRef<PyTuple<PyRef<T>>>> for PyTupleRef { #[inline] fn from(tup: PyRef<PyTuple<PyRef<T>>>) -> Self { tup.into_untyped() } } #[pyclass(module = false, name = "tuple_iterator", traverse)] #[derive(Debug)] pub(crate) struct PyTupleIterator { internal: PyMutex<PositionIterInternal<PyTupleRef>>, } impl PyPayload for PyTupleIterator { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.tuple_iterator_type } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] impl PyTupleIterator { #[pymethod] fn __length_hint__(&self) -> usize { self.internal.lock().length_hint(|obj| obj.len()) } #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal .lock() .set_state(state, |obj, pos| pos.min(obj.len()), vm) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef { self.internal .lock() .builtins_iter_reduce(|x| x.clone().into(), vm) } } impl SelfIter for PyTupleIterator {} impl IterNext for PyTupleIterator { fn next(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyIterReturn> { zelf.internal.lock().next(|tuple, pos| { Ok(PyIterReturn::from_result( tuple.get(pos).cloned().ok_or(None), )) }) } } pub(crate) fn init(context: &Context) { PyTuple::extend_class(context, context.types.tuple_type); PyTupleIterator::extend_class(context, context.types.tuple_iterator_type); } pub(super) fn tuple_hash(elements: &[PyObjectRef], vm: &VirtualMachine) -> PyResult<PyHash> { #[cfg(target_pointer_width = "64")] const PRIME1: PyUHash = 11400714785074694791; #[cfg(target_pointer_width = "64")] const PRIME2: PyUHash = 14029467366897019727; #[cfg(target_pointer_width = "64")] const PRIME5: PyUHash = 2870177450012600261; #[cfg(target_pointer_width = "64")] const ROTATE: u32 = 31; #[cfg(target_pointer_width = "32")] const PRIME1: PyUHash = 2654435761; #[cfg(target_pointer_width = "32")] const PRIME2: PyUHash = 2246822519; #[cfg(target_pointer_width = "32")] const PRIME5: PyUHash = 374761393; #[cfg(target_pointer_width = "32")] const ROTATE: u32 = 13; let mut acc = PRIME5; let len = elements.len() as PyUHash; for val in elements { let lane = val.hash(vm)? as PyUHash; acc = acc.wrapping_add(lane.wrapping_mul(PRIME2)); acc = acc.rotate_left(ROTATE); acc = acc.wrapping_mul(PRIME1); } acc = acc.wrapping_add(len ^ (PRIME5 ^ 3527539)); if acc as PyHash == -1 { return Ok(1546275796); } Ok(acc as PyHash) }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/generator.rs
crates/vm/src/builtins/generator.rs
/* * The mythical generator. */ use super::{PyCode, PyGenericAlias, PyStrRef, PyType, PyTypeRef}; use crate::{ AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, class::PyClassImpl, coroutine::{Coro, warn_deprecated_throw_signature}, frame::FrameRef, function::OptionalArg, protocol::PyIterReturn, types::{IterNext, Iterable, Representable, SelfIter}, }; #[pyclass(module = false, name = "generator")] #[derive(Debug)] pub struct PyGenerator { inner: Coro, } impl PyPayload for PyGenerator { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.generator_type } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(Py, IterNext, Iterable))] impl PyGenerator { pub const fn as_coro(&self) -> &Coro { &self.inner } pub fn new(frame: FrameRef, name: PyStrRef, qualname: PyStrRef) -> Self { Self { inner: Coro::new(frame, name, qualname), } } #[pygetset] fn __name__(&self) -> PyStrRef { self.inner.name() } #[pygetset(setter)] fn set___name__(&self, name: PyStrRef) { self.inner.set_name(name) } #[pygetset] fn __qualname__(&self) -> PyStrRef { self.inner.qualname() } #[pygetset(setter)] fn set___qualname__(&self, qualname: PyStrRef) { self.inner.set_qualname(qualname) } #[pygetset] fn gi_frame(&self, _vm: &VirtualMachine) -> FrameRef { self.inner.frame() } #[pygetset] fn gi_running(&self, _vm: &VirtualMachine) -> bool { self.inner.running() } #[pygetset] fn gi_code(&self, _vm: &VirtualMachine) -> PyRef<PyCode> { self.inner.frame().code.clone() } #[pygetset] fn gi_yieldfrom(&self, _vm: &VirtualMachine) -> Option<PyObjectRef> { self.inner.frame().yield_from_target() } #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } #[pyclass] impl Py<PyGenerator> { #[pymethod] fn send(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyIterReturn> { self.inner.send(self.as_object(), value, vm) } #[pymethod] fn throw( &self, exc_type: PyObjectRef, exc_val: OptionalArg, exc_tb: OptionalArg, vm: &VirtualMachine, ) -> PyResult<PyIterReturn> { warn_deprecated_throw_signature(&exc_val, &exc_tb, vm)?; self.inner.throw( self.as_object(), exc_type, exc_val.unwrap_or_none(vm), exc_tb.unwrap_or_none(vm), vm, ) } #[pymethod] fn close(&self, vm: &VirtualMachine) -> PyResult<()> { self.inner.close(self.as_object(), vm) } } impl Representable for PyGenerator { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { Ok(zelf.inner.repr(zelf.as_object(), zelf.get_id(), vm)) } } impl SelfIter for PyGenerator {} impl IterNext for PyGenerator { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { zelf.send(vm.ctx.none(), vm) } } pub fn init(ctx: &Context) { PyGenerator::extend_class(ctx, ctx.types.generator_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/mod.rs
crates/vm/src/builtins/mod.rs
//! This package contains the python basic/builtin types //! 7 common PyRef type aliases are exposed - [`PyBytesRef`], [`PyDictRef`], [`PyIntRef`], [`PyListRef`], [`PyStrRef`], [`PyTypeRef`], [`PyTupleRef`] //! Do not add more PyRef type aliases. They will be rare enough to use directly `PyRef<T>`. pub(crate) mod asyncgenerator; pub use asyncgenerator::PyAsyncGen; pub(crate) mod builtin_func; pub(crate) mod bytearray; pub use bytearray::PyByteArray; pub(crate) mod bytes; pub use bytes::{PyBytes, PyBytesRef}; pub(crate) mod classmethod; pub use classmethod::PyClassMethod; pub(crate) mod code; pub use code::PyCode; pub(crate) mod complex; pub use complex::PyComplex; pub(crate) mod coroutine; pub use coroutine::PyCoroutine; pub(crate) mod dict; pub use dict::{PyDict, PyDictRef}; pub(crate) mod enumerate; pub use enumerate::PyEnumerate; pub(crate) mod filter; pub use filter::PyFilter; pub(crate) mod float; pub use float::PyFloat; pub(crate) mod frame; pub(crate) mod function; pub use function::{PyBoundMethod, PyFunction}; pub(crate) mod generator; pub use generator::PyGenerator; pub(crate) mod genericalias; pub use genericalias::PyGenericAlias; pub(crate) mod getset; pub use getset::PyGetSet; pub(crate) mod int; pub use int::{PyInt, PyIntRef}; pub(crate) mod iter; pub use iter::*; pub(crate) mod list; pub use list::{PyList, PyListRef}; pub(crate) mod map; pub use map::PyMap; pub(crate) mod mappingproxy; pub use mappingproxy::PyMappingProxy; pub(crate) mod memory; pub use memory::PyMemoryView; pub(crate) mod module; pub use module::{PyModule, PyModuleDef}; pub(crate) mod namespace; pub use namespace::PyNamespace; pub(crate) mod object; pub use object::PyBaseObject; pub(crate) mod property; pub use property::PyProperty; #[path = "bool.rs"] pub(crate) mod bool_; pub use bool_::PyBool; #[path = "str.rs"] pub(crate) mod pystr; pub use pystr::{PyStr, PyStrInterned, PyStrRef, PyUtf8Str, PyUtf8StrRef}; #[path = "super.rs"] pub(crate) mod super_; pub use super_::PySuper; #[path = "type.rs"] pub(crate) mod type_; pub use type_::{PyType, PyTypeRef}; pub(crate) mod range; pub use range::PyRange; pub(crate) mod set; pub use set::{PyFrozenSet, PySet}; pub(crate) mod singletons; pub use singletons::{PyNone, PyNotImplemented}; pub(crate) mod slice; pub use slice::{PyEllipsis, PySlice}; pub(crate) mod staticmethod; pub use staticmethod::PyStaticMethod; pub(crate) mod traceback; pub use traceback::PyTraceback; pub(crate) mod tuple; pub use tuple::{PyTuple, PyTupleRef}; pub(crate) mod weakproxy; pub use weakproxy::PyWeakProxy; pub(crate) mod weakref; pub use weakref::PyWeak; pub(crate) mod zip; pub use zip::PyZip; #[path = "union.rs"] pub(crate) mod union_; pub use union_::PyUnion; pub(crate) mod descriptor; pub use float::try_to_bigint as try_f64_to_bigint; pub use int::try_to_float as try_bigint_to_f64; pub use crate::exceptions::types::*;
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/float.rs
crates/vm/src/builtins/float.rs
use super::{ PyByteArray, PyBytes, PyInt, PyIntRef, PyStr, PyStrRef, PyType, PyTypeRef, try_bigint_to_f64, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine, class::PyClassImpl, common::{float_ops, format::FormatSpec, hash}, convert::{IntoPyException, ToPyObject, ToPyResult}, function::{ ArgBytesLike, FuncArgs, OptionalArg, OptionalOption, PyArithmeticValue::*, PyComparisonValue, }, protocol::PyNumberMethods, types::{AsNumber, Callable, Comparable, Constructor, Hashable, PyComparisonOp, Representable}, }; use malachite_bigint::{BigInt, ToBigInt}; use num_complex::Complex64; use num_traits::{Signed, ToPrimitive, Zero}; use rustpython_common::int::float_to_ratio; #[pyclass(module = false, name = "float")] #[derive(Debug, Copy, Clone, PartialEq)] pub struct PyFloat { value: f64, } impl PyFloat { pub const fn to_f64(&self) -> f64 { self.value } } impl PyPayload for PyFloat { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.float_type } } impl ToPyObject for f64 { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.new_float(self).into() } } impl ToPyObject for f32 { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.new_float(f64::from(self)).into() } } impl From<f64> for PyFloat { fn from(value: f64) -> Self { Self { value } } } pub(crate) fn to_op_float(obj: &PyObject, vm: &VirtualMachine) -> PyResult<Option<f64>> { let v = if let Some(float) = obj.downcast_ref::<PyFloat>() { Some(float.value) } else if let Some(int) = obj.downcast_ref::<PyInt>() { Some(try_bigint_to_f64(int.as_bigint(), vm)?) } else { None }; Ok(v) } macro_rules! impl_try_from_object_float { ($($t:ty),*) => { $(impl TryFromObject for $t { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { PyRef::<PyFloat>::try_from_object(vm, obj).map(|f| f.to_f64() as $t) } })* }; } impl_try_from_object_float!(f32, f64); fn inner_div(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<f64> { float_ops::div(v1, v2).ok_or_else(|| vm.new_zero_division_error("float division by zero")) } fn inner_mod(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<f64> { float_ops::mod_(v1, v2).ok_or_else(|| vm.new_zero_division_error("float mod by zero")) } pub fn try_to_bigint(value: f64, vm: &VirtualMachine) -> PyResult<BigInt> { match value.to_bigint() { Some(int) => Ok(int), None => { if value.is_infinite() { Err(vm .new_overflow_error("OverflowError: cannot convert float infinity to integer")) } else if value.is_nan() { Err(vm.new_value_error("ValueError: cannot convert float NaN to integer")) } else { // unreachable unless BigInt has a bug unreachable!( "A finite float value failed to be converted to bigint: {}", value ) } } } } fn inner_floordiv(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<f64> { float_ops::floordiv(v1, v2).ok_or_else(|| vm.new_zero_division_error("float floordiv by zero")) } fn inner_divmod(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<(f64, f64)> { float_ops::divmod(v1, v2).ok_or_else(|| vm.new_zero_division_error("float divmod()")) } pub fn float_pow(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult { if v1.is_zero() && v2.is_sign_negative() { let msg = "0.0 cannot be raised to a negative power"; Err(vm.new_zero_division_error(msg.to_owned())) } else if v1.is_sign_negative() && (v2.floor() - v2).abs() > f64::EPSILON { let v1 = Complex64::new(v1, 0.); let v2 = Complex64::new(v2, 0.); Ok(v1.powc(v2).to_pyobject(vm)) } else { Ok(v1.powf(v2).to_pyobject(vm)) } } impl Constructor for PyFloat { type Args = OptionalArg<PyObjectRef>; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { // Optimization: return exact float as-is if cls.is(vm.ctx.types.float_type) && args.kwargs.is_empty() && let Some(first) = args.args.first() && first.class().is(vm.ctx.types.float_type) { return Ok(first.clone()); } let arg: Self::Args = args.bind(vm)?; let payload = Self::py_new(&cls, arg, vm)?; payload.into_ref_with_type(vm, cls).map(Into::into) } fn py_new(_cls: &Py<PyType>, arg: Self::Args, vm: &VirtualMachine) -> PyResult<Self> { let float_val = match arg { OptionalArg::Missing => 0.0, OptionalArg::Present(val) => { if let Some(f) = val.try_float_opt(vm) { f?.value } else { float_from_string(val, vm)? } } }; Ok(Self::from(float_val)) } } fn float_from_string(val: PyObjectRef, vm: &VirtualMachine) -> PyResult<f64> { let (bytearray, buffer, buffer_lock, mapped_string); let b = if let Some(s) = val.downcast_ref::<PyStr>() { use crate::common::str::PyKindStr; match s.as_str_kind() { PyKindStr::Ascii(s) => s.trim().as_bytes(), PyKindStr::Utf8(s) => { mapped_string = s .trim() .chars() .map(|c| { if let Some(n) = rustpython_common::str::char_to_decimal(c) { char::from_digit(n.into(), 10).unwrap() } else if c.is_whitespace() { ' ' } else { c } }) .collect::<String>(); mapped_string.as_bytes() } // if there are surrogates, it's not gonna parse anyway, // so we can just choose a known bad value PyKindStr::Wtf8(_) => b"", } } else if let Some(bytes) = val.downcast_ref::<PyBytes>() { bytes.as_bytes() } else if let Some(buf) = val.downcast_ref::<PyByteArray>() { bytearray = buf.borrow_buf(); &*bytearray } else if let Ok(b) = ArgBytesLike::try_from_borrowed_object(vm, &val) { buffer = b; buffer_lock = buffer.borrow_buf(); &*buffer_lock } else { return Err(vm.new_type_error(format!( "float() argument must be a string or a number, not '{}'", val.class().name() ))); }; crate::literal::float::parse_bytes(b).ok_or_else(|| { val.repr(vm) .map(|repr| vm.new_value_error(format!("could not convert string to float: {repr}"))) .unwrap_or_else(|e| e) }) } #[pyclass( flags(BASETYPE, _MATCH_SELF), with(Comparable, Hashable, Constructor, AsNumber, Representable) )] impl PyFloat { #[pymethod] fn __format__(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> { FormatSpec::parse(spec.as_str()) .and_then(|format_spec| format_spec.format_float(self.value)) .map_err(|err| err.into_pyexception(vm)) } #[pystaticmethod] fn __getformat__(spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> { if !matches!(spec.as_str(), "double" | "float") { return Err( vm.new_value_error("__getformat__() argument 1 must be 'double' or 'float'") ); } const BIG_ENDIAN: bool = cfg!(target_endian = "big"); Ok(if BIG_ENDIAN { "IEEE, big-endian" } else { "IEEE, little-endian" } .to_owned()) } #[pymethod] fn __trunc__(&self, vm: &VirtualMachine) -> PyResult<BigInt> { try_to_bigint(self.value, vm) } #[pymethod] fn __floor__(&self, vm: &VirtualMachine) -> PyResult<BigInt> { try_to_bigint(self.value.floor(), vm) } #[pymethod] fn __ceil__(&self, vm: &VirtualMachine) -> PyResult<BigInt> { try_to_bigint(self.value.ceil(), vm) } #[pymethod] fn __round__(&self, ndigits: OptionalOption<PyIntRef>, vm: &VirtualMachine) -> PyResult { let ndigits = ndigits.flatten(); let value = if let Some(ndigits) = ndigits { let ndigits = ndigits.as_bigint(); let ndigits = match ndigits.to_i32() { Some(n) => n, None if ndigits.is_positive() => i32::MAX, None => i32::MIN, }; let float = float_ops::round_float_digits(self.value, ndigits) .ok_or_else(|| vm.new_overflow_error("overflow occurred during round"))?; vm.ctx.new_float(float).into() } else { let fract = self.value.fract(); let value = if (fract.abs() - 0.5).abs() < f64::EPSILON { if self.value.trunc() % 2.0 == 0.0 { self.value - fract } else { self.value + fract } } else { self.value.round() }; let int = try_to_bigint(value, vm)?; vm.ctx.new_int(int).into() }; Ok(value) } #[pygetset] const fn real(zelf: PyRef<Self>) -> PyRef<Self> { zelf } #[pygetset] const fn imag(&self) -> f64 { 0.0f64 } #[pymethod] const fn conjugate(zelf: PyRef<Self>) -> PyRef<Self> { zelf } #[pymethod] fn is_integer(&self) -> bool { crate::literal::float::is_integer(self.value) } #[pymethod] fn as_integer_ratio(&self, vm: &VirtualMachine) -> PyResult<(PyIntRef, PyIntRef)> { let value = self.value; float_to_ratio(value) .map(|(numer, denom)| (vm.ctx.new_bigint(&numer), vm.ctx.new_bigint(&denom))) .ok_or_else(|| { if value.is_infinite() { vm.new_overflow_error("cannot convert Infinity to integer ratio") } else if value.is_nan() { vm.new_value_error("cannot convert NaN to integer ratio") } else { unreachable!("finite float must able to convert to integer ratio") } }) } #[pyclassmethod] fn fromhex(cls: PyTypeRef, string: PyStrRef, vm: &VirtualMachine) -> PyResult { let result = crate::literal::float::from_hex(string.as_str().trim()) .ok_or_else(|| vm.new_value_error("invalid hexadecimal floating-point string"))?; PyType::call(&cls, vec![vm.ctx.new_float(result).into()].into(), vm) } #[pymethod] fn hex(&self) -> String { crate::literal::float::to_hex(self.value) } #[pymethod] fn __getnewargs__(&self, vm: &VirtualMachine) -> PyObjectRef { (self.value,).to_pyobject(vm) } } impl Comparable for PyFloat { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, _vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { let ret = if let Some(other) = other.downcast_ref::<Self>() { zelf.value .partial_cmp(&other.value) .map_or_else(|| op == PyComparisonOp::Ne, |ord| op.eval_ord(ord)) } else if let Some(other) = other.downcast_ref::<PyInt>() { let a = zelf.to_f64(); let b = other.as_bigint(); match op { PyComparisonOp::Lt => float_ops::lt_int(a, b), PyComparisonOp::Le => { if let (Some(a_int), Some(b_float)) = (a.to_bigint(), b.to_f64()) { a <= b_float && a_int <= *b } else { float_ops::lt_int(a, b) } } PyComparisonOp::Eq => float_ops::eq_int(a, b), PyComparisonOp::Ne => !float_ops::eq_int(a, b), PyComparisonOp::Ge => { if let (Some(a_int), Some(b_float)) = (a.to_bigint(), b.to_f64()) { a >= b_float && a_int >= *b } else { float_ops::gt_int(a, b) } } PyComparisonOp::Gt => float_ops::gt_int(a, b), } } else { return Ok(NotImplemented); }; Ok(Implemented(ret)) } } impl Hashable for PyFloat { #[inline] fn hash(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<hash::PyHash> { Ok(hash::hash_float(zelf.to_f64()).unwrap_or_else(|| hash::hash_object_id(zelf.get_id()))) } } impl AsNumber for PyFloat { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { add: Some(|a, b, vm| PyFloat::number_op(a, b, |a, b, _vm| a + b, vm)), subtract: Some(|a, b, vm| PyFloat::number_op(a, b, |a, b, _vm| a - b, vm)), multiply: Some(|a, b, vm| PyFloat::number_op(a, b, |a, b, _vm| a * b, vm)), remainder: Some(|a, b, vm| PyFloat::number_op(a, b, inner_mod, vm)), divmod: Some(|a, b, vm| PyFloat::number_op(a, b, inner_divmod, vm)), power: Some(|a, b, c, vm| { if vm.is_none(c) { PyFloat::number_op(a, b, float_pow, vm) } else { Err(vm.new_type_error( "pow() 3rd argument not allowed unless all arguments are integers", )) } }), negative: Some(|num, vm| { let value = PyFloat::number_downcast(num).value; (-value).to_pyresult(vm) }), positive: Some(|num, vm| PyFloat::number_downcast_exact(num, vm).to_pyresult(vm)), absolute: Some(|num, vm| { let value = PyFloat::number_downcast(num).value; value.abs().to_pyresult(vm) }), boolean: Some(|num, _vm| Ok(!PyFloat::number_downcast(num).value.is_zero())), int: Some(|num, vm| { let value = PyFloat::number_downcast(num).value; try_to_bigint(value, vm).map(|x| PyInt::from(x).into_pyobject(vm)) }), float: Some(|num, vm| Ok(PyFloat::number_downcast_exact(num, vm).into())), floor_divide: Some(|a, b, vm| PyFloat::number_op(a, b, inner_floordiv, vm)), true_divide: Some(|a, b, vm| PyFloat::number_op(a, b, inner_div, vm)), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } #[inline] fn clone_exact(zelf: &Py<Self>, vm: &VirtualMachine) -> PyRef<Self> { vm.ctx.new_float(zelf.value) } } impl Representable for PyFloat { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { Ok(crate::literal::float::to_string(zelf.value)) } } impl PyFloat { fn number_op<F, R>(a: &PyObject, b: &PyObject, op: F, vm: &VirtualMachine) -> PyResult where F: FnOnce(f64, f64, &VirtualMachine) -> R, R: ToPyResult, { if let (Some(a), Some(b)) = (to_op_float(a, vm)?, to_op_float(b, vm)?) { op(a, b, vm).to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } } } // Retrieve inner float value: #[cfg(feature = "serde")] pub(crate) fn get_value(obj: &PyObject) -> f64 { obj.downcast_ref::<PyFloat>().unwrap().value } #[rustfmt::skip] // to avoid line splitting pub fn init(context: &Context) { PyFloat::extend_class(context, context.types.float_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/super.rs
crates/vm/src/builtins/super.rs
// spell-checker:ignore cmeth /*! Python `super` class. See also [CPython source code.](https://github.com/python/cpython/blob/50b48572d9a90c5bb36e2bef6179548ea927a35a/Objects/typeobject.c#L7663) */ use super::{PyStr, PyType, PyTypeRef}; use crate::{ AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, class::PyClassImpl, common::lock::PyRwLock, function::{FuncArgs, IntoFuncArgs, OptionalArg}, types::{Callable, Constructor, GetAttr, GetDescriptor, Initializer, Representable}, }; #[pyclass(module = false, name = "super", traverse)] #[derive(Debug)] pub struct PySuper { inner: PyRwLock<PySuperInner>, } #[derive(Debug, Traverse)] struct PySuperInner { typ: PyTypeRef, obj: Option<(PyObjectRef, PyTypeRef)>, } impl PySuperInner { fn new(typ: PyTypeRef, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> { let obj = if vm.is_none(&obj) { None } else { let obj_type = super_check(typ.clone(), obj.clone(), vm)?; Some((obj, obj_type)) }; Ok(Self { typ, obj }) } } impl PyPayload for PySuper { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.super_type } } impl Constructor for PySuper { type Args = FuncArgs; fn py_new(_cls: &Py<PyType>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> { Ok(Self { inner: PyRwLock::new(PySuperInner::new( vm.ctx.types.object_type.to_owned(), // is this correct? vm.ctx.none(), vm, )?), }) } } #[derive(FromArgs)] pub struct InitArgs { #[pyarg(positional, optional)] py_type: OptionalArg<PyObjectRef>, #[pyarg(positional, optional)] py_obj: OptionalArg<PyObjectRef>, } impl Initializer for PySuper { type Args = InitArgs; fn init( zelf: PyRef<Self>, Self::Args { py_type, py_obj }: Self::Args, vm: &VirtualMachine, ) -> PyResult<()> { // Get the type: let (typ, obj) = if let OptionalArg::Present(ty_obj) = py_type { let ty = ty_obj .downcast::<PyType>() .map_err(|_| vm.new_type_error("super() argument 1 must be a type"))?; (ty, py_obj.unwrap_or_none(vm)) } else { let frame = vm .current_frame() .ok_or_else(|| vm.new_runtime_error("super(): no current frame"))?; if frame.code.arg_count == 0 { return Err(vm.new_runtime_error("super(): no arguments")); } let obj = frame.fastlocals.lock()[0] .clone() .or_else(|| { if let Some(cell2arg) = frame.code.cell2arg.as_deref() { cell2arg[..frame.code.cellvars.len()] .iter() .enumerate() .find(|(_, arg_idx)| **arg_idx == 0) .and_then(|(cell_idx, _)| frame.cells_frees[cell_idx].get()) } else { None } }) .ok_or_else(|| vm.new_runtime_error("super(): arg[0] deleted"))?; let mut typ = None; for (i, var) in frame.code.freevars.iter().enumerate() { if var.as_bytes() == b"__class__" { let i = frame.code.cellvars.len() + i; let class = frame.cells_frees[i] .get() .ok_or_else(|| vm.new_runtime_error("super(): empty __class__ cell"))?; typ = Some(class.downcast().map_err(|o| { vm.new_type_error(format!( "super(): __class__ is not a type ({})", o.class().name() )) })?); break; } } let typ = typ.ok_or_else(|| { vm.new_type_error( "super must be called with 1 argument or from inside class method", ) })?; (typ, obj) }; let inner = PySuperInner::new(typ, obj, vm)?; *zelf.inner.write() = inner; Ok(()) } } #[pyclass(with(GetAttr, GetDescriptor, Constructor, Initializer, Representable))] impl PySuper { #[pygetset] fn __thisclass__(&self) -> PyTypeRef { self.inner.read().typ.clone() } #[pygetset] fn __self_class__(&self) -> Option<PyTypeRef> { Some(self.inner.read().obj.as_ref()?.1.clone()) } #[pygetset] fn __self__(&self) -> Option<PyObjectRef> { Some(self.inner.read().obj.as_ref()?.0.clone()) } } impl GetAttr for PySuper { fn getattro(zelf: &Py<Self>, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult { let skip = |zelf: &Py<Self>, name| zelf.as_object().generic_getattr(name, vm); let (obj, start_type): (PyObjectRef, PyTypeRef) = match &zelf.inner.read().obj { Some(o) => o.clone(), None => return skip(zelf, name), }; // We want __class__ to return the class of the super object // (i.e. super, or a subclass), not the class of su->obj. if name.as_bytes() == b"__class__" { return skip(zelf, name); } if let Some(name) = vm.ctx.interned_str(name) { // skip the classes in start_type.mro up to and including zelf.typ let mro: Vec<PyRef<PyType>> = start_type.mro_map_collect(|x| x.to_owned()); let mro: Vec<_> = mro .iter() .skip_while(|cls| !cls.is(&zelf.inner.read().typ)) .skip(1) // skip su->type (if any) .collect(); for cls in &mro { if let Some(descr) = cls.get_direct_attr(name) { return vm .call_get_descriptor_specific( &descr, // Only pass 'obj' param if this is instance-mode super (See https://bugs.python.org/issue743267) if obj.is(&start_type) { None } else { Some(obj) }, Some(start_type.as_object().to_owned()), ) .unwrap_or(Ok(descr)); } } } skip(zelf, name) } } impl GetDescriptor for PySuper { fn descr_get( zelf_obj: PyObjectRef, obj: Option<PyObjectRef>, _cls: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { let (zelf, obj) = Self::_unwrap(&zelf_obj, obj, vm)?; if vm.is_none(&obj) || zelf.inner.read().obj.is_some() { return Ok(zelf_obj); } let zelf_class = zelf.as_object().class(); if zelf_class.is(vm.ctx.types.super_type) { let typ = zelf.inner.read().typ.clone(); Ok(Self { inner: PyRwLock::new(PySuperInner::new(typ, obj, vm)?), } .into_ref(&vm.ctx) .into()) } else { let (obj, typ) = { let lock = zelf.inner.read(); let obj = lock.obj.as_ref().map(|(o, _)| o.to_owned()); let typ = lock.typ.clone(); (obj, typ) }; let obj = vm.unwrap_or_none(obj); PyType::call(zelf.class(), (typ, obj).into_args(vm), vm) } } } impl Representable for PySuper { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { let type_name = zelf.inner.read().typ.name().to_owned(); let obj = zelf.inner.read().obj.clone(); let repr = match obj { Some((_, ref ty)) => { format!("<super: <class '{}'>, <{} object>>", &type_name, ty.name()) } None => format!("<super: <class '{type_name}'>, NULL>"), }; Ok(repr) } } fn super_check(ty: PyTypeRef, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyTypeRef> { let typ = match obj.clone().downcast::<PyType>() { Ok(cls) if cls.fast_issubclass(&ty) => return Ok(cls), Ok(cls) => Some(cls), Err(_) => None, }; if obj.fast_isinstance(&ty) { return Ok(obj.class().to_owned()); } let class_attr = obj.get_attr("__class__", vm)?; if let Ok(cls) = class_attr.downcast::<PyType>() && !cls.is(&ty) && cls.fast_issubclass(&ty) { return Ok(cls); } let (type_or_instance, obj_str) = match typ { Some(t) => ("type", t.name().to_owned()), None => ("instance of", obj.class().name().to_owned()), }; Err(vm.new_type_error(format!( "super(type, obj): obj ({} {}) is not an instance or subtype of type ({}).", type_or_instance, obj_str, ty.name(), ))) } pub fn init(context: &Context) { let super_type = &context.types.super_type; PySuper::extend_class(context, super_type); let super_doc = "super() -> same as super(__class__, <first argument>)\n\ super(type) -> unbound super object\n\ super(type, obj) -> bound super object; requires isinstance(obj, type)\n\ super(type, type2) -> bound super object; requires issubclass(type2, type)\n\ Typical use to call a cooperative superclass method:\n\ class C(B):\n \ def meth(self, arg):\n \ super().meth(arg)\n\ This works for class methods too:\n\ class C(B):\n \ @classmethod\n \ def cmeth(cls, arg):\n \ super().cmeth(arg)\n"; extend_class!(context, super_type, { "__doc__" => context.new_str(super_doc), }); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/frame.rs
crates/vm/src/builtins/frame.rs
/*! The python `frame` type. */ use super::{PyCode, PyDictRef, PyIntRef, PyStrRef}; use crate::{ AsObject, Context, Py, PyObjectRef, PyRef, PyResult, VirtualMachine, class::PyClassImpl, frame::{Frame, FrameRef}, function::PySetterValue, types::Representable, }; use num_traits::Zero; pub fn init(context: &Context) { Frame::extend_class(context, context.types.frame_type); } impl Representable for Frame { #[inline] fn repr(_zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> { const REPR: &str = "<frame object at .. >"; Ok(vm.ctx.intern_str(REPR).to_owned()) } #[cold] fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { unreachable!("use repr instead") } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(Py))] impl Frame { #[pymethod] const fn clear(&self) { // TODO } #[pygetset] fn f_globals(&self) -> PyDictRef { self.globals.clone() } #[pygetset] fn f_builtins(&self) -> PyDictRef { self.builtins.clone() } #[pygetset] fn f_locals(&self, vm: &VirtualMachine) -> PyResult { self.locals(vm).map(Into::into) } #[pygetset] pub fn f_code(&self) -> PyRef<PyCode> { self.code.clone() } #[pygetset] fn f_lasti(&self) -> u32 { // Return byte offset (each instruction is 2 bytes) for compatibility self.lasti() * 2 } #[pygetset] pub fn f_lineno(&self) -> usize { // If lasti is 0, execution hasn't started yet - use first line number // Similar to PyCode_Addr2Line which returns co_firstlineno for addr_q < 0 if self.lasti() == 0 { self.code.first_line_number.map(|n| n.get()).unwrap_or(1) } else { self.current_location().line.get() } } #[pygetset] fn f_trace(&self) -> PyObjectRef { let boxed = self.trace.lock(); boxed.clone() } #[pygetset(setter)] fn set_f_trace(&self, value: PySetterValue, vm: &VirtualMachine) { let mut storage = self.trace.lock(); *storage = value.unwrap_or_none(vm); } #[pymember(type = "bool")] fn f_trace_lines(vm: &VirtualMachine, zelf: PyObjectRef) -> PyResult { let zelf: FrameRef = zelf.downcast().unwrap_or_else(|_| unreachable!()); let boxed = zelf.trace_lines.lock(); Ok(vm.ctx.new_bool(*boxed).into()) } #[pymember(type = "bool", setter)] fn set_f_trace_lines( vm: &VirtualMachine, zelf: PyObjectRef, value: PySetterValue, ) -> PyResult<()> { match value { PySetterValue::Assign(value) => { let zelf: FrameRef = zelf.downcast().unwrap_or_else(|_| unreachable!()); let value: PyIntRef = value .downcast() .map_err(|_| vm.new_type_error("attribute value type must be bool"))?; let mut trace_lines = zelf.trace_lines.lock(); *trace_lines = !value.as_bigint().is_zero(); Ok(()) } PySetterValue::Delete => Err(vm.new_type_error("can't delete numeric/char attribute")), } } } #[pyclass] impl Py<Frame> { #[pygetset] pub fn f_back(&self, vm: &VirtualMachine) -> Option<PyRef<Frame>> { // TODO: actually store f_back inside Frame struct // get the frame in the frame stack that appears before this one. // won't work if this frame isn't in the frame stack, hence the todo above vm.frames .borrow() .iter() .rev() .skip_while(|p| !p.is(self.as_object())) .nth(1) .cloned() } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/traceback.rs
crates/vm/src/builtins/traceback.rs
use super::PyType; use crate::{ AsObject, Context, Py, PyPayload, PyRef, PyResult, VirtualMachine, class::PyClassImpl, frame::FrameRef, types::Constructor, }; use rustpython_common::lock::PyMutex; use rustpython_compiler_core::OneIndexed; #[pyclass(module = false, name = "traceback", traverse)] #[derive(Debug)] pub struct PyTraceback { pub next: PyMutex<Option<PyTracebackRef>>, pub frame: FrameRef, #[pytraverse(skip)] pub lasti: u32, #[pytraverse(skip)] pub lineno: OneIndexed, } pub type PyTracebackRef = PyRef<PyTraceback>; impl PyPayload for PyTraceback { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.traceback_type } } #[pyclass(with(Constructor))] impl PyTraceback { pub const fn new( next: Option<PyRef<Self>>, frame: FrameRef, lasti: u32, lineno: OneIndexed, ) -> Self { Self { next: PyMutex::new(next), frame, lasti, lineno, } } #[pygetset] fn tb_frame(&self) -> FrameRef { self.frame.clone() } #[pygetset] const fn tb_lasti(&self) -> u32 { self.lasti } #[pygetset] const fn tb_lineno(&self) -> usize { self.lineno.get() } #[pygetset] fn tb_next(&self) -> Option<PyRef<Self>> { self.next.lock().as_ref().cloned() } #[pygetset(setter)] fn set_tb_next( zelf: &Py<Self>, value: Option<PyRef<Self>>, vm: &VirtualMachine, ) -> PyResult<()> { if let Some(ref new_next) = value { let mut cursor = new_next.clone(); loop { if cursor.is(zelf) { return Err(vm.new_value_error("traceback loop detected".to_owned())); } let next = cursor.next.lock().clone(); match next { Some(n) => cursor = n, None => break, } } } *zelf.next.lock() = value; Ok(()) } } impl Constructor for PyTraceback { type Args = (Option<PyRef<Self>>, FrameRef, u32, usize); fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> { let (next, frame, lasti, lineno) = args; let lineno = OneIndexed::new(lineno) .ok_or_else(|| vm.new_value_error("lineno must be positive".to_owned()))?; Ok(Self::new(next, frame, lasti, lineno)) } } impl PyTracebackRef { pub fn iter(&self) -> impl Iterator<Item = Self> { core::iter::successors(Some(self.clone()), |tb| tb.next.lock().clone()) } } pub fn init(context: &Context) { PyTraceback::extend_class(context, context.types.traceback_type); } #[cfg(feature = "serde")] impl serde::Serialize for PyTraceback { fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { use serde::ser::SerializeStruct; let mut struc = s.serialize_struct("PyTraceback", 3)?; struc.serialize_field("name", self.frame.code.obj_name.as_str())?; struc.serialize_field("lineno", &self.lineno.get())?; struc.serialize_field("filename", self.frame.code.source_path.as_str())?; struc.end() } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/int.rs
crates/vm/src/builtins/int.rs
use super::{PyByteArray, PyBytes, PyStr, PyType, PyTypeRef, float}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact, PyResult, TryFromBorrowedObject, VirtualMachine, builtins::PyStrRef, bytes_inner::PyBytesInner, class::PyClassImpl, common::{ format::FormatSpec, hash, int::{bigint_to_finite_float, bytes_to_int, true_div}, }, convert::{IntoPyException, ToPyObject, ToPyResult}, function::{ ArgByteOrder, ArgIntoBool, FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue, }, protocol::{PyNumberMethods, handle_bytes_to_int_err}, types::{AsNumber, Comparable, Constructor, Hashable, PyComparisonOp, Representable}, }; use alloc::fmt; use core::ops::{Neg, Not}; use malachite_bigint::{BigInt, Sign}; use num_integer::Integer; use num_traits::{One, Pow, PrimInt, Signed, ToPrimitive, Zero}; #[pyclass(module = false, name = "int")] #[derive(Debug)] pub struct PyInt { value: BigInt, } impl fmt::Display for PyInt { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { BigInt::fmt(&self.value, f) } } pub type PyIntRef = PyRef<PyInt>; impl<T> From<T> for PyInt where T: Into<BigInt>, { fn from(v: T) -> Self { Self { value: v.into() } } } impl PyPayload for PyInt { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.int_type } fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.new_int(self.value).into() } } macro_rules! impl_into_pyobject_int { ($($t:ty)*) => {$( impl ToPyObject for $t { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.new_int(self).into() } } )*}; } impl_into_pyobject_int!(isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 BigInt); macro_rules! impl_try_from_object_int { ($(($t:ty, $to_prim:ident),)*) => {$( impl<'a> TryFromBorrowedObject<'a> for $t { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> { obj.try_value_with(|int: &PyInt| { int.try_to_primitive(vm) }, vm) } } )*}; } impl_try_from_object_int!( (isize, to_isize), (i8, to_i8), (i16, to_i16), (i32, to_i32), (i64, to_i64), (i128, to_i128), (usize, to_usize), (u8, to_u8), (u16, to_u16), (u32, to_u32), (u64, to_u64), (u128, to_u128), ); fn inner_pow(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult { if int2.is_negative() { let v1 = try_to_float(int1, vm)?; let v2 = try_to_float(int2, vm)?; float::float_pow(v1, v2, vm) } else { let value = if let Some(v2) = int2.to_u64() { return Ok(vm.ctx.new_int(Pow::pow(int1, v2)).into()); } else if int1.is_one() { 1 } else if int1.is_zero() { 0 } else if int1 == &BigInt::from(-1) { if int2.is_odd() { -1 } else { 1 } } else { // missing feature: BigInt exp // practically, exp over u64 is not possible to calculate anyway return Ok(vm.ctx.not_implemented()); }; Ok(vm.ctx.new_int(value).into()) } } fn inner_mod(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult { if int2.is_zero() { Err(vm.new_zero_division_error("integer modulo by zero")) } else { Ok(vm.ctx.new_int(int1.mod_floor(int2)).into()) } } fn inner_floordiv(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult { if int2.is_zero() { Err(vm.new_zero_division_error("integer division or modulo by zero")) } else { Ok(vm.ctx.new_int(int1.div_floor(int2)).into()) } } fn inner_divmod(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult { if int2.is_zero() { return Err(vm.new_zero_division_error("integer division or modulo by zero")); } let (div, modulo) = int1.div_mod_floor(int2); Ok(vm.new_tuple((div, modulo)).into()) } fn inner_lshift(base: &BigInt, bits: &BigInt, vm: &VirtualMachine) -> PyResult { inner_shift( base, bits, |base, bits| base << bits, |bits, vm| { bits.to_usize() .ok_or_else(|| vm.new_overflow_error("the number is too large to convert to int")) }, vm, ) } fn inner_rshift(base: &BigInt, bits: &BigInt, vm: &VirtualMachine) -> PyResult { inner_shift( base, bits, |base, bits| base >> bits, |bits, _vm| Ok(bits.to_usize().unwrap_or(usize::MAX)), vm, ) } fn inner_shift<F, S>( base: &BigInt, bits: &BigInt, shift_op: F, shift_bits: S, vm: &VirtualMachine, ) -> PyResult where F: Fn(&BigInt, usize) -> BigInt, S: Fn(&BigInt, &VirtualMachine) -> PyResult<usize>, { if bits.is_negative() { Err(vm.new_value_error("negative shift count")) } else if base.is_zero() { Ok(vm.ctx.new_int(0).into()) } else { shift_bits(bits, vm).map(|bits| vm.ctx.new_int(shift_op(base, bits)).into()) } } fn inner_truediv(i1: &BigInt, i2: &BigInt, vm: &VirtualMachine) -> PyResult { if i2.is_zero() { return Err(vm.new_zero_division_error("division by zero")); } let float = true_div(i1, i2); if float.is_infinite() { Err(vm.new_exception_msg( vm.ctx.exceptions.overflow_error.to_owned(), "integer division result too large for a float".to_owned(), )) } else { Ok(vm.ctx.new_float(float).into()) } } impl Constructor for PyInt { type Args = FuncArgs; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { if cls.is(vm.ctx.types.bool_type) { return Err(vm.new_type_error("int.__new__(bool) is not safe, use bool.__new__()")); } // Optimization: return exact int as-is (only for exact int type, not subclasses) if cls.is(vm.ctx.types.int_type) && args.args.len() == 1 && args.kwargs.is_empty() && args.args[0].class().is(vm.ctx.types.int_type) { return Ok(args.args[0].clone()); } let options: IntOptions = args.bind(vm)?; let value = if let OptionalArg::Present(val) = options.val_options { if let OptionalArg::Present(base) = options.base { let base = base .try_index(vm)? .as_bigint() .to_u32() .filter(|&v| v == 0 || (2..=36).contains(&v)) .ok_or_else(|| vm.new_value_error("int() base must be >= 2 and <= 36, or 0"))?; try_int_radix(&val, base, vm) } else { val.try_int(vm).map(|x| x.as_bigint().clone()) } } else if let OptionalArg::Present(_) = options.base { Err(vm.new_type_error("int() missing string argument")) } else { Ok(Zero::zero()) }?; Self::with_value(cls, value, vm).map(Into::into) } fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> { unimplemented!("use slot_new") } } impl PyInt { fn with_value<T>(cls: PyTypeRef, value: T, vm: &VirtualMachine) -> PyResult<PyRef<Self>> where T: Into<BigInt> + ToPrimitive, { if cls.is(vm.ctx.types.int_type) { Ok(vm.ctx.new_int(value)) } else if cls.is(vm.ctx.types.bool_type) { Ok(vm.ctx.new_bool(!value.into().eq(&BigInt::zero())).upcast()) } else { Self::from(value).into_ref_with_type(vm, cls) } } pub const fn as_bigint(&self) -> &BigInt { &self.value } // _PyLong_AsUnsignedLongMask pub fn as_u32_mask(&self) -> u32 { let v = self.as_bigint(); v.to_u32() .or_else(|| v.to_i32().map(|i| i as u32)) .unwrap_or_else(|| { let mut out = 0u32; for digit in v.iter_u32_digits() { out = out.wrapping_shl(32) | digit; } match v.sign() { Sign::Minus => out * -1i32 as u32, _ => out, } }) } pub fn try_to_primitive<'a, I>(&'a self, vm: &VirtualMachine) -> PyResult<I> where I: PrimInt + TryFrom<&'a BigInt>, { I::try_from(self.as_bigint()).map_err(|_| { vm.new_overflow_error(format!( "Python int too large to convert to Rust {}", core::any::type_name::<I>() )) }) } #[inline] fn int_op<F>(&self, other: PyObjectRef, op: F) -> PyArithmeticValue<BigInt> where F: Fn(&BigInt, &BigInt) -> BigInt, { let r = other .downcast_ref::<Self>() .map(|other| op(&self.value, &other.value)); PyArithmeticValue::from_option(r) } #[inline] fn general_op<F>(&self, other: PyObjectRef, op: F, vm: &VirtualMachine) -> PyResult where F: Fn(&BigInt, &BigInt) -> PyResult, { if let Some(other) = other.downcast_ref::<Self>() { op(&self.value, &other.value) } else { Ok(vm.ctx.not_implemented()) } } } #[pyclass( itemsize = 4, flags(BASETYPE, _MATCH_SELF), with(PyRef, Comparable, Hashable, Constructor, AsNumber, Representable) )] impl PyInt { pub(crate) fn __xor__(&self, other: PyObjectRef) -> PyArithmeticValue<BigInt> { self.int_op(other, |a, b| a ^ b) } pub(crate) fn __or__(&self, other: PyObjectRef) -> PyArithmeticValue<BigInt> { self.int_op(other, |a, b| a | b) } pub(crate) fn __and__(&self, other: PyObjectRef) -> PyArithmeticValue<BigInt> { self.int_op(other, |a, b| a & b) } fn modpow(&self, other: PyObjectRef, modulus: PyObjectRef, vm: &VirtualMachine) -> PyResult { let modulus = match modulus.downcast_ref::<Self>() { Some(val) => val.as_bigint(), None => return Ok(vm.ctx.not_implemented()), }; if modulus.is_zero() { return Err(vm.new_value_error("pow() 3rd argument cannot be 0")); } self.general_op( other, |a, b| { let i = if b.is_negative() { // modular multiplicative inverse // based on rust-num/num-integer#10, should hopefully be published soon fn normalize(a: BigInt, n: &BigInt) -> BigInt { let a = a % n; if a.is_negative() { a + n } else { a } } fn inverse(a: BigInt, n: &BigInt) -> Option<BigInt> { use num_integer::*; let ExtendedGcd { gcd, x: c, .. } = a.extended_gcd(n); if gcd.is_one() { Some(normalize(c, n)) } else { None } } let a = inverse(a % modulus, modulus).ok_or_else(|| { vm.new_value_error("base is not invertible for the given modulus") })?; let b = -b; a.modpow(&b, modulus) } else { a.modpow(b, modulus) }; Ok(vm.ctx.new_int(i).into()) }, vm, ) } #[pymethod] fn __round__( zelf: PyRef<Self>, ndigits: OptionalArg<PyIntRef>, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { if let OptionalArg::Present(ndigits) = ndigits { let ndigits = ndigits.as_bigint(); // round(12345, -2) == 12300 // If precision >= 0, then any integer is already rounded correctly if let Some(ndigits) = ndigits.neg().to_u32() && ndigits > 0 { // Work with positive integers and negate at the end if necessary let sign = if zelf.value.is_negative() { BigInt::from(-1) } else { BigInt::from(1) }; let value = zelf.value.abs(); // Divide and multiply by the power of 10 to get the approximate answer let pow10 = BigInt::from(10).pow(ndigits); let quotient = &value / &pow10; let rounded = &quotient * &pow10; // Malachite division uses floor rounding, Python uses half-even let remainder = &value - &rounded; let half_pow10 = &pow10 / BigInt::from(2); let correction = if remainder > half_pow10 || (remainder == half_pow10 && quotient.is_odd()) { pow10 } else { BigInt::from(0) }; let rounded = (rounded + correction) * sign; return Ok(vm.ctx.new_int(rounded)); } } Ok(zelf) } #[pymethod] fn __trunc__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> { zelf.__int__(vm) } #[pymethod] fn __floor__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> { zelf.__int__(vm) } #[pymethod] fn __ceil__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> { zelf.__int__(vm) } #[pymethod] fn __format__(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> { FormatSpec::parse(spec.as_str()) .and_then(|format_spec| format_spec.format_int(&self.value)) .map_err(|err| err.into_pyexception(vm)) } #[pymethod] fn __sizeof__(&self) -> usize { core::mem::size_of::<Self>() + (((self.value.bits() + 7) & !7) / 8) as usize } #[pymethod] fn as_integer_ratio(&self, vm: &VirtualMachine) -> (PyRef<Self>, i32) { (vm.ctx.new_bigint(&self.value), 1) } #[pymethod] fn bit_length(&self) -> u64 { self.value.bits() } #[pymethod] fn conjugate(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> { zelf.__int__(vm) } #[pyclassmethod] fn from_bytes( cls: PyTypeRef, args: IntFromByteArgs, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { let signed = args.signed.map_or(false, Into::into); let value = match (args.byteorder, signed) { (ArgByteOrder::Big, true) => BigInt::from_signed_bytes_be(args.bytes.as_bytes()), (ArgByteOrder::Big, false) => BigInt::from_bytes_be(Sign::Plus, args.bytes.as_bytes()), (ArgByteOrder::Little, true) => BigInt::from_signed_bytes_le(args.bytes.as_bytes()), (ArgByteOrder::Little, false) => { BigInt::from_bytes_le(Sign::Plus, args.bytes.as_bytes()) } }; Self::with_value(cls, value, vm) } #[pymethod] fn to_bytes(&self, args: IntToByteArgs, vm: &VirtualMachine) -> PyResult<PyBytes> { let signed = args.signed.map_or(false, Into::into); let byte_len = args.length; let value = self.as_bigint(); match value.sign() { Sign::Minus if !signed => { return Err(vm.new_overflow_error("can't convert negative int to unsigned")); } Sign::NoSign => return Ok(vec![0u8; byte_len].into()), _ => {} } let mut origin_bytes = match (args.byteorder, signed) { (ArgByteOrder::Big, true) => value.to_signed_bytes_be(), (ArgByteOrder::Big, false) => value.to_bytes_be().1, (ArgByteOrder::Little, true) => value.to_signed_bytes_le(), (ArgByteOrder::Little, false) => value.to_bytes_le().1, }; let origin_len = origin_bytes.len(); if origin_len > byte_len { return Err(vm.new_overflow_error("int too big to convert")); } let mut append_bytes = match value.sign() { Sign::Minus => vec![255u8; byte_len - origin_len], _ => vec![0u8; byte_len - origin_len], }; let bytes = match args.byteorder { ArgByteOrder::Big => { let mut bytes = append_bytes; bytes.append(&mut origin_bytes); bytes } ArgByteOrder::Little => { let mut bytes = origin_bytes; bytes.append(&mut append_bytes); bytes } }; Ok(bytes.into()) } #[pygetset] fn real(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> { zelf.__int__(vm) } #[pygetset] const fn imag(&self) -> usize { 0 } #[pygetset] fn numerator(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> { zelf.__int__(vm) } #[pygetset] const fn denominator(&self) -> usize { 1 } #[pymethod] const fn is_integer(&self) -> bool { true } #[pymethod] fn bit_count(&self) -> u32 { self.value.iter_u32_digits().map(|n| n.count_ones()).sum() } #[pymethod] fn __getnewargs__(&self, vm: &VirtualMachine) -> PyObjectRef { (self.value.clone(),).to_pyobject(vm) } } #[pyclass] impl PyRef<PyInt> { pub(crate) fn __int__(self, vm: &VirtualMachine) -> PyRefExact<PyInt> { self.into_exact_or(&vm.ctx, |zelf| unsafe { // TODO: this is actually safe. we need better interface PyRefExact::new_unchecked(vm.ctx.new_bigint(&zelf.value)) }) } } impl Comparable for PyInt { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, _vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { let r = other .downcast_ref::<Self>() .map(|other| op.eval_ord(zelf.value.cmp(&other.value))); Ok(PyComparisonValue::from_option(r)) } } impl Representable for PyInt { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { Ok(zelf.value.to_string()) } } impl Hashable for PyInt { #[inline] fn hash(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<hash::PyHash> { Ok(hash::hash_bigint(zelf.as_bigint())) } } impl AsNumber for PyInt { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyInt::AS_NUMBER; &AS_NUMBER } #[inline] fn clone_exact(zelf: &Py<Self>, vm: &VirtualMachine) -> PyRef<Self> { vm.ctx.new_bigint(&zelf.value) } } impl PyInt { pub(super) const AS_NUMBER: PyNumberMethods = PyNumberMethods { add: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a + b, vm)), subtract: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a - b, vm)), multiply: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a * b, vm)), remainder: Some(|a, b, vm| Self::number_op(a, b, inner_mod, vm)), divmod: Some(|a, b, vm| Self::number_op(a, b, inner_divmod, vm)), power: Some(|a, b, c, vm| { if let Some(a) = a.downcast_ref::<Self>() { if vm.is_none(c) { a.general_op(b.to_owned(), |a, b| inner_pow(a, b, vm), vm) } else { a.modpow(b.to_owned(), c.to_owned(), vm) } } else { Ok(vm.ctx.not_implemented()) } }), negative: Some(|num, vm| (&Self::number_downcast(num).value).neg().to_pyresult(vm)), positive: Some(|num, vm| Ok(Self::number_downcast_exact(num, vm).into())), absolute: Some(|num, vm| Self::number_downcast(num).value.abs().to_pyresult(vm)), boolean: Some(|num, _vm| Ok(!Self::number_downcast(num).value.is_zero())), invert: Some(|num, vm| (&Self::number_downcast(num).value).not().to_pyresult(vm)), lshift: Some(|a, b, vm| Self::number_op(a, b, inner_lshift, vm)), rshift: Some(|a, b, vm| Self::number_op(a, b, inner_rshift, vm)), and: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a & b, vm)), xor: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a ^ b, vm)), or: Some(|a, b, vm| Self::number_op(a, b, |a, b, _vm| a | b, vm)), int: Some(|num, vm| Ok(Self::number_downcast_exact(num, vm).into())), float: Some(|num, vm| { let zelf = Self::number_downcast(num); try_to_float(&zelf.value, vm).map(|x| vm.ctx.new_float(x).into()) }), floor_divide: Some(|a, b, vm| Self::number_op(a, b, inner_floordiv, vm)), true_divide: Some(|a, b, vm| Self::number_op(a, b, inner_truediv, vm)), index: Some(|num, vm| Ok(Self::number_downcast_exact(num, vm).into())), ..PyNumberMethods::NOT_IMPLEMENTED }; fn number_op<F, R>(a: &PyObject, b: &PyObject, op: F, vm: &VirtualMachine) -> PyResult where F: FnOnce(&BigInt, &BigInt, &VirtualMachine) -> R, R: ToPyResult, { if let (Some(a), Some(b)) = (a.downcast_ref::<Self>(), b.downcast_ref::<Self>()) { op(&a.value, &b.value, vm).to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } } } #[derive(FromArgs)] pub struct IntOptions { #[pyarg(positional, optional)] val_options: OptionalArg<PyObjectRef>, #[pyarg(any, optional)] base: OptionalArg<PyObjectRef>, } #[derive(FromArgs)] struct IntFromByteArgs { bytes: PyBytesInner, #[pyarg(any, default = ArgByteOrder::Big)] byteorder: ArgByteOrder, #[pyarg(named, optional)] signed: OptionalArg<ArgIntoBool>, } #[derive(FromArgs)] struct IntToByteArgs { #[pyarg(any, default = 1)] length: usize, #[pyarg(any, default = ArgByteOrder::Big)] byteorder: ArgByteOrder, #[pyarg(named, optional)] signed: OptionalArg<ArgIntoBool>, } fn try_int_radix(obj: &PyObject, base: u32, vm: &VirtualMachine) -> PyResult<BigInt> { match_class!(match obj.to_owned() { string @ PyStr => { let s = string.as_wtf8().trim(); bytes_to_int(s.as_bytes(), base, vm.state.int_max_str_digits.load()) .map_err(|e| handle_bytes_to_int_err(e, obj, vm)) } bytes @ PyBytes => { bytes_to_int(bytes.as_bytes(), base, vm.state.int_max_str_digits.load()) .map_err(|e| handle_bytes_to_int_err(e, obj, vm)) } bytearray @ PyByteArray => { let inner = bytearray.borrow_buf(); bytes_to_int(&inner, base, vm.state.int_max_str_digits.load()) .map_err(|e| handle_bytes_to_int_err(e, obj, vm)) } _ => Err(vm.new_type_error("int() can't convert non-string with explicit base")), }) } // Retrieve inner int value: pub(crate) fn get_value(obj: &PyObject) -> &BigInt { &obj.downcast_ref::<PyInt>().unwrap().value } pub fn try_to_float(int: &BigInt, vm: &VirtualMachine) -> PyResult<f64> { bigint_to_finite_float(int) .ok_or_else(|| vm.new_overflow_error("int too large to convert to float")) } pub(crate) fn init(context: &Context) { PyInt::extend_class(context, context.types.int_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/property.rs
crates/vm/src/builtins/property.rs
/*! Python `property` descriptor class. */ use super::{PyStrRef, PyType}; use crate::common::lock::PyRwLock; use crate::function::{IntoFuncArgs, PosArgs}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, class::PyClassImpl, function::{FuncArgs, PySetterValue}, types::{Constructor, GetDescriptor, Initializer}, }; use core::sync::atomic::{AtomicBool, Ordering}; #[pyclass(module = false, name = "property", traverse)] #[derive(Debug)] pub struct PyProperty { getter: PyRwLock<Option<PyObjectRef>>, setter: PyRwLock<Option<PyObjectRef>>, deleter: PyRwLock<Option<PyObjectRef>>, doc: PyRwLock<Option<PyObjectRef>>, name: PyRwLock<Option<PyObjectRef>>, #[pytraverse(skip)] getter_doc: core::sync::atomic::AtomicBool, } impl PyPayload for PyProperty { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.property_type } } #[derive(FromArgs)] pub struct PropertyArgs { #[pyarg(any, default)] fget: Option<PyObjectRef>, #[pyarg(any, default)] fset: Option<PyObjectRef>, #[pyarg(any, default)] fdel: Option<PyObjectRef>, #[pyarg(any, default)] doc: Option<PyObjectRef>, #[pyarg(any, default)] name: Option<PyStrRef>, } impl GetDescriptor for PyProperty { fn descr_get( zelf_obj: PyObjectRef, obj: Option<PyObjectRef>, _cls: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { let (zelf, obj) = Self::_unwrap(&zelf_obj, obj, vm)?; if vm.is_none(&obj) { Ok(zelf_obj) } else if let Some(getter) = zelf.getter.read().clone() { // Clone and release lock before calling Python code to prevent deadlock getter.call((obj,), vm) } else { let error_msg = zelf.format_property_error(&obj, "getter", vm)?; Err(vm.new_attribute_error(error_msg)) } } } #[pyclass(with(Constructor, Initializer, GetDescriptor), flags(BASETYPE))] impl PyProperty { // Helper method to get property name // Returns the name if available, None if not found, or propagates errors fn get_property_name(&self, vm: &VirtualMachine) -> PyResult<Option<PyObjectRef>> { // First check if name was set via __set_name__ if let Some(name) = self.name.read().clone() { return Ok(Some(name)); } // Clone and release lock before calling Python code to prevent deadlock let Some(getter) = self.getter.read().clone() else { return Ok(None); }; match getter.get_attr("__name__", vm) { Ok(name) => Ok(Some(name)), Err(e) => { // If it's an AttributeError from the getter, return None // Otherwise, propagate the original exception (e.g., RuntimeError) if e.class().is(vm.ctx.exceptions.attribute_error) { Ok(None) } else { Err(e) } } } } // Descriptor methods #[pyslot] fn descr_set( zelf: &PyObject, obj: PyObjectRef, value: PySetterValue, vm: &VirtualMachine, ) -> PyResult<()> { let zelf = zelf.try_to_ref::<Self>(vm)?; match value { PySetterValue::Assign(value) => { // Clone and release lock before calling Python code to prevent deadlock if let Some(setter) = zelf.setter.read().clone() { setter.call((obj, value), vm).map(drop) } else { let error_msg = zelf.format_property_error(&obj, "setter", vm)?; Err(vm.new_attribute_error(error_msg)) } } PySetterValue::Delete => { // Clone and release lock before calling Python code to prevent deadlock if let Some(deleter) = zelf.deleter.read().clone() { deleter.call((obj,), vm).map(drop) } else { let error_msg = zelf.format_property_error(&obj, "deleter", vm)?; Err(vm.new_attribute_error(error_msg)) } } } } // Access functions #[pygetset] fn fget(&self) -> Option<PyObjectRef> { self.getter.read().clone() } #[pygetset] fn fset(&self) -> Option<PyObjectRef> { self.setter.read().clone() } #[pygetset] fn fdel(&self) -> Option<PyObjectRef> { self.deleter.read().clone() } #[pygetset(name = "__name__")] fn name_getter(&self, vm: &VirtualMachine) -> PyResult { match self.get_property_name(vm)? { Some(name) => Ok(name), None => Err( vm.new_attribute_error("'property' object has no attribute '__name__'".to_owned()) ), } } #[pygetset(name = "__name__", setter)] fn name_setter(&self, value: PyObjectRef) { *self.name.write() = Some(value); } fn doc_getter(&self) -> Option<PyObjectRef> { self.doc.read().clone() } fn doc_setter(&self, value: Option<PyObjectRef>) { *self.doc.write() = value; } #[pymethod] fn __set_name__(&self, args: PosArgs, vm: &VirtualMachine) -> PyResult<()> { let func_args = args.into_args(vm); let func_args_len = func_args.args.len(); let (_owner, name): (PyObjectRef, PyObjectRef) = func_args.bind(vm).map_err(|_e| { vm.new_type_error(format!( "__set_name__() takes 2 positional arguments but {func_args_len} were given" )) })?; *self.name.write() = Some(name); Ok(()) } // Python builder functions // Helper method to create a new property with updated attributes fn clone_property_with( zelf: PyRef<Self>, new_getter: Option<PyObjectRef>, new_setter: Option<PyObjectRef>, new_deleter: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { // Determine doc based on getter_doc flag and whether we're updating the getter let doc = if zelf.getter_doc.load(Ordering::Relaxed) && new_getter.is_some() { // If the original property uses getter doc and we have a new getter, // pass Py_None to let __init__ get the doc from the new getter Some(vm.ctx.none()) } else if zelf.getter_doc.load(Ordering::Relaxed) { // If original used getter_doc but we're not changing the getter, // pass None to let init get doc from existing getter Some(vm.ctx.none()) } else { // Otherwise use the existing doc zelf.doc_getter() }; // Create property args with updated values let args = PropertyArgs { fget: new_getter.or_else(|| zelf.fget()), fset: new_setter.or_else(|| zelf.fset()), fdel: new_deleter.or_else(|| zelf.fdel()), doc, name: None, }; // Create new property using py_new and init let new_prop = Self::slot_new(zelf.class().to_owned(), FuncArgs::default(), vm)?; let new_prop_ref = new_prop.downcast::<Self>().unwrap(); Self::init(new_prop_ref.clone(), args, vm)?; // Copy the name if it exists if let Some(name) = zelf.name.read().clone() { *new_prop_ref.name.write() = Some(name); } Ok(new_prop_ref) } #[pymethod] fn getter( zelf: PyRef<Self>, getter: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { Self::clone_property_with(zelf, getter, None, None, vm) } #[pymethod] fn setter( zelf: PyRef<Self>, setter: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { Self::clone_property_with(zelf, None, setter, None, vm) } #[pymethod] fn deleter( zelf: PyRef<Self>, deleter: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<PyRef<Self>> { Self::clone_property_with(zelf, None, None, deleter, vm) } #[pygetset] fn __isabstractmethod__(&self, vm: &VirtualMachine) -> PyResult { // Helper to check if a method is abstract let is_abstract = |method: &PyObject| -> PyResult<bool> { match method.get_attr("__isabstractmethod__", vm) { Ok(isabstract) => isabstract.try_to_bool(vm), Err(_) => Ok(false), } }; // Clone and release lock before calling Python code to prevent deadlock // Check getter if let Some(getter) = self.getter.read().clone() && is_abstract(&getter)? { return Ok(vm.ctx.new_bool(true).into()); } // Check setter if let Some(setter) = self.setter.read().clone() && is_abstract(&setter)? { return Ok(vm.ctx.new_bool(true).into()); } // Check deleter if let Some(deleter) = self.deleter.read().clone() && is_abstract(&deleter)? { return Ok(vm.ctx.new_bool(true).into()); } Ok(vm.ctx.new_bool(false).into()) } #[pygetset(setter)] fn set___isabstractmethod__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { // Clone and release lock before calling Python code to prevent deadlock if let Some(getter) = self.getter.read().clone() { getter.set_attr("__isabstractmethod__", value, vm)?; } Ok(()) } // Helper method to format property error messages #[cold] fn format_property_error( &self, obj: &PyObject, error_type: &str, vm: &VirtualMachine, ) -> PyResult<String> { let prop_name = self.get_property_name(vm)?; let obj_type = obj.class(); let qualname = obj_type.__qualname__(vm); match prop_name { Some(name) => Ok(format!( "property {} of {} object has no {}", name.repr(vm)?, qualname.repr(vm)?, error_type )), None => Ok(format!( "property of {} object has no {}", qualname.repr(vm)?, error_type )), } } } impl Constructor for PyProperty { type Args = FuncArgs; fn py_new(_cls: &Py<PyType>, _args: FuncArgs, _vm: &VirtualMachine) -> PyResult<Self> { Ok(Self { getter: PyRwLock::new(None), setter: PyRwLock::new(None), deleter: PyRwLock::new(None), doc: PyRwLock::new(None), name: PyRwLock::new(None), getter_doc: AtomicBool::new(false), }) } } impl Initializer for PyProperty { type Args = PropertyArgs; fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { // Set doc and getter_doc flag let mut getter_doc = false; // Helper to get doc from getter let get_getter_doc = |fget: &PyObject| -> Option<PyObjectRef> { fget.get_attr("__doc__", vm) .ok() .filter(|doc| !vm.is_none(doc)) }; let doc = match args.doc { Some(doc) if !vm.is_none(&doc) => Some(doc), _ => { // No explicit doc or doc is None, try to get from getter args.fget.as_ref().and_then(|fget| { get_getter_doc(fget).inspect(|_| { getter_doc = true; }) }) } }; // Check if this is a property subclass let is_exact_property = zelf.class().is(vm.ctx.types.property_type); if is_exact_property { // For exact property type, store doc in the field *zelf.doc.write() = doc; } else { // For property subclass, set __doc__ as an attribute let doc_to_set = doc.unwrap_or_else(|| vm.ctx.none()); match zelf.as_object().set_attr("__doc__", doc_to_set, vm) { Ok(()) => {} Err(e) if !getter_doc && e.class().is(vm.ctx.exceptions.attribute_error) => { // Silently ignore AttributeError for backwards compatibility // (only when not using getter_doc) } Err(e) => return Err(e), } } *zelf.getter.write() = args.fget; *zelf.setter.write() = args.fset; *zelf.deleter.write() = args.fdel; *zelf.name.write() = args.name.map(|a| a.as_object().to_owned()); zelf.getter_doc.store(getter_doc, Ordering::Relaxed); Ok(()) } } pub(crate) fn init(context: &Context) { PyProperty::extend_class(context, context.types.property_type); // This is a bit unfortunate, but this instance attribute overlaps with the // class __doc__ string.. extend_class!(context, context.types.property_type, { "__doc__" => context.new_static_getset( "__doc__", context.types.property_type, PyProperty::doc_getter, PyProperty::doc_setter, ), }); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/namespace.rs
crates/vm/src/builtins/namespace.rs
use super::{PyTupleRef, PyType, tuple::IntoPyTuple}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::PyDict, class::PyClassImpl, function::{FuncArgs, PyComparisonValue}, recursion::ReprGuard, types::{ Comparable, Constructor, DefaultConstructor, Initializer, PyComparisonOp, Representable, }, }; /// A simple attribute-based namespace. /// /// SimpleNamespace(**kwargs) #[pyclass(module = "types", name = "SimpleNamespace")] #[derive(Debug, Default)] pub struct PyNamespace {} impl PyPayload for PyNamespace { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.namespace_type } } impl DefaultConstructor for PyNamespace {} #[pyclass( flags(BASETYPE, HAS_DICT), with(Constructor, Initializer, Comparable, Representable) )] impl PyNamespace { #[pymethod] fn __reduce__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyTupleRef { let dict = zelf.as_object().dict().unwrap(); let obj = zelf.as_object().to_owned(); let result: (PyObjectRef, PyObjectRef, PyObjectRef) = ( obj.class().to_owned().into(), vm.new_tuple(()).into(), dict.into(), ); result.into_pytuple(vm) } } impl Initializer for PyNamespace { type Args = FuncArgs; fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { if !args.args.is_empty() { return Err(vm.new_type_error("no positional arguments expected")); } for (name, value) in args.kwargs { let name = vm.ctx.new_str(name); zelf.as_object().set_attr(&name, value, vm)?; } Ok(()) } } impl Comparable for PyNamespace { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { let other = class_or_notimplemented!(Self, other); let (d1, d2) = ( zelf.as_object().dict().unwrap(), other.as_object().dict().unwrap(), ); PyDict::cmp(&d1, d2.as_object(), op, vm) } } impl Representable for PyNamespace { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { let o = zelf.as_object(); let name = if o.class().is(vm.ctx.types.namespace_type) { "namespace".to_owned() } else { o.class().slot_name().to_owned() }; let repr = if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { let dict = zelf.as_object().dict().unwrap(); let mut parts = Vec::with_capacity(dict.__len__()); for (key, value) in dict { let k = key.repr(vm)?; let key_str = k.as_wtf8(); let value_repr = value.repr(vm)?; parts.push(format!("{}={}", &key_str[1..key_str.len() - 1], value_repr)); } format!("{}({})", name, parts.join(", ")) } else { format!("{name}(...)") }; Ok(repr) } } pub fn init(context: &Context) { PyNamespace::extend_class(context, context.types.namespace_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/zip.rs
crates/vm/src/builtins/zip.rs
use super::PyType; use crate::{ AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, builtins::PyTupleRef, class::PyClassImpl, function::{ArgIntoBool, OptionalArg, PosArgs}, protocol::{PyIter, PyIterReturn}, types::{Constructor, IterNext, Iterable, SelfIter}, }; use rustpython_common::atomic::{self, PyAtomic, Radium}; #[pyclass(module = false, name = "zip", traverse)] #[derive(Debug)] pub struct PyZip { iterators: Vec<PyIter>, #[pytraverse(skip)] strict: PyAtomic<bool>, } impl PyPayload for PyZip { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.zip_type } } #[derive(FromArgs)] pub struct PyZipNewArgs { #[pyarg(named, optional)] strict: OptionalArg<bool>, } impl Constructor for PyZip { type Args = (PosArgs<PyIter>, PyZipNewArgs); fn py_new( _cls: &Py<PyType>, (iterators, args): Self::Args, _vm: &VirtualMachine, ) -> PyResult<Self> { let iterators = iterators.into_vec(); let strict = Radium::new(args.strict.unwrap_or(false)); Ok(Self { iterators, strict }) } } #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyZip { #[pymethod] fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> { let cls = zelf.class().to_owned(); let iterators = zelf .iterators .iter() .map(|obj| obj.clone().into()) .collect::<Vec<_>>(); let tuple_iter = vm.ctx.new_tuple(iterators); Ok(if zelf.strict.load(atomic::Ordering::Acquire) { vm.new_tuple((cls, tuple_iter, true)) } else { vm.new_tuple((cls, tuple_iter)) }) } #[pymethod] fn __setstate__(zelf: PyRef<Self>, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { if let Ok(obj) = ArgIntoBool::try_from_object(vm, state) { zelf.strict.store(obj.into(), atomic::Ordering::Release); } Ok(()) } } impl SelfIter for PyZip {} impl IterNext for PyZip { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { if zelf.iterators.is_empty() { return Ok(PyIterReturn::StopIteration(None)); } let mut next_objs = Vec::new(); for (idx, iterator) in zelf.iterators.iter().enumerate() { let item = match iterator.next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => { if zelf.strict.load(atomic::Ordering::Acquire) { if idx > 0 { let plural = if idx == 1 { " " } else { "s 1-" }; return Err(vm.new_value_error(format!( "zip() argument {} is shorter than argument{}{}", idx + 1, plural, idx ))); } for (idx, iterator) in zelf.iterators[1..].iter().enumerate() { if let PyIterReturn::Return(_obj) = iterator.next(vm)? { let plural = if idx == 0 { " " } else { "s 1-" }; return Err(vm.new_value_error(format!( "zip() argument {} is longer than argument{}{}", idx + 2, plural, idx + 1 ))); } } } return Ok(PyIterReturn::StopIteration(v)); } }; next_objs.push(item); } Ok(PyIterReturn::Return(vm.ctx.new_tuple(next_objs).into())) } } pub fn init(ctx: &Context) { PyZip::extend_class(ctx, ctx.types.zip_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/genericalias.rs
crates/vm/src/builtins/genericalias.rs
// spell-checker:ignore iparam use std::sync::LazyLock; use super::type_; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, atomic_func, builtins::{PyList, PyStr, PyTuple, PyTupleRef, PyType, PyTypeRef}, class::PyClassImpl, common::hash, convert::ToPyObject, function::{FuncArgs, PyComparisonValue}, protocol::{PyMappingMethods, PyNumberMethods}, types::{ AsMapping, AsNumber, Callable, Comparable, Constructor, GetAttr, Hashable, Iterable, PyComparisonOp, Representable, }, }; use alloc::fmt; // attr_exceptions static ATTR_EXCEPTIONS: [&str; 12] = [ "__class__", "__bases__", "__origin__", "__args__", "__unpacked__", "__parameters__", "__typing_unpacked_tuple_args__", "__mro_entries__", "__reduce_ex__", // needed so we don't look up object.__reduce_ex__ "__reduce__", "__copy__", "__deepcopy__", ]; #[pyclass(module = "types", name = "GenericAlias")] pub struct PyGenericAlias { origin: PyTypeRef, args: PyTupleRef, parameters: PyTupleRef, starred: bool, // for __unpacked__ attribute } impl fmt::Debug for PyGenericAlias { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("GenericAlias") } } impl PyPayload for PyGenericAlias { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.generic_alias_type } } impl Constructor for PyGenericAlias { type Args = FuncArgs; fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> { if !args.kwargs.is_empty() { return Err(vm.new_type_error("GenericAlias() takes no keyword arguments")); } let (origin, arguments): (_, PyObjectRef) = args.bind(vm)?; let args = if let Ok(tuple) = arguments.try_to_ref::<PyTuple>(vm) { tuple.to_owned() } else { PyTuple::new_ref(vec![arguments], &vm.ctx) }; Ok(Self::new(origin, args, false, vm)) } } #[pyclass( with( AsNumber, AsMapping, Callable, Comparable, Constructor, GetAttr, Hashable, Iterable, Representable ), flags(BASETYPE) )] impl PyGenericAlias { pub fn new(origin: PyTypeRef, args: PyTupleRef, starred: bool, vm: &VirtualMachine) -> Self { let parameters = make_parameters(&args, vm); Self { origin, args, parameters, starred, } } /// Create a GenericAlias from an origin and PyObjectRef arguments (helper for compatibility) pub fn from_args(origin: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> Self { let args = if let Ok(tuple) = args.try_to_ref::<PyTuple>(vm) { tuple.to_owned() } else { PyTuple::new_ref(vec![args], &vm.ctx) }; Self::new(origin, args, false, vm) } fn repr(&self, vm: &VirtualMachine) -> PyResult<String> { fn repr_item(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<String> { if obj.is(&vm.ctx.ellipsis) { return Ok("...".to_string()); } if vm .get_attribute_opt(obj.clone(), identifier!(vm, __origin__))? .is_some() && vm .get_attribute_opt(obj.clone(), identifier!(vm, __args__))? .is_some() { return Ok(obj.repr(vm)?.to_string()); } match ( vm.get_attribute_opt(obj.clone(), identifier!(vm, __qualname__))? .and_then(|o| o.downcast_ref::<PyStr>().map(|n| n.to_string())), vm.get_attribute_opt(obj.clone(), identifier!(vm, __module__))? .and_then(|o| o.downcast_ref::<PyStr>().map(|m| m.to_string())), ) { (None, _) | (_, None) => Ok(obj.repr(vm)?.to_string()), (Some(qualname), Some(module)) => Ok(if module == "builtins" { qualname } else { format!("{module}.{qualname}") }), } } let repr_str = format!( "{}[{}]", repr_item(self.origin.clone().into(), vm)?, if self.args.is_empty() { "()".to_owned() } else { self.args .iter() .map(|o| repr_item(o.clone(), vm)) .collect::<PyResult<Vec<_>>>()? .join(", ") } ); // Add * prefix if this is a starred GenericAlias Ok(if self.starred { format!("*{repr_str}") } else { repr_str }) } #[pygetset] fn __parameters__(&self) -> PyObjectRef { self.parameters.clone().into() } #[pygetset] fn __args__(&self) -> PyObjectRef { self.args.clone().into() } #[pygetset] fn __origin__(&self) -> PyObjectRef { self.origin.clone().into() } #[pygetset] const fn __unpacked__(&self) -> bool { self.starred } #[pygetset] fn __typing_unpacked_tuple_args__(&self, vm: &VirtualMachine) -> PyObjectRef { if self.starred && self.origin.is(vm.ctx.types.tuple_type) { self.args.clone().into() } else { vm.ctx.none() } } fn __getitem__(zelf: PyRef<Self>, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { let new_args = subs_parameters( zelf.to_owned().into(), zelf.args.clone(), zelf.parameters.clone(), needle, vm, )?; Ok(Self::new(zelf.origin.clone(), new_args, false, vm).into_pyobject(vm)) } #[pymethod] fn __dir__(&self, vm: &VirtualMachine) -> PyResult<PyList> { let dir = vm.dir(Some(self.__origin__()))?; for exc in &ATTR_EXCEPTIONS { if !dir.__contains__((*exc).to_pyobject(vm), vm)? { dir.append((*exc).to_pyobject(vm)); } } Ok(dir) } #[pymethod] fn __reduce__(zelf: &Py<Self>, vm: &VirtualMachine) -> (PyTypeRef, (PyTypeRef, PyTupleRef)) { ( vm.ctx.types.generic_alias_type.to_owned(), (zelf.origin.clone(), zelf.args.clone()), ) } #[pymethod] fn __mro_entries__(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyTupleRef { PyTuple::new_ref(vec![self.__origin__()], &vm.ctx) } #[pymethod] fn __instancecheck__(_zelf: PyRef<Self>, _obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { Err(vm.new_type_error("isinstance() argument 2 cannot be a parameterized generic")) } #[pymethod] fn __subclasscheck__(_zelf: PyRef<Self>, _obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { Err(vm.new_type_error("issubclass() argument 2 cannot be a parameterized generic")) } fn __ror__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { type_::or_(other, zelf, vm) } fn __or__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { type_::or_(zelf, other, vm) } } pub(crate) fn make_parameters(args: &Py<PyTuple>, vm: &VirtualMachine) -> PyTupleRef { let mut parameters: Vec<PyObjectRef> = Vec::with_capacity(args.len()); let mut iparam = 0; for arg in args { // We don't want __parameters__ descriptor of a bare Python class. if arg.class().is(vm.ctx.types.type_type) { continue; } // Check for __typing_subst__ attribute if arg.get_attr(identifier!(vm, __typing_subst__), vm).is_ok() { // Use tuple_add equivalent logic if tuple_index(&parameters, arg).is_none() { if iparam >= parameters.len() { parameters.resize(iparam + 1, vm.ctx.none()); } parameters[iparam] = arg.clone(); iparam += 1; } } else if let Ok(subparams) = arg.get_attr(identifier!(vm, __parameters__), vm) && let Ok(sub_params) = subparams.try_to_ref::<PyTuple>(vm) { let len2 = sub_params.len(); // Resize if needed if iparam + len2 > parameters.len() { parameters.resize(iparam + len2, vm.ctx.none()); } for sub_param in sub_params { // Use tuple_add equivalent logic if tuple_index(&parameters[..iparam], sub_param).is_none() { if iparam >= parameters.len() { parameters.resize(iparam + 1, vm.ctx.none()); } parameters[iparam] = sub_param.clone(); iparam += 1; } } } } // Resize to actual size parameters.truncate(iparam); PyTuple::new_ref(parameters, &vm.ctx) } #[inline] fn tuple_index(vec: &[PyObjectRef], item: &PyObject) -> Option<usize> { vec.iter().position(|element| element.is(item)) } fn is_unpacked_typevartuple(arg: &PyObject, vm: &VirtualMachine) -> PyResult<bool> { if arg.class().is(vm.ctx.types.type_type) { return Ok(false); } if let Ok(attr) = arg.get_attr(identifier!(vm, __typing_is_unpacked_typevartuple__), vm) { attr.try_to_bool(vm) } else { Ok(false) } } fn subs_tvars( obj: PyObjectRef, params: &Py<PyTuple>, arg_items: &[PyObjectRef], vm: &VirtualMachine, ) -> PyResult { obj.get_attr(identifier!(vm, __parameters__), vm) .ok() .and_then(|sub_params| { PyTupleRef::try_from_object(vm, sub_params) .ok() .filter(|sub_params| !sub_params.is_empty()) .map(|sub_params| { let mut sub_args = Vec::new(); for arg in sub_params.iter() { if let Some(idx) = tuple_index(params.as_slice(), arg) { let param = &params[idx]; let substituted_arg = &arg_items[idx]; // Check if this is a TypeVarTuple (has tp_iter) if param.class().slots.iter.load().is_some() && substituted_arg.try_to_ref::<PyTuple>(vm).is_ok() { // TypeVarTuple case - extend with tuple elements if let Ok(tuple) = substituted_arg.try_to_ref::<PyTuple>(vm) { for elem in tuple { sub_args.push(elem.clone()); } continue; } } sub_args.push(substituted_arg.clone()); } else { sub_args.push(arg.clone()); } } let sub_args: PyObjectRef = PyTuple::new_ref(sub_args, &vm.ctx).into(); obj.get_item(&*sub_args, vm) }) }) .unwrap_or(Ok(obj)) } // CPython's _unpack_args equivalent fn unpack_args(item: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyTupleRef> { let mut new_args = Vec::new(); let arg_items = if let Ok(tuple) = item.try_to_ref::<PyTuple>(vm) { tuple.as_slice().to_vec() } else { vec![item] }; for item in arg_items { // Skip PyType objects - they can't be unpacked if item.class().is(vm.ctx.types.type_type) { new_args.push(item); continue; } // Try to get __typing_unpacked_tuple_args__ if let Ok(sub_args) = item.get_attr(identifier!(vm, __typing_unpacked_tuple_args__), vm) && !sub_args.is(&vm.ctx.none) && let Ok(tuple) = sub_args.try_to_ref::<PyTuple>(vm) { // Check for ellipsis at the end let has_ellipsis_at_end = tuple .as_slice() .last() .is_some_and(|item| item.is(&vm.ctx.ellipsis)); if !has_ellipsis_at_end { // Safe to unpack - add all elements's PyList_SetSlice for arg in tuple { new_args.push(arg.clone()); } continue; } } // Default case: add the item as-is's PyList_Append new_args.push(item); } Ok(PyTuple::new_ref(new_args, &vm.ctx)) } // _Py_subs_parameters pub fn subs_parameters( alias: PyObjectRef, // = self args: PyTupleRef, parameters: PyTupleRef, item: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyTupleRef> { let n_params = parameters.len(); if n_params == 0 { return Err(vm.new_type_error(format!("{} is not a generic class", alias.repr(vm)?))); } // Step 1: Unpack args let mut item: PyObjectRef = unpack_args(item, vm)?.into(); // Step 2: Call __typing_prepare_subst__ on each parameter for param in parameters.iter() { if let Ok(prepare) = param.get_attr(identifier!(vm, __typing_prepare_subst__), vm) && !prepare.is(&vm.ctx.none) { // Call prepare(self, item) item = if item.try_to_ref::<PyTuple>(vm).is_ok() { prepare.call((alias.clone(), item.clone()), vm)? } else { // Create a tuple with the single item's "O(O)" format let tuple_args = PyTuple::new_ref(vec![item.clone()], &vm.ctx); prepare.call((alias.clone(), tuple_args.to_pyobject(vm)), vm)? }; } } // Step 3: Extract final arg items let arg_items = if let Ok(tuple) = item.try_to_ref::<PyTuple>(vm) { tuple.as_slice().to_vec() } else { vec![item] }; let n_items = arg_items.len(); if n_items != n_params { return Err(vm.new_type_error(format!( "Too {} arguments for {}; actual {}, expected {}", if n_items > n_params { "many" } else { "few" }, alias.repr(vm)?, n_items, n_params ))); } // Step 4: Replace all type variables let mut new_args = Vec::new(); for arg in args.iter() { // Skip PyType objects if arg.class().is(vm.ctx.types.type_type) { new_args.push(arg.clone()); continue; } // Check if this is an unpacked TypeVarTuple's _is_unpacked_typevartuple let unpack = is_unpacked_typevartuple(arg, vm)?; // Try __typing_subst__ method first, let substituted_arg = if let Ok(subst) = arg.get_attr(identifier!(vm, __typing_subst__), vm) { // Find parameter index's tuple_index if let Some(iparam) = tuple_index(parameters.as_slice(), arg) { subst.call((arg_items[iparam].clone(),), vm)? } else { // This shouldn't happen in well-formed generics but handle gracefully subs_tvars(arg.clone(), &parameters, &arg_items, vm)? } } else { // Use subs_tvars for objects with __parameters__ subs_tvars(arg.clone(), &parameters, &arg_items, vm)? }; if unpack { // Handle unpacked TypeVarTuple's tuple_extend if let Ok(tuple) = substituted_arg.try_to_ref::<PyTuple>(vm) { for elem in tuple { new_args.push(elem.clone()); } } else { // This shouldn't happen but handle gracefully new_args.push(substituted_arg); } } else { new_args.push(substituted_arg); } } Ok(PyTuple::new_ref(new_args, &vm.ctx)) } impl AsMapping for PyGenericAlias { fn as_mapping() -> &'static PyMappingMethods { static AS_MAPPING: LazyLock<PyMappingMethods> = LazyLock::new(|| PyMappingMethods { subscript: atomic_func!(|mapping, needle, vm| { let zelf = PyGenericAlias::mapping_downcast(mapping); PyGenericAlias::__getitem__(zelf.to_owned(), needle.to_owned(), vm) }), ..PyMappingMethods::NOT_IMPLEMENTED }); &AS_MAPPING } } impl AsNumber for PyGenericAlias { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { or: Some(|a, b, vm| Ok(PyGenericAlias::__or__(a.to_owned(), b.to_owned(), vm))), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } } impl Callable for PyGenericAlias { type Args = FuncArgs; fn call(zelf: &Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult { PyType::call(&zelf.origin, args, vm).map(|obj| { if let Err(exc) = obj.set_attr(identifier!(vm, __orig_class__), zelf.to_owned(), vm) && !exc.fast_isinstance(vm.ctx.exceptions.attribute_error) && !exc.fast_isinstance(vm.ctx.exceptions.type_error) { return Err(exc); } Ok(obj) })? } } impl Comparable for PyGenericAlias { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { op.eq_only(|| { let other = class_or_notimplemented!(Self, other); Ok(PyComparisonValue::Implemented( if !zelf.__origin__().rich_compare_bool( &other.__origin__(), PyComparisonOp::Eq, vm, )? { false } else { zelf.__args__() .rich_compare_bool(&other.__args__(), PyComparisonOp::Eq, vm)? }, )) }) } } impl Hashable for PyGenericAlias { #[inline] fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<hash::PyHash> { Ok(zelf.origin.as_object().hash(vm)? ^ zelf.args.as_object().hash(vm)?) } } impl GetAttr for PyGenericAlias { fn getattro(zelf: &Py<Self>, attr: &Py<PyStr>, vm: &VirtualMachine) -> PyResult { for exc in &ATTR_EXCEPTIONS { if *(*exc) == attr.to_string() { return zelf.as_object().generic_getattr(attr, vm); } } zelf.__origin__().get_attr(attr, vm) } } impl Representable for PyGenericAlias { #[inline] fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { zelf.repr(vm) } } impl Iterable for PyGenericAlias { // ga_iter // spell-checker:ignore gaiterobject // TODO: gaiterobject fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { // CPython's ga_iter creates an iterator that yields one starred GenericAlias // we don't have gaiterobject yet let starred_alias = Self::new( zelf.origin.clone(), zelf.args.clone(), true, // starred vm, ); let starred_ref = PyRef::new_ref( starred_alias, vm.ctx.types.generic_alias_type.to_owned(), None, ); let items = vec![starred_ref.into()]; let iter_tuple = PyTuple::new_ref(items, &vm.ctx); Ok(iter_tuple.to_pyobject(vm).get_iter(vm)?.into()) } } /// Creates a GenericAlias from type parameters, equivalent to CPython's _Py_subscript_generic /// This is used for PEP 695 classes to create Generic[T] from type parameters // _Py_subscript_generic pub fn subscript_generic(type_params: PyObjectRef, vm: &VirtualMachine) -> PyResult { // Get typing module and _GenericAlias let typing_module = vm.import("typing", 0)?; let generic_type = typing_module.get_attr("Generic", vm)?; // Call typing._GenericAlias(Generic, type_params) let generic_alias_class = typing_module.get_attr("_GenericAlias", vm)?; let args = if let Ok(tuple) = type_params.try_to_ref::<PyTuple>(vm) { tuple.to_owned() } else { PyTuple::new_ref(vec![type_params], &vm.ctx) }; // Create _GenericAlias instance generic_alias_class.call((generic_type, args.to_pyobject(vm)), vm) } pub fn init(context: &Context) { let generic_alias_type = &context.types.generic_alias_type; PyGenericAlias::extend_class(context, generic_alias_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/weakref.rs
crates/vm/src/builtins/weakref.rs
use super::{PyGenericAlias, PyType, PyTypeRef}; use crate::common::{ atomic::{Ordering, Radium}, hash::{self, PyHash}, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, class::PyClassImpl, function::{FuncArgs, OptionalArg}, types::{ Callable, Comparable, Constructor, Hashable, Initializer, PyComparisonOp, Representable, }, }; pub use crate::object::PyWeak; #[derive(FromArgs)] pub struct WeakNewArgs { #[pyarg(positional)] referent: PyObjectRef, #[pyarg(positional, optional)] callback: OptionalArg<PyObjectRef>, } impl PyPayload for PyWeak { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.weakref_type } } impl Callable for PyWeak { type Args = (); #[inline] fn call(zelf: &Py<Self>, _: Self::Args, vm: &VirtualMachine) -> PyResult { Ok(vm.unwrap_or_none(zelf.upgrade())) } } impl Constructor for PyWeak { type Args = WeakNewArgs; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let Self::Args { referent, callback } = args.bind(vm)?; let weak = referent.downgrade_with_typ(callback.into_option(), cls, vm)?; Ok(weak.into()) } fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> { unimplemented!("use slot_new") } } impl Initializer for PyWeak { type Args = WeakNewArgs; // weakref_tp_init: accepts args but does nothing (all init done in slot_new) fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> { Ok(()) } } #[pyclass( with( Callable, Hashable, Comparable, Constructor, Initializer, Representable ), flags(BASETYPE) )] impl PyWeak { #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } impl Hashable for PyWeak { fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> { let hash = match zelf.hash.load(Ordering::Relaxed) { hash::SENTINEL => { let obj = zelf .upgrade() .ok_or_else(|| vm.new_type_error("weak object has gone away"))?; let hash = obj.hash(vm)?; match Radium::compare_exchange( &zelf.hash, hash::SENTINEL, hash::fix_sentinel(hash), Ordering::Relaxed, Ordering::Relaxed, ) { Ok(_) => hash, Err(prev_stored) => prev_stored, } } hash => hash, }; Ok(hash) } } impl Comparable for PyWeak { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<crate::function::PyComparisonValue> { op.eq_only(|| { let other = class_or_notimplemented!(Self, other); let both = zelf.upgrade().and_then(|s| other.upgrade().map(|o| (s, o))); let eq = match both { Some((a, b)) => vm.bool_eq(&a, &b)?, None => zelf.is(other), }; Ok(eq.into()) }) } } impl Representable for PyWeak { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { let id = zelf.get_id(); let repr = if let Some(o) = zelf.upgrade() { format!( "<weakref at {:#x}; to '{}' at {:#x}>", id, o.class().name(), o.get_id(), ) } else { format!("<weakref at {id:#x}; dead>") }; Ok(repr) } } pub fn init(context: &Context) { PyWeak::extend_class(context, context.types.weakref_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/iter.rs
crates/vm/src/builtins/iter.rs
/* * iterator types */ use super::{PyInt, PyTupleRef, PyType}; use crate::{ Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, class::PyClassImpl, function::ArgCallable, object::{Traverse, TraverseFn}, protocol::PyIterReturn, types::{IterNext, Iterable, SelfIter}, }; use rustpython_common::{ lock::{PyMutex, PyRwLock, PyRwLockUpgradableReadGuard}, static_cell, }; /// Marks status of iterator. #[derive(Debug, Clone)] pub enum IterStatus<T> { /// Iterator hasn't raised StopIteration. Active(T), /// Iterator has raised StopIteration. Exhausted, } unsafe impl<T: Traverse> Traverse for IterStatus<T> { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { match self { Self::Active(r) => r.traverse(tracer_fn), Self::Exhausted => (), } } } #[derive(Debug)] pub struct PositionIterInternal<T> { pub status: IterStatus<T>, pub position: usize, } unsafe impl<T: Traverse> Traverse for PositionIterInternal<T> { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { self.status.traverse(tracer_fn) } } impl<T> PositionIterInternal<T> { pub const fn new(obj: T, position: usize) -> Self { Self { status: IterStatus::Active(obj), position, } } pub fn set_state<F>(&mut self, state: PyObjectRef, f: F, vm: &VirtualMachine) -> PyResult<()> where F: FnOnce(&T, usize) -> usize, { if let IterStatus::Active(obj) = &self.status { if let Some(i) = state.downcast_ref::<PyInt>() { let i = i.try_to_primitive(vm).unwrap_or(0); self.position = f(obj, i); Ok(()) } else { Err(vm.new_type_error("an integer is required.")) } } else { Ok(()) } } fn _reduce<F>(&self, func: PyObjectRef, f: F, vm: &VirtualMachine) -> PyTupleRef where F: FnOnce(&T) -> PyObjectRef, { if let IterStatus::Active(obj) = &self.status { vm.new_tuple((func, (f(obj),), self.position)) } else { vm.new_tuple((func, (vm.ctx.new_list(Vec::new()),))) } } pub fn builtins_iter_reduce<F>(&self, f: F, vm: &VirtualMachine) -> PyTupleRef where F: FnOnce(&T) -> PyObjectRef, { let iter = builtins_iter(vm).to_owned(); self._reduce(iter, f, vm) } pub fn builtins_reversed_reduce<F>(&self, f: F, vm: &VirtualMachine) -> PyTupleRef where F: FnOnce(&T) -> PyObjectRef, { let reversed = builtins_reversed(vm).to_owned(); self._reduce(reversed, f, vm) } fn _next<F, OP>(&mut self, f: F, op: OP) -> PyResult<PyIterReturn> where F: FnOnce(&T, usize) -> PyResult<PyIterReturn>, OP: FnOnce(&mut Self), { if let IterStatus::Active(obj) = &self.status { let ret = f(obj, self.position); if let Ok(PyIterReturn::Return(_)) = ret { op(self); } else { self.status = IterStatus::Exhausted; } ret } else { Ok(PyIterReturn::StopIteration(None)) } } pub fn next<F>(&mut self, f: F) -> PyResult<PyIterReturn> where F: FnOnce(&T, usize) -> PyResult<PyIterReturn>, { self._next(f, |zelf| zelf.position += 1) } pub fn rev_next<F>(&mut self, f: F) -> PyResult<PyIterReturn> where F: FnOnce(&T, usize) -> PyResult<PyIterReturn>, { self._next(f, |zelf| { if zelf.position == 0 { zelf.status = IterStatus::Exhausted; } else { zelf.position -= 1; } }) } pub fn length_hint<F>(&self, f: F) -> usize where F: FnOnce(&T) -> usize, { if let IterStatus::Active(obj) = &self.status { f(obj).saturating_sub(self.position) } else { 0 } } pub fn rev_length_hint<F>(&self, f: F) -> usize where F: FnOnce(&T) -> usize, { if let IterStatus::Active(obj) = &self.status && self.position <= f(obj) { return self.position + 1; } 0 } } pub fn builtins_iter(vm: &VirtualMachine) -> &PyObject { static_cell! { static INSTANCE: PyObjectRef; } INSTANCE.get_or_init(|| vm.builtins.get_attr("iter", vm).unwrap()) } pub fn builtins_reversed(vm: &VirtualMachine) -> &PyObject { static_cell! { static INSTANCE: PyObjectRef; } INSTANCE.get_or_init(|| vm.builtins.get_attr("reversed", vm).unwrap()) } #[pyclass(module = false, name = "iterator", traverse)] #[derive(Debug)] pub struct PySequenceIterator { internal: PyMutex<PositionIterInternal<PyObjectRef>>, } impl PyPayload for PySequenceIterator { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.iter_type } } #[pyclass(with(IterNext, Iterable))] impl PySequenceIterator { pub fn new(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> { let _seq = obj.try_sequence(vm)?; Ok(Self { internal: PyMutex::new(PositionIterInternal::new(obj, 0)), }) } #[pymethod] fn __length_hint__(&self, vm: &VirtualMachine) -> PyObjectRef { let internal = self.internal.lock(); if let IterStatus::Active(obj) = &internal.status { let seq = obj.sequence_unchecked(); seq.length(vm) .map(|x| PyInt::from(x).into_pyobject(vm)) .unwrap_or_else(|_| vm.ctx.not_implemented()) } else { PyInt::from(0).into_pyobject(vm) } } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef { self.internal.lock().builtins_iter_reduce(|x| x.clone(), vm) } #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal.lock().set_state(state, |_, pos| pos, vm) } } impl SelfIter for PySequenceIterator {} impl IterNext for PySequenceIterator { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { zelf.internal.lock().next(|obj, pos| { let seq = obj.sequence_unchecked(); PyIterReturn::from_getitem_result(seq.get_item(pos as isize, vm), vm) }) } } #[pyclass(module = false, name = "callable_iterator", traverse)] #[derive(Debug)] pub struct PyCallableIterator { sentinel: PyObjectRef, status: PyRwLock<IterStatus<ArgCallable>>, } impl PyPayload for PyCallableIterator { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.callable_iterator } } #[pyclass(with(IterNext, Iterable))] impl PyCallableIterator { pub const fn new(callable: ArgCallable, sentinel: PyObjectRef) -> Self { Self { sentinel, status: PyRwLock::new(IterStatus::Active(callable)), } } } impl SelfIter for PyCallableIterator {} impl IterNext for PyCallableIterator { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let status = zelf.status.upgradable_read(); let next = if let IterStatus::Active(callable) = &*status { let ret = callable.invoke((), vm)?; if vm.bool_eq(&ret, &zelf.sentinel)? { *PyRwLockUpgradableReadGuard::upgrade(status) = IterStatus::Exhausted; PyIterReturn::StopIteration(None) } else { PyIterReturn::Return(ret) } } else { PyIterReturn::StopIteration(None) }; Ok(next) } } pub fn init(context: &Context) { PySequenceIterator::extend_class(context, context.types.iter_type); PyCallableIterator::extend_class(context, context.types.callable_iterator); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/set.rs
crates/vm/src/builtins/set.rs
/* * Builtin set type with a sequence of unique items. */ use super::{ IterStatus, PositionIterInternal, PyDict, PyDictRef, PyGenericAlias, PyTupleRef, PyType, PyTypeRef, builtins_iter, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, atomic_func, class::PyClassImpl, common::{ascii, hash::PyHash, lock::PyMutex, rc::PyRc}, convert::ToPyResult, dict_inner::{self, DictSize}, function::{ArgIterable, FuncArgs, OptionalArg, PosArgs, PyArithmeticValue, PyComparisonValue}, protocol::{PyIterReturn, PyNumberMethods, PySequenceMethods}, recursion::ReprGuard, types::AsNumber, types::{ AsSequence, Comparable, Constructor, DefaultConstructor, Hashable, Initializer, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, }, utils::collection_repr, vm::VirtualMachine, }; use alloc::fmt; use core::ops::Deref; use rustpython_common::{ atomic::{Ordering, PyAtomic, Radium}, hash, }; use std::sync::LazyLock; pub type SetContentType = dict_inner::Dict<()>; #[pyclass(module = false, name = "set", unhashable = true, traverse)] #[derive(Default)] pub struct PySet { pub(super) inner: PySetInner, } impl PySet { #[deprecated(note = "Use `PySet::default().into_ref(ctx)` instead")] pub fn new_ref(ctx: &Context) -> PyRef<Self> { Self::default().into_ref(ctx) } pub fn elements(&self) -> Vec<PyObjectRef> { self.inner.elements() } fn fold_op( &self, others: impl core::iter::Iterator<Item = ArgIterable>, op: fn(&PySetInner, ArgIterable, &VirtualMachine) -> PyResult<PySetInner>, vm: &VirtualMachine, ) -> PyResult<Self> { Ok(Self { inner: self.inner.fold_op(others, op, vm)?, }) } fn op( &self, other: AnySet, op: fn(&PySetInner, ArgIterable, &VirtualMachine) -> PyResult<PySetInner>, vm: &VirtualMachine, ) -> PyResult<Self> { Ok(Self { inner: self .inner .fold_op(core::iter::once(other.into_iterable(vm)?), op, vm)?, }) } } #[pyclass(module = false, name = "frozenset", unhashable = true)] pub struct PyFrozenSet { inner: PySetInner, hash: PyAtomic<PyHash>, } impl Default for PyFrozenSet { fn default() -> Self { Self { inner: PySetInner::default(), hash: hash::SENTINEL.into(), } } } impl PyFrozenSet { // Also used by ssl.rs windows. pub fn from_iter( vm: &VirtualMachine, it: impl IntoIterator<Item = PyObjectRef>, ) -> PyResult<Self> { let inner = PySetInner::default(); for elem in it { inner.add(elem, vm)?; } // FIXME: empty set check Ok(Self { inner, ..Default::default() }) } pub fn elements(&self) -> Vec<PyObjectRef> { self.inner.elements() } fn fold_op( &self, others: impl core::iter::Iterator<Item = ArgIterable>, op: fn(&PySetInner, ArgIterable, &VirtualMachine) -> PyResult<PySetInner>, vm: &VirtualMachine, ) -> PyResult<Self> { Ok(Self { inner: self.inner.fold_op(others, op, vm)?, ..Default::default() }) } fn op( &self, other: AnySet, op: fn(&PySetInner, ArgIterable, &VirtualMachine) -> PyResult<PySetInner>, vm: &VirtualMachine, ) -> PyResult<Self> { Ok(Self { inner: self .inner .fold_op(core::iter::once(other.into_iterable(vm)?), op, vm)?, ..Default::default() }) } } impl fmt::Debug for PySet { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // TODO: implement more detailed, non-recursive Debug formatter f.write_str("set") } } impl fmt::Debug for PyFrozenSet { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // TODO: implement more detailed, non-recursive Debug formatter f.write_str("PyFrozenSet ")?; f.debug_set().entries(self.elements().iter()).finish() } } impl PyPayload for PySet { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.set_type } } impl PyPayload for PyFrozenSet { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.frozenset_type } } #[derive(Default, Clone)] pub(super) struct PySetInner { content: PyRc<SetContentType>, } unsafe impl crate::object::Traverse for PySetInner { fn traverse(&self, tracer_fn: &mut crate::object::TraverseFn<'_>) { // FIXME(discord9): Rc means shared ref, so should it be traced? self.content.traverse(tracer_fn) } } impl PySetInner { pub(super) fn from_iter<T>(iter: T, vm: &VirtualMachine) -> PyResult<Self> where T: IntoIterator<Item = PyResult<PyObjectRef>>, { let set = Self::default(); for item in iter { set.add(item?, vm)?; } Ok(set) } fn fold_op<O>( &self, others: impl core::iter::Iterator<Item = O>, op: fn(&Self, O, &VirtualMachine) -> PyResult<Self>, vm: &VirtualMachine, ) -> PyResult<Self> { let mut res = self.copy(); for other in others { res = op(&res, other, vm)?; } Ok(res) } fn len(&self) -> usize { self.content.len() } fn sizeof(&self) -> usize { self.content.sizeof() } fn copy(&self) -> Self { Self { content: PyRc::new((*self.content).clone()), } } fn contains(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<bool> { self.retry_op_with_frozenset(needle, vm, |needle, vm| self.content.contains(vm, needle)) } fn compare(&self, other: &Self, op: PyComparisonOp, vm: &VirtualMachine) -> PyResult<bool> { if op == PyComparisonOp::Ne { return self.compare(other, PyComparisonOp::Eq, vm).map(|eq| !eq); } if !op.eval_ord(self.len().cmp(&other.len())) { return Ok(false); } let (superset, subset) = match op { PyComparisonOp::Lt | PyComparisonOp::Le => (other, self), _ => (self, other), }; for key in subset.elements() { if !superset.contains(&key, vm)? { return Ok(false); } } Ok(true) } pub(super) fn union(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<Self> { let set = self.clone(); for item in other.iter(vm)? { set.add(item?, vm)?; } Ok(set) } pub(super) fn intersection(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<Self> { let set = Self::default(); for item in other.iter(vm)? { let obj = item?; if self.contains(&obj, vm)? { set.add(obj, vm)?; } } Ok(set) } pub(super) fn difference(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<Self> { let set = self.copy(); for item in other.iter(vm)? { set.content.delete_if_exists(vm, &*item?)?; } Ok(set) } pub(super) fn symmetric_difference( &self, other: ArgIterable, vm: &VirtualMachine, ) -> PyResult<Self> { let new_inner = self.clone(); // We want to remove duplicates in other let other_set = Self::from_iter(other.iter(vm)?, vm)?; for item in other_set.elements() { new_inner.content.delete_or_insert(vm, &item, ())? } Ok(new_inner) } fn issuperset(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<bool> { for item in other.iter(vm)? { if !self.contains(&*item?, vm)? { return Ok(false); } } Ok(true) } fn issubset(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<bool> { let other_set = Self::from_iter(other.iter(vm)?, vm)?; self.compare(&other_set, PyComparisonOp::Le, vm) } pub(super) fn isdisjoint(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<bool> { for item in other.iter(vm)? { if self.contains(&*item?, vm)? { return Ok(false); } } Ok(true) } fn iter(&self) -> PySetIterator { PySetIterator { size: self.content.size(), internal: PyMutex::new(PositionIterInternal::new(self.content.clone(), 0)), } } fn repr(&self, class_name: Option<&str>, vm: &VirtualMachine) -> PyResult<String> { collection_repr(class_name, "{", "}", self.elements().iter(), vm) } fn add(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.content.insert(vm, &*item, ()) } fn remove(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.retry_op_with_frozenset(&item, vm, |item, vm| self.content.delete(vm, item)) } fn discard(&self, item: &PyObject, vm: &VirtualMachine) -> PyResult<bool> { self.retry_op_with_frozenset(item, vm, |item, vm| self.content.delete_if_exists(vm, item)) } fn clear(&self) { self.content.clear() } fn elements(&self) -> Vec<PyObjectRef> { self.content.keys() } fn pop(&self, vm: &VirtualMachine) -> PyResult { // TODO: should be pop_front, but that requires rearranging every index if let Some((key, _)) = self.content.pop_back() { Ok(key) } else { let err_msg = vm.ctx.new_str(ascii!("pop from an empty set")).into(); Err(vm.new_key_error(err_msg)) } } fn update( &self, others: impl core::iter::Iterator<Item = ArgIterable>, vm: &VirtualMachine, ) -> PyResult<()> { for iterable in others { for item in iterable.iter(vm)? { self.add(item?, vm)?; } } Ok(()) } fn update_internal(&self, iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { // check AnySet if let Ok(any_set) = AnySet::try_from_object(vm, iterable.to_owned()) { self.merge_set(any_set, vm) // check Dict } else if let Ok(dict) = iterable.to_owned().downcast_exact::<PyDict>(vm) { self.merge_dict(dict.into_pyref(), vm) } else { // add iterable that is not AnySet or Dict for item in iterable.try_into_value::<ArgIterable>(vm)?.iter(vm)? { self.add(item?, vm)?; } Ok(()) } } fn merge_set(&self, any_set: AnySet, vm: &VirtualMachine) -> PyResult<()> { for item in any_set.as_inner().elements() { self.add(item, vm)?; } Ok(()) } fn merge_dict(&self, dict: PyDictRef, vm: &VirtualMachine) -> PyResult<()> { for (key, _value) in dict { self.add(key, vm)?; } Ok(()) } fn intersection_update( &self, others: impl core::iter::Iterator<Item = ArgIterable>, vm: &VirtualMachine, ) -> PyResult<()> { let temp_inner = self.fold_op(others, Self::intersection, vm)?; self.clear(); for obj in temp_inner.elements() { self.add(obj, vm)?; } Ok(()) } fn difference_update( &self, others: impl core::iter::Iterator<Item = ArgIterable>, vm: &VirtualMachine, ) -> PyResult<()> { for iterable in others { let items = iterable.iter(vm)?.collect::<Result<Vec<_>, _>>()?; for item in items { self.content.delete_if_exists(vm, &*item)?; } } Ok(()) } fn symmetric_difference_update( &self, others: impl core::iter::Iterator<Item = ArgIterable>, vm: &VirtualMachine, ) -> PyResult<()> { for iterable in others { // We want to remove duplicates in iterable let iterable_set = Self::from_iter(iterable.iter(vm)?, vm)?; for item in iterable_set.elements() { self.content.delete_or_insert(vm, &item, ())?; } } Ok(()) } fn hash(&self, vm: &VirtualMachine) -> PyResult<PyHash> { // Work to increase the bit dispersion for closely spaced hash values. // This is important because some use cases have many combinations of a // small number of elements with nearby hashes so that many distinct // combinations collapse to only a handful of distinct hash values. const fn _shuffle_bits(h: u64) -> u64 { ((h ^ 89869747) ^ (h.wrapping_shl(16))).wrapping_mul(3644798167) } // Factor in the number of active entries let mut hash: u64 = (self.len() as u64 + 1).wrapping_mul(1927868237); // Xor-in shuffled bits from every entry's hash field because xor is // commutative and a frozenset hash should be independent of order. hash = self.content.try_fold_keys(hash, |h, element| { Ok(h ^ _shuffle_bits(element.hash(vm)? as u64)) })?; // Disperse patterns arising in nested frozen-sets hash ^= (hash >> 11) ^ (hash >> 25); hash = hash.wrapping_mul(69069).wrapping_add(907133923); // -1 is reserved as an error code if hash == u64::MAX { hash = 590923713; } Ok(hash as PyHash) } // Run operation, on failure, if item is a set/set subclass, convert it // into a frozenset and try the operation again. Propagates original error // on failure to convert and restores item in KeyError on failure (remove). fn retry_op_with_frozenset<T, F>( &self, item: &PyObject, vm: &VirtualMachine, op: F, ) -> PyResult<T> where F: Fn(&PyObject, &VirtualMachine) -> PyResult<T>, { op(item, vm).or_else(|original_err| { item.downcast_ref::<PySet>() // Keep original error around. .ok_or(original_err) .and_then(|set| { op( &PyFrozenSet { inner: set.inner.copy(), ..Default::default() } .into_pyobject(vm), vm, ) // If operation raised KeyError, report original set (set.remove) .map_err(|op_err| { if op_err.fast_isinstance(vm.ctx.exceptions.key_error) { vm.new_key_error(item.to_owned()) } else { op_err } }) }) }) } } fn extract_set(obj: &PyObject) -> Option<&PySetInner> { match_class!(match obj { ref set @ PySet => Some(&set.inner), ref frozen @ PyFrozenSet => Some(&frozen.inner), _ => None, }) } fn reduce_set( zelf: &PyObject, vm: &VirtualMachine, ) -> PyResult<(PyTypeRef, PyTupleRef, Option<PyDictRef>)> { Ok(( zelf.class().to_owned(), vm.new_tuple((extract_set(zelf) .unwrap_or(&PySetInner::default()) .elements(),)), zelf.dict(), )) } #[pyclass( with( Constructor, Initializer, AsSequence, Comparable, Iterable, AsNumber, Representable ), flags(BASETYPE, _MATCH_SELF) )] impl PySet { fn __len__(&self) -> usize { self.inner.len() } fn __contains__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<bool> { self.inner.contains(needle, vm) } #[pymethod] fn __sizeof__(&self) -> usize { core::mem::size_of::<Self>() + self.inner.sizeof() } #[pymethod] fn copy(&self) -> Self { Self { inner: self.inner.copy(), } } #[pymethod] fn union(&self, others: PosArgs<ArgIterable>, vm: &VirtualMachine) -> PyResult<Self> { self.fold_op(others.into_iter(), PySetInner::union, vm) } #[pymethod] fn intersection(&self, others: PosArgs<ArgIterable>, vm: &VirtualMachine) -> PyResult<Self> { self.fold_op(others.into_iter(), PySetInner::intersection, vm) } #[pymethod] fn difference(&self, others: PosArgs<ArgIterable>, vm: &VirtualMachine) -> PyResult<Self> { self.fold_op(others.into_iter(), PySetInner::difference, vm) } #[pymethod] fn symmetric_difference( &self, others: PosArgs<ArgIterable>, vm: &VirtualMachine, ) -> PyResult<Self> { self.fold_op(others.into_iter(), PySetInner::symmetric_difference, vm) } #[pymethod] fn issubset(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<bool> { self.inner.issubset(other, vm) } #[pymethod] fn issuperset(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<bool> { self.inner.issuperset(other, vm) } #[pymethod] fn isdisjoint(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<bool> { self.inner.isdisjoint(other, vm) } fn __or__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<Self>> { if let Ok(other) = AnySet::try_from_object(vm, other) { Ok(PyArithmeticValue::Implemented(self.op( other, PySetInner::union, vm, )?)) } else { Ok(PyArithmeticValue::NotImplemented) } } fn __and__( &self, other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyArithmeticValue<Self>> { if let Ok(other) = AnySet::try_from_object(vm, other) { Ok(PyArithmeticValue::Implemented(self.op( other, PySetInner::intersection, vm, )?)) } else { Ok(PyArithmeticValue::NotImplemented) } } fn __sub__( &self, other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyArithmeticValue<Self>> { if let Ok(other) = AnySet::try_from_object(vm, other) { Ok(PyArithmeticValue::Implemented(self.op( other, PySetInner::difference, vm, )?)) } else { Ok(PyArithmeticValue::NotImplemented) } } fn __rsub__( zelf: PyRef<Self>, other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyArithmeticValue<Self>> { if let Ok(other) = AnySet::try_from_object(vm, other) { Ok(PyArithmeticValue::Implemented(Self { inner: other .as_inner() .difference(ArgIterable::try_from_object(vm, zelf.into())?, vm)?, })) } else { Ok(PyArithmeticValue::NotImplemented) } } fn __xor__( &self, other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<PyArithmeticValue<Self>> { if let Ok(other) = AnySet::try_from_object(vm, other) { Ok(PyArithmeticValue::Implemented(self.op( other, PySetInner::symmetric_difference, vm, )?)) } else { Ok(PyArithmeticValue::NotImplemented) } } #[pymethod] pub fn add(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.inner.add(item, vm)?; Ok(()) } #[pymethod] fn remove(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.inner.remove(item, vm) } #[pymethod] fn discard(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.inner.discard(&item, vm)?; Ok(()) } #[pymethod] fn clear(&self) { self.inner.clear() } #[pymethod] fn pop(&self, vm: &VirtualMachine) -> PyResult { self.inner.pop(vm) } fn __ior__(zelf: PyRef<Self>, set: AnySet, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { zelf.inner.update(set.into_iterable_iter(vm)?, vm)?; Ok(zelf) } #[pymethod] fn update(&self, others: PosArgs<PyObjectRef>, vm: &VirtualMachine) -> PyResult<()> { for iterable in others { self.inner.update_internal(iterable, vm)?; } Ok(()) } #[pymethod] fn intersection_update( &self, others: PosArgs<ArgIterable>, vm: &VirtualMachine, ) -> PyResult<()> { self.inner.intersection_update(others.into_iter(), vm)?; Ok(()) } fn __iand__(zelf: PyRef<Self>, set: AnySet, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { zelf.inner .intersection_update(core::iter::once(set.into_iterable(vm)?), vm)?; Ok(zelf) } #[pymethod] fn difference_update(&self, others: PosArgs<ArgIterable>, vm: &VirtualMachine) -> PyResult<()> { self.inner.difference_update(others.into_iter(), vm)?; Ok(()) } fn __isub__(zelf: PyRef<Self>, set: AnySet, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { zelf.inner .difference_update(set.into_iterable_iter(vm)?, vm)?; Ok(zelf) } #[pymethod] fn symmetric_difference_update( &self, others: PosArgs<ArgIterable>, vm: &VirtualMachine, ) -> PyResult<()> { self.inner .symmetric_difference_update(others.into_iter(), vm)?; Ok(()) } fn __ixor__(zelf: PyRef<Self>, set: AnySet, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { zelf.inner .symmetric_difference_update(set.into_iterable_iter(vm)?, vm)?; Ok(zelf) } #[pymethod] fn __reduce__( zelf: PyRef<Self>, vm: &VirtualMachine, ) -> PyResult<(PyTypeRef, PyTupleRef, Option<PyDictRef>)> { reduce_set(zelf.as_ref(), vm) } #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } impl DefaultConstructor for PySet {} impl Initializer for PySet { type Args = OptionalArg<PyObjectRef>; fn init(zelf: PyRef<Self>, iterable: Self::Args, vm: &VirtualMachine) -> PyResult<()> { zelf.clear(); if let OptionalArg::Present(it) = iterable { zelf.update(PosArgs::new(vec![it]), vm)?; } Ok(()) } } impl AsSequence for PySet { fn as_sequence() -> &'static PySequenceMethods { static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods { length: atomic_func!(|seq, _vm| Ok(PySet::sequence_downcast(seq).__len__())), contains: atomic_func!( |seq, needle, vm| PySet::sequence_downcast(seq).__contains__(needle, vm) ), ..PySequenceMethods::NOT_IMPLEMENTED }); &AS_SEQUENCE } } impl Comparable for PySet { fn cmp( zelf: &crate::Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { extract_set(other).map_or(Ok(PyComparisonValue::NotImplemented), |other| { Ok(zelf.inner.compare(other, op, vm)?.into()) }) } } impl Iterable for PySet { fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { Ok(zelf.inner.iter().into_pyobject(vm)) } } impl AsNumber for PySet { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { // Binary ops check both operands are sets (like CPython's set_sub, etc.) // This is needed because __rsub__ swaps operands: a.__rsub__(b) calls subtract(b, a) subtract: Some(|a, b, vm| { if !AnySet::check(a, vm) || !AnySet::check(b, vm) { return Ok(vm.ctx.not_implemented()); } if let Some(a) = a.downcast_ref::<PySet>() { a.__sub__(b.to_owned(), vm).to_pyresult(vm) } else if let Some(a) = a.downcast_ref::<PyFrozenSet>() { // When called via __rsub__, a might be PyFrozenSet a.__sub__(b.to_owned(), vm) .map(|r| { r.map(|s| PySet { inner: s.inner.clone(), }) }) .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } }), and: Some(|a, b, vm| { if !AnySet::check(a, vm) || !AnySet::check(b, vm) { return Ok(vm.ctx.not_implemented()); } if let Some(a) = a.downcast_ref::<PySet>() { a.__and__(b.to_owned(), vm).to_pyresult(vm) } else if let Some(a) = a.downcast_ref::<PyFrozenSet>() { a.__and__(b.to_owned(), vm) .map(|r| { r.map(|s| PySet { inner: s.inner.clone(), }) }) .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } }), xor: Some(|a, b, vm| { if !AnySet::check(a, vm) || !AnySet::check(b, vm) { return Ok(vm.ctx.not_implemented()); } if let Some(a) = a.downcast_ref::<PySet>() { a.__xor__(b.to_owned(), vm).to_pyresult(vm) } else if let Some(a) = a.downcast_ref::<PyFrozenSet>() { a.__xor__(b.to_owned(), vm) .map(|r| { r.map(|s| PySet { inner: s.inner.clone(), }) }) .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } }), or: Some(|a, b, vm| { if !AnySet::check(a, vm) || !AnySet::check(b, vm) { return Ok(vm.ctx.not_implemented()); } if let Some(a) = a.downcast_ref::<PySet>() { a.__or__(b.to_owned(), vm).to_pyresult(vm) } else if let Some(a) = a.downcast_ref::<PyFrozenSet>() { a.__or__(b.to_owned(), vm) .map(|r| { r.map(|s| PySet { inner: s.inner.clone(), }) }) .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } }), inplace_subtract: Some(|a, b, vm| { if let Some(a) = a.downcast_ref::<PySet>() { PySet::__isub__(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm) .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } }), inplace_and: Some(|a, b, vm| { if let Some(a) = a.downcast_ref::<PySet>() { PySet::__iand__(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm) .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } }), inplace_xor: Some(|a, b, vm| { if let Some(a) = a.downcast_ref::<PySet>() { PySet::__ixor__(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm) .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } }), inplace_or: Some(|a, b, vm| { if let Some(a) = a.downcast_ref::<PySet>() { PySet::__ior__(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm) .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } }), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } } impl Representable for PySet { #[inline] fn repr_str(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<String> { let class = zelf.class(); let borrowed_name = class.name(); let class_name = borrowed_name.deref(); let s = if zelf.inner.len() == 0 { format!("{class_name}()") } else if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { let name = if class_name != "set" { Some(class_name) } else { None }; zelf.inner.repr(name, vm)? } else { format!("{class_name}(...)") }; Ok(s) } } impl Constructor for PyFrozenSet { type Args = Vec<PyObjectRef>; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let iterable: OptionalArg<PyObjectRef> = args.bind(vm)?; // Optimizations for exact frozenset type if cls.is(vm.ctx.types.frozenset_type) { // Return exact frozenset as-is if let OptionalArg::Present(ref input) = iterable && let Ok(fs) = input.clone().downcast_exact::<PyFrozenSet>(vm) { return Ok(fs.into_pyref().into()); } // Return empty frozenset singleton if iterable.is_missing() { return Ok(vm.ctx.empty_frozenset.clone().into()); } } let elements: Vec<PyObjectRef> = if let OptionalArg::Present(iterable) = iterable { iterable.try_to_value(vm)? } else { vec![] }; // Return empty frozenset singleton for exact frozenset types (when iterable was empty) if elements.is_empty() && cls.is(vm.ctx.types.frozenset_type) { return Ok(vm.ctx.empty_frozenset.clone().into()); } let payload = Self::py_new(&cls, elements, vm)?; payload.into_ref_with_type(vm, cls).map(Into::into) } fn py_new(_cls: &Py<PyType>, elements: Self::Args, vm: &VirtualMachine) -> PyResult<Self> { Self::from_iter(vm, elements) } } #[pyclass( flags(BASETYPE, _MATCH_SELF), with( Constructor, AsSequence, Hashable, Comparable, Iterable, AsNumber, Representable ) )] impl PyFrozenSet { fn __len__(&self) -> usize { self.inner.len() } fn __contains__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<bool> { self.inner.contains(needle, vm) } #[pymethod] fn __sizeof__(&self) -> usize { core::mem::size_of::<Self>() + self.inner.sizeof() } #[pymethod] fn copy(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRef<Self> { if zelf.class().is(vm.ctx.types.frozenset_type) { zelf } else { Self { inner: zelf.inner.copy(), ..Default::default() } .into_ref(&vm.ctx) } } #[pymethod] fn union(&self, others: PosArgs<ArgIterable>, vm: &VirtualMachine) -> PyResult<Self> { self.fold_op(others.into_iter(), PySetInner::union, vm) } #[pymethod] fn intersection(&self, others: PosArgs<ArgIterable>, vm: &VirtualMachine) -> PyResult<Self> { self.fold_op(others.into_iter(), PySetInner::intersection, vm) } #[pymethod] fn difference(&self, others: PosArgs<ArgIterable>, vm: &VirtualMachine) -> PyResult<Self> { self.fold_op(others.into_iter(), PySetInner::difference, vm) } #[pymethod] fn symmetric_difference( &self, others: PosArgs<ArgIterable>, vm: &VirtualMachine, ) -> PyResult<Self> { self.fold_op(others.into_iter(), PySetInner::symmetric_difference, vm) } #[pymethod] fn issubset(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<bool> { self.inner.issubset(other, vm) }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/str.rs
crates/vm/src/builtins/str.rs
use super::{ PositionIterInternal, PyBytesRef, PyDict, PyTupleRef, PyType, PyTypeRef, int::{PyInt, PyIntRef}, iter::IterStatus::{self, Exhausted}, }; use crate::{ AsObject, Context, Py, PyExact, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact, PyResult, TryFromBorrowedObject, VirtualMachine, anystr::{self, AnyStr, AnyStrContainer, AnyStrWrapper, adjust_indices}, atomic_func, cformat::cformat_string, class::PyClassImpl, common::str::{PyKindStr, StrData, StrKind}, convert::{IntoPyException, ToPyException, ToPyObject, ToPyResult}, format::{format, format_map}, function::{ArgIterable, ArgSize, FuncArgs, OptionalArg, OptionalOption, PyComparisonValue}, intern::PyInterned, object::{MaybeTraverse, Traverse, TraverseFn}, protocol::{PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods}, sequence::SequenceExt, sliceable::{SequenceIndex, SliceableSequenceOp}, types::{ AsMapping, AsNumber, AsSequence, Comparable, Constructor, Hashable, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, }, }; use alloc::{borrow::Cow, fmt}; use ascii::{AsciiChar, AsciiStr, AsciiString}; use bstr::ByteSlice; use core::{char, mem, ops::Range}; use itertools::Itertools; use num_traits::ToPrimitive; use rustpython_common::{ ascii, atomic::{self, PyAtomic, Radium}, format::{FormatSpec, FormatString, FromTemplate}, hash, lock::PyMutex, str::DeduceStrKind, wtf8::{CodePoint, Wtf8, Wtf8Buf, Wtf8Chunk}, }; use std::sync::LazyLock; use unic_ucd_bidi::BidiClass; use unic_ucd_category::GeneralCategory; use unic_ucd_ident::{is_xid_continue, is_xid_start}; use unicode_casing::CharExt; impl<'a> TryFromBorrowedObject<'a> for String { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> { obj.try_value_with(|pystr: &PyStr| Ok(pystr.as_str().to_owned()), vm) } } impl<'a> TryFromBorrowedObject<'a> for &'a str { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> { let pystr: &Py<PyStr> = TryFromBorrowedObject::try_from_borrowed_object(vm, obj)?; Ok(pystr.as_str()) } } impl<'a> TryFromBorrowedObject<'a> for &'a Wtf8 { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> { let pystr: &Py<PyStr> = TryFromBorrowedObject::try_from_borrowed_object(vm, obj)?; Ok(pystr.as_wtf8()) } } pub type PyStrRef = PyRef<PyStr>; pub type PyUtf8StrRef = PyRef<PyUtf8Str>; #[pyclass(module = false, name = "str")] pub struct PyStr { data: StrData, hash: PyAtomic<hash::PyHash>, } impl fmt::Debug for PyStr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PyStr") .field("value", &self.as_wtf8()) .field("kind", &self.data.kind()) .field("hash", &self.hash) .finish() } } impl AsRef<str> for PyStr { #[track_caller] // <- can remove this once it doesn't panic fn as_ref(&self) -> &str { self.as_str() } } impl AsRef<str> for Py<PyStr> { #[track_caller] // <- can remove this once it doesn't panic fn as_ref(&self) -> &str { self.as_str() } } impl AsRef<str> for PyStrRef { #[track_caller] // <- can remove this once it doesn't panic fn as_ref(&self) -> &str { self.as_str() } } impl AsRef<Wtf8> for PyStr { fn as_ref(&self) -> &Wtf8 { self.as_wtf8() } } impl AsRef<Wtf8> for Py<PyStr> { fn as_ref(&self) -> &Wtf8 { self.as_wtf8() } } impl AsRef<Wtf8> for PyStrRef { fn as_ref(&self) -> &Wtf8 { self.as_wtf8() } } impl<'a> From<&'a AsciiStr> for PyStr { fn from(s: &'a AsciiStr) -> Self { s.to_owned().into() } } impl From<AsciiString> for PyStr { fn from(s: AsciiString) -> Self { s.into_boxed_ascii_str().into() } } impl From<Box<AsciiStr>> for PyStr { fn from(s: Box<AsciiStr>) -> Self { StrData::from(s).into() } } impl From<AsciiChar> for PyStr { fn from(ch: AsciiChar) -> Self { AsciiString::from(ch).into() } } impl<'a> From<&'a str> for PyStr { fn from(s: &'a str) -> Self { s.to_owned().into() } } impl<'a> From<&'a Wtf8> for PyStr { fn from(s: &'a Wtf8) -> Self { s.to_owned().into() } } impl From<String> for PyStr { fn from(s: String) -> Self { s.into_boxed_str().into() } } impl From<Wtf8Buf> for PyStr { fn from(w: Wtf8Buf) -> Self { w.into_box().into() } } impl From<char> for PyStr { fn from(ch: char) -> Self { StrData::from(ch).into() } } impl From<CodePoint> for PyStr { fn from(ch: CodePoint) -> Self { StrData::from(ch).into() } } impl From<StrData> for PyStr { fn from(data: StrData) -> Self { Self { data, hash: Radium::new(hash::SENTINEL), } } } impl<'a> From<alloc::borrow::Cow<'a, str>> for PyStr { fn from(s: alloc::borrow::Cow<'a, str>) -> Self { s.into_owned().into() } } impl From<Box<str>> for PyStr { #[inline] fn from(value: Box<str>) -> Self { StrData::from(value).into() } } impl From<Box<Wtf8>> for PyStr { #[inline] fn from(value: Box<Wtf8>) -> Self { StrData::from(value).into() } } impl Default for PyStr { fn default() -> Self { Self { data: StrData::default(), hash: Radium::new(hash::SENTINEL), } } } impl fmt::Display for PyStr { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.as_wtf8().fmt(f) } } pub trait AsPyStr<'a> where Self: 'a, { #[allow(clippy::wrong_self_convention)] // to implement on refs fn as_pystr(self, ctx: &Context) -> &'a Py<PyStr>; } impl<'a> AsPyStr<'a> for &'a Py<PyStr> { #[inline] fn as_pystr(self, _ctx: &Context) -> &'a Py<PyStr> { self } } impl<'a> AsPyStr<'a> for &'a PyStrRef { #[inline] fn as_pystr(self, _ctx: &Context) -> &'a Py<PyStr> { self } } impl AsPyStr<'static> for &'static str { #[inline] fn as_pystr(self, ctx: &Context) -> &'static Py<PyStr> { ctx.intern_str(self) } } impl<'a> AsPyStr<'a> for &'a PyStrInterned { #[inline] fn as_pystr(self, _ctx: &Context) -> &'a Py<PyStr> { self } } #[pyclass(module = false, name = "str_iterator", traverse = "manual")] #[derive(Debug)] pub struct PyStrIterator { internal: PyMutex<(PositionIterInternal<PyStrRef>, usize)>, } unsafe impl Traverse for PyStrIterator { fn traverse(&self, tracer: &mut TraverseFn<'_>) { // No need to worry about deadlock, for inner is a PyStr and can't make ref cycle self.internal.lock().0.traverse(tracer); } } impl PyPayload for PyStrIterator { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.str_iterator_type } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] impl PyStrIterator { #[pymethod] fn __length_hint__(&self) -> usize { self.internal.lock().0.length_hint(|obj| obj.char_len()) } #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let mut internal = self.internal.lock(); internal.1 = usize::MAX; internal .0 .set_state(state, |obj, pos| pos.min(obj.char_len()), vm) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef { self.internal .lock() .0 .builtins_iter_reduce(|x| x.clone().into(), vm) } } impl SelfIter for PyStrIterator {} impl IterNext for PyStrIterator { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let mut internal = zelf.internal.lock(); if let IterStatus::Active(s) = &internal.0.status { let value = s.as_wtf8(); if internal.1 == usize::MAX { if let Some((offset, ch)) = value.code_point_indices().nth(internal.0.position) { internal.0.position += 1; internal.1 = offset + ch.len_wtf8(); return Ok(PyIterReturn::Return(ch.to_pyobject(vm))); } } else if let Some(value) = value.get(internal.1..) && let Some(ch) = value.code_points().next() { internal.0.position += 1; internal.1 += ch.len_wtf8(); return Ok(PyIterReturn::Return(ch.to_pyobject(vm))); } internal.0.status = Exhausted; } Ok(PyIterReturn::StopIteration(None)) } } #[derive(FromArgs)] pub struct StrArgs { #[pyarg(any, optional)] object: OptionalArg<PyObjectRef>, #[pyarg(any, optional)] encoding: OptionalArg<PyStrRef>, #[pyarg(any, optional)] errors: OptionalArg<PyStrRef>, } impl Constructor for PyStr { type Args = StrArgs; fn slot_new(cls: PyTypeRef, func_args: FuncArgs, vm: &VirtualMachine) -> PyResult { // Optimization: return exact str as-is (only when no encoding/errors provided) if cls.is(vm.ctx.types.str_type) && func_args.args.len() == 1 && func_args.kwargs.is_empty() && func_args.args[0].class().is(vm.ctx.types.str_type) { return Ok(func_args.args[0].clone()); } let args: Self::Args = func_args.bind(vm)?; let payload = Self::py_new(&cls, args, vm)?; payload.into_ref_with_type(vm, cls).map(Into::into) } fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> { match args.object { OptionalArg::Present(input) => { if let OptionalArg::Present(enc) = args.encoding { let s = vm.state.codec_registry.decode_text( input, enc.as_str(), args.errors.into_option(), vm, )?; Ok(Self::from(s.as_wtf8().to_owned())) } else { let s = input.str(vm)?; Ok(Self::from(s.as_wtf8().to_owned())) } } OptionalArg::Missing => Ok(Self::from(String::new())), } } } impl PyStr { /// # Safety: Given `bytes` must be valid data for given `kind` unsafe fn new_str_unchecked(data: Box<Wtf8>, kind: StrKind) -> Self { unsafe { StrData::new_str_unchecked(data, kind) }.into() } unsafe fn new_with_char_len<T: DeduceStrKind + Into<Box<Wtf8>>>(s: T, char_len: usize) -> Self { let kind = s.str_kind(); unsafe { StrData::new_with_char_len(s.into(), kind, char_len) }.into() } /// # Safety /// Given `bytes` must be ascii pub unsafe fn new_ascii_unchecked(bytes: Vec<u8>) -> Self { unsafe { AsciiString::from_ascii_unchecked(bytes) }.into() } #[deprecated(note = "use PyStr::from(...).into_ref() instead")] pub fn new_ref(zelf: impl Into<Self>, ctx: &Context) -> PyRef<Self> { let zelf = zelf.into(); zelf.into_ref(ctx) } fn new_substr(&self, s: Wtf8Buf) -> Self { let kind = if self.kind().is_ascii() || s.is_ascii() { StrKind::Ascii } else if self.kind().is_utf8() || s.is_utf8() { StrKind::Utf8 } else { StrKind::Wtf8 }; unsafe { // SAFETY: kind is properly decided for substring Self::new_str_unchecked(s.into(), kind) } } #[inline] pub const fn as_wtf8(&self) -> &Wtf8 { self.data.as_wtf8() } pub const fn as_bytes(&self) -> &[u8] { self.data.as_wtf8().as_bytes() } // FIXME: make this return an Option #[inline] #[track_caller] // <- can remove this once it doesn't panic pub fn as_str(&self) -> &str { self.data.as_str().expect("str has surrogates") } pub fn to_str(&self) -> Option<&str> { self.data.as_str() } pub(crate) fn ensure_valid_utf8(&self, vm: &VirtualMachine) -> PyResult<()> { if self.is_utf8() { Ok(()) } else { let start = self .as_wtf8() .code_points() .position(|c| c.to_char().is_none()) .unwrap(); Err(vm.new_unicode_encode_error_real( identifier!(vm, utf_8).to_owned(), vm.ctx.new_str(self.data.clone()), start, start + 1, vm.ctx.new_str("surrogates not allowed"), )) } } pub fn to_string_lossy(&self) -> Cow<'_, str> { self.to_str() .map(Cow::Borrowed) .unwrap_or_else(|| self.as_wtf8().to_string_lossy()) } pub const fn kind(&self) -> StrKind { self.data.kind() } #[inline] pub fn as_str_kind(&self) -> PyKindStr<'_> { self.data.as_str_kind() } pub const fn is_utf8(&self) -> bool { self.kind().is_utf8() } fn char_all<F>(&self, test: F) -> bool where F: Fn(char) -> bool, { match self.as_str_kind() { PyKindStr::Ascii(s) => s.chars().all(|ch| test(ch.into())), PyKindStr::Utf8(s) => s.chars().all(test), PyKindStr::Wtf8(w) => w.code_points().all(|ch| ch.is_char_and(&test)), } } fn repeat(zelf: PyRef<Self>, value: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { if value == 0 && zelf.class().is(vm.ctx.types.str_type) { // Special case: when some `str` is multiplied by `0`, // returns the empty `str`. return Ok(vm.ctx.empty_str.to_owned()); } if (value == 1 || zelf.is_empty()) && zelf.class().is(vm.ctx.types.str_type) { // Special case: when some `str` is multiplied by `1` or is the empty `str`, // nothing really happens, we need to return an object itself // with the same `id()` to be compatible with CPython. // This only works for `str` itself, not its subclasses. return Ok(zelf); } zelf.as_wtf8() .as_bytes() .mul(vm, value) .map(|x| Self::from(unsafe { Wtf8Buf::from_bytes_unchecked(x) }).into_ref(&vm.ctx)) } pub fn try_as_utf8<'a>(&'a self, vm: &VirtualMachine) -> PyResult<&'a PyUtf8Str> { // Check if the string contains surrogates self.ensure_valid_utf8(vm)?; // If no surrogates, we can safely cast to PyStr Ok(unsafe { &*(self as *const _ as *const PyUtf8Str) }) } } impl Py<PyStr> { pub fn try_as_utf8<'a>(&'a self, vm: &VirtualMachine) -> PyResult<&'a Py<PyUtf8Str>> { // Check if the string contains surrogates self.ensure_valid_utf8(vm)?; // If no surrogates, we can safely cast to PyStr Ok(unsafe { &*(self as *const _ as *const Py<PyUtf8Str>) }) } } #[pyclass( flags(BASETYPE, _MATCH_SELF), with( AsMapping, AsNumber, AsSequence, Representable, Hashable, Comparable, Iterable, Constructor ) )] impl PyStr { fn __add__(zelf: PyRef<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if let Some(other) = other.downcast_ref::<Self>() { let bytes = zelf.as_wtf8().py_add(other.as_wtf8()); Ok(unsafe { // SAFETY: `kind` is safely decided let kind = zelf.kind() | other.kind(); Self::new_str_unchecked(bytes.into(), kind) } .to_pyobject(vm)) } else if let Some(radd) = vm.get_method(other.clone(), identifier!(vm, __radd__)) { // hack to get around not distinguishing number add from seq concat radd?.call((zelf,), vm) } else { Err(vm.new_type_error(format!( r#"can only concatenate str (not "{}") to str"#, other.class().name() ))) } } fn _contains(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<bool> { if let Some(needle) = needle.downcast_ref::<Self>() { Ok(memchr::memmem::find(self.as_bytes(), needle.as_bytes()).is_some()) } else { Err(vm.new_type_error(format!( "'in <string>' requires string as left operand, not {}", needle.class().name() ))) } } fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> { self._contains(&needle, vm) } fn _getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { let item = match SequenceIndex::try_from_borrowed_object(vm, needle, "str")? { SequenceIndex::Int(i) => self.getitem_by_index(vm, i)?.to_pyobject(vm), SequenceIndex::Slice(slice) => self.getitem_by_slice(vm, slice)?.to_pyobject(vm), }; Ok(item) } fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { self._getitem(&needle, vm) } #[inline] pub(crate) fn hash(&self, vm: &VirtualMachine) -> hash::PyHash { match self.hash.load(atomic::Ordering::Relaxed) { hash::SENTINEL => self._compute_hash(vm), hash => hash, } } #[cold] fn _compute_hash(&self, vm: &VirtualMachine) -> hash::PyHash { let hash_val = vm.state.hash_secret.hash_bytes(self.as_bytes()); debug_assert_ne!(hash_val, hash::SENTINEL); // spell-checker:ignore cmpxchg // like with char_len, we don't need a cmpxchg loop, since it'll always be the same value self.hash.store(hash_val, atomic::Ordering::Relaxed); hash_val } #[inline] pub fn byte_len(&self) -> usize { self.data.len() } #[inline] pub fn is_empty(&self) -> bool { self.data.is_empty() } #[pymethod(name = "__len__")] #[inline] pub fn char_len(&self) -> usize { self.data.char_len() } #[pymethod] #[inline(always)] pub const fn isascii(&self) -> bool { matches!(self.kind(), StrKind::Ascii) } #[pymethod] fn __sizeof__(&self) -> usize { core::mem::size_of::<Self>() + self.byte_len() * core::mem::size_of::<u8>() } fn __mul__(zelf: PyRef<Self>, value: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { Self::repeat(zelf, value.into(), vm) } #[inline] pub(crate) fn repr(&self, vm: &VirtualMachine) -> PyResult<String> { use crate::literal::escape::UnicodeEscape; UnicodeEscape::new_repr(self.as_wtf8()) .str_repr() .to_string() .ok_or_else(|| vm.new_overflow_error("string is too long to generate repr")) } #[pymethod] fn lower(&self) -> Self { match self.as_str_kind() { PyKindStr::Ascii(s) => s.to_ascii_lowercase().into(), PyKindStr::Utf8(s) => s.to_lowercase().into(), PyKindStr::Wtf8(w) => w .chunks() .map(|c| match c { Wtf8Chunk::Utf8(s) => s.to_lowercase().into(), Wtf8Chunk::Surrogate(c) => Wtf8Buf::from(c), }) .collect::<Wtf8Buf>() .into(), } } // casefold is much more aggressive than lower #[pymethod] fn casefold(&self) -> Self { match self.as_str_kind() { PyKindStr::Ascii(s) => caseless::default_case_fold_str(s.as_str()).into(), PyKindStr::Utf8(s) => caseless::default_case_fold_str(s).into(), PyKindStr::Wtf8(w) => w .chunks() .map(|c| match c { Wtf8Chunk::Utf8(s) => Wtf8Buf::from_string(caseless::default_case_fold_str(s)), Wtf8Chunk::Surrogate(c) => Wtf8Buf::from(c), }) .collect::<Wtf8Buf>() .into(), } } #[pymethod] fn upper(&self) -> Self { match self.as_str_kind() { PyKindStr::Ascii(s) => s.to_ascii_uppercase().into(), PyKindStr::Utf8(s) => s.to_uppercase().into(), PyKindStr::Wtf8(w) => w .chunks() .map(|c| match c { Wtf8Chunk::Utf8(s) => s.to_uppercase().into(), Wtf8Chunk::Surrogate(c) => Wtf8Buf::from(c), }) .collect::<Wtf8Buf>() .into(), } } #[pymethod] fn capitalize(&self) -> Wtf8Buf { match self.as_str_kind() { PyKindStr::Ascii(s) => { let mut s = s.to_owned(); if let [first, rest @ ..] = s.as_mut_slice() { first.make_ascii_uppercase(); ascii::AsciiStr::make_ascii_lowercase(rest.into()); } s.into() } PyKindStr::Utf8(s) => { let mut chars = s.chars(); let mut out = String::with_capacity(s.len()); if let Some(c) = chars.next() { out.extend(c.to_titlecase()); out.push_str(&chars.as_str().to_lowercase()); } out.into() } PyKindStr::Wtf8(s) => { let mut out = Wtf8Buf::with_capacity(s.len()); let mut chars = s.code_points(); if let Some(ch) = chars.next() { match ch.to_char() { Some(ch) => out.extend(ch.to_titlecase()), None => out.push(ch), } for chunk in chars.as_wtf8().chunks() { match chunk { Wtf8Chunk::Utf8(s) => out.push_str(&s.to_lowercase()), Wtf8Chunk::Surrogate(ch) => out.push(ch), } } } out } } } #[pymethod] fn split(zelf: &Py<Self>, args: SplitArgs, vm: &VirtualMachine) -> PyResult<Vec<PyObjectRef>> { let elements = match zelf.as_str_kind() { PyKindStr::Ascii(s) => s.py_split( args, vm, || zelf.as_object().to_owned(), |v, s, vm| { v.as_bytes() .split_str(s) .map(|s| unsafe { AsciiStr::from_ascii_unchecked(s) }.to_pyobject(vm)) .collect() }, |v, s, n, vm| { v.as_bytes() .splitn_str(n, s) .map(|s| unsafe { AsciiStr::from_ascii_unchecked(s) }.to_pyobject(vm)) .collect() }, |v, n, vm| { v.as_bytes().py_split_whitespace(n, |s| { unsafe { AsciiStr::from_ascii_unchecked(s) }.to_pyobject(vm) }) }, ), PyKindStr::Utf8(s) => s.py_split( args, vm, || zelf.as_object().to_owned(), |v, s, vm| v.split(s).map(|s| vm.ctx.new_str(s).into()).collect(), |v, s, n, vm| v.splitn(n, s).map(|s| vm.ctx.new_str(s).into()).collect(), |v, n, vm| v.py_split_whitespace(n, |s| vm.ctx.new_str(s).into()), ), PyKindStr::Wtf8(w) => w.py_split( args, vm, || zelf.as_object().to_owned(), |v, s, vm| v.split(s).map(|s| vm.ctx.new_str(s).into()).collect(), |v, s, n, vm| v.splitn(n, s).map(|s| vm.ctx.new_str(s).into()).collect(), |v, n, vm| v.py_split_whitespace(n, |s| vm.ctx.new_str(s).into()), ), }?; Ok(elements) } #[pymethod] fn rsplit(zelf: &Py<Self>, args: SplitArgs, vm: &VirtualMachine) -> PyResult<Vec<PyObjectRef>> { let mut elements = zelf.as_wtf8().py_split( args, vm, || zelf.as_object().to_owned(), |v, s, vm| v.rsplit(s).map(|s| vm.ctx.new_str(s).into()).collect(), |v, s, n, vm| v.rsplitn(n, s).map(|s| vm.ctx.new_str(s).into()).collect(), |v, n, vm| v.py_rsplit_whitespace(n, |s| vm.ctx.new_str(s).into()), )?; // Unlike Python rsplit, Rust rsplitn returns an iterator that // starts from the end of the string. elements.reverse(); Ok(elements) } #[pymethod] fn strip(&self, chars: OptionalOption<PyStrRef>) -> Self { match self.as_str_kind() { PyKindStr::Ascii(s) => s .py_strip( chars, |s, chars| { let s = s .as_str() .trim_matches(|c| memchr::memchr(c as _, chars.as_bytes()).is_some()); unsafe { AsciiStr::from_ascii_unchecked(s.as_bytes()) } }, |s| s.trim(), ) .into(), PyKindStr::Utf8(s) => s .py_strip( chars, |s, chars| s.trim_matches(|c| chars.contains(c)), |s| s.trim(), ) .into(), PyKindStr::Wtf8(w) => w .py_strip( chars, |s, chars| s.trim_matches(|c| chars.code_points().contains(&c)), |s| s.trim(), ) .into(), } } #[pymethod] fn lstrip( zelf: PyRef<Self>, chars: OptionalOption<PyStrRef>, vm: &VirtualMachine, ) -> PyRef<Self> { let s = zelf.as_wtf8(); let stripped = s.py_strip( chars, |s, chars| s.trim_start_matches(|c| chars.contains_code_point(c)), |s| s.trim_start(), ); if s == stripped { zelf } else { vm.ctx.new_str(stripped) } } #[pymethod] fn rstrip( zelf: PyRef<Self>, chars: OptionalOption<PyStrRef>, vm: &VirtualMachine, ) -> PyRef<Self> { let s = zelf.as_wtf8(); let stripped = s.py_strip( chars, |s, chars| s.trim_end_matches(|c| chars.contains_code_point(c)), |s| s.trim_end(), ); if s == stripped { zelf } else { vm.ctx.new_str(stripped) } } #[pymethod] fn endswith(&self, options: anystr::StartsEndsWithArgs, vm: &VirtualMachine) -> PyResult<bool> { let (affix, substr) = match options.prepare(self.as_wtf8(), self.len(), |s, r| s.get_chars(r)) { Some(x) => x, None => return Ok(false), }; substr.py_starts_ends_with( &affix, "endswith", "str", |s, x: &Py<Self>| s.ends_with(x.as_wtf8()), vm, ) } #[pymethod] fn startswith( &self, options: anystr::StartsEndsWithArgs, vm: &VirtualMachine, ) -> PyResult<bool> { let (affix, substr) = match options.prepare(self.as_wtf8(), self.len(), |s, r| s.get_chars(r)) { Some(x) => x, None => return Ok(false), }; substr.py_starts_ends_with( &affix, "startswith", "str", |s, x: &Py<Self>| s.starts_with(x.as_wtf8()), vm, ) } #[pymethod] fn removeprefix(&self, pref: PyStrRef) -> Wtf8Buf { self.as_wtf8() .py_removeprefix(pref.as_wtf8(), pref.byte_len(), |s, p| s.starts_with(p)) .to_owned() } #[pymethod] fn removesuffix(&self, suffix: PyStrRef) -> Wtf8Buf { self.as_wtf8() .py_removesuffix(suffix.as_wtf8(), suffix.byte_len(), |s, p| s.ends_with(p)) .to_owned() } #[pymethod] fn isalnum(&self) -> bool { !self.data.is_empty() && self.char_all(char::is_alphanumeric) } #[pymethod] fn isnumeric(&self) -> bool { !self.data.is_empty() && self.char_all(char::is_numeric) } #[pymethod] fn isdigit(&self) -> bool { // python's isdigit also checks if exponents are digits, these are the unicode codepoints for exponents !self.data.is_empty() && self.char_all(|c| { c.is_ascii_digit() || matches!(c, '⁰' | '¹' | '²' | '³' | '⁴' | '⁵' | '⁶' | '⁷' | '⁸' | '⁹') }) } #[pymethod] fn isdecimal(&self) -> bool { !self.data.is_empty() && self.char_all(|c| GeneralCategory::of(c) == GeneralCategory::DecimalNumber) } fn __mod__(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult<Wtf8Buf> { cformat_string(vm, self.as_wtf8(), values) } #[pymethod] fn format(&self, args: FuncArgs, vm: &VirtualMachine) -> PyResult<Wtf8Buf> { let format_str = FormatString::from_str(self.as_wtf8()).map_err(|e| e.to_pyexception(vm))?; format(&format_str, &args, vm) } #[pymethod] fn format_map(&self, mapping: PyObjectRef, vm: &VirtualMachine) -> PyResult<Wtf8Buf> { let format_string = FormatString::from_str(self.as_wtf8()).map_err(|err| err.to_pyexception(vm))?; format_map(&format_string, &mapping, vm) } #[pymethod] fn __format__( zelf: PyRef<PyStr>, spec: PyStrRef, vm: &VirtualMachine, ) -> PyResult<PyRef<PyStr>> { let spec = spec.as_str(); if spec.is_empty() { return if zelf.class().is(vm.ctx.types.str_type) { Ok(zelf) } else { zelf.as_object().str(vm) }; } let zelf = zelf.try_into_utf8(vm)?; let s = FormatSpec::parse(spec) .and_then(|format_spec| { format_spec.format_string(&CharLenStr(zelf.as_str(), zelf.char_len())) }) .map_err(|err| err.into_pyexception(vm))?; Ok(vm.ctx.new_str(s)) } #[pymethod] fn title(&self) -> Wtf8Buf { let mut title = Wtf8Buf::with_capacity(self.data.len()); let mut previous_is_cased = false; for c_orig in self.as_wtf8().code_points() { let c = c_orig.to_char_lossy(); if c.is_lowercase() { if !previous_is_cased { title.extend(c.to_titlecase()); } else { title.push_char(c); } previous_is_cased = true; } else if c.is_uppercase() || c.is_titlecase() { if previous_is_cased { title.extend(c.to_lowercase()); } else { title.push_char(c); } previous_is_cased = true; } else { previous_is_cased = false; title.push(c_orig); } } title } #[pymethod] fn swapcase(&self) -> Wtf8Buf { let mut swapped_str = Wtf8Buf::with_capacity(self.data.len()); for c_orig in self.as_wtf8().code_points() { let c = c_orig.to_char_lossy(); // to_uppercase returns an iterator, to_ascii_uppercase returns the char if c.is_lowercase() { swapped_str.push_char(c.to_ascii_uppercase()); } else if c.is_uppercase() { swapped_str.push_char(c.to_ascii_lowercase()); } else { swapped_str.push(c_orig); } } swapped_str } #[pymethod] fn isalpha(&self) -> bool { !self.data.is_empty() && self.char_all(char::is_alphabetic) } #[pymethod] fn replace(&self, args: ReplaceArgs) -> Wtf8Buf { use core::cmp::Ordering; let s = self.as_wtf8(); let ReplaceArgs { old, new, count } = args; match count.cmp(&0) { Ordering::Less => s.replace(old.as_wtf8(), new.as_wtf8()), Ordering::Equal => s.to_owned(), Ordering::Greater => { let s_is_empty = s.is_empty(); let old_is_empty = old.is_empty(); if s_is_empty && !old_is_empty {
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/builtin_func.rs
crates/vm/src/builtins/builtin_func.rs
use super::{PyStrInterned, PyStrRef, PyType, type_}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, class::PyClassImpl, common::wtf8::Wtf8, convert::TryFromObject, function::{FuncArgs, PyComparisonValue, PyMethodDef, PyMethodFlags, PyNativeFn}, types::{Callable, Comparable, PyComparisonOp, Representable}, }; use alloc::fmt; // PyCFunctionObject in CPython #[pyclass(name = "builtin_function_or_method", module = false)] pub struct PyNativeFunction { pub(crate) value: &'static PyMethodDef, pub(crate) zelf: Option<PyObjectRef>, pub(crate) module: Option<&'static PyStrInterned>, // None for bound method } impl PyPayload for PyNativeFunction { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.builtin_function_or_method_type } } impl fmt::Debug for PyNativeFunction { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "builtin function {}.{} ({:?}) self as instance of {:?}", self.module.map_or(Wtf8::new("<unknown>"), |m| m.as_wtf8()), self.value.name, self.value.flags, self.zelf.as_ref().map(|z| z.class().name().to_owned()) ) } } impl PyNativeFunction { pub const fn with_module(mut self, module: &'static PyStrInterned) -> Self { self.module = Some(module); self } pub fn into_ref(self, ctx: &Context) -> PyRef<Self> { PyRef::new_ref( self, ctx.types.builtin_function_or_method_type.to_owned(), None, ) } // PyCFunction_GET_SELF pub fn get_self(&self) -> Option<&PyObject> { if self.value.flags.contains(PyMethodFlags::STATIC) { return None; } self.zelf.as_deref() } pub const fn as_func(&self) -> &'static dyn PyNativeFn { self.value.func } } impl Callable for PyNativeFunction { type Args = FuncArgs; #[inline] fn call(zelf: &Py<Self>, mut args: FuncArgs, vm: &VirtualMachine) -> PyResult { if let Some(z) = &zelf.zelf { args.prepend_arg(z.clone()); } (zelf.value.func)(vm, args) } } #[pyclass(with(Callable), flags(HAS_DICT, DISALLOW_INSTANTIATION))] impl PyNativeFunction { #[pygetset] fn __module__(zelf: NativeFunctionOrMethod) -> Option<&'static PyStrInterned> { zelf.0.module } #[pygetset] fn __name__(zelf: NativeFunctionOrMethod) -> &'static str { zelf.0.value.name } #[pygetset] fn __qualname__(zelf: NativeFunctionOrMethod, vm: &VirtualMachine) -> PyResult<PyStrRef> { let zelf = zelf.0; let flags = zelf.value.flags; // if flags.contains(PyMethodFlags::CLASS) || flags.contains(PyMethodFlags::STATIC) { let qualname = if let Some(bound) = &zelf.zelf { let prefix = if flags.contains(PyMethodFlags::CLASS) { bound .get_attr("__qualname__", vm) .unwrap() .str(vm) .unwrap() .to_string() } else { bound.class().name().to_string() }; vm.ctx.new_str(format!("{}.{}", prefix, &zelf.value.name)) } else { vm.ctx.intern_str(zelf.value.name).to_owned() }; Ok(qualname) } #[pygetset] fn __doc__(zelf: NativeFunctionOrMethod) -> Option<&'static str> { zelf.0.value.doc } #[pygetset] fn __self__(_zelf: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.none() } #[pymethod] const fn __reduce__(&self) -> &'static str { // TODO: return (getattr, (self.object, self.name)) if this is a method self.value.name } #[pymethod] fn __reduce_ex__(zelf: PyObjectRef, _ver: PyObjectRef, vm: &VirtualMachine) -> PyResult { vm.call_special_method(&zelf, identifier!(vm, __reduce__), ()) } #[pygetset] fn __text_signature__(zelf: NativeFunctionOrMethod) -> Option<&'static str> { let doc = zelf.0.value.doc?; let signature = type_::get_text_signature_from_internal_doc(zelf.0.value.name, doc)?; Some(signature) } } impl Representable for PyNativeFunction { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { Ok(format!("<built-in function {}>", zelf.value.name)) } } // `PyCMethodObject` in CPython #[pyclass(name = "builtin_method", module = false, base = PyNativeFunction, ctx = "builtin_method_type")] pub struct PyNativeMethod { pub(crate) func: PyNativeFunction, pub(crate) class: &'static Py<PyType>, // TODO: the actual life is &'self } #[pyclass( with(Callable, Comparable, Representable), flags(HAS_DICT, DISALLOW_INSTANTIATION) )] impl PyNativeMethod { #[pygetset] fn __qualname__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> { let prefix = zelf.class.name().to_string(); Ok(vm .ctx .new_str(format!("{}.{}", prefix, &zelf.func.value.name))) } #[pymethod] fn __reduce__( &self, vm: &VirtualMachine, ) -> PyResult<(PyObjectRef, (PyObjectRef, &'static str))> { // TODO: return (getattr, (self.object, self.name)) if this is a method let getattr = vm.builtins.get_attr("getattr", vm)?; let target = self .func .zelf .clone() .unwrap_or_else(|| self.class.to_owned().into()); let name = self.func.value.name; Ok((getattr, (target, name))) } #[pygetset] fn __self__(zelf: PyRef<Self>, _vm: &VirtualMachine) -> Option<PyObjectRef> { zelf.func.zelf.clone() } } impl fmt::Debug for PyNativeMethod { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "builtin method of {:?} with {:?}", &*self.class.name(), &self.func ) } } impl Comparable for PyNativeMethod { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, _vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { op.eq_only(|| { if let Some(other) = other.downcast_ref::<Self>() { let eq = match (zelf.func.zelf.as_ref(), other.func.zelf.as_ref()) { (Some(z), Some(o)) => z.is(o), (None, None) => true, _ => false, }; let eq = eq && core::ptr::eq(zelf.func.value, other.func.value); Ok(eq.into()) } else { Ok(PyComparisonValue::NotImplemented) } }) } } impl Callable for PyNativeMethod { type Args = FuncArgs; #[inline] fn call(zelf: &Py<Self>, mut args: FuncArgs, vm: &VirtualMachine) -> PyResult { if let Some(zelf) = &zelf.func.zelf { args.prepend_arg(zelf.clone()); } (zelf.func.value.func)(vm, args) } } impl Representable for PyNativeMethod { #[inline] fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { Ok(format!( "<built-in method {} of {} object at ...>", &zelf.func.value.name, zelf.class.name() )) } } pub fn init(context: &Context) { PyNativeFunction::extend_class(context, context.types.builtin_function_or_method_type); PyNativeMethod::extend_class(context, context.types.builtin_method_type); } struct NativeFunctionOrMethod(PyRef<PyNativeFunction>); impl TryFromObject for NativeFunctionOrMethod { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { let class = vm.ctx.types.builtin_function_or_method_type; if obj.fast_isinstance(class) { Ok(Self(unsafe { obj.downcast_unchecked() })) } else { Err(vm.new_downcast_type_error(class, &obj)) } } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/dict.rs
crates/vm/src/builtins/dict.rs
use super::{ IterStatus, PositionIterInternal, PyBaseExceptionRef, PyGenericAlias, PyMappingProxy, PySet, PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef, set::PySetInner, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact, PyResult, TryFromObject, atomic_func, builtins::{ PyTuple, iter::{builtins_iter, builtins_reversed}, type_::PyAttributes, }, class::{PyClassDef, PyClassImpl}, common::ascii, dict_inner::{self, DictKey}, function::{ArgIterable, KwArgs, OptionalArg, PyArithmeticValue::*, PyComparisonValue}, iter::PyExactSizeIterator, protocol::{PyIterIter, PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods}, recursion::ReprGuard, types::{ AsMapping, AsNumber, AsSequence, Callable, Comparable, Constructor, DefaultConstructor, Initializer, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, }, vm::VirtualMachine, }; use alloc::fmt; use rustpython_common::lock::PyMutex; use std::sync::LazyLock; pub type DictContentType = dict_inner::Dict; #[pyclass(module = false, name = "dict", unhashable = true, traverse)] #[derive(Default)] pub struct PyDict { entries: DictContentType, } pub type PyDictRef = PyRef<PyDict>; impl fmt::Debug for PyDict { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // TODO: implement more detailed, non-recursive Debug formatter f.write_str("dict") } } impl PyPayload for PyDict { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.dict_type } } impl PyDict { #[deprecated(note = "use PyDict::default().into_ref() instead")] pub fn new_ref(ctx: &Context) -> PyRef<Self> { Self::default().into_ref(ctx) } /// escape hatch to access the underlying data structure directly. prefer adding a method on /// PyDict instead of using this pub(crate) const fn _as_dict_inner(&self) -> &DictContentType { &self.entries } // Used in update and ior. pub(crate) fn merge_object(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let casted: Result<PyRefExact<Self>, _> = other.downcast_exact(vm); let other = match casted { Ok(dict_other) => return self.merge_dict(dict_other.into_pyref(), vm), Err(other) => other, }; let dict = &self.entries; // Use get_attr to properly invoke __getattribute__ for proxy objects let keys_result = other.get_attr(vm.ctx.intern_str("keys"), vm); let has_keys = match keys_result { Ok(keys_method) => { let keys = keys_method.call((), vm)?.get_iter(vm)?; while let PyIterReturn::Return(key) = keys.next(vm)? { let val = other.get_item(&*key, vm)?; dict.insert(vm, &*key, val)?; } true } Err(e) if e.fast_isinstance(vm.ctx.exceptions.attribute_error) => false, Err(e) => return Err(e), }; if !has_keys { let iter = other.get_iter(vm)?; loop { fn err(vm: &VirtualMachine) -> PyBaseExceptionRef { vm.new_value_error("Iterator must have exactly two elements") } let element = match iter.next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(_) => break, }; let elem_iter = element.get_iter(vm)?; let key = elem_iter.next(vm)?.into_result().map_err(|_| err(vm))?; let value = elem_iter.next(vm)?.into_result().map_err(|_| err(vm))?; if matches!(elem_iter.next(vm)?, PyIterReturn::Return(_)) { return Err(err(vm)); } dict.insert(vm, &*key, value)?; } } Ok(()) } fn merge_dict(&self, dict_other: PyDictRef, vm: &VirtualMachine) -> PyResult<()> { let dict = &self.entries; let dict_size = &dict_other.size(); for (key, value) in &dict_other { dict.insert(vm, &*key, value)?; } if dict_other.entries.has_changed_size(dict_size) { return Err(vm.new_runtime_error("dict mutated during update")); } Ok(()) } pub fn is_empty(&self) -> bool { self.entries.len() == 0 } /// Set item variant which can be called with multiple /// key types, such as str to name a notable one. pub(crate) fn inner_setitem<K: DictKey + ?Sized>( &self, key: &K, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { self.entries.insert(vm, key, value) } pub(crate) fn inner_delitem<K: DictKey + ?Sized>( &self, key: &K, vm: &VirtualMachine, ) -> PyResult<()> { self.entries.delete(vm, key) } pub fn get_or_insert( &self, vm: &VirtualMachine, key: PyObjectRef, default: impl FnOnce() -> PyObjectRef, ) -> PyResult { self.entries.setdefault(vm, &*key, default) } pub fn from_attributes(attrs: PyAttributes, vm: &VirtualMachine) -> PyResult<Self> { let entries = DictContentType::default(); for (key, value) in attrs { entries.insert(vm, key, value)?; } Ok(Self { entries }) } pub fn contains_key<K: DictKey + ?Sized>(&self, key: &K, vm: &VirtualMachine) -> bool { self.entries.contains(vm, key).unwrap() } pub fn size(&self) -> dict_inner::DictSize { self.entries.size() } } // Python dict methods: #[allow(clippy::len_without_is_empty)] #[pyclass( with( Py, PyRef, Constructor, Initializer, Comparable, Iterable, AsSequence, AsNumber, AsMapping, Representable ), flags(BASETYPE, MAPPING, _MATCH_SELF) )] impl PyDict { #[pyclassmethod] fn fromkeys( class: PyTypeRef, iterable: ArgIterable, value: OptionalArg<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { let value = value.unwrap_or_none(vm); let d = PyType::call(&class, ().into(), vm)?; match d.downcast_exact::<Self>(vm) { Ok(pydict) => { for key in iterable.iter(vm)? { pydict.__setitem__(key?, value.clone(), vm)?; } Ok(pydict.into_pyref().into()) } Err(pyobj) => { for key in iterable.iter(vm)? { pyobj.set_item(&*key?, value.clone(), vm)?; } Ok(pyobj) } } } pub fn __len__(&self) -> usize { self.entries.len() } #[pymethod] fn __sizeof__(&self) -> usize { core::mem::size_of::<Self>() + self.entries.sizeof() } fn __contains__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> { self.entries.contains(vm, &*key) } fn __delitem__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.inner_delitem(&*key, vm) } #[pymethod] pub fn clear(&self) { self.entries.clear() } fn __setitem__( &self, key: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { self.inner_setitem(&*key, value, vm) } #[pymethod] fn get( &self, key: PyObjectRef, default: OptionalArg<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { match self.entries.get(vm, &*key)? { Some(value) => Ok(value), None => Ok(default.unwrap_or_none(vm)), } } #[pymethod] fn setdefault( &self, key: PyObjectRef, default: OptionalArg<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { self.entries .setdefault(vm, &*key, || default.unwrap_or_none(vm)) } #[pymethod] pub fn copy(&self) -> Self { Self { entries: self.entries.clone(), } } #[pymethod] fn update( &self, dict_obj: OptionalArg<PyObjectRef>, kwargs: KwArgs, vm: &VirtualMachine, ) -> PyResult<()> { if let OptionalArg::Present(dict_obj) = dict_obj { self.merge_object(dict_obj, vm)?; } for (key, value) in kwargs { self.entries.insert(vm, &key, value)?; } Ok(()) } fn __or__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { let other_dict: Result<PyDictRef, _> = other.downcast(); if let Ok(other) = other_dict { let self_cp = self.copy(); self_cp.merge_dict(other, vm)?; return Ok(self_cp.into_pyobject(vm)); } Ok(vm.ctx.not_implemented()) } #[pymethod] fn pop( &self, key: PyObjectRef, default: OptionalArg<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { match self.entries.pop(vm, &*key)? { Some(value) => Ok(value), None => default.ok_or_else(|| vm.new_key_error(key)), } } #[pymethod] fn popitem(&self, vm: &VirtualMachine) -> PyResult<(PyObjectRef, PyObjectRef)> { let (key, value) = self.entries.pop_back().ok_or_else(|| { let err_msg = vm .ctx .new_str(ascii!("popitem(): dictionary is empty")) .into(); vm.new_key_error(err_msg) })?; Ok((key, value)) } #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } #[pyclass] impl Py<PyDict> { fn inner_cmp( &self, other: &Self, op: PyComparisonOp, item: bool, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { if op == PyComparisonOp::Ne { return Self::inner_cmp(self, other, PyComparisonOp::Eq, item, vm) .map(|x| x.map(|eq| !eq)); } if !op.eval_ord(self.__len__().cmp(&other.__len__())) { return Ok(Implemented(false)); } let (superset, subset) = if self.__len__() < other.__len__() { (other, self) } else { (self, other) }; for (k, v1) in subset { match superset.get_item_opt(&*k, vm)? { Some(v2) => { if v1.is(&v2) { continue; } if item && !vm.bool_eq(&v1, &v2)? { return Ok(Implemented(false)); } } None => { return Ok(Implemented(false)); } } } Ok(Implemented(true)) } #[cfg_attr(feature = "flame-it", flame("PyDictRef"))] fn __getitem__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { self.inner_getitem(&*key, vm) } } #[pyclass] impl PyRef<PyDict> { #[pymethod] const fn keys(self) -> PyDictKeys { PyDictKeys::new(self) } #[pymethod] const fn values(self) -> PyDictValues { PyDictValues::new(self) } #[pymethod] const fn items(self) -> PyDictItems { PyDictItems::new(self) } #[pymethod] fn __reversed__(self) -> PyDictReverseKeyIterator { PyDictReverseKeyIterator::new(self) } fn __ior__(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> { self.merge_object(other, vm)?; Ok(self) } fn __ror__(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { let other_dict: Result<Self, _> = other.downcast(); if let Ok(other) = other_dict { let other_cp = other.copy(); other_cp.merge_dict(self, vm)?; return Ok(other_cp.into_pyobject(vm)); } Ok(vm.ctx.not_implemented()) } } impl DefaultConstructor for PyDict {} impl Initializer for PyDict { type Args = (OptionalArg<PyObjectRef>, KwArgs); fn init( zelf: PyRef<Self>, (dict_obj, kwargs): Self::Args, vm: &VirtualMachine, ) -> PyResult<()> { zelf.update(dict_obj, kwargs, vm) } } impl AsMapping for PyDict { fn as_mapping() -> &'static PyMappingMethods { static AS_MAPPING: PyMappingMethods = PyMappingMethods { length: atomic_func!(|mapping, _vm| Ok(PyDict::mapping_downcast(mapping).__len__())), subscript: atomic_func!(|mapping, needle, vm| { PyDict::mapping_downcast(mapping).inner_getitem(needle, vm) }), ass_subscript: atomic_func!(|mapping, needle, value, vm| { let zelf = PyDict::mapping_downcast(mapping); if let Some(value) = value { zelf.inner_setitem(needle, value, vm) } else { zelf.inner_delitem(needle, vm) } }), }; &AS_MAPPING } } impl AsSequence for PyDict { fn as_sequence() -> &'static PySequenceMethods { static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods { contains: atomic_func!(|seq, target, vm| PyDict::sequence_downcast(seq) .entries .contains(vm, target)), ..PySequenceMethods::NOT_IMPLEMENTED }); &AS_SEQUENCE } } impl AsNumber for PyDict { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { or: Some(|a, b, vm| { if let Some(a) = a.downcast_ref::<PyDict>() { PyDict::__or__(a, b.to_pyobject(vm), vm) } else { Ok(vm.ctx.not_implemented()) } }), inplace_or: Some(|a, b, vm| { if let Some(a) = a.downcast_ref::<PyDict>() { a.to_owned() .__ior__(b.to_pyobject(vm), vm) .map(|d| d.into()) } else { Ok(vm.ctx.not_implemented()) } }), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER } } impl Comparable for PyDict { fn cmp( zelf: &Py<Self>, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<PyComparisonValue> { op.eq_only(|| { let other = class_or_notimplemented!(Self, other); zelf.inner_cmp(other, PyComparisonOp::Eq, true, vm) }) } } impl Iterable for PyDict { fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { Ok(PyDictKeyIterator::new(zelf).into_pyobject(vm)) } } impl Representable for PyDict { #[inline] fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> { let s = if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { let mut str_parts = Vec::with_capacity(zelf.__len__()); for (key, value) in zelf { let key_repr = &key.repr(vm)?; let value_repr = value.repr(vm)?; str_parts.push(format!("{key_repr}: {value_repr}")); } vm.ctx.new_str(format!("{{{}}}", str_parts.join(", "))) } else { vm.ctx.intern_str("{...}").to_owned() }; Ok(s) } #[cold] fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { unreachable!("use repr instead") } } impl Py<PyDict> { #[inline] fn exact_dict(&self, vm: &VirtualMachine) -> bool { self.class().is(vm.ctx.types.dict_type) } fn missing_opt<K: DictKey + ?Sized>( &self, key: &K, vm: &VirtualMachine, ) -> PyResult<Option<PyObjectRef>> { vm.get_method(self.to_owned().into(), identifier!(vm, __missing__)) .map(|methods| methods?.call((key.to_pyobject(vm),), vm)) .transpose() } #[inline] fn inner_getitem<K: DictKey + ?Sized>( &self, key: &K, vm: &VirtualMachine, ) -> PyResult<PyObjectRef> { if let Some(value) = self.entries.get(vm, key)? { Ok(value) } else if let Some(value) = self.missing_opt(key, vm)? { Ok(value) } else { Err(vm.new_key_error(key.to_pyobject(vm))) } } /// Take a python dictionary and convert it to attributes. pub fn to_attributes(&self, vm: &VirtualMachine) -> PyAttributes { let mut attrs = PyAttributes::default(); for (key, value) in self { let key: PyRefExact<PyStr> = key.downcast_exact(vm).expect("dict has non-string keys"); attrs.insert(vm.ctx.intern_str(key), value); } attrs } pub fn get_item_opt<K: DictKey + ?Sized>( &self, key: &K, vm: &VirtualMachine, ) -> PyResult<Option<PyObjectRef>> { if self.exact_dict(vm) { self.entries.get(vm, key) // FIXME: check __missing__? } else { match self.as_object().get_item(key, vm) { Ok(value) => Ok(Some(value)), Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => { self.missing_opt(key, vm) } Err(e) => Err(e), } } } pub fn get_item<K: DictKey + ?Sized>(&self, key: &K, vm: &VirtualMachine) -> PyResult { if self.exact_dict(vm) { self.inner_getitem(key, vm) } else { self.as_object().get_item(key, vm) } } pub fn set_item<K: DictKey + ?Sized>( &self, key: &K, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { if self.exact_dict(vm) { self.inner_setitem(key, value, vm) } else { self.as_object().set_item(key, value, vm) } } pub fn del_item<K: DictKey + ?Sized>(&self, key: &K, vm: &VirtualMachine) -> PyResult<()> { if self.exact_dict(vm) { self.inner_delitem(key, vm) } else { self.as_object().del_item(key, vm) } } pub fn pop_item<K: DictKey + ?Sized>( &self, key: &K, vm: &VirtualMachine, ) -> PyResult<Option<PyObjectRef>> { if self.exact_dict(vm) { self.entries.remove_if_exists(vm, key) } else { let value = self.as_object().get_item(key, vm)?; self.as_object().del_item(key, vm)?; Ok(Some(value)) } } pub fn get_chain<K: DictKey + ?Sized>( &self, other: &Self, key: &K, vm: &VirtualMachine, ) -> PyResult<Option<PyObjectRef>> { let self_exact = self.exact_dict(vm); let other_exact = other.exact_dict(vm); if self_exact && other_exact { self.entries.get_chain(&other.entries, vm, key) } else if let Some(value) = self.get_item_opt(key, vm)? { Ok(Some(value)) } else { other.get_item_opt(key, vm) } } } // Implement IntoIterator so that we can easily iterate dictionaries from rust code. impl IntoIterator for PyDictRef { type Item = (PyObjectRef, PyObjectRef); type IntoIter = DictIntoIter; fn into_iter(self) -> Self::IntoIter { DictIntoIter::new(self) } } impl<'a> IntoIterator for &'a PyDictRef { type Item = (PyObjectRef, PyObjectRef); type IntoIter = DictIter<'a>; fn into_iter(self) -> Self::IntoIter { DictIter::new(self) } } impl<'a> IntoIterator for &'a Py<PyDict> { type Item = (PyObjectRef, PyObjectRef); type IntoIter = DictIter<'a>; fn into_iter(self) -> Self::IntoIter { DictIter::new(self) } } impl<'a> IntoIterator for &'a PyDict { type Item = (PyObjectRef, PyObjectRef); type IntoIter = DictIter<'a>; fn into_iter(self) -> Self::IntoIter { DictIter::new(self) } } pub struct DictIntoIter { dict: PyDictRef, position: usize, } impl DictIntoIter { pub const fn new(dict: PyDictRef) -> Self { Self { dict, position: 0 } } } impl Iterator for DictIntoIter { type Item = (PyObjectRef, PyObjectRef); fn next(&mut self) -> Option<Self::Item> { let (position, key, value) = self.dict.entries.next_entry(self.position)?; self.position = position; Some((key, value)) } fn size_hint(&self) -> (usize, Option<usize>) { let l = self.len(); (l, Some(l)) } } impl ExactSizeIterator for DictIntoIter { fn len(&self) -> usize { self.dict.entries.len_from_entry_index(self.position) } } pub struct DictIter<'a> { dict: &'a PyDict, position: usize, } impl<'a> DictIter<'a> { pub const fn new(dict: &'a PyDict) -> Self { DictIter { dict, position: 0 } } } impl Iterator for DictIter<'_> { type Item = (PyObjectRef, PyObjectRef); fn next(&mut self) -> Option<Self::Item> { let (position, key, value) = self.dict.entries.next_entry(self.position)?; self.position = position; Some((key, value)) } fn size_hint(&self) -> (usize, Option<usize>) { let l = self.len(); (l, Some(l)) } } impl ExactSizeIterator for DictIter<'_> { fn len(&self) -> usize { self.dict.entries.len_from_entry_index(self.position) } } #[pyclass] trait DictView: PyPayload + PyClassDef + Iterable + Representable { type ReverseIter: PyPayload + core::fmt::Debug; fn dict(&self) -> &Py<PyDict>; fn item(vm: &VirtualMachine, key: PyObjectRef, value: PyObjectRef) -> PyObjectRef; fn __len__(&self) -> usize { self.dict().__len__() } #[pymethod] fn __reversed__(&self) -> Self::ReverseIter; } macro_rules! dict_view { ( $name: ident, $iter_name: ident, $reverse_iter_name: ident, $class: ident, $iter_class: ident, $reverse_iter_class: ident, $class_name: literal, $iter_class_name: literal, $reverse_iter_class_name: literal, $result_fn: expr) => { #[pyclass(module = false, name = $class_name)] #[derive(Debug)] pub(crate) struct $name { pub dict: PyDictRef, } impl $name { pub const fn new(dict: PyDictRef) -> Self { $name { dict } } } impl DictView for $name { type ReverseIter = $reverse_iter_name; fn dict(&self) -> &Py<PyDict> { &self.dict } fn item(vm: &VirtualMachine, key: PyObjectRef, value: PyObjectRef) -> PyObjectRef { #[allow(clippy::redundant_closure_call)] $result_fn(vm, key, value) } fn __reversed__(&self) -> Self::ReverseIter { $reverse_iter_name::new(self.dict.clone()) } } impl Iterable for $name { fn iter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult { Ok($iter_name::new(zelf.dict.clone()).into_pyobject(vm)) } } impl PyPayload for $name { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.$class } } impl Representable for $name { #[inline] fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> { let s = if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { let mut str_parts = Vec::with_capacity(zelf.__len__()); for (key, value) in zelf.dict().clone() { let s = &Self::item(vm, key, value).repr(vm)?; str_parts.push(s.as_str().to_owned()); } vm.ctx .new_str(format!("{}([{}])", Self::NAME, str_parts.join(", "))) } else { vm.ctx.intern_str("{...}").to_owned() }; Ok(s) } #[cold] fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> { unreachable!("use repr instead") } } #[pyclass(module = false, name = $iter_class_name)] #[derive(Debug)] pub(crate) struct $iter_name { pub size: dict_inner::DictSize, pub internal: PyMutex<PositionIterInternal<PyDictRef>>, } impl PyPayload for $iter_name { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.$iter_class } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] impl $iter_name { fn new(dict: PyDictRef) -> Self { $iter_name { size: dict.size(), internal: PyMutex::new(PositionIterInternal::new(dict, 0)), } } #[pymethod] fn __length_hint__(&self) -> usize { self.internal.lock().length_hint(|_| self.size.entries_size) } #[allow(clippy::redundant_closure_call)] #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef { let iter = builtins_iter(vm).to_owned(); let internal = self.internal.lock(); let entries = match &internal.status { IterStatus::Active(dict) => dict .into_iter() .map(|(key, value)| ($result_fn)(vm, key, value)) .collect::<Vec<_>>(), IterStatus::Exhausted => vec![], }; vm.new_tuple((iter, (vm.ctx.new_list(entries),))) } } impl SelfIter for $iter_name {} impl IterNext for $iter_name { #[allow(clippy::redundant_closure_call)] fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let mut internal = zelf.internal.lock(); let next = if let IterStatus::Active(dict) = &internal.status { if dict.entries.has_changed_size(&zelf.size) { internal.status = IterStatus::Exhausted; return Err( vm.new_runtime_error("dictionary changed size during iteration") ); } match dict.entries.next_entry(internal.position) { Some((position, key, value)) => { internal.position = position; PyIterReturn::Return(($result_fn)(vm, key, value)) } None => { internal.status = IterStatus::Exhausted; PyIterReturn::StopIteration(None) } } } else { PyIterReturn::StopIteration(None) }; Ok(next) } } #[pyclass(module = false, name = $reverse_iter_class_name)] #[derive(Debug)] pub(crate) struct $reverse_iter_name { pub size: dict_inner::DictSize, internal: PyMutex<PositionIterInternal<PyDictRef>>, } impl PyPayload for $reverse_iter_name { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.$reverse_iter_class } } #[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] impl $reverse_iter_name { fn new(dict: PyDictRef) -> Self { let size = dict.size(); let position = size.entries_size.saturating_sub(1); $reverse_iter_name { size, internal: PyMutex::new(PositionIterInternal::new(dict, position)), } } #[allow(clippy::redundant_closure_call)] #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef { let iter = builtins_reversed(vm).to_owned(); let internal = self.internal.lock(); // TODO: entries must be reversed too let entries = match &internal.status { IterStatus::Active(dict) => dict .into_iter() .map(|(key, value)| ($result_fn)(vm, key, value)) .collect::<Vec<_>>(), IterStatus::Exhausted => vec![], }; vm.new_tuple((iter, (vm.ctx.new_list(entries),))) } #[pymethod] fn __length_hint__(&self) -> usize { self.internal .lock() .rev_length_hint(|_| self.size.entries_size) } } impl SelfIter for $reverse_iter_name {} impl IterNext for $reverse_iter_name { #[allow(clippy::redundant_closure_call)] fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { let mut internal = zelf.internal.lock(); let next = if let IterStatus::Active(dict) = &internal.status { if dict.entries.has_changed_size(&zelf.size) { internal.status = IterStatus::Exhausted; return Err( vm.new_runtime_error("dictionary changed size during iteration") ); } match dict.entries.prev_entry(internal.position) { Some((position, key, value)) => { if internal.position == position { internal.status = IterStatus::Exhausted; } else { internal.position = position; } PyIterReturn::Return(($result_fn)(vm, key, value)) } None => { internal.status = IterStatus::Exhausted; PyIterReturn::StopIteration(None) } } } else { PyIterReturn::StopIteration(None) }; Ok(next) } } }; } dict_view! { PyDictKeys, PyDictKeyIterator, PyDictReverseKeyIterator, dict_keys_type, dict_keyiterator_type, dict_reversekeyiterator_type, "dict_keys", "dict_keyiterator", "dict_reversekeyiterator", |_vm: &VirtualMachine, key: PyObjectRef, _value: PyObjectRef| key } dict_view! { PyDictValues, PyDictValueIterator, PyDictReverseValueIterator, dict_values_type, dict_valueiterator_type, dict_reversevalueiterator_type, "dict_values", "dict_valueiterator", "dict_reversevalueiterator", |_vm: &VirtualMachine, _key: PyObjectRef, value: PyObjectRef| value } dict_view! { PyDictItems, PyDictItemIterator, PyDictReverseItemIterator, dict_items_type, dict_itemiterator_type, dict_reverseitemiterator_type, "dict_items", "dict_itemiterator", "dict_reverseitemiterator", |vm: &VirtualMachine, key: PyObjectRef, value: PyObjectRef| vm.new_tuple((key, value)).into() } // Set operations defined on set-like views of the dictionary. #[pyclass] trait ViewSetOps: DictView { fn to_set(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PySetInner> { let len = zelf.dict().__len__(); let zelf: PyObjectRef = Self::iter(zelf, vm)?; let iter = PyIterIter::new(vm, zelf, Some(len)); PySetInner::from_iter(iter, vm) } fn __xor__(zelf: PyRef<Self>, other: ArgIterable, vm: &VirtualMachine) -> PyResult<PySet> { let zelf = Self::to_set(zelf, vm)?; let inner = zelf.symmetric_difference(other, vm)?; Ok(PySet { inner }) } fn __and__(zelf: PyRef<Self>, other: ArgIterable, vm: &VirtualMachine) -> PyResult<PySet> { let zelf = Self::to_set(zelf, vm)?; let inner = zelf.intersection(other, vm)?;
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/staticmethod.rs
crates/vm/src/builtins/staticmethod.rs
use super::{PyGenericAlias, PyStr, PyType, PyTypeRef}; use crate::{ Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, class::PyClassImpl, common::lock::PyMutex, function::FuncArgs, types::{Callable, Constructor, GetDescriptor, Initializer, Representable}, }; #[pyclass(module = false, name = "staticmethod", traverse)] #[derive(Debug)] pub struct PyStaticMethod { pub callable: PyMutex<PyObjectRef>, } impl PyPayload for PyStaticMethod { #[inline] fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.staticmethod_type } } impl GetDescriptor for PyStaticMethod { fn descr_get( zelf: PyObjectRef, obj: Option<PyObjectRef>, _cls: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { let (zelf, _obj) = Self::_unwrap(&zelf, obj, vm)?; Ok(zelf.callable.lock().clone()) } } impl From<PyObjectRef> for PyStaticMethod { fn from(callable: PyObjectRef) -> Self { Self { callable: PyMutex::new(callable), } } } impl Constructor for PyStaticMethod { type Args = PyObjectRef; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let callable: Self::Args = args.bind(vm)?; let doc = callable.get_attr("__doc__", vm); let result = Self { callable: PyMutex::new(callable), } .into_ref_with_type(vm, cls)?; let obj = PyObjectRef::from(result); if let Ok(doc) = doc { obj.set_attr("__doc__", doc, vm)?; } Ok(obj) } fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> { unimplemented!("use slot_new") } } impl PyStaticMethod { pub fn new(callable: PyObjectRef) -> Self { Self { callable: PyMutex::new(callable), } } #[deprecated(note = "use PyStaticMethod::new(...).into_ref() instead")] pub fn new_ref(callable: PyObjectRef, ctx: &Context) -> PyRef<Self> { Self::new(callable).into_ref(ctx) } } impl Initializer for PyStaticMethod { type Args = PyObjectRef; fn init(zelf: PyRef<Self>, callable: Self::Args, _vm: &VirtualMachine) -> PyResult<()> { *zelf.callable.lock() = callable; Ok(()) } } #[pyclass( with(Callable, GetDescriptor, Constructor, Initializer, Representable), flags(BASETYPE, HAS_DICT) )] impl PyStaticMethod { #[pygetset] fn __func__(&self) -> PyObjectRef { self.callable.lock().clone() } #[pygetset] fn __wrapped__(&self) -> PyObjectRef { self.callable.lock().clone() } #[pygetset] fn __module__(&self, vm: &VirtualMachine) -> PyResult { self.callable.lock().get_attr("__module__", vm) } #[pygetset] fn __qualname__(&self, vm: &VirtualMachine) -> PyResult { self.callable.lock().get_attr("__qualname__", vm) } #[pygetset] fn __name__(&self, vm: &VirtualMachine) -> PyResult { self.callable.lock().get_attr("__name__", vm) } #[pygetset] fn __annotations__(&self, vm: &VirtualMachine) -> PyResult { self.callable.lock().get_attr("__annotations__", vm) } #[pygetset] fn __isabstractmethod__(&self, vm: &VirtualMachine) -> PyObjectRef { match vm.get_attribute_opt(self.callable.lock().clone(), "__isabstractmethod__") { Ok(Some(is_abstract)) => is_abstract, _ => vm.ctx.new_bool(false).into(), } } #[pygetset(setter)] fn set___isabstractmethod__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.callable .lock() .set_attr("__isabstractmethod__", value, vm)?; Ok(()) } #[pyclassmethod] fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias { PyGenericAlias::from_args(cls, args, vm) } } impl Callable for PyStaticMethod { type Args = FuncArgs; #[inline] fn call(zelf: &Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let callable = zelf.callable.lock().clone(); callable.call(args, vm) } } impl Representable for PyStaticMethod { fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> { let callable = zelf.callable.lock().repr(vm).unwrap(); let class = Self::class(&vm.ctx); match ( class .__qualname__(vm) .downcast_ref::<PyStr>() .map(|n| n.as_str()), class .__module__(vm) .downcast_ref::<PyStr>() .map(|m| m.as_str()), ) { (None, _) => Err(vm.new_type_error("Unknown qualified name")), (Some(qualname), Some(module)) if module != "builtins" => { Ok(format!("<{module}.{qualname}({callable})>")) } _ => Ok(format!("<{}({})>", class.slot_name(), callable)), } } } pub fn init(context: &Context) { PyStaticMethod::extend_class(context, context.types.staticmethod_type); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/builtins/function/jit.rs
crates/vm/src/builtins/function/jit.rs
use crate::{ AsObject, Py, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, builtins::{ PyBaseExceptionRef, PyDict, PyDictRef, PyFunction, PyStrInterned, bool_, float, int, }, bytecode::CodeFlags, convert::ToPyObject, function::FuncArgs, }; use num_traits::ToPrimitive; use rustpython_jit::{AbiValue, Args, CompiledCode, JitArgumentError, JitType}; #[derive(Debug, thiserror::Error)] pub enum ArgsError { #[error("wrong number of arguments passed")] WrongNumberOfArgs, #[error("argument passed multiple times")] ArgPassedMultipleTimes, #[error("not a keyword argument")] NotAKeywordArg, #[error("not all arguments passed")] NotAllArgsPassed, #[error("integer can't fit into a machine integer")] IntOverflow, #[error("type can't be used in a jit function")] NonJitType, #[error("{0}")] JitError(#[from] JitArgumentError), } impl ToPyObject for AbiValue { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { match self { AbiValue::Int(i) => i.to_pyobject(vm), AbiValue::Float(f) => f.to_pyobject(vm), AbiValue::Bool(b) => b.to_pyobject(vm), _ => unimplemented!(), } } } pub fn new_jit_error(msg: String, vm: &VirtualMachine) -> PyBaseExceptionRef { let jit_error = vm.ctx.exceptions.jit_error.to_owned(); vm.new_exception_msg(jit_error, msg) } fn get_jit_arg_type(dict: &Py<PyDict>, name: &str, vm: &VirtualMachine) -> PyResult<JitType> { if let Some(value) = dict.get_item_opt(name, vm)? { if value.is(vm.ctx.types.int_type) { Ok(JitType::Int) } else if value.is(vm.ctx.types.float_type) { Ok(JitType::Float) } else if value.is(vm.ctx.types.bool_type) { Ok(JitType::Bool) } else { Err(new_jit_error( "Jit requires argument to be either int, float or bool".to_owned(), vm, )) } } else { Err(new_jit_error( format!("argument {name} needs annotation"), vm, )) } } pub fn get_jit_arg_types(func: &Py<PyFunction>, vm: &VirtualMachine) -> PyResult<Vec<JitType>> { let code = func.code.lock(); let arg_names = code.arg_names(); if code .flags .intersects(CodeFlags::HAS_VARARGS | CodeFlags::HAS_VARKEYWORDS) { return Err(new_jit_error( "Can't jit functions with variable number of arguments".to_owned(), vm, )); } if arg_names.args.is_empty() && arg_names.kwonlyargs.is_empty() { return Ok(Vec::new()); } let func_obj: PyObjectRef = func.as_ref().to_owned(); let annotations = func_obj.get_attr("__annotations__", vm)?; if vm.is_none(&annotations) { Err(new_jit_error( "Jitting function requires arguments to have annotations".to_owned(), vm, )) } else if let Ok(dict) = PyDictRef::try_from_object(vm, annotations) { let mut arg_types = Vec::new(); for arg in arg_names.args { arg_types.push(get_jit_arg_type(&dict, arg.as_str(), vm)?); } for arg in arg_names.kwonlyargs { arg_types.push(get_jit_arg_type(&dict, arg.as_str(), vm)?); } Ok(arg_types) } else { Err(vm.new_type_error("Function annotations aren't a dict")) } } pub fn jit_ret_type(func: &Py<PyFunction>, vm: &VirtualMachine) -> PyResult<Option<JitType>> { let func_obj: PyObjectRef = func.as_ref().to_owned(); let annotations = func_obj.get_attr("__annotations__", vm)?; if vm.is_none(&annotations) { Err(new_jit_error( "Jitting function requires return type to have annotations".to_owned(), vm, )) } else if let Ok(dict) = PyDictRef::try_from_object(vm, annotations) { if dict.contains_key("return", vm) { get_jit_arg_type(&dict, "return", vm).map_or(Ok(None), |t| Ok(Some(t))) } else { Ok(None) } } else { Err(vm.new_type_error("Function annotations aren't a dict")) } } fn get_jit_value(vm: &VirtualMachine, obj: &PyObject) -> Result<AbiValue, ArgsError> { // This does exact type checks as subclasses of int/float can't be passed to jitted functions let cls = obj.class(); if cls.is(vm.ctx.types.int_type) { int::get_value(obj) .to_i64() .map(AbiValue::Int) .ok_or(ArgsError::IntOverflow) } else if cls.is(vm.ctx.types.float_type) { Ok(AbiValue::Float( obj.downcast_ref::<float::PyFloat>().unwrap().to_f64(), )) } else if cls.is(vm.ctx.types.bool_type) { Ok(AbiValue::Bool(bool_::get_value(obj))) } else { Err(ArgsError::NonJitType) } } /// Like `fill_locals_from_args` but to populate arguments for calling a jit function. /// This also doesn't do full error handling but instead return None if anything is wrong. In /// that case it falls back to the executing the bytecode version which will call /// `fill_locals_from_args` which will raise the actual exception if needed. #[cfg(feature = "jit")] pub(crate) fn get_jit_args<'a>( func: &PyFunction, func_args: &FuncArgs, jitted_code: &'a CompiledCode, vm: &VirtualMachine, ) -> Result<Args<'a>, ArgsError> { let mut jit_args = jitted_code.args_builder(); let nargs = func_args.args.len(); let code = func.code.lock(); let arg_names = code.arg_names(); let arg_count = code.arg_count; let posonlyarg_count = code.posonlyarg_count; if nargs > arg_count as usize || nargs < posonlyarg_count as usize { return Err(ArgsError::WrongNumberOfArgs); } // Add positional arguments for i in 0..nargs { jit_args.set(i, get_jit_value(vm, &func_args.args[i])?)?; } // Handle keyword arguments for (name, value) in &func_args.kwargs { let arg_pos = |args: &[&PyStrInterned], name: &str| args.iter().position(|arg| arg.as_str() == name); if let Some(arg_idx) = arg_pos(arg_names.args, name) { if jit_args.is_set(arg_idx) { return Err(ArgsError::ArgPassedMultipleTimes); } jit_args.set(arg_idx, get_jit_value(vm, value)?)?; } else if let Some(kwarg_idx) = arg_pos(arg_names.kwonlyargs, name) { let arg_idx = kwarg_idx + arg_count as usize; if jit_args.is_set(arg_idx) { return Err(ArgsError::ArgPassedMultipleTimes); } jit_args.set(arg_idx, get_jit_value(vm, value)?)?; } else { return Err(ArgsError::NotAKeywordArg); } } let (defaults, kwdefaults) = func.defaults_and_kwdefaults.lock().clone(); // fill in positional defaults if let Some(defaults) = defaults { for (i, default) in defaults.iter().enumerate() { let arg_idx = i + arg_count as usize - defaults.len(); if !jit_args.is_set(arg_idx) { jit_args.set(arg_idx, get_jit_value(vm, default)?)?; } } } // fill in keyword only defaults if let Some(kw_only_defaults) = kwdefaults { for (i, name) in arg_names.kwonlyargs.iter().enumerate() { let arg_idx = i + arg_count as usize; if !jit_args.is_set(arg_idx) { let default = kw_only_defaults .get_item(&**name, vm) .map_err(|_| ArgsError::NotAllArgsPassed) .and_then(|obj| get_jit_value(vm, &obj))?; jit_args.set(arg_idx, default)?; } } } drop(code); jit_args.into_args().ok_or(ArgsError::NotAllArgsPassed) }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/object/ext.rs
crates/vm/src/object/ext.rs
use super::{ core::{Py, PyObject, PyObjectRef, PyRef}, payload::PyPayload, }; use crate::common::{ atomic::{Ordering, PyAtomic, Radium}, lock::PyRwLockReadGuard, }; use crate::{ VirtualMachine, builtins::{PyBaseExceptionRef, PyStrInterned, PyType}, convert::{IntoPyException, ToPyObject, ToPyResult, TryFromObject}, vm::Context, }; use alloc::fmt; use core::{ borrow::Borrow, marker::PhantomData, ops::Deref, ptr::{NonNull, null_mut}, }; /* Python objects and references. Okay, so each python object itself is an class itself (PyObject). Each python object can have several references to it (PyObjectRef). These references are Rc (reference counting) rust smart pointers. So when all references are destroyed, the object itself also can be cleaned up. Basically reference counting, but then done by rust. */ /* * Good reference: https://github.com/ProgVal/pythonvm-rust/blob/master/src/objects/mod.rs */ /// Use this type for functions which return a python object or an exception. /// Both the python object and the python exception are `PyObjectRef` types /// since exceptions are also python objects. pub type PyResult<T = PyObjectRef> = Result<T, PyBaseExceptionRef>; // A valid value, or an exception impl<T: fmt::Display> fmt::Display for PyRef<T> where T: PyPayload + fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&**self, f) } } impl<T: fmt::Display> fmt::Display for Py<T> where T: PyPayload + fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&**self, f) } } #[repr(transparent)] pub struct PyExact<T> { inner: Py<T>, } impl<T: PyPayload> PyExact<T> { /// # Safety /// Given reference must be exact type of payload T #[inline(always)] pub const unsafe fn ref_unchecked(r: &Py<T>) -> &Self { unsafe { &*(r as *const _ as *const Self) } } } impl<T: PyPayload> Deref for PyExact<T> { type Target = Py<T>; #[inline(always)] fn deref(&self) -> &Py<T> { &self.inner } } impl<T: PyPayload> Borrow<PyObject> for PyExact<T> { #[inline(always)] fn borrow(&self) -> &PyObject { self.inner.borrow() } } impl<T: PyPayload> AsRef<PyObject> for PyExact<T> { #[inline(always)] fn as_ref(&self) -> &PyObject { self.inner.as_ref() } } impl<T: PyPayload> Borrow<Py<T>> for PyExact<T> { #[inline(always)] fn borrow(&self) -> &Py<T> { &self.inner } } impl<T: PyPayload> AsRef<Py<T>> for PyExact<T> { #[inline(always)] fn as_ref(&self) -> &Py<T> { &self.inner } } impl<T: PyPayload> alloc::borrow::ToOwned for PyExact<T> { type Owned = PyRefExact<T>; fn to_owned(&self) -> Self::Owned { let owned = self.inner.to_owned(); unsafe { PyRefExact::new_unchecked(owned) } } } impl<T: PyPayload> PyRef<T> { pub fn into_exact_or( self, ctx: &Context, f: impl FnOnce(Self) -> PyRefExact<T>, ) -> PyRefExact<T> { if self.class().is(T::class(ctx)) { unsafe { PyRefExact::new_unchecked(self) } } else { f(self) } } } /// PyRef but guaranteed not to be a subtype instance #[derive(Debug)] #[repr(transparent)] pub struct PyRefExact<T: PyPayload> { inner: PyRef<T>, } impl<T: PyPayload> PyRefExact<T> { /// # Safety /// obj must have exact type for the payload pub const unsafe fn new_unchecked(obj: PyRef<T>) -> Self { Self { inner: obj } } pub fn into_pyref(self) -> PyRef<T> { self.inner } } impl<T: PyPayload> Clone for PyRefExact<T> { fn clone(&self) -> Self { let inner = self.inner.clone(); Self { inner } } } impl<T: PyPayload> TryFromObject for PyRefExact<T> { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { let target_cls = T::class(&vm.ctx); let cls = obj.class(); if cls.is(target_cls) { let obj = obj .downcast() .map_err(|obj| vm.new_downcast_runtime_error(target_cls, &obj))?; Ok(Self { inner: obj }) } else if cls.fast_issubclass(target_cls) { Err(vm.new_type_error(format!( "Expected an exact instance of '{}', not a subclass '{}'", target_cls.name(), cls.name(), ))) } else { Err(vm.new_type_error(format!( "Expected type '{}', not '{}'", target_cls.name(), cls.name(), ))) } } } impl<T: PyPayload> Deref for PyRefExact<T> { type Target = PyExact<T>; #[inline(always)] fn deref(&self) -> &PyExact<T> { unsafe { PyExact::ref_unchecked(self.inner.deref()) } } } impl<T: PyPayload> Borrow<PyObject> for PyRefExact<T> { #[inline(always)] fn borrow(&self) -> &PyObject { self.inner.borrow() } } impl<T: PyPayload> AsRef<PyObject> for PyRefExact<T> { #[inline(always)] fn as_ref(&self) -> &PyObject { self.inner.as_ref() } } impl<T: PyPayload> Borrow<Py<T>> for PyRefExact<T> { #[inline(always)] fn borrow(&self) -> &Py<T> { self.inner.borrow() } } impl<T: PyPayload> AsRef<Py<T>> for PyRefExact<T> { #[inline(always)] fn as_ref(&self) -> &Py<T> { self.inner.as_ref() } } impl<T: PyPayload> Borrow<PyExact<T>> for PyRefExact<T> { #[inline(always)] fn borrow(&self) -> &PyExact<T> { self } } impl<T: PyPayload> AsRef<PyExact<T>> for PyRefExact<T> { #[inline(always)] fn as_ref(&self) -> &PyExact<T> { self } } impl<T: PyPayload> ToPyObject for PyRefExact<T> { #[inline(always)] fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { self.inner.into() } } pub struct PyAtomicRef<T> { inner: PyAtomic<*mut u8>, _phantom: PhantomData<T>, } impl<T> Drop for PyAtomicRef<T> { fn drop(&mut self) { // SAFETY: We are dropping the atomic reference, so we can safely // release the pointer. unsafe { let ptr = Radium::swap(&self.inner, null_mut(), Ordering::Relaxed); if let Some(ptr) = NonNull::<PyObject>::new(ptr.cast()) { let _: PyObjectRef = PyObjectRef::from_raw(ptr); } } } } cfg_if::cfg_if! { if #[cfg(feature = "threading")] { unsafe impl<T: Send + PyPayload> Send for PyAtomicRef<T> {} unsafe impl<T: Sync + PyPayload> Sync for PyAtomicRef<T> {} unsafe impl<T: Send + PyPayload> Send for PyAtomicRef<Option<T>> {} unsafe impl<T: Sync + PyPayload> Sync for PyAtomicRef<Option<T>> {} unsafe impl Send for PyAtomicRef<PyObject> {} unsafe impl Sync for PyAtomicRef<PyObject> {} unsafe impl Send for PyAtomicRef<Option<PyObject>> {} unsafe impl Sync for PyAtomicRef<Option<PyObject>> {} } } impl<T: fmt::Debug> fmt::Debug for PyAtomicRef<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "PyAtomicRef(")?; unsafe { self.inner .load(Ordering::Relaxed) .cast::<T>() .as_ref() .fmt(f) }?; write!(f, ")") } } impl<T: PyPayload> From<PyRef<T>> for PyAtomicRef<T> { fn from(pyref: PyRef<T>) -> Self { let py = PyRef::leak(pyref); Self { inner: Radium::new(py as *const _ as *mut _), _phantom: Default::default(), } } } impl<T: PyPayload> Deref for PyAtomicRef<T> { type Target = Py<T>; fn deref(&self) -> &Self::Target { unsafe { self.inner .load(Ordering::Relaxed) .cast::<Py<T>>() .as_ref() .unwrap_unchecked() } } } impl<T: PyPayload> PyAtomicRef<T> { /// # Safety /// The caller is responsible to keep the returned PyRef alive /// until no more reference can be used via PyAtomicRef::deref() #[must_use] pub unsafe fn swap(&self, pyref: PyRef<T>) -> PyRef<T> { let py = PyRef::leak(pyref) as *const Py<T> as *mut _; let old = Radium::swap(&self.inner, py, Ordering::AcqRel); unsafe { PyRef::from_raw(old.cast()) } } pub fn swap_to_temporary_refs(&self, pyref: PyRef<T>, vm: &VirtualMachine) { let old = unsafe { self.swap(pyref) }; if let Some(frame) = vm.current_frame() { frame.temporary_refs.lock().push(old.into()); } } } impl<T: PyPayload> From<Option<PyRef<T>>> for PyAtomicRef<Option<T>> { fn from(opt_ref: Option<PyRef<T>>) -> Self { let val = opt_ref .map(|x| PyRef::leak(x) as *const Py<T> as *mut _) .unwrap_or(null_mut()); Self { inner: Radium::new(val), _phantom: Default::default(), } } } impl<T: PyPayload> PyAtomicRef<Option<T>> { pub fn deref(&self) -> Option<&Py<T>> { unsafe { self.inner.load(Ordering::Relaxed).cast::<Py<T>>().as_ref() } } pub fn to_owned(&self) -> Option<PyRef<T>> { self.deref().map(|x| x.to_owned()) } /// # Safety /// The caller is responsible to keep the returned PyRef alive /// until no more reference can be used via PyAtomicRef::deref() #[must_use] pub unsafe fn swap(&self, opt_ref: Option<PyRef<T>>) -> Option<PyRef<T>> { let val = opt_ref .map(|x| PyRef::leak(x) as *const Py<T> as *mut _) .unwrap_or(null_mut()); let old = Radium::swap(&self.inner, val, Ordering::AcqRel); unsafe { old.cast::<Py<T>>().as_ref().map(|x| PyRef::from_raw(x)) } } pub fn swap_to_temporary_refs(&self, opt_ref: Option<PyRef<T>>, vm: &VirtualMachine) { let Some(old) = (unsafe { self.swap(opt_ref) }) else { return; }; if let Some(frame) = vm.current_frame() { frame.temporary_refs.lock().push(old.into()); } } } impl From<PyObjectRef> for PyAtomicRef<PyObject> { fn from(obj: PyObjectRef) -> Self { let obj = obj.into_raw(); Self { inner: Radium::new(obj.cast().as_ptr()), _phantom: Default::default(), } } } impl Deref for PyAtomicRef<PyObject> { type Target = PyObject; fn deref(&self) -> &Self::Target { unsafe { self.inner .load(Ordering::Relaxed) .cast::<PyObject>() .as_ref() .unwrap_unchecked() } } } impl PyAtomicRef<PyObject> { /// # Safety /// The caller is responsible to keep the returned PyRef alive /// until no more reference can be used via PyAtomicRef::deref() #[must_use] pub unsafe fn swap(&self, obj: PyObjectRef) -> PyObjectRef { let obj = obj.into_raw(); let old = Radium::swap(&self.inner, obj.cast().as_ptr(), Ordering::AcqRel); unsafe { PyObjectRef::from_raw(NonNull::new_unchecked(old.cast())) } } pub fn swap_to_temporary_refs(&self, obj: PyObjectRef, vm: &VirtualMachine) { let old = unsafe { self.swap(obj) }; if let Some(frame) = vm.current_frame() { frame.temporary_refs.lock().push(old); } } } impl From<Option<PyObjectRef>> for PyAtomicRef<Option<PyObject>> { fn from(obj: Option<PyObjectRef>) -> Self { let val = obj .map(|x| x.into_raw().as_ptr().cast()) .unwrap_or(null_mut()); Self { inner: Radium::new(val), _phantom: Default::default(), } } } impl PyAtomicRef<Option<PyObject>> { pub fn deref(&self) -> Option<&PyObject> { unsafe { self.inner .load(Ordering::Relaxed) .cast::<PyObject>() .as_ref() } } pub fn to_owned(&self) -> Option<PyObjectRef> { self.deref().map(|x| x.to_owned()) } /// # Safety /// The caller is responsible to keep the returned PyRef alive /// until no more reference can be used via PyAtomicRef::deref() #[must_use] pub unsafe fn swap(&self, obj: Option<PyObjectRef>) -> Option<PyObjectRef> { let val = obj .map(|x| x.into_raw().as_ptr().cast()) .unwrap_or(null_mut()); let old = Radium::swap(&self.inner, val, Ordering::AcqRel); unsafe { NonNull::new(old.cast::<PyObject>()).map(|x| PyObjectRef::from_raw(x)) } } pub fn swap_to_temporary_refs(&self, obj: Option<PyObjectRef>, vm: &VirtualMachine) { let Some(old) = (unsafe { self.swap(obj) }) else { return; }; if let Some(frame) = vm.current_frame() { frame.temporary_refs.lock().push(old); } } } pub trait AsObject where Self: Borrow<PyObject>, { #[inline(always)] fn as_object(&self) -> &PyObject { self.borrow() } #[inline(always)] fn get_id(&self) -> usize { self.as_object().unique_id() } #[inline(always)] fn is<T>(&self, other: &T) -> bool where T: AsObject, { self.get_id() == other.get_id() } #[inline(always)] fn class(&self) -> &Py<PyType> { self.as_object().class() } fn get_class_attr(&self, attr_name: &'static PyStrInterned) -> Option<PyObjectRef> { self.class().get_attr(attr_name) } /// Determines if `obj` actually an instance of `cls`, this doesn't call __instancecheck__, so only /// use this if `cls` is known to have not overridden the base __instancecheck__ magic method. #[inline] fn fast_isinstance(&self, cls: &Py<PyType>) -> bool { self.class().fast_issubclass(cls) } } impl<T> AsObject for T where T: Borrow<PyObject> {} impl PyObject { #[inline(always)] fn unique_id(&self) -> usize { self as *const Self as usize } } // impl<T: ?Sized> Borrow<PyObject> for PyRc<T> { // #[inline(always)] // fn borrow(&self) -> &PyObject { // unsafe { &*(&**self as *const T as *const PyObject) } // } // } /// A borrow of a reference to a Python object. This avoids having clone the `PyRef<T>`/ /// `PyObjectRef`, which isn't that cheap as that increments the atomic reference counter. // TODO: check if we still need this #[allow(dead_code)] pub struct PyLease<'a, T: PyPayload> { inner: PyRwLockReadGuard<'a, PyRef<T>>, } impl<T: PyPayload> PyLease<'_, T> { #[inline(always)] pub fn into_owned(self) -> PyRef<T> { self.inner.clone() } } impl<T: PyPayload> Borrow<PyObject> for PyLease<'_, T> { #[inline(always)] fn borrow(&self) -> &PyObject { self.inner.as_ref() } } impl<T: PyPayload> Deref for PyLease<'_, T> { type Target = PyRef<T>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.inner } } impl<T> fmt::Display for PyLease<'_, T> where T: PyPayload + fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&**self, f) } } impl<T: PyPayload> ToPyObject for PyRef<T> { #[inline(always)] fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { self.into() } } impl ToPyObject for PyObjectRef { #[inline(always)] fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { self } } impl ToPyObject for &PyObject { #[inline(always)] fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { self.to_owned() } } // Allows a built-in function to return any built-in object payload without // explicitly implementing `ToPyObject`. impl<T> ToPyObject for T where T: PyPayload + core::fmt::Debug + Sized, { #[inline(always)] fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { PyPayload::into_pyobject(self, vm) } } impl<T> ToPyResult for T where T: ToPyObject, { #[inline(always)] fn to_pyresult(self, vm: &VirtualMachine) -> PyResult { Ok(self.to_pyobject(vm)) } } impl<T, E> ToPyResult for Result<T, E> where T: ToPyObject, E: IntoPyException, { #[inline(always)] fn to_pyresult(self, vm: &VirtualMachine) -> PyResult { self.map(|res| T::to_pyobject(res, vm)) .map_err(|e| E::into_pyexception(e, vm)) } } impl IntoPyException for PyBaseExceptionRef { #[inline(always)] fn into_pyexception(self, _vm: &VirtualMachine) -> PyBaseExceptionRef { self } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/object/core.rs
crates/vm/src/object/core.rs
//! Essential types for object models //! //! +-------------------------+--------------+-----------------------+ //! | Management | Typed | Untyped | //! +-------------------------+------------------+-------------------+ //! | Interpreter-independent | [`Py<T>`] | [`PyObject`] | //! | Reference-counted | [`PyRef<T>`] | [`PyObjectRef`] | //! | Weak | [`PyWeakRef<T>`] | [`PyRef<PyWeak>`] | //! +-------------------------+--------------+-----------------------+ //! //! [`PyRef<PyWeak>`] may looking like to be called as PyObjectWeak by the rule, //! but not to do to remember it is a PyRef object. use super::{ PyAtomicRef, ext::{AsObject, PyRefExact, PyResult}, payload::PyPayload, }; use crate::object::traverse_object::PyObjVTable; use crate::{ builtins::{PyDictRef, PyType, PyTypeRef}, common::{ atomic::{OncePtr, PyAtomic, Radium}, linked_list::{Link, LinkedList, Pointers}, lock::{PyMutex, PyMutexGuard, PyRwLock}, refcount::RefCount, }, vm::VirtualMachine, }; use crate::{ class::StaticType, object::traverse::{MaybeTraverse, Traverse, TraverseFn}, }; use itertools::Itertools; use alloc::fmt; use core::{ any::TypeId, borrow::Borrow, cell::UnsafeCell, marker::PhantomData, mem::ManuallyDrop, ops::Deref, ptr::{self, NonNull}, }; // so, PyObjectRef is basically equivalent to `PyRc<PyInner<dyn PyObjectPayload>>`, except it's // only one pointer in width rather than 2. We do that by manually creating a vtable, and putting // a &'static reference to it inside the `PyRc` rather than adjacent to it, like trait objects do. // This can lead to faster code since there's just less data to pass around, as well as because of // some weird stuff with trait objects, alignment, and padding. // // So, every type has an alignment, which means that if you create a value of it it's location in // memory has to be a multiple of it's alignment. e.g., a type with alignment 4 (like i32) could be // at 0xb7befbc0, 0xb7befbc4, or 0xb7befbc8, but not 0xb7befbc2. If you have a struct and there are // 2 fields whose sizes/alignments don't perfectly fit in with each other, e.g.: // +-------------+-------------+---------------------------+ // | u16 | ? | i32 | // | 0x00 | 0x01 | 0x02 | 0x03 | 0x04 | 0x05 | 0x06 | 0x07 | // +-------------+-------------+---------------------------+ // There has to be padding in the space between the 2 fields. But, if that field is a trait object // (like `dyn PyObjectPayload`) we don't *know* how much padding there is between the `payload` // field and the previous field. So, Rust has to consult the vtable to know the exact offset of // `payload` in `PyInner<dyn PyObjectPayload>`, which has a huge performance impact when *every // single payload access* requires a vtable lookup. Thankfully, we're able to avoid that because of // the way we use PyObjectRef, in that whenever we want to access the payload we (almost) always // access it from a generic function. So, rather than doing // // - check vtable for payload offset // - get offset in PyInner struct // - call as_any() method of PyObjectPayload // - call downcast_ref() method of Any // we can just do // - check vtable that typeid matches // - pointer cast directly to *const PyInner<T> // // and at that point the compiler can know the offset of `payload` for us because **we've given it a // concrete type to work with before we ever access the `payload` field** /// A type to just represent "we've erased the type of this object, cast it before you use it" #[derive(Debug)] pub(super) struct Erased; pub(super) unsafe fn drop_dealloc_obj<T: PyPayload>(x: *mut PyObject) { drop(unsafe { Box::from_raw(x as *mut PyInner<T>) }); } pub(super) unsafe fn debug_obj<T: PyPayload + core::fmt::Debug>( x: &PyObject, f: &mut fmt::Formatter<'_>, ) -> fmt::Result { let x = unsafe { &*(x as *const PyObject as *const PyInner<T>) }; fmt::Debug::fmt(x, f) } /// Call `try_trace` on payload pub(super) unsafe fn try_trace_obj<T: PyPayload>(x: &PyObject, tracer_fn: &mut TraverseFn<'_>) { let x = unsafe { &*(x as *const PyObject as *const PyInner<T>) }; let payload = &x.payload; payload.try_traverse(tracer_fn) } /// This is an actual python object. It consists of a `typ` which is the /// python class, and carries some rust payload optionally. This rust /// payload can be a rust float or rust int in case of float and int objects. #[repr(C)] pub(super) struct PyInner<T> { pub(super) ref_count: RefCount, // TODO: move typeid into vtable once TypeId::of is const pub(super) typeid: TypeId, pub(super) vtable: &'static PyObjVTable, pub(super) typ: PyAtomicRef<PyType>, // __class__ member pub(super) dict: Option<InstanceDict>, pub(super) weak_list: WeakRefList, pub(super) slots: Box<[PyRwLock<Option<PyObjectRef>>]>, pub(super) payload: T, } pub(crate) const SIZEOF_PYOBJECT_HEAD: usize = core::mem::size_of::<PyInner<()>>(); impl<T: fmt::Debug> fmt::Debug for PyInner<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "[PyObject {:?}]", &self.payload) } } unsafe impl<T: MaybeTraverse> Traverse for Py<T> { /// DO notice that call `trace` on `Py<T>` means apply `tracer_fn` on `Py<T>`'s children, /// not like call `trace` on `PyRef<T>` which apply `tracer_fn` on `PyRef<T>` itself fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { self.0.traverse(tracer_fn) } } unsafe impl Traverse for PyObject { /// DO notice that call `trace` on `PyObject` means apply `tracer_fn` on `PyObject`'s children, /// not like call `trace` on `PyObjectRef` which apply `tracer_fn` on `PyObjectRef` itself fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { self.0.traverse(tracer_fn) } } pub(super) struct WeakRefList { inner: OncePtr<PyMutex<WeakListInner>>, } impl fmt::Debug for WeakRefList { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("WeakRefList").finish_non_exhaustive() } } struct WeakListInner { list: LinkedList<WeakLink, Py<PyWeak>>, generic_weakref: Option<NonNull<Py<PyWeak>>>, obj: Option<NonNull<PyObject>>, // one for each live PyWeak with a reference to this, + 1 for the referent object if it's not dead ref_count: usize, } cfg_if::cfg_if! { if #[cfg(feature = "threading")] { unsafe impl Send for WeakListInner {} unsafe impl Sync for WeakListInner {} } } impl WeakRefList { pub fn new() -> Self { Self { inner: OncePtr::new(), } } /// returns None if there have never been any weakrefs in this list fn try_lock(&self) -> Option<PyMutexGuard<'_, WeakListInner>> { self.inner.get().map(|mu| unsafe { mu.as_ref().lock() }) } fn add( &self, obj: &PyObject, cls: PyTypeRef, cls_is_weakref: bool, callback: Option<PyObjectRef>, dict: Option<PyDictRef>, ) -> PyRef<PyWeak> { let is_generic = cls_is_weakref && callback.is_none(); let inner_ptr = self.inner.get_or_init(|| { Box::new(PyMutex::new(WeakListInner { list: LinkedList::default(), generic_weakref: None, obj: Some(NonNull::from(obj)), ref_count: 1, })) }); let mut inner = unsafe { inner_ptr.as_ref().lock() }; if is_generic && let Some(generic_weakref) = inner.generic_weakref { let generic_weakref = unsafe { generic_weakref.as_ref() }; if generic_weakref.0.ref_count.get() != 0 { return generic_weakref.to_owned(); } } let obj = PyWeak { pointers: Pointers::new(), parent: inner_ptr, callback: UnsafeCell::new(callback), hash: Radium::new(crate::common::hash::SENTINEL), }; let weak = PyRef::new_ref(obj, cls, dict); // SAFETY: we don't actually own the PyObjectWeak's inside `list`, and every time we take // one out of the list we immediately wrap it in ManuallyDrop or forget it inner.list.push_front(unsafe { ptr::read(&weak) }); inner.ref_count += 1; if is_generic { inner.generic_weakref = Some(NonNull::from(&*weak)); } weak } fn clear(&self) { let to_dealloc = { let ptr = match self.inner.get() { Some(ptr) => ptr, None => return, }; let mut inner = unsafe { ptr.as_ref().lock() }; inner.obj = None; // TODO: can be an arrayvec let mut v = Vec::with_capacity(16); loop { let inner2 = &mut *inner; let iter = inner2 .list .drain_filter(|_| true) .filter_map(|wr| { // we don't have actual ownership of the reference counts in the list. // but, now we do want ownership (and so incref these *while the lock // is held*) to avoid weird things if PyWeakObj::drop happens after // this but before we reach the loop body below let wr = ManuallyDrop::new(wr); if Some(NonNull::from(&**wr)) == inner2.generic_weakref { inner2.generic_weakref = None } // if strong_count == 0 there's some reentrancy going on. we don't // want to call the callback (wr.as_object().strong_count() > 0).then(|| (*wr).clone()) }) .take(16); v.extend(iter); if v.is_empty() { break; } PyMutexGuard::unlocked(&mut inner, || { for wr in v.drain(..) { let cb = unsafe { wr.callback.get().replace(None) }; if let Some(cb) = cb { crate::vm::thread::with_vm(&cb, |vm| { // TODO: handle unraisable exception let _ = cb.call((wr.clone(),), vm); }); } } }) } inner.ref_count -= 1; (inner.ref_count == 0).then_some(ptr) }; if let Some(ptr) = to_dealloc { unsafe { Self::dealloc(ptr) } } } fn count(&self) -> usize { self.try_lock() // we assume the object is still alive (and this is only // called from PyObject::weak_count so it should be) .map(|inner| inner.ref_count - 1) .unwrap_or(0) } unsafe fn dealloc(ptr: NonNull<PyMutex<WeakListInner>>) { drop(unsafe { Box::from_raw(ptr.as_ptr()) }); } fn get_weak_references(&self) -> Vec<PyRef<PyWeak>> { let inner = match self.try_lock() { Some(inner) => inner, None => return vec![], }; let mut v = Vec::with_capacity(inner.ref_count - 1); v.extend(inner.iter().map(|wr| wr.to_owned())); v } } impl WeakListInner { fn iter(&self) -> impl Iterator<Item = &Py<PyWeak>> { self.list.iter().filter(|wr| wr.0.ref_count.get() > 0) } } impl Default for WeakRefList { fn default() -> Self { Self::new() } } struct WeakLink; unsafe impl Link for WeakLink { type Handle = PyRef<PyWeak>; type Target = Py<PyWeak>; #[inline(always)] fn as_raw(handle: &PyRef<PyWeak>) -> NonNull<Self::Target> { NonNull::from(&**handle) } #[inline(always)] unsafe fn from_raw(ptr: NonNull<Self::Target>) -> Self::Handle { // SAFETY: requirements forwarded from caller unsafe { PyRef::from_raw(ptr.as_ptr()) } } #[inline(always)] unsafe fn pointers(target: NonNull<Self::Target>) -> NonNull<Pointers<Self::Target>> { // SAFETY: requirements forwarded from caller unsafe { NonNull::new_unchecked(&raw mut (*target.as_ptr()).0.payload.pointers) } } } #[pyclass(name = "weakref", module = false)] #[derive(Debug)] pub struct PyWeak { pointers: Pointers<Py<PyWeak>>, parent: NonNull<PyMutex<WeakListInner>>, // this is treated as part of parent's mutex - you must hold that lock to access it callback: UnsafeCell<Option<PyObjectRef>>, pub(crate) hash: PyAtomic<crate::common::hash::PyHash>, } cfg_if::cfg_if! { if #[cfg(feature = "threading")] { #[allow(clippy::non_send_fields_in_send_ty)] // false positive? unsafe impl Send for PyWeak {} unsafe impl Sync for PyWeak {} } } impl PyWeak { pub(crate) fn upgrade(&self) -> Option<PyObjectRef> { let guard = unsafe { self.parent.as_ref().lock() }; let obj_ptr = guard.obj?; unsafe { if !obj_ptr.as_ref().0.ref_count.safe_inc() { return None; } Some(PyObjectRef::from_raw(obj_ptr)) } } pub(crate) fn is_dead(&self) -> bool { let guard = unsafe { self.parent.as_ref().lock() }; guard.obj.is_none() } fn drop_inner(&self) { let dealloc = { let mut guard = unsafe { self.parent.as_ref().lock() }; let offset = std::mem::offset_of!(PyInner<Self>, payload); let py_inner = (self as *const Self) .cast::<u8>() .wrapping_sub(offset) .cast::<PyInner<Self>>(); let node_ptr = unsafe { NonNull::new_unchecked(py_inner as *mut Py<Self>) }; // the list doesn't have ownership over its PyRef<PyWeak>! we're being dropped // right now so that should be obvious!! core::mem::forget(unsafe { guard.list.remove(node_ptr) }); guard.ref_count -= 1; if Some(node_ptr) == guard.generic_weakref { guard.generic_weakref = None; } guard.ref_count == 0 }; if dealloc { unsafe { WeakRefList::dealloc(self.parent) } } } } impl Drop for PyWeak { #[inline(always)] fn drop(&mut self) { // we do NOT have actual exclusive access! // no clue if doing this actually reduces chance of UB let me: &Self = self; me.drop_inner(); } } impl Py<PyWeak> { #[inline(always)] pub fn upgrade(&self) -> Option<PyObjectRef> { PyWeak::upgrade(self) } } #[derive(Debug)] pub(super) struct InstanceDict { pub(super) d: PyRwLock<PyDictRef>, } impl From<PyDictRef> for InstanceDict { #[inline(always)] fn from(d: PyDictRef) -> Self { Self::new(d) } } impl InstanceDict { #[inline] pub const fn new(d: PyDictRef) -> Self { Self { d: PyRwLock::new(d), } } #[inline] pub fn get(&self) -> PyDictRef { self.d.read().clone() } #[inline] pub fn set(&self, d: PyDictRef) { self.replace(d); } #[inline] pub fn replace(&self, d: PyDictRef) -> PyDictRef { core::mem::replace(&mut self.d.write(), d) } } impl<T: PyPayload + core::fmt::Debug> PyInner<T> { fn new(payload: T, typ: PyTypeRef, dict: Option<PyDictRef>) -> Box<Self> { let member_count = typ.slots.member_count; Box::new(Self { ref_count: RefCount::new(), typeid: T::payload_type_id(), vtable: PyObjVTable::of::<T>(), typ: PyAtomicRef::from(typ), dict: dict.map(InstanceDict::new), weak_list: WeakRefList::new(), payload, slots: core::iter::repeat_with(|| PyRwLock::new(None)) .take(member_count) .collect_vec() .into_boxed_slice(), }) } } /// The `PyObjectRef` is one of the most used types. It is a reference to a /// python object. A single python object can have multiple references, and /// this reference counting is accounted for by this type. Use the `.clone()` /// method to create a new reference and increment the amount of references /// to the python object by 1. #[repr(transparent)] pub struct PyObjectRef { ptr: NonNull<PyObject>, } impl Clone for PyObjectRef { #[inline(always)] fn clone(&self) -> Self { (**self).to_owned() } } cfg_if::cfg_if! { if #[cfg(feature = "threading")] { unsafe impl Send for PyObjectRef {} unsafe impl Sync for PyObjectRef {} } } #[repr(transparent)] pub struct PyObject(PyInner<Erased>); impl Deref for PyObjectRef { type Target = PyObject; #[inline(always)] fn deref(&self) -> &PyObject { unsafe { self.ptr.as_ref() } } } impl ToOwned for PyObject { type Owned = PyObjectRef; #[inline(always)] fn to_owned(&self) -> Self::Owned { self.0.ref_count.inc(); PyObjectRef { ptr: NonNull::from(self), } } } impl PyObjectRef { #[inline(always)] pub const fn into_raw(self) -> NonNull<PyObject> { let ptr = self.ptr; core::mem::forget(self); ptr } /// # Safety /// The raw pointer must have been previously returned from a call to /// [`PyObjectRef::into_raw`]. The user is responsible for ensuring that the inner data is not /// dropped more than once due to mishandling the reference count by calling this function /// too many times. #[inline(always)] pub const unsafe fn from_raw(ptr: NonNull<PyObject>) -> Self { Self { ptr } } /// Attempt to downcast this reference to a subclass. /// /// If the downcast fails, the original ref is returned in as `Err` so /// another downcast can be attempted without unnecessary cloning. #[inline(always)] pub fn downcast<T: PyPayload>(self) -> Result<PyRef<T>, Self> { if self.downcastable::<T>() { Ok(unsafe { self.downcast_unchecked() }) } else { Err(self) } } pub fn try_downcast<T: PyPayload>(self, vm: &VirtualMachine) -> PyResult<PyRef<T>> { T::try_downcast_from(&self, vm)?; Ok(unsafe { self.downcast_unchecked() }) } /// Force to downcast this reference to a subclass. /// /// # Safety /// T must be the exact payload type #[inline(always)] pub unsafe fn downcast_unchecked<T>(self) -> PyRef<T> { // PyRef::from_obj_unchecked(self) // manual impl to avoid assertion let obj = ManuallyDrop::new(self); PyRef { ptr: obj.ptr.cast(), } } // ideally we'd be able to define these in pyobject.rs, but method visibility rules are weird /// Attempt to downcast this reference to the specific class that is associated `T`. /// /// If the downcast fails, the original ref is returned in as `Err` so /// another downcast can be attempted without unnecessary cloning. #[inline] pub fn downcast_exact<T: PyPayload>(self, vm: &VirtualMachine) -> Result<PyRefExact<T>, Self> { if self.class().is(T::class(&vm.ctx)) { // TODO: is this always true? assert!( self.downcastable::<T>(), "obj.__class__ is T::class() but payload is not T" ); // SAFETY: just asserted that downcastable::<T>() Ok(unsafe { PyRefExact::new_unchecked(PyRef::from_obj_unchecked(self)) }) } else { Err(self) } } } impl PyObject { #[inline(always)] const fn weak_ref_list(&self) -> Option<&WeakRefList> { Some(&self.0.weak_list) } pub(crate) fn downgrade_with_weakref_typ_opt( &self, callback: Option<PyObjectRef>, // a reference to weakref_type **specifically** typ: PyTypeRef, ) -> Option<PyRef<PyWeak>> { self.weak_ref_list() .map(|wrl| wrl.add(self, typ, true, callback, None)) } pub(crate) fn downgrade_with_typ( &self, callback: Option<PyObjectRef>, typ: PyTypeRef, vm: &VirtualMachine, ) -> PyResult<PyRef<PyWeak>> { let dict = if typ .slots .flags .has_feature(crate::types::PyTypeFlags::HAS_DICT) { Some(vm.ctx.new_dict()) } else { None }; let cls_is_weakref = typ.is(vm.ctx.types.weakref_type); let wrl = self.weak_ref_list().ok_or_else(|| { vm.new_type_error(format!( "cannot create weak reference to '{}' object", self.class().name() )) })?; Ok(wrl.add(self, typ, cls_is_weakref, callback, dict)) } pub fn downgrade( &self, callback: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<PyRef<PyWeak>> { self.downgrade_with_typ(callback, vm.ctx.types.weakref_type.to_owned(), vm) } pub fn get_weak_references(&self) -> Option<Vec<PyRef<PyWeak>>> { self.weak_ref_list().map(|wrl| wrl.get_weak_references()) } #[deprecated(note = "use downcastable instead")] #[inline(always)] pub fn payload_is<T: PyPayload>(&self) -> bool { self.0.typeid == T::payload_type_id() } /// Force to return payload as T. /// /// # Safety /// The actual payload type must be T. #[deprecated(note = "use downcast_unchecked_ref instead")] #[inline(always)] pub const unsafe fn payload_unchecked<T: PyPayload>(&self) -> &T { // we cast to a PyInner<T> first because we don't know T's exact offset because of // varying alignment, but once we get a PyInner<T> the compiler can get it for us let inner = unsafe { &*(&self.0 as *const PyInner<Erased> as *const PyInner<T>) }; &inner.payload } #[deprecated(note = "use downcast_ref instead")] #[inline(always)] pub fn payload<T: PyPayload>(&self) -> Option<&T> { #[allow(deprecated)] if self.payload_is::<T>() { #[allow(deprecated)] Some(unsafe { self.payload_unchecked() }) } else { None } } #[inline(always)] pub fn class(&self) -> &Py<PyType> { self.0.typ.deref() } pub fn set_class(&self, typ: PyTypeRef, vm: &VirtualMachine) { self.0.typ.swap_to_temporary_refs(typ, vm); } #[deprecated(note = "use downcast_ref_if_exact instead")] #[inline(always)] pub fn payload_if_exact<T: PyPayload>(&self, vm: &VirtualMachine) -> Option<&T> { if self.class().is(T::class(&vm.ctx)) { #[allow(deprecated)] self.payload() } else { None } } #[inline(always)] const fn instance_dict(&self) -> Option<&InstanceDict> { self.0.dict.as_ref() } #[inline(always)] pub fn dict(&self) -> Option<PyDictRef> { self.instance_dict().map(|d| d.get()) } /// Set the dict field. Returns `Err(dict)` if this object does not have a dict field /// in the first place. pub fn set_dict(&self, dict: PyDictRef) -> Result<(), PyDictRef> { match self.instance_dict() { Some(d) => { d.set(dict); Ok(()) } None => Err(dict), } } #[deprecated(note = "use downcast_ref instead")] #[inline(always)] pub fn payload_if_subclass<T: crate::PyPayload>(&self, vm: &VirtualMachine) -> Option<&T> { if self.class().fast_issubclass(T::class(&vm.ctx)) { #[allow(deprecated)] self.payload() } else { None } } #[inline] pub(crate) fn typeid(&self) -> TypeId { self.0.typeid } /// Check if this object can be downcast to T. #[inline(always)] pub fn downcastable<T: PyPayload>(&self) -> bool { T::downcastable_from(self) } /// Attempt to downcast this reference to a subclass. pub fn try_downcast_ref<'a, T: PyPayload>( &'a self, vm: &VirtualMachine, ) -> PyResult<&'a Py<T>> { T::try_downcast_from(self, vm)?; Ok(unsafe { self.downcast_unchecked_ref::<T>() }) } /// Attempt to downcast this reference to a subclass. #[inline(always)] pub fn downcast_ref<T: PyPayload>(&self) -> Option<&Py<T>> { if self.downcastable::<T>() { // SAFETY: just checked that the payload is T, and PyRef is repr(transparent) over // PyObjectRef Some(unsafe { self.downcast_unchecked_ref::<T>() }) } else { None } } #[inline(always)] pub fn downcast_ref_if_exact<T: PyPayload>(&self, vm: &VirtualMachine) -> Option<&Py<T>> { self.class() .is(T::class(&vm.ctx)) .then(|| unsafe { self.downcast_unchecked_ref::<T>() }) } /// # Safety /// T must be the exact payload type #[inline(always)] pub unsafe fn downcast_unchecked_ref<T: PyPayload>(&self) -> &Py<T> { debug_assert!(self.downcastable::<T>()); // SAFETY: requirements forwarded from caller unsafe { &*(self as *const Self as *const Py<T>) } } #[inline(always)] pub fn strong_count(&self) -> usize { self.0.ref_count.get() } #[inline] pub fn weak_count(&self) -> Option<usize> { self.weak_ref_list().map(|wrl| wrl.count()) } #[inline(always)] pub const fn as_raw(&self) -> *const Self { self } #[inline(always)] // the outer function is never inlined fn drop_slow_inner(&self) -> Result<(), ()> { // __del__ is mostly not implemented #[inline(never)] #[cold] fn call_slot_del( zelf: &PyObject, slot_del: fn(&PyObject, &VirtualMachine) -> PyResult<()>, ) -> Result<(), ()> { let ret = crate::vm::thread::with_vm(zelf, |vm| { zelf.0.ref_count.inc(); if let Err(e) = slot_del(zelf, vm) { let del_method = zelf.get_class_attr(identifier!(vm, __del__)).unwrap(); vm.run_unraisable(e, None, del_method); } zelf.0.ref_count.dec() }); match ret { // the decref right above set ref_count back to 0 Some(true) => Ok(()), // we've been resurrected by __del__ Some(false) => Err(()), None => { warn!("couldn't run __del__ method for object"); Ok(()) } } } // CPython-compatible drop implementation let del = self.class().slots.del.load(); if let Some(slot_del) = del { call_slot_del(self, slot_del)?; } if let Some(wrl) = self.weak_ref_list() { wrl.clear(); } Ok(()) } /// Can only be called when ref_count has dropped to zero. `ptr` must be valid #[inline(never)] unsafe fn drop_slow(ptr: NonNull<Self>) { if let Err(()) = unsafe { ptr.as_ref().drop_slow_inner() } { // abort drop for whatever reason return; } let drop_dealloc = unsafe { ptr.as_ref().0.vtable.drop_dealloc }; // call drop only when there are no references in scope - stacked borrows stuff unsafe { drop_dealloc(ptr.as_ptr()) } } /// # Safety /// This call will make the object live forever. pub(crate) unsafe fn mark_intern(&self) { self.0.ref_count.leak(); } pub(crate) fn is_interned(&self) -> bool { self.0.ref_count.is_leaked() } pub(crate) fn get_slot(&self, offset: usize) -> Option<PyObjectRef> { self.0.slots[offset].read().clone() } pub(crate) fn set_slot(&self, offset: usize, value: Option<PyObjectRef>) { *self.0.slots[offset].write() = value; } } impl Borrow<PyObject> for PyObjectRef { #[inline(always)] fn borrow(&self) -> &PyObject { self } } impl AsRef<PyObject> for PyObjectRef { #[inline(always)] fn as_ref(&self) -> &PyObject { self } } impl<'a, T: PyPayload> From<&'a Py<T>> for &'a PyObject { #[inline(always)] fn from(py_ref: &'a Py<T>) -> Self { py_ref.as_object() } } impl Drop for PyObjectRef { #[inline] fn drop(&mut self) { if self.0.ref_count.dec() { unsafe { PyObject::drop_slow(self.ptr) } } } } impl fmt::Debug for PyObject { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // SAFETY: the vtable contains functions that accept payload types that always match up // with the payload of the object unsafe { (self.0.vtable.debug)(self, f) } } } impl fmt::Debug for PyObjectRef { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.as_object().fmt(f) } } #[repr(transparent)] pub struct Py<T>(PyInner<T>); impl<T: PyPayload> Py<T> { pub fn downgrade( &self, callback: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<PyWeakRef<T>> { Ok(PyWeakRef { weak: self.as_object().downgrade(callback, vm)?, _marker: PhantomData, }) } #[inline] pub fn payload(&self) -> &T { &self.0.payload } } impl<T> ToOwned for Py<T> { type Owned = PyRef<T>; #[inline(always)] fn to_owned(&self) -> Self::Owned { self.0.ref_count.inc(); PyRef { ptr: NonNull::from(self), } } } impl<T> Deref for Py<T> { type Target = T; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0.payload } } impl<T: PyPayload> Borrow<PyObject> for Py<T> { #[inline(always)] fn borrow(&self) -> &PyObject { unsafe { &*(&self.0 as *const PyInner<T> as *const PyObject) } } } impl<T> core::hash::Hash for Py<T> where T: core::hash::Hash + PyPayload, { #[inline] fn hash<H: core::hash::Hasher>(&self, state: &mut H) { self.deref().hash(state) } } impl<T> PartialEq for Py<T> where T: PartialEq + PyPayload, { #[inline] fn eq(&self, other: &Self) -> bool { self.deref().eq(other.deref()) } } impl<T> Eq for Py<T> where T: Eq + PyPayload {} impl<T> AsRef<PyObject> for Py<T> where T: PyPayload, { #[inline(always)] fn as_ref(&self) -> &PyObject { self.borrow() } } impl<T: PyPayload + core::fmt::Debug> fmt::Debug for Py<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { (**self).fmt(f) } } /// A reference to a Python object. /// /// Note that a `PyRef<T>` can only deref to a shared / immutable reference. /// It is the payload type's responsibility to handle (possibly concurrent) /// mutability with locks or concurrent data structures if required. /// /// A `PyRef<T>` can be directly returned from a built-in function to handle /// situations (such as when implementing in-place methods such as `__iadd__`) /// where a reference to the same object must be returned. #[repr(transparent)] pub struct PyRef<T> { ptr: NonNull<Py<T>>, } cfg_if::cfg_if! { if #[cfg(feature = "threading")] { unsafe impl<T> Send for PyRef<T> {} unsafe impl<T> Sync for PyRef<T> {} } } impl<T: fmt::Debug> fmt::Debug for PyRef<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { (**self).fmt(f) } } impl<T> Drop for PyRef<T> { #[inline] fn drop(&mut self) { if self.0.ref_count.dec() { unsafe { PyObject::drop_slow(self.ptr.cast::<PyObject>()) } } } } impl<T> Clone for PyRef<T> { #[inline(always)] fn clone(&self) -> Self { (**self).to_owned() } } impl<T: PyPayload> PyRef<T> { // #[inline(always)] // pub(crate) const fn into_non_null(self) -> NonNull<Py<T>> { // let ptr = self.ptr; // std::mem::forget(self); // ptr // } #[inline(always)] pub(crate) const unsafe fn from_non_null(ptr: NonNull<Py<T>>) -> Self { Self { ptr } } /// # Safety /// The raw pointer must point to a valid `Py<T>` object #[inline(always)] pub(crate) const unsafe fn from_raw(raw: *const Py<T>) -> Self { unsafe { Self::from_non_null(NonNull::new_unchecked(raw as *mut _)) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/object/traverse_object.rs
crates/vm/src/object/traverse_object.rs
use alloc::fmt; use crate::{ PyObject, object::{ Erased, InstanceDict, MaybeTraverse, PyInner, PyObjectPayload, debug_obj, drop_dealloc_obj, try_trace_obj, }, }; use super::{Traverse, TraverseFn}; pub(in crate::object) struct PyObjVTable { pub(in crate::object) drop_dealloc: unsafe fn(*mut PyObject), pub(in crate::object) debug: unsafe fn(&PyObject, &mut fmt::Formatter<'_>) -> fmt::Result, pub(in crate::object) trace: Option<unsafe fn(&PyObject, &mut TraverseFn<'_>)>, } impl PyObjVTable { pub const fn of<T: PyObjectPayload>() -> &'static Self { &Self { drop_dealloc: drop_dealloc_obj::<T>, debug: debug_obj::<T>, trace: const { if T::IS_TRACE { Some(try_trace_obj::<T>) } else { None } }, } } } unsafe impl Traverse for InstanceDict { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { self.d.traverse(tracer_fn) } } unsafe impl Traverse for PyInner<Erased> { /// Because PyObject hold a `PyInner<Erased>`, so we need to trace it fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { // 1. trace `dict` and `slots` field(`typ` can't trace for it's a AtomicRef while is leaked by design) // 2. call vtable's trace function to trace payload // self.typ.trace(tracer_fn); self.dict.traverse(tracer_fn); // weak_list keeps a *pointer* to a struct for maintenance of weak ref, so no ownership, no trace self.slots.traverse(tracer_fn); if let Some(f) = self.vtable.trace { unsafe { let zelf = &*(self as *const Self as *const PyObject); f(zelf, tracer_fn) } }; } } unsafe impl<T: MaybeTraverse> Traverse for PyInner<T> { /// Type is known, so we can call `try_trace` directly instead of using erased type vtable fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { // 1. trace `dict` and `slots` field(`typ` can't trace for it's a AtomicRef while is leaked by design) // 2. call corresponding `try_trace` function to trace payload // (No need to call vtable's trace function because we already know the type) // self.typ.trace(tracer_fn); self.dict.traverse(tracer_fn); // weak_list keeps a *pointer* to a struct for maintenance of weak ref, so no ownership, no trace self.slots.traverse(tracer_fn); T::try_traverse(&self.payload, tracer_fn); } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/object/mod.rs
crates/vm/src/object/mod.rs
mod core; mod ext; mod payload; mod traverse; mod traverse_object; pub use self::core::*; pub use self::ext::*; pub use self::payload::*; pub(crate) use core::SIZEOF_PYOBJECT_HEAD; pub use traverse::{MaybeTraverse, Traverse, TraverseFn};
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/object/traverse.rs
crates/vm/src/object/traverse.rs
use core::ptr::NonNull; use rustpython_common::lock::{PyMutex, PyRwLock}; use crate::{AsObject, PyObject, PyObjectRef, PyRef, function::Either, object::PyObjectPayload}; pub type TraverseFn<'a> = dyn FnMut(&PyObject) + 'a; /// This trait is used as a "Optional Trait"(I 'd like to use `Trace?` but it's not allowed yet) for PyObjectPayload type /// /// impl for PyObjectPayload, `pyclass` proc macro will handle the actual dispatch if type impl `Trace` /// Every PyObjectPayload impl `MaybeTrace`, which may or may not be traceable pub trait MaybeTraverse { /// if is traceable, will be used by vtable to determine const IS_TRACE: bool = false; // if this type is traceable, then call with tracer_fn, default to do nothing fn try_traverse(&self, traverse_fn: &mut TraverseFn<'_>); } /// Type that need traverse it's children should impl [`Traverse`] (not [`MaybeTraverse`]) /// # Safety /// Please carefully read [`Traverse::traverse()`] and follow the guideline pub unsafe trait Traverse { /// impl `traverse()` with caution! Following those guideline so traverse doesn't cause memory error!: /// - Make sure that every owned object(Every PyObjectRef/PyRef) is called with traverse_fn **at most once**. /// If some field is not called, the worst results is just memory leak, /// but if some field is called repeatedly, panic and deadlock can happen. /// /// - _**DO NOT**_ clone a [`PyObjectRef`] or [`PyRef<T>`] in [`Traverse::traverse()`] fn traverse(&self, traverse_fn: &mut TraverseFn<'_>); } unsafe impl Traverse for PyObjectRef { fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) { traverse_fn(self) } } unsafe impl<T: PyObjectPayload> Traverse for PyRef<T> { fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) { traverse_fn(self.as_object()) } } unsafe impl Traverse for () { fn traverse(&self, _traverse_fn: &mut TraverseFn<'_>) {} } unsafe impl<T: Traverse> Traverse for Option<T> { #[inline] fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) { if let Some(v) = self { v.traverse(traverse_fn); } } } unsafe impl<T> Traverse for [T] where T: Traverse, { #[inline] fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) { for elem in self { elem.traverse(traverse_fn); } } } unsafe impl<T> Traverse for Box<[T]> where T: Traverse, { #[inline] fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) { for elem in &**self { elem.traverse(traverse_fn); } } } unsafe impl<T> Traverse for Vec<T> where T: Traverse, { #[inline] fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) { for elem in self { elem.traverse(traverse_fn); } } } unsafe impl<T: Traverse> Traverse for PyRwLock<T> { #[inline] fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) { // if can't get a lock, this means something else is holding the lock, // but since gc stopped the world, during gc the lock is always held // so it is safe to ignore those in gc if let Some(inner) = self.try_read_recursive() { inner.traverse(traverse_fn) } } } /// Safety: We can't hold lock during traverse it's child because it may cause deadlock. /// TODO(discord9): check if this is thread-safe to do /// (Outside of gc phase, only incref/decref will call trace, /// and refcnt is atomic, so it should be fine?) unsafe impl<T: Traverse> Traverse for PyMutex<T> { #[inline] fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) { let mut chs: Vec<NonNull<PyObject>> = Vec::new(); if let Some(obj) = self.try_lock() { obj.traverse(&mut |ch| { chs.push(NonNull::from(ch)); }) } chs.iter() .map(|ch| { // Safety: during gc, this should be fine, because nothing should write during gc's tracing? let ch = unsafe { ch.as_ref() }; traverse_fn(ch); }) .count(); } } macro_rules! trace_tuple { ($(($NAME: ident, $NUM: tt)),*) => { unsafe impl<$($NAME: Traverse),*> Traverse for ($($NAME),*) { #[inline] fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) { $( self.$NUM.traverse(traverse_fn); )* } } }; } unsafe impl<A: Traverse, B: Traverse> Traverse for Either<A, B> { #[inline] fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { match self { Self::A(a) => a.traverse(tracer_fn), Self::B(b) => b.traverse(tracer_fn), } } } // only tuple with 12 elements or less is supported, // because long tuple is extremely rare in almost every case unsafe impl<A: Traverse> Traverse for (A,) { #[inline] fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { self.0.traverse(tracer_fn); } } trace_tuple!((A, 0), (B, 1)); trace_tuple!((A, 0), (B, 1), (C, 2)); trace_tuple!((A, 0), (B, 1), (C, 2), (D, 3)); trace_tuple!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4)); trace_tuple!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5)); trace_tuple!((A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6)); trace_tuple!( (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7) ); trace_tuple!( (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8) ); trace_tuple!( (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9) ); trace_tuple!( (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10) ); trace_tuple!( (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9), (K, 10), (L, 11) );
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/object/payload.rs
crates/vm/src/object/payload.rs
use crate::object::{MaybeTraverse, Py, PyObjectRef, PyRef, PyResult}; use crate::{ PyObject, PyRefExact, builtins::{PyBaseExceptionRef, PyType, PyTypeRef}, types::PyTypeFlags, vm::{Context, VirtualMachine}, }; cfg_if::cfg_if! { if #[cfg(feature = "threading")] { pub trait PyThreadingConstraint: Send + Sync {} impl<T: Send + Sync> PyThreadingConstraint for T {} } else { pub trait PyThreadingConstraint {} impl<T> PyThreadingConstraint for T {} } } #[cold] pub(crate) fn cold_downcast_type_error( vm: &VirtualMachine, class: &Py<PyType>, obj: &PyObject, ) -> PyBaseExceptionRef { vm.new_downcast_type_error(class, obj) } pub trait PyPayload: MaybeTraverse + PyThreadingConstraint + Sized + 'static { #[inline] fn payload_type_id() -> core::any::TypeId { core::any::TypeId::of::<Self>() } /// # Safety: this function should only be called if `payload_type_id` matches the type of `obj`. #[inline] fn downcastable_from(obj: &PyObject) -> bool { obj.typeid() == Self::payload_type_id() && Self::validate_downcastable_from(obj) } #[inline] fn validate_downcastable_from(_obj: &PyObject) -> bool { true } fn try_downcast_from(obj: &PyObject, vm: &VirtualMachine) -> PyResult<()> { if Self::downcastable_from(obj) { return Ok(()); } let class = Self::class(&vm.ctx); Err(cold_downcast_type_error(vm, class, obj)) } fn class(ctx: &Context) -> &'static Py<PyType>; #[inline] fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef where Self: core::fmt::Debug, { self.into_ref(&vm.ctx).into() } #[inline] fn _into_ref(self, cls: PyTypeRef, ctx: &Context) -> PyRef<Self> where Self: core::fmt::Debug, { let dict = if cls.slots.flags.has_feature(PyTypeFlags::HAS_DICT) { Some(ctx.new_dict()) } else { None }; PyRef::new_ref(self, cls, dict) } #[inline] fn into_exact_ref(self, ctx: &Context) -> PyRefExact<Self> where Self: core::fmt::Debug, { unsafe { // Self::into_ref() always returns exact typed PyRef PyRefExact::new_unchecked(self.into_ref(ctx)) } } #[inline] fn into_ref(self, ctx: &Context) -> PyRef<Self> where Self: core::fmt::Debug, { let cls = Self::class(ctx); self._into_ref(cls.to_owned(), ctx) } #[inline] fn into_ref_with_type(self, vm: &VirtualMachine, cls: PyTypeRef) -> PyResult<PyRef<Self>> where Self: core::fmt::Debug, { let exact_class = Self::class(&vm.ctx); if cls.fast_issubclass(exact_class) { if exact_class.slots.basicsize != cls.slots.basicsize { #[cold] #[inline(never)] fn _into_ref_size_error( vm: &VirtualMachine, cls: &Py<PyType>, exact_class: &Py<PyType>, ) -> PyBaseExceptionRef { vm.new_type_error(format!( "cannot create '{}' instance: size differs from base type '{}'", cls.name(), exact_class.name() )) } return Err(_into_ref_size_error(vm, &cls, exact_class)); } Ok(self._into_ref(cls, &vm.ctx)) } else { #[cold] #[inline(never)] fn _into_ref_with_type_error( vm: &VirtualMachine, cls: &Py<PyType>, exact_class: &Py<PyType>, ) -> PyBaseExceptionRef { vm.new_type_error(format!( "'{}' is not a subtype of '{}'", &cls.name(), exact_class.name() )) } Err(_into_ref_with_type_error(vm, &cls, exact_class)) } } } pub trait PyObjectPayload: PyPayload + core::any::Any + core::fmt::Debug + MaybeTraverse + PyThreadingConstraint + 'static { } impl<T: PyPayload + core::fmt::Debug + 'static> PyObjectPayload for T {} pub trait SlotOffset { fn offset() -> usize; }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/types/slot.rs
crates/vm/src/types/slot.rs
use crate::common::lock::{ PyMappedRwLockReadGuard, PyMappedRwLockWriteGuard, PyRwLockReadGuard, PyRwLockWriteGuard, }; use crate::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::{PyInt, PyStr, PyStrInterned, PyStrRef, PyType, PyTypeRef}, bytecode::ComparisonOperator, common::hash::{PyHash, fix_sentinel, hash_bigint}, convert::ToPyObject, function::{ Either, FromArgs, FuncArgs, OptionalArg, PyComparisonValue, PyMethodDef, PySetterValue, }, protocol::{ PyBuffer, PyIterReturn, PyMapping, PyMappingMethods, PyMappingSlots, PyNumber, PyNumberMethods, PyNumberSlots, PySequence, PySequenceMethods, PySequenceSlots, }, types::slot_defs::{SlotAccessor, find_slot_defs_by_name}, vm::Context, }; use core::{any::Any, any::TypeId, borrow::Borrow, cmp::Ordering, ops::Deref}; use crossbeam_utils::atomic::AtomicCell; use num_traits::{Signed, ToPrimitive}; /// Type-erased storage for extension module data attached to heap types. pub struct TypeDataSlot { // PyObject_GetTypeData type_id: TypeId, data: Box<dyn Any + Send + Sync>, } impl TypeDataSlot { /// Create a new type data slot with the given data. pub fn new<T: Any + Send + Sync + 'static>(data: T) -> Self { Self { type_id: TypeId::of::<T>(), data: Box::new(data), } } /// Get a reference to the data if the type matches. pub fn get<T: Any + 'static>(&self) -> Option<&T> { if self.type_id == TypeId::of::<T>() { self.data.downcast_ref() } else { None } } /// Get a mutable reference to the data if the type matches. pub fn get_mut<T: Any + 'static>(&mut self) -> Option<&mut T> { if self.type_id == TypeId::of::<T>() { self.data.downcast_mut() } else { None } } } /// Read guard for type data access, using mapped guard for zero-cost deref. pub struct TypeDataRef<'a, T: 'static> { guard: PyMappedRwLockReadGuard<'a, T>, } impl<'a, T: Any + 'static> TypeDataRef<'a, T> { /// Try to create a TypeDataRef from a read guard. /// Returns None if the slot is empty or contains a different type. pub fn try_new(guard: PyRwLockReadGuard<'a, Option<TypeDataSlot>>) -> Option<Self> { PyRwLockReadGuard::try_map(guard, |opt| opt.as_ref().and_then(|slot| slot.get::<T>())) .ok() .map(|guard| Self { guard }) } } impl<T: Any + 'static> core::ops::Deref for TypeDataRef<'_, T> { type Target = T; fn deref(&self) -> &Self::Target { &self.guard } } /// Write guard for type data access, using mapped guard for zero-cost deref. pub struct TypeDataRefMut<'a, T: 'static> { guard: PyMappedRwLockWriteGuard<'a, T>, } impl<'a, T: Any + 'static> TypeDataRefMut<'a, T> { /// Try to create a TypeDataRefMut from a write guard. /// Returns None if the slot is empty or contains a different type. pub fn try_new(guard: PyRwLockWriteGuard<'a, Option<TypeDataSlot>>) -> Option<Self> { PyRwLockWriteGuard::try_map(guard, |opt| { opt.as_mut().and_then(|slot| slot.get_mut::<T>()) }) .ok() .map(|guard| Self { guard }) } } impl<T: Any + 'static> core::ops::Deref for TypeDataRefMut<'_, T> { type Target = T; fn deref(&self) -> &Self::Target { &self.guard } } impl<T: Any + 'static> core::ops::DerefMut for TypeDataRefMut<'_, T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.guard } } #[macro_export] macro_rules! atomic_func { ($x:expr) => { Some($x) }; } // The corresponding field in CPython is `tp_` prefixed. // e.g. name -> tp_name #[derive(Default)] #[non_exhaustive] pub struct PyTypeSlots { /// # Safety /// For static types, always safe. /// For heap types, `__name__` must alive pub(crate) name: &'static str, // tp_name with <module>.<class> for print, not class name pub basicsize: usize, pub itemsize: usize, // tp_itemsize // Methods to implement standard operations // Method suites for standard classes pub as_number: PyNumberSlots, pub as_sequence: PySequenceSlots, pub as_mapping: PyMappingSlots, // More standard operations (here for binary compatibility) pub hash: AtomicCell<Option<HashFunc>>, pub call: AtomicCell<Option<GenericMethod>>, pub str: AtomicCell<Option<StringifyFunc>>, pub repr: AtomicCell<Option<StringifyFunc>>, pub getattro: AtomicCell<Option<GetattroFunc>>, pub setattro: AtomicCell<Option<SetattroFunc>>, // Functions to access object as input/output buffer pub as_buffer: Option<AsBufferFunc>, // Assigned meaning in release 2.1 // rich comparisons pub richcompare: AtomicCell<Option<RichCompareFunc>>, // Iterators pub iter: AtomicCell<Option<IterFunc>>, pub iternext: AtomicCell<Option<IterNextFunc>>, pub methods: &'static [PyMethodDef], // Flags to define presence of optional/expanded features pub flags: PyTypeFlags, // tp_doc pub doc: Option<&'static str>, // Strong reference on a heap type, borrowed reference on a static type // tp_base // tp_dict pub descr_get: AtomicCell<Option<DescrGetFunc>>, pub descr_set: AtomicCell<Option<DescrSetFunc>>, // tp_dictoffset pub init: AtomicCell<Option<InitFunc>>, // tp_alloc pub new: AtomicCell<Option<NewFunc>>, // tp_free // tp_is_gc // tp_bases // tp_mro // tp_cache // tp_subclasses // tp_weaklist pub del: AtomicCell<Option<DelFunc>>, // The count of tp_members. pub member_count: usize, } impl PyTypeSlots { pub fn new(name: &'static str, flags: PyTypeFlags) -> Self { Self { name, flags, ..Default::default() } } pub fn heap_default() -> Self { Self { // init: AtomicCell::new(Some(init_wrapper)), ..Default::default() } } } impl core::fmt::Debug for PyTypeSlots { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.write_str("PyTypeSlots") } } bitflags! { #[derive(Copy, Clone, Debug, PartialEq)] #[non_exhaustive] pub struct PyTypeFlags: u64 { const MANAGED_DICT = 1 << 4; const SEQUENCE = 1 << 5; const MAPPING = 1 << 6; const DISALLOW_INSTANTIATION = 1 << 7; const IMMUTABLETYPE = 1 << 8; const HEAPTYPE = 1 << 9; const BASETYPE = 1 << 10; const METHOD_DESCRIPTOR = 1 << 17; // For built-in types that match the subject itself in pattern matching // (bool, int, float, str, bytes, bytearray, list, tuple, dict, set, frozenset) // This is not a stable API const _MATCH_SELF = 1 << 22; const HAS_DICT = 1 << 40; #[cfg(debug_assertions)] const _CREATED_WITH_FLAGS = 1 << 63; } } impl PyTypeFlags { // Default used for both built-in and normal classes: empty, for now. // CPython default: Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | Py_TPFLAGS_HAVE_VERSION_TAG pub const DEFAULT: Self = Self::empty(); // CPython: See initialization of flags in type_new. /// Used for types created in Python. Subclassable and are a /// heaptype. pub const fn heap_type_flags() -> Self { match Self::from_bits(Self::DEFAULT.bits() | Self::HEAPTYPE.bits() | Self::BASETYPE.bits()) { Some(flags) => flags, None => unreachable!(), } } pub const fn has_feature(self, flag: Self) -> bool { self.contains(flag) } #[cfg(debug_assertions)] pub const fn is_created_with_flags(self) -> bool { self.contains(Self::_CREATED_WITH_FLAGS) } } impl Default for PyTypeFlags { fn default() -> Self { Self::DEFAULT } } pub(crate) type GenericMethod = fn(&PyObject, FuncArgs, &VirtualMachine) -> PyResult; pub(crate) type HashFunc = fn(&PyObject, &VirtualMachine) -> PyResult<PyHash>; // CallFunc = GenericMethod pub(crate) type StringifyFunc = fn(&PyObject, &VirtualMachine) -> PyResult<PyRef<PyStr>>; pub(crate) type GetattroFunc = fn(&PyObject, &Py<PyStr>, &VirtualMachine) -> PyResult; pub(crate) type SetattroFunc = fn(&PyObject, &Py<PyStr>, PySetterValue, &VirtualMachine) -> PyResult<()>; pub(crate) type AsBufferFunc = fn(&PyObject, &VirtualMachine) -> PyResult<PyBuffer>; pub(crate) type RichCompareFunc = fn( &PyObject, &PyObject, PyComparisonOp, &VirtualMachine, ) -> PyResult<Either<PyObjectRef, PyComparisonValue>>; pub(crate) type IterFunc = fn(PyObjectRef, &VirtualMachine) -> PyResult; pub(crate) type IterNextFunc = fn(&PyObject, &VirtualMachine) -> PyResult<PyIterReturn>; pub(crate) type DescrGetFunc = fn(PyObjectRef, Option<PyObjectRef>, Option<PyObjectRef>, &VirtualMachine) -> PyResult; pub(crate) type DescrSetFunc = fn(&PyObject, PyObjectRef, PySetterValue, &VirtualMachine) -> PyResult<()>; pub(crate) type NewFunc = fn(PyTypeRef, FuncArgs, &VirtualMachine) -> PyResult; pub(crate) type InitFunc = fn(PyObjectRef, FuncArgs, &VirtualMachine) -> PyResult<()>; pub(crate) type DelFunc = fn(&PyObject, &VirtualMachine) -> PyResult<()>; // Sequence sub-slot function types pub(crate) type SeqLenFunc = fn(PySequence<'_>, &VirtualMachine) -> PyResult<usize>; pub(crate) type SeqConcatFunc = fn(PySequence<'_>, &PyObject, &VirtualMachine) -> PyResult; pub(crate) type SeqRepeatFunc = fn(PySequence<'_>, isize, &VirtualMachine) -> PyResult; pub(crate) type SeqItemFunc = fn(PySequence<'_>, isize, &VirtualMachine) -> PyResult; pub(crate) type SeqAssItemFunc = fn(PySequence<'_>, isize, Option<PyObjectRef>, &VirtualMachine) -> PyResult<()>; pub(crate) type SeqContainsFunc = fn(PySequence<'_>, &PyObject, &VirtualMachine) -> PyResult<bool>; // Mapping sub-slot function types pub(crate) type MapLenFunc = fn(PyMapping<'_>, &VirtualMachine) -> PyResult<usize>; pub(crate) type MapSubscriptFunc = fn(PyMapping<'_>, &PyObject, &VirtualMachine) -> PyResult; pub(crate) type MapAssSubscriptFunc = fn(PyMapping<'_>, &PyObject, Option<PyObjectRef>, &VirtualMachine) -> PyResult<()>; // slot_sq_length pub(crate) fn len_wrapper(obj: &PyObject, vm: &VirtualMachine) -> PyResult<usize> { let ret = vm.call_special_method(obj, identifier!(vm, __len__), ())?; let len = ret.downcast_ref::<PyInt>().ok_or_else(|| { vm.new_type_error(format!( "'{}' object cannot be interpreted as an integer", ret.class() )) })?; let len = len.as_bigint(); if len.is_negative() { return Err(vm.new_value_error("__len__() should return >= 0")); } let len = len .to_isize() .ok_or_else(|| vm.new_overflow_error("cannot fit 'int' into an index-sized integer"))?; Ok(len as usize) } pub(crate) fn contains_wrapper( obj: &PyObject, needle: &PyObject, vm: &VirtualMachine, ) -> PyResult<bool> { let ret = vm.call_special_method(obj, identifier!(vm, __contains__), (needle,))?; ret.try_to_bool(vm) } macro_rules! number_unary_op_wrapper { ($name:ident) => { |a, vm| vm.call_special_method(a.deref(), identifier!(vm, $name), ()) }; } macro_rules! number_binary_op_wrapper { ($name:ident) => { |a, b, vm| vm.call_special_method(a, identifier!(vm, $name), (b.to_owned(),)) }; } macro_rules! number_binary_right_op_wrapper { ($name:ident) => { |a, b, vm| vm.call_special_method(b, identifier!(vm, $name), (a.to_owned(),)) }; } macro_rules! number_ternary_op_wrapper { ($name:ident) => { |a, b, c, vm: &VirtualMachine| { if vm.is_none(c) { vm.call_special_method(a, identifier!(vm, $name), (b.to_owned(),)) } else { vm.call_special_method(a, identifier!(vm, $name), (b.to_owned(), c.to_owned())) } } }; } macro_rules! number_ternary_right_op_wrapper { ($name:ident) => { |a, b, c, vm: &VirtualMachine| { if vm.is_none(c) { vm.call_special_method(b, identifier!(vm, $name), (a.to_owned(),)) } else { vm.call_special_method(b, identifier!(vm, $name), (a.to_owned(), c.to_owned())) } } }; } fn getitem_wrapper<K: ToPyObject>(obj: &PyObject, needle: K, vm: &VirtualMachine) -> PyResult { vm.call_special_method(obj, identifier!(vm, __getitem__), (needle,)) } fn setitem_wrapper<K: ToPyObject>( obj: &PyObject, needle: K, value: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<()> { match value { Some(value) => vm.call_special_method(obj, identifier!(vm, __setitem__), (needle, value)), None => vm.call_special_method(obj, identifier!(vm, __delitem__), (needle,)), } .map(drop) } #[inline(never)] fn mapping_setitem_wrapper( mapping: PyMapping<'_>, key: &PyObject, value: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<()> { setitem_wrapper(mapping.obj, key, value, vm) } #[inline(never)] fn mapping_getitem_wrapper( mapping: PyMapping<'_>, key: &PyObject, vm: &VirtualMachine, ) -> PyResult { getitem_wrapper(mapping.obj, key, vm) } #[inline(never)] fn mapping_len_wrapper(mapping: PyMapping<'_>, vm: &VirtualMachine) -> PyResult<usize> { len_wrapper(mapping.obj, vm) } #[inline(never)] fn sequence_len_wrapper(seq: PySequence<'_>, vm: &VirtualMachine) -> PyResult<usize> { len_wrapper(seq.obj, vm) } #[inline(never)] fn sequence_getitem_wrapper(seq: PySequence<'_>, i: isize, vm: &VirtualMachine) -> PyResult { getitem_wrapper(seq.obj, i, vm) } #[inline(never)] fn sequence_setitem_wrapper( seq: PySequence<'_>, i: isize, value: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult<()> { setitem_wrapper(seq.obj, i, value, vm) } #[inline(never)] fn sequence_contains_wrapper( seq: PySequence<'_>, needle: &PyObject, vm: &VirtualMachine, ) -> PyResult<bool> { contains_wrapper(seq.obj, needle, vm) } #[inline(never)] fn sequence_repeat_wrapper(seq: PySequence<'_>, n: isize, vm: &VirtualMachine) -> PyResult { vm.call_special_method(seq.obj, identifier!(vm, __mul__), (n,)) } #[inline(never)] fn sequence_inplace_repeat_wrapper(seq: PySequence<'_>, n: isize, vm: &VirtualMachine) -> PyResult { vm.call_special_method(seq.obj, identifier!(vm, __imul__), (n,)) } fn repr_wrapper(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyRef<PyStr>> { let ret = vm.call_special_method(zelf, identifier!(vm, __repr__), ())?; ret.downcast::<PyStr>().map_err(|obj| { vm.new_type_error(format!( "__repr__ returned non-string (type {})", obj.class() )) }) } fn str_wrapper(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyRef<PyStr>> { let ret = vm.call_special_method(zelf, identifier!(vm, __str__), ())?; ret.downcast::<PyStr>().map_err(|obj| { vm.new_type_error(format!( "__str__ returned non-string (type {})", obj.class() )) }) } fn hash_wrapper(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyHash> { let hash_obj = vm.call_special_method(zelf, identifier!(vm, __hash__), ())?; let py_int = hash_obj .downcast_ref::<PyInt>() .ok_or_else(|| vm.new_type_error("__hash__ method should return an integer"))?; let big_int = py_int.as_bigint(); let hash = big_int .to_i64() .map(fix_sentinel) .unwrap_or_else(|| hash_bigint(big_int)); Ok(hash) } /// Marks a type as unhashable. Similar to PyObject_HashNotImplemented in CPython pub fn hash_not_implemented(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyHash> { Err(vm.new_type_error(format!("unhashable type: {}", zelf.class().name()))) } fn call_wrapper(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult { vm.call_special_method(zelf, identifier!(vm, __call__), args) } fn getattro_wrapper(zelf: &PyObject, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult { let __getattribute__ = identifier!(vm, __getattribute__); let __getattr__ = identifier!(vm, __getattr__); match vm.call_special_method(zelf, __getattribute__, (name.to_owned(),)) { Ok(r) => Ok(r), Err(e) if e.fast_isinstance(vm.ctx.exceptions.attribute_error) && zelf.class().has_attr(__getattr__) => { vm.call_special_method(zelf, __getattr__, (name.to_owned(),)) } Err(e) => Err(e), } } fn setattro_wrapper( zelf: &PyObject, name: &Py<PyStr>, value: PySetterValue, vm: &VirtualMachine, ) -> PyResult<()> { let name = name.to_owned(); match value { PySetterValue::Assign(value) => { vm.call_special_method(zelf, identifier!(vm, __setattr__), (name, value))?; } PySetterValue::Delete => { vm.call_special_method(zelf, identifier!(vm, __delattr__), (name,))?; } }; Ok(()) } pub(crate) fn richcompare_wrapper( zelf: &PyObject, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<Either<PyObjectRef, PyComparisonValue>> { vm.call_special_method(zelf, op.method_name(&vm.ctx), (other.to_owned(),)) .map(Either::A) } fn iter_wrapper(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { vm.call_special_method(&zelf, identifier!(vm, __iter__), ()) } fn bool_wrapper(num: PyNumber<'_>, vm: &VirtualMachine) -> PyResult<bool> { let result = vm.call_special_method(num.obj, identifier!(vm, __bool__), ())?; // __bool__ must return exactly bool, not int subclass if !result.class().is(vm.ctx.types.bool_type) { return Err(vm.new_type_error(format!( "__bool__ should return bool, returned {}", result.class().name() ))); } Ok(crate::builtins::bool_::get_value(&result)) } // PyObject_SelfIter in CPython const fn self_iter(zelf: PyObjectRef, _vm: &VirtualMachine) -> PyResult { Ok(zelf) } fn iternext_wrapper(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyIterReturn> { PyIterReturn::from_pyresult( vm.call_special_method(zelf, identifier!(vm, __next__), ()), vm, ) } fn descr_get_wrapper( zelf: PyObjectRef, obj: Option<PyObjectRef>, cls: Option<PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { vm.call_special_method(&zelf, identifier!(vm, __get__), (obj, cls)) } fn descr_set_wrapper( zelf: &PyObject, obj: PyObjectRef, value: PySetterValue, vm: &VirtualMachine, ) -> PyResult<()> { match value { PySetterValue::Assign(val) => { vm.call_special_method(zelf, identifier!(vm, __set__), (obj, val)) } PySetterValue::Delete => vm.call_special_method(zelf, identifier!(vm, __delete__), (obj,)), } .map(drop) } fn init_wrapper(obj: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { let res = vm.call_special_method(&obj, identifier!(vm, __init__), args)?; if !vm.is_none(&res) { return Err(vm.new_type_error(format!( "__init__ should return None, not '{:.200}'", res.class().name() ))); } Ok(()) } pub(crate) fn new_wrapper(cls: PyTypeRef, mut args: FuncArgs, vm: &VirtualMachine) -> PyResult { let new = cls.get_attr(identifier!(vm, __new__)).unwrap(); args.prepend_arg(cls.into()); new.call(args, vm) } fn del_wrapper(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<()> { vm.call_special_method(zelf, identifier!(vm, __del__), ())?; Ok(()) } impl PyType { /// Update slots based on dunder method changes /// /// Iterates SLOT_DEFS to find all slots matching the given name and updates them. /// Also recursively updates subclasses that don't have their own definition. pub(crate) fn update_slot<const ADD: bool>(&self, name: &'static PyStrInterned, ctx: &Context) { debug_assert!(name.as_str().starts_with("__")); debug_assert!(name.as_str().ends_with("__")); // Find all slot_defs matching this name and update each // NOTE: Collect into Vec first to avoid issues during iteration let defs: Vec<_> = find_slot_defs_by_name(name.as_str()).collect(); for def in defs { self.update_one_slot::<ADD>(&def.accessor, name, ctx); } // Recursively update subclasses that don't have their own definition self.update_subclasses::<ADD>(name, ctx); } /// Recursively update subclasses' slots /// recurse_down_subclasses fn update_subclasses<const ADD: bool>(&self, name: &'static PyStrInterned, ctx: &Context) { let subclasses = self.subclasses.read(); for weak_ref in subclasses.iter() { let Some(subclass) = weak_ref.upgrade() else { continue; }; let Some(subclass) = subclass.downcast_ref::<PyType>() else { continue; }; // Skip if subclass has its own definition for this attribute if subclass.attributes.read().contains_key(name) { continue; } // Update subclass's slots for def in find_slot_defs_by_name(name.as_str()) { subclass.update_one_slot::<ADD>(&def.accessor, name, ctx); } // Recurse into subclass's subclasses subclass.update_subclasses::<ADD>(name, ctx); } } /// Update a single slot fn update_one_slot<const ADD: bool>( &self, accessor: &SlotAccessor, name: &'static PyStrInterned, ctx: &Context, ) { use crate::builtins::descriptor::SlotFunc; // Helper macro for main slots macro_rules! update_main_slot { ($slot:ident, $wrapper:expr, $variant:ident) => {{ if ADD { if let Some(func) = self.lookup_slot_in_mro(name, ctx, |sf| { if let SlotFunc::$variant(f) = sf { Some(*f) } else { None } }) { self.slots.$slot.store(Some(func)); } else { self.slots.$slot.store(Some($wrapper)); } } else { accessor.inherit_from_mro(self); } }}; } // Helper macro for number/sequence/mapping sub-slots macro_rules! update_sub_slot { ($group:ident, $slot:ident, $wrapper:expr, $variant:ident) => {{ if ADD { // Check if this type defines any method that maps to this slot. // Some slots like SqAssItem/MpAssSubscript are shared by multiple // methods (__setitem__ and __delitem__). If any of those methods // is defined, we must use the wrapper to ensure Python method calls. let has_own = { let guard = self.attributes.read(); // Check the current method name let mut result = guard.contains_key(name); // For ass_item/ass_subscript slots, also check the paired method // (__setitem__ and __delitem__ share the same slot) if !result && (stringify!($slot) == "ass_item" || stringify!($slot) == "ass_subscript") { let setitem = ctx.intern_str("__setitem__"); let delitem = ctx.intern_str("__delitem__"); result = guard.contains_key(setitem) || guard.contains_key(delitem); } result }; if has_own { self.slots.$group.$slot.store(Some($wrapper)); } else if let Some(func) = self.lookup_slot_in_mro(name, ctx, |sf| { if let SlotFunc::$variant(f) = sf { Some(*f) } else { None } }) { self.slots.$group.$slot.store(Some(func)); } else { self.slots.$group.$slot.store(Some($wrapper)); } } else { accessor.inherit_from_mro(self); } }}; } match accessor { // === Main slots === SlotAccessor::TpRepr => update_main_slot!(repr, repr_wrapper, Repr), SlotAccessor::TpStr => update_main_slot!(str, str_wrapper, Str), SlotAccessor::TpHash => { // Special handling for __hash__ = None if ADD { let method = self.attributes.read().get(name).cloned().or_else(|| { self.mro .read() .iter() .find_map(|cls| cls.attributes.read().get(name).cloned()) }); if method.as_ref().is_some_and(|m| m.is(&ctx.none)) { self.slots.hash.store(Some(hash_not_implemented)); } else if let Some(func) = self.lookup_slot_in_mro(name, ctx, |sf| { if let SlotFunc::Hash(f) = sf { Some(*f) } else { None } }) { self.slots.hash.store(Some(func)); } else { self.slots.hash.store(Some(hash_wrapper)); } } else { accessor.inherit_from_mro(self); } } SlotAccessor::TpCall => update_main_slot!(call, call_wrapper, Call), SlotAccessor::TpIter => update_main_slot!(iter, iter_wrapper, Iter), SlotAccessor::TpIternext => update_main_slot!(iternext, iternext_wrapper, IterNext), SlotAccessor::TpInit => update_main_slot!(init, init_wrapper, Init), SlotAccessor::TpNew => { // __new__ is not wrapped via PyWrapper if ADD { self.slots.new.store(Some(new_wrapper)); } else { accessor.inherit_from_mro(self); } } SlotAccessor::TpDel => update_main_slot!(del, del_wrapper, Del), SlotAccessor::TpGetattro => { // __getattribute__ and __getattr__ both map to TpGetattro. // If __getattr__ is defined anywhere in MRO, we must use the wrapper // because the native slot won't call __getattr__. let __getattr__ = identifier!(ctx, __getattr__); let has_getattr = { let attrs = self.attributes.read(); let in_self = attrs.contains_key(__getattr__); drop(attrs); // mro[0] is self, so skip it in_self || self .mro .read() .iter() .skip(1) .any(|cls| cls.attributes.read().contains_key(__getattr__)) }; if has_getattr { // Must use wrapper to handle __getattr__ self.slots.getattro.store(Some(getattro_wrapper)); } else if ADD { if let Some(func) = self.lookup_slot_in_mro(name, ctx, |sf| { if let SlotFunc::GetAttro(f) = sf { Some(*f) } else { None } }) { self.slots.getattro.store(Some(func)); } else { self.slots.getattro.store(Some(getattro_wrapper)); } } else { accessor.inherit_from_mro(self); } } SlotAccessor::TpSetattro => { // __setattr__ and __delattr__ share the same slot if ADD { if let Some(func) = self.lookup_slot_in_mro(name, ctx, |sf| match sf { SlotFunc::SetAttro(f) | SlotFunc::DelAttro(f) => Some(*f), _ => None, }) { self.slots.setattro.store(Some(func)); } else { self.slots.setattro.store(Some(setattro_wrapper)); } } else { accessor.inherit_from_mro(self); } } SlotAccessor::TpDescrGet => update_main_slot!(descr_get, descr_get_wrapper, DescrGet), SlotAccessor::TpDescrSet => { // __set__ and __delete__ share the same slot if ADD { if let Some(func) = self.lookup_slot_in_mro(name, ctx, |sf| match sf { SlotFunc::DescrSet(f) | SlotFunc::DescrDel(f) => Some(*f), _ => None, }) { self.slots.descr_set.store(Some(func)); } else { self.slots.descr_set.store(Some(descr_set_wrapper)); } } else { accessor.inherit_from_mro(self); } } // === Rich compare (__lt__, __le__, __eq__, __ne__, __gt__, __ge__) === SlotAccessor::TpRichcompare => { if ADD { // Check if self or any class in MRO has a Python-defined comparison method // All comparison ops share the same slot, so if any is overridden anywhere // in the hierarchy with a Python function, we need to use the wrapper let cmp_names = [ identifier!(ctx, __eq__), identifier!(ctx, __ne__), identifier!(ctx, __lt__), identifier!(ctx, __le__), identifier!(ctx, __gt__), identifier!(ctx, __ge__), ]; let has_python_cmp = { // Check self first let attrs = self.attributes.read(); let in_self = cmp_names.iter().any(|n| attrs.contains_key(*n)); drop(attrs); // mro[0] is self, so skip it since we already checked self above in_self || self.mro.read()[1..].iter().any(|cls| { let attrs = cls.attributes.read(); cmp_names.iter().any(|n| { if let Some(attr) = attrs.get(*n) { // Check if it's a Python function (not wrapper_descriptor) !attr.class().is(ctx.types.wrapper_descriptor_type) } else { false } }) }) }; if has_python_cmp { // Use wrapper to call the Python method self.slots.richcompare.store(Some(richcompare_wrapper)); } else if let Some(func) = self.lookup_slot_in_mro(name, ctx, |sf| { if let SlotFunc::RichCompare(f, _) = sf { Some(*f) } else { None } }) { self.slots.richcompare.store(Some(func)); } else { self.slots.richcompare.store(Some(richcompare_wrapper)); } } else { accessor.inherit_from_mro(self); } } // === Number binary operations === SlotAccessor::NbAdd => {
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/types/zoo.rs
crates/vm/src/types/zoo.rs
use crate::{ Py, builtins::{ asyncgenerator, bool_, builtin_func, bytearray, bytes, classmethod, code, complex, coroutine, descriptor, dict, enumerate, filter, float, frame, function, generator, genericalias, getset, int, iter, list, map, mappingproxy, memory, module, namespace, object, property, pystr, range, set, singletons, slice, staticmethod, super_, traceback, tuple, type_::{self, PyType}, union_, weakproxy, weakref, zip, }, class::StaticType, vm::Context, }; /// Holder of references to builtin types. #[derive(Debug, Clone)] #[non_exhaustive] pub struct TypeZoo { pub async_generator: &'static Py<PyType>, pub async_generator_asend: &'static Py<PyType>, pub async_generator_athrow: &'static Py<PyType>, pub async_generator_wrapped_value: &'static Py<PyType>, pub anext_awaitable: &'static Py<PyType>, pub bytes_type: &'static Py<PyType>, pub bytes_iterator_type: &'static Py<PyType>, pub bytearray_type: &'static Py<PyType>, pub bytearray_iterator_type: &'static Py<PyType>, pub bool_type: &'static Py<PyType>, pub callable_iterator: &'static Py<PyType>, pub cell_type: &'static Py<PyType>, pub classmethod_type: &'static Py<PyType>, pub code_type: &'static Py<PyType>, pub coroutine_type: &'static Py<PyType>, pub coroutine_wrapper_type: &'static Py<PyType>, pub dict_type: &'static Py<PyType>, pub enumerate_type: &'static Py<PyType>, pub filter_type: &'static Py<PyType>, pub float_type: &'static Py<PyType>, pub frame_type: &'static Py<PyType>, pub frozenset_type: &'static Py<PyType>, pub generator_type: &'static Py<PyType>, pub int_type: &'static Py<PyType>, pub iter_type: &'static Py<PyType>, pub reverse_iter_type: &'static Py<PyType>, pub complex_type: &'static Py<PyType>, pub list_type: &'static Py<PyType>, pub list_iterator_type: &'static Py<PyType>, pub list_reverseiterator_type: &'static Py<PyType>, pub str_iterator_type: &'static Py<PyType>, pub dict_keyiterator_type: &'static Py<PyType>, pub dict_reversekeyiterator_type: &'static Py<PyType>, pub dict_valueiterator_type: &'static Py<PyType>, pub dict_reversevalueiterator_type: &'static Py<PyType>, pub dict_itemiterator_type: &'static Py<PyType>, pub dict_reverseitemiterator_type: &'static Py<PyType>, pub dict_keys_type: &'static Py<PyType>, pub dict_values_type: &'static Py<PyType>, pub dict_items_type: &'static Py<PyType>, pub map_type: &'static Py<PyType>, pub memoryview_type: &'static Py<PyType>, pub memoryviewiterator_type: &'static Py<PyType>, pub tuple_type: &'static Py<PyType>, pub tuple_iterator_type: &'static Py<PyType>, pub set_type: &'static Py<PyType>, pub set_iterator_type: &'static Py<PyType>, pub staticmethod_type: &'static Py<PyType>, pub super_type: &'static Py<PyType>, pub str_type: &'static Py<PyType>, pub range_type: &'static Py<PyType>, pub range_iterator_type: &'static Py<PyType>, pub long_range_iterator_type: &'static Py<PyType>, pub slice_type: &'static Py<PyType>, pub type_type: &'static Py<PyType>, pub zip_type: &'static Py<PyType>, pub function_type: &'static Py<PyType>, pub builtin_function_or_method_type: &'static Py<PyType>, pub builtin_method_type: &'static Py<PyType>, pub method_descriptor_type: &'static Py<PyType>, pub property_type: &'static Py<PyType>, pub getset_type: &'static Py<PyType>, pub module_type: &'static Py<PyType>, pub namespace_type: &'static Py<PyType>, pub bound_method_type: &'static Py<PyType>, pub weakref_type: &'static Py<PyType>, pub weakproxy_type: &'static Py<PyType>, pub mappingproxy_type: &'static Py<PyType>, pub traceback_type: &'static Py<PyType>, pub object_type: &'static Py<PyType>, pub ellipsis_type: &'static Py<PyType>, pub none_type: &'static Py<PyType>, pub typing_no_default_type: &'static Py<PyType>, pub not_implemented_type: &'static Py<PyType>, pub generic_alias_type: &'static Py<PyType>, pub union_type: &'static Py<PyType>, pub member_descriptor_type: &'static Py<PyType>, pub wrapper_descriptor_type: &'static Py<PyType>, pub method_wrapper_type: &'static Py<PyType>, // RustPython-original types pub method_def: &'static Py<PyType>, } impl TypeZoo { #[cold] pub(crate) fn init() -> Self { let (type_type, object_type, weakref_type) = crate::object::init_type_hierarchy(); Self { // the order matters for type, object, weakref, and int type_type: type_::PyType::init_manually(type_type), object_type: object::PyBaseObject::init_manually(object_type), weakref_type: weakref::PyWeak::init_manually(weakref_type), int_type: int::PyInt::init_builtin_type(), // types exposed as builtins bool_type: bool_::PyBool::init_builtin_type(), bytearray_type: bytearray::PyByteArray::init_builtin_type(), bytes_type: bytes::PyBytes::init_builtin_type(), classmethod_type: classmethod::PyClassMethod::init_builtin_type(), complex_type: complex::PyComplex::init_builtin_type(), dict_type: dict::PyDict::init_builtin_type(), enumerate_type: enumerate::PyEnumerate::init_builtin_type(), float_type: float::PyFloat::init_builtin_type(), frozenset_type: set::PyFrozenSet::init_builtin_type(), filter_type: filter::PyFilter::init_builtin_type(), list_type: list::PyList::init_builtin_type(), map_type: map::PyMap::init_builtin_type(), memoryview_type: memory::PyMemoryView::init_builtin_type(), property_type: property::PyProperty::init_builtin_type(), range_type: range::PyRange::init_builtin_type(), set_type: set::PySet::init_builtin_type(), slice_type: slice::PySlice::init_builtin_type(), staticmethod_type: staticmethod::PyStaticMethod::init_builtin_type(), str_type: pystr::PyStr::init_builtin_type(), super_type: super_::PySuper::init_builtin_type(), tuple_type: tuple::PyTuple::init_builtin_type(), zip_type: zip::PyZip::init_builtin_type(), // hidden internal types. is this really need to be cached here? async_generator: asyncgenerator::PyAsyncGen::init_builtin_type(), async_generator_asend: asyncgenerator::PyAsyncGenASend::init_builtin_type(), async_generator_athrow: asyncgenerator::PyAsyncGenAThrow::init_builtin_type(), async_generator_wrapped_value: asyncgenerator::PyAsyncGenWrappedValue::init_builtin_type(), anext_awaitable: asyncgenerator::PyAnextAwaitable::init_builtin_type(), bound_method_type: function::PyBoundMethod::init_builtin_type(), builtin_function_or_method_type: builtin_func::PyNativeFunction::init_builtin_type(), builtin_method_type: builtin_func::PyNativeMethod::init_builtin_type(), bytearray_iterator_type: bytearray::PyByteArrayIterator::init_builtin_type(), bytes_iterator_type: bytes::PyBytesIterator::init_builtin_type(), callable_iterator: iter::PyCallableIterator::init_builtin_type(), cell_type: function::PyCell::init_builtin_type(), code_type: code::PyCode::init_builtin_type(), coroutine_type: coroutine::PyCoroutine::init_builtin_type(), coroutine_wrapper_type: coroutine::PyCoroutineWrapper::init_builtin_type(), dict_keys_type: dict::PyDictKeys::init_builtin_type(), dict_values_type: dict::PyDictValues::init_builtin_type(), dict_items_type: dict::PyDictItems::init_builtin_type(), dict_keyiterator_type: dict::PyDictKeyIterator::init_builtin_type(), dict_reversekeyiterator_type: dict::PyDictReverseKeyIterator::init_builtin_type(), dict_valueiterator_type: dict::PyDictValueIterator::init_builtin_type(), dict_reversevalueiterator_type: dict::PyDictReverseValueIterator::init_builtin_type(), dict_itemiterator_type: dict::PyDictItemIterator::init_builtin_type(), dict_reverseitemiterator_type: dict::PyDictReverseItemIterator::init_builtin_type(), ellipsis_type: slice::PyEllipsis::init_builtin_type(), frame_type: crate::frame::Frame::init_builtin_type(), function_type: function::PyFunction::init_builtin_type(), generator_type: generator::PyGenerator::init_builtin_type(), getset_type: getset::PyGetSet::init_builtin_type(), iter_type: iter::PySequenceIterator::init_builtin_type(), reverse_iter_type: enumerate::PyReverseSequenceIterator::init_builtin_type(), list_iterator_type: list::PyListIterator::init_builtin_type(), list_reverseiterator_type: list::PyListReverseIterator::init_builtin_type(), mappingproxy_type: mappingproxy::PyMappingProxy::init_builtin_type(), memoryviewiterator_type: memory::PyMemoryViewIterator::init_builtin_type(), module_type: module::PyModule::init_builtin_type(), namespace_type: namespace::PyNamespace::init_builtin_type(), range_iterator_type: range::PyRangeIterator::init_builtin_type(), long_range_iterator_type: range::PyLongRangeIterator::init_builtin_type(), set_iterator_type: set::PySetIterator::init_builtin_type(), str_iterator_type: pystr::PyStrIterator::init_builtin_type(), traceback_type: traceback::PyTraceback::init_builtin_type(), tuple_iterator_type: tuple::PyTupleIterator::init_builtin_type(), weakproxy_type: weakproxy::PyWeakProxy::init_builtin_type(), method_descriptor_type: descriptor::PyMethodDescriptor::init_builtin_type(), none_type: singletons::PyNone::init_builtin_type(), typing_no_default_type: crate::stdlib::typing::NoDefault::init_builtin_type(), not_implemented_type: singletons::PyNotImplemented::init_builtin_type(), generic_alias_type: genericalias::PyGenericAlias::init_builtin_type(), union_type: union_::PyUnion::init_builtin_type(), member_descriptor_type: descriptor::PyMemberDescriptor::init_builtin_type(), wrapper_descriptor_type: descriptor::PyWrapper::init_builtin_type(), method_wrapper_type: descriptor::PyMethodWrapper::init_builtin_type(), method_def: crate::function::HeapMethodDef::init_builtin_type(), } } /// Fill attributes of builtin types. #[cold] pub(crate) fn extend(context: &Context) { // object must be initialized before type to set object.slots.init, // which type will inherit via inherit_slots() object::init(context); type_::init(context); list::init(context); set::init(context); tuple::init(context); dict::init(context); builtin_func::init(context); function::init(context); staticmethod::init(context); classmethod::init(context); generator::init(context); coroutine::init(context); asyncgenerator::init(context); int::init(context); float::init(context); complex::init(context); bytes::init(context); bytearray::init(context); property::init(context); getset::init(context); memory::init(context); pystr::init(context); range::init(context); slice::init(context); super_::init(context); iter::init(context); enumerate::init(context); filter::init(context); map::init(context); zip::init(context); bool_::init(context); code::init(context); frame::init(context); weakref::init(context); weakproxy::init(context); singletons::init(context); module::init(context); namespace::init(context); mappingproxy::init(context); traceback::init(context); genericalias::init(context); union_::init(context); descriptor::init(context); crate::stdlib::typing::init(context); } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/types/structseq.rs
crates/vm/src/types/structseq.rs
use crate::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, atomic_func, builtins::{PyBaseExceptionRef, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef}, class::{PyClassImpl, StaticType}, function::{Either, PyComparisonValue}, iter::PyExactSizeIterator, protocol::{PyMappingMethods, PySequenceMethods}, sliceable::{SequenceIndex, SliceableSequenceOp}, types::PyComparisonOp, vm::Context, }; use std::sync::LazyLock; /// Create a new struct sequence instance from a sequence. /// /// The class must have `n_sequence_fields` and `n_fields` attributes set /// (done automatically by `PyStructSequence::extend_pyclass`). pub fn struct_sequence_new(cls: PyTypeRef, seq: PyObjectRef, vm: &VirtualMachine) -> PyResult { // = structseq_new #[cold] fn length_error( tp_name: &str, min_len: usize, max_len: usize, len: usize, vm: &VirtualMachine, ) -> PyBaseExceptionRef { if min_len == max_len { vm.new_type_error(format!( "{tp_name}() takes a {min_len}-sequence ({len}-sequence given)" )) } else if len < min_len { vm.new_type_error(format!( "{tp_name}() takes an at least {min_len}-sequence ({len}-sequence given)" )) } else { vm.new_type_error(format!( "{tp_name}() takes an at most {max_len}-sequence ({len}-sequence given)" )) } } let min_len: usize = cls .get_attr(identifier!(vm.ctx, n_sequence_fields)) .ok_or_else(|| vm.new_type_error("missing n_sequence_fields attribute"))? .try_into_value(vm)?; let max_len: usize = cls .get_attr(identifier!(vm.ctx, n_fields)) .ok_or_else(|| vm.new_type_error("missing n_fields attribute"))? .try_into_value(vm)?; let seq: Vec<PyObjectRef> = seq.try_into_value(vm)?; let len = seq.len(); if len < min_len || len > max_len { return Err(length_error(&cls.slot_name(), min_len, max_len, len, vm)); } // Copy items and pad with None let mut items = seq; items.resize_with(max_len, || vm.ctx.none()); PyTuple::new_unchecked(items.into_boxed_slice()) .into_ref_with_type(vm, cls) .map(Into::into) } fn get_visible_len(obj: &PyObject, vm: &VirtualMachine) -> PyResult<usize> { obj.class() .get_attr(identifier!(vm.ctx, n_sequence_fields)) .ok_or_else(|| vm.new_type_error("missing n_sequence_fields"))? .try_into_value(vm) } /// Sequence methods for struct sequences. /// Uses n_sequence_fields to determine visible length. static STRUCT_SEQUENCE_AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods { length: atomic_func!(|seq, vm| get_visible_len(seq.obj, vm)), concat: atomic_func!(|seq, other, vm| { // Convert to visible-only tuple, then use regular tuple concat let n_seq = get_visible_len(seq.obj, vm)?; let tuple = seq.obj.downcast_ref::<PyTuple>().unwrap(); let visible: Vec<_> = tuple.iter().take(n_seq).cloned().collect(); let visible_tuple = PyTuple::new_ref(visible, &vm.ctx); // Use tuple's concat implementation visible_tuple .as_object() .sequence_unchecked() .concat(other, vm) }), repeat: atomic_func!(|seq, n, vm| { // Convert to visible-only tuple, then use regular tuple repeat let n_seq = get_visible_len(seq.obj, vm)?; let tuple = seq.obj.downcast_ref::<PyTuple>().unwrap(); let visible: Vec<_> = tuple.iter().take(n_seq).cloned().collect(); let visible_tuple = PyTuple::new_ref(visible, &vm.ctx); // Use tuple's repeat implementation visible_tuple.as_object().sequence_unchecked().repeat(n, vm) }), item: atomic_func!(|seq, i, vm| { let n_seq = get_visible_len(seq.obj, vm)?; let tuple = seq.obj.downcast_ref::<PyTuple>().unwrap(); let idx = if i < 0 { let pos_i = n_seq as isize + i; if pos_i < 0 { return Err(vm.new_index_error("tuple index out of range")); } pos_i as usize } else { i as usize }; if idx >= n_seq { return Err(vm.new_index_error("tuple index out of range")); } Ok(tuple[idx].clone()) }), contains: atomic_func!(|seq, needle, vm| { let n_seq = get_visible_len(seq.obj, vm)?; let tuple = seq.obj.downcast_ref::<PyTuple>().unwrap(); for item in tuple.iter().take(n_seq) { if item.rich_compare_bool(needle, PyComparisonOp::Eq, vm)? { return Ok(true); } } Ok(false) }), ..PySequenceMethods::NOT_IMPLEMENTED }); /// Mapping methods for struct sequences. /// Handles subscript (indexing) with visible length bounds. static STRUCT_SEQUENCE_AS_MAPPING: LazyLock<PyMappingMethods> = LazyLock::new(|| PyMappingMethods { length: atomic_func!(|mapping, vm| get_visible_len(mapping.obj, vm)), subscript: atomic_func!(|mapping, needle, vm| { let n_seq = get_visible_len(mapping.obj, vm)?; let tuple = mapping.obj.downcast_ref::<PyTuple>().unwrap(); let visible_elements = &tuple.as_slice()[..n_seq]; match SequenceIndex::try_from_borrowed_object(vm, needle, "tuple")? { SequenceIndex::Int(i) => visible_elements.getitem_by_index(vm, i), SequenceIndex::Slice(slice) => visible_elements .getitem_by_slice(vm, slice) .map(|x| vm.ctx.new_tuple(x).into()), } }), ..PyMappingMethods::NOT_IMPLEMENTED }); /// Trait for Data structs that back a PyStructSequence. /// /// This trait is implemented by `#[pystruct_sequence_data]` on the Data struct. /// It provides field information, tuple conversion, and element parsing. pub trait PyStructSequenceData: Sized { /// Names of required fields (in order). Shown in repr. const REQUIRED_FIELD_NAMES: &'static [&'static str]; /// Names of optional/skipped fields (in order, after required fields). const OPTIONAL_FIELD_NAMES: &'static [&'static str]; /// Number of unnamed fields (visible but index-only access). const UNNAMED_FIELDS_LEN: usize = 0; /// Convert this Data struct into a PyTuple. fn into_tuple(self, vm: &VirtualMachine) -> PyTuple; /// Construct this Data struct from tuple elements. /// Default implementation returns an error. /// Override with `#[pystruct_sequence_data(try_from_object)]` to enable. fn try_from_elements(_elements: Vec<PyObjectRef>, vm: &VirtualMachine) -> PyResult<Self> { Err(vm.new_type_error("This struct sequence does not support construction from elements")) } } /// Trait for Python struct sequence types. /// /// This trait is implemented by the `#[pystruct_sequence]` macro on the Python type struct. /// It connects to the Data struct and provides Python-level functionality. #[pyclass] pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static { /// The Data struct that provides field definitions. type Data: PyStructSequenceData; /// Convert a Data struct into a PyStructSequence instance. fn from_data(data: Self::Data, vm: &VirtualMachine) -> PyTupleRef { let tuple = <Self::Data as ::rustpython_vm::types::PyStructSequenceData>::into_tuple(data, vm); let typ = Self::static_type(); tuple .into_ref_with_type(vm, typ.to_owned()) .expect("Every PyStructSequence must be a valid tuple. This is a RustPython bug.") } #[pyslot] fn slot_repr(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyStrRef> { let zelf = zelf .downcast_ref::<PyTuple>() .ok_or_else(|| vm.new_type_error("unexpected payload for __repr__"))?; let field_names = Self::Data::REQUIRED_FIELD_NAMES; let format_field = |(value, name): (&PyObject, _)| { let s = value.repr(vm)?; Ok(format!("{name}={s}")) }; let (body, suffix) = if let Some(_guard) = rustpython_vm::recursion::ReprGuard::enter(vm, zelf.as_ref()) { if field_names.len() == 1 { let value = zelf.first().unwrap(); let formatted = format_field((value, field_names[0]))?; (formatted, ",") } else { let fields: PyResult<Vec<_>> = zelf .iter() .map(|value| value.as_ref()) .zip(field_names.iter().copied()) .map(format_field) .collect(); (fields?.join(", "), "") } } else { (String::new(), "...") }; let repr_str = format!("{}({}{})", Self::TP_NAME, body, suffix); Ok(vm.ctx.new_str(repr_str)) } #[pymethod] fn __repr__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStrRef> { Self::slot_repr(&zelf, vm) } #[pymethod] fn __reduce__(zelf: PyRef<PyTuple>, vm: &VirtualMachine) -> PyTupleRef { vm.new_tuple((zelf.class().to_owned(), (vm.ctx.new_tuple(zelf.to_vec()),))) } #[pymethod] fn __getitem__(zelf: PyRef<PyTuple>, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { let n_seq = get_visible_len(zelf.as_ref(), vm)?; let visible_elements = &zelf.as_slice()[..n_seq]; match SequenceIndex::try_from_borrowed_object(vm, &needle, "tuple")? { SequenceIndex::Int(i) => visible_elements.getitem_by_index(vm, i), SequenceIndex::Slice(slice) => visible_elements .getitem_by_slice(vm, slice) .map(|x| vm.ctx.new_tuple(x).into()), } } #[extend_class] fn extend_pyclass(ctx: &Context, class: &'static Py<PyType>) { // Getters for named visible fields (indices 0 to REQUIRED_FIELD_NAMES.len() - 1) for (i, &name) in Self::Data::REQUIRED_FIELD_NAMES.iter().enumerate() { // cast i to a u8 so there's less to store in the getter closure. // Hopefully there's not struct sequences with >=256 elements :P let i = i as u8; class.set_attr( ctx.intern_str(name), ctx.new_readonly_getset(name, class, move |zelf: &PyTuple| { zelf[i as usize].to_owned() }) .into(), ); } // Getters for hidden/skipped fields (indices after visible fields) let visible_count = Self::Data::REQUIRED_FIELD_NAMES.len() + Self::Data::UNNAMED_FIELDS_LEN; for (i, &name) in Self::Data::OPTIONAL_FIELD_NAMES.iter().enumerate() { let idx = (visible_count + i) as u8; class.set_attr( ctx.intern_str(name), ctx.new_readonly_getset(name, class, move |zelf: &PyTuple| { zelf[idx as usize].to_owned() }) .into(), ); } class.set_attr( identifier!(ctx, __match_args__), ctx.new_tuple( Self::Data::REQUIRED_FIELD_NAMES .iter() .map(|&name| ctx.new_str(name).into()) .collect::<Vec<_>>(), ) .into(), ); // special fields: // n_sequence_fields = visible fields (named + unnamed) // n_fields = all fields (visible + hidden/skipped) // n_unnamed_fields let n_unnamed_fields = Self::Data::UNNAMED_FIELDS_LEN; let n_sequence_fields = Self::Data::REQUIRED_FIELD_NAMES.len() + n_unnamed_fields; let n_fields = n_sequence_fields + Self::Data::OPTIONAL_FIELD_NAMES.len(); class.set_attr( identifier!(ctx, n_sequence_fields), ctx.new_int(n_sequence_fields).into(), ); class.set_attr(identifier!(ctx, n_fields), ctx.new_int(n_fields).into()); class.set_attr( identifier!(ctx, n_unnamed_fields), ctx.new_int(n_unnamed_fields).into(), ); // Override as_sequence and as_mapping slots to use visible length class .slots .as_sequence .copy_from(&STRUCT_SEQUENCE_AS_SEQUENCE); class .slots .as_mapping .copy_from(&STRUCT_SEQUENCE_AS_MAPPING); // Override iter slot to return only visible elements class.slots.iter.store(Some(struct_sequence_iter)); // Override hash slot to hash only visible elements class.slots.hash.store(Some(struct_sequence_hash)); // Override richcompare slot to compare only visible elements class .slots .richcompare .store(Some(struct_sequence_richcompare)); } } /// Iterator function for struct sequences - returns only visible elements fn struct_sequence_iter(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { let tuple = zelf .downcast_ref::<PyTuple>() .ok_or_else(|| vm.new_type_error("expected tuple"))?; let n_seq = get_visible_len(&zelf, vm)?; let visible: Vec<_> = tuple.iter().take(n_seq).cloned().collect(); let visible_tuple = PyTuple::new_ref(visible, &vm.ctx); visible_tuple .as_object() .to_owned() .get_iter(vm) .map(Into::into) } /// Hash function for struct sequences - hashes only visible elements fn struct_sequence_hash( zelf: &PyObject, vm: &VirtualMachine, ) -> PyResult<crate::common::hash::PyHash> { let tuple = zelf .downcast_ref::<PyTuple>() .ok_or_else(|| vm.new_type_error("expected tuple"))?; let n_seq = get_visible_len(zelf, vm)?; // Create a visible-only tuple and hash it let visible: Vec<_> = tuple.iter().take(n_seq).cloned().collect(); let visible_tuple = PyTuple::new_ref(visible, &vm.ctx); visible_tuple.as_object().hash(vm) } /// Rich comparison for struct sequences - compares only visible elements fn struct_sequence_richcompare( zelf: &PyObject, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult<Either<PyObjectRef, PyComparisonValue>> { let zelf_tuple = zelf .downcast_ref::<PyTuple>() .ok_or_else(|| vm.new_type_error("expected tuple"))?; // If other is not a tuple, return NotImplemented let Some(other_tuple) = other.downcast_ref::<PyTuple>() else { return Ok(Either::B(PyComparisonValue::NotImplemented)); }; let zelf_len = get_visible_len(zelf, vm)?; // For other, try to get visible len; if it fails (not a struct sequence), use full length let other_len = get_visible_len(other, vm).unwrap_or(other_tuple.len()); let zelf_visible = &zelf_tuple.as_slice()[..zelf_len]; let other_visible = &other_tuple.as_slice()[..other_len]; // Use the same comparison logic as regular tuples zelf_visible .iter() .richcompare(other_visible.iter(), op, vm) .map(|v| Either::B(PyComparisonValue::Implemented(v))) }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/types/mod.rs
crates/vm/src/types/mod.rs
mod slot; pub mod slot_defs; mod structseq; mod zoo; pub use slot::*; pub use slot_defs::{SLOT_DEFS, SlotAccessor, SlotDef}; pub use structseq::{PyStructSequence, PyStructSequenceData, struct_sequence_new}; pub(crate) use zoo::TypeZoo;
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/types/slot_defs.rs
crates/vm/src/types/slot_defs.rs
//! Slot definitions array //! //! This module provides a centralized array of all slot definitions, use super::{PyComparisonOp, PyTypeSlots}; use crate::builtins::descriptor::SlotFunc; /// Slot operation type /// /// Used to distinguish between different operations that share the same slot: /// - RichCompare: Lt, Le, Eq, Ne, Gt, Ge /// - Binary ops: Left (__add__) vs Right (__radd__) #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SlotOp { // RichCompare operations Lt, Le, Eq, Ne, Gt, Ge, // Binary operation direction Left, Right, // Setter vs Deleter Delete, } impl SlotOp { /// Convert to PyComparisonOp if this is a comparison operation pub fn as_compare_op(&self) -> Option<PyComparisonOp> { match self { Self::Lt => Some(PyComparisonOp::Lt), Self::Le => Some(PyComparisonOp::Le), Self::Eq => Some(PyComparisonOp::Eq), Self::Ne => Some(PyComparisonOp::Ne), Self::Gt => Some(PyComparisonOp::Gt), Self::Ge => Some(PyComparisonOp::Ge), _ => None, } } /// Check if this is a right operation (__radd__, __rsub__, etc.) pub fn is_right(&self) -> bool { matches!(self, Self::Right) } } /// Slot definition entry #[derive(Clone, Copy)] pub struct SlotDef { /// Method name ("__init__", "__add__", etc.) pub name: &'static str, /// Slot accessor (which slot field to access) pub accessor: SlotAccessor, /// Operation type (for shared slots like RichCompare, binary ops) pub op: Option<SlotOp>, /// Documentation string pub doc: &'static str, } /// Slot accessor /// /// Values match CPython's Py_* slot IDs from typeslots.h. /// Unused slots are included for value reservation. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum SlotAccessor { // Buffer protocol (1-2) - Reserved, not used in RustPython BfGetBuffer = 1, BfReleaseBuffer = 2, // Mapping protocol (3-5) MpAssSubscript = 3, MpLength = 4, MpSubscript = 5, // Number protocol (6-38) NbAbsolute = 6, NbAdd = 7, NbAnd = 8, NbBool = 9, NbDivmod = 10, NbFloat = 11, NbFloorDivide = 12, NbIndex = 13, NbInplaceAdd = 14, NbInplaceAnd = 15, NbInplaceFloorDivide = 16, NbInplaceLshift = 17, NbInplaceMultiply = 18, NbInplaceOr = 19, NbInplacePower = 20, NbInplaceRemainder = 21, NbInplaceRshift = 22, NbInplaceSubtract = 23, NbInplaceTrueDivide = 24, NbInplaceXor = 25, NbInt = 26, NbInvert = 27, NbLshift = 28, NbMultiply = 29, NbNegative = 30, NbOr = 31, NbPositive = 32, NbPower = 33, NbRemainder = 34, NbRshift = 35, NbSubtract = 36, NbTrueDivide = 37, NbXor = 38, // Sequence protocol (39-46) SqAssItem = 39, SqConcat = 40, SqContains = 41, SqInplaceConcat = 42, SqInplaceRepeat = 43, SqItem = 44, SqLength = 45, SqRepeat = 46, // Type slots (47-74) TpAlloc = 47, // Reserved TpBase = 48, // Reserved TpBases = 49, // Reserved TpCall = 50, TpClear = 51, // Reserved TpDealloc = 52, // Reserved TpDel = 53, TpDescrGet = 54, TpDescrSet = 55, TpDoc = 56, // Reserved TpGetattr = 57, // Reserved (use TpGetattro) TpGetattro = 58, TpHash = 59, TpInit = 60, TpIsGc = 61, // Reserved TpIter = 62, TpIternext = 63, TpMethods = 64, // Reserved TpNew = 65, TpRepr = 66, TpRichcompare = 67, TpSetattr = 68, // Reserved (use TpSetattro) TpSetattro = 69, TpStr = 70, TpTraverse = 71, // Reserved TpMembers = 72, // Reserved TpGetset = 73, // Reserved TpFree = 74, // Reserved // Number protocol additions (75-76) NbMatrixMultiply = 75, NbInplaceMatrixMultiply = 76, // Async protocol (77-81) - Reserved for future AmAwait = 77, AmAiter = 78, AmAnext = 79, TpFinalize = 80, AmSend = 81, } impl SlotAccessor { /// Check if this accessor is for a reserved/unused slot pub fn is_reserved(&self) -> bool { matches!( self, Self::BfGetBuffer | Self::BfReleaseBuffer | Self::TpAlloc | Self::TpBase | Self::TpBases | Self::TpClear | Self::TpDealloc | Self::TpDoc | Self::TpGetattr | Self::TpIsGc | Self::TpMethods | Self::TpSetattr | Self::TpTraverse | Self::TpMembers | Self::TpGetset | Self::TpFree | Self::TpFinalize | Self::AmAwait | Self::AmAiter | Self::AmAnext | Self::AmSend ) } /// Check if this is a number binary operation slot pub fn is_number_binary(&self) -> bool { matches!( self, Self::NbAdd | Self::NbSubtract | Self::NbMultiply | Self::NbRemainder | Self::NbDivmod | Self::NbPower | Self::NbLshift | Self::NbRshift | Self::NbAnd | Self::NbXor | Self::NbOr | Self::NbFloorDivide | Self::NbTrueDivide | Self::NbMatrixMultiply ) } /// Check if this accessor refers to a shared slot /// /// Shared slots are used by multiple dunder methods: /// - TpSetattro: __setattr__ and __delattr__ /// - TpRichcompare: __lt__, __le__, __eq__, __ne__, __gt__, __ge__ /// - TpDescrSet: __set__ and __delete__ /// - SqAssItem/MpAssSubscript: __setitem__ and __delitem__ /// - Number binaries: __add__ and __radd__, etc. pub fn is_shared_slot(&self) -> bool { matches!( self, Self::TpSetattro | Self::TpRichcompare | Self::TpDescrSet | Self::SqAssItem | Self::MpAssSubscript ) || self.is_number_binary() } /// Get underlying slot field name for debugging pub fn slot_name(&self) -> &'static str { match self { Self::BfGetBuffer => "bf_getbuffer", Self::BfReleaseBuffer => "bf_releasebuffer", Self::MpAssSubscript => "mp_ass_subscript", Self::MpLength => "mp_length", Self::MpSubscript => "mp_subscript", Self::NbAbsolute => "nb_absolute", Self::NbAdd => "nb_add", Self::NbAnd => "nb_and", Self::NbBool => "nb_bool", Self::NbDivmod => "nb_divmod", Self::NbFloat => "nb_float", Self::NbFloorDivide => "nb_floor_divide", Self::NbIndex => "nb_index", Self::NbInplaceAdd => "nb_inplace_add", Self::NbInplaceAnd => "nb_inplace_and", Self::NbInplaceFloorDivide => "nb_inplace_floor_divide", Self::NbInplaceLshift => "nb_inplace_lshift", Self::NbInplaceMultiply => "nb_inplace_multiply", Self::NbInplaceOr => "nb_inplace_or", Self::NbInplacePower => "nb_inplace_power", Self::NbInplaceRemainder => "nb_inplace_remainder", Self::NbInplaceRshift => "nb_inplace_rshift", Self::NbInplaceSubtract => "nb_inplace_subtract", Self::NbInplaceTrueDivide => "nb_inplace_true_divide", Self::NbInplaceXor => "nb_inplace_xor", Self::NbInt => "nb_int", Self::NbInvert => "nb_invert", Self::NbLshift => "nb_lshift", Self::NbMultiply => "nb_multiply", Self::NbNegative => "nb_negative", Self::NbOr => "nb_or", Self::NbPositive => "nb_positive", Self::NbPower => "nb_power", Self::NbRemainder => "nb_remainder", Self::NbRshift => "nb_rshift", Self::NbSubtract => "nb_subtract", Self::NbTrueDivide => "nb_true_divide", Self::NbXor => "nb_xor", Self::SqAssItem => "sq_ass_item", Self::SqConcat => "sq_concat", Self::SqContains => "sq_contains", Self::SqInplaceConcat => "sq_inplace_concat", Self::SqInplaceRepeat => "sq_inplace_repeat", Self::SqItem => "sq_item", Self::SqLength => "sq_length", Self::SqRepeat => "sq_repeat", Self::TpAlloc => "tp_alloc", Self::TpBase => "tp_base", Self::TpBases => "tp_bases", Self::TpCall => "tp_call", Self::TpClear => "tp_clear", Self::TpDealloc => "tp_dealloc", Self::TpDel => "tp_del", Self::TpDescrGet => "tp_descr_get", Self::TpDescrSet => "tp_descr_set", Self::TpDoc => "tp_doc", Self::TpGetattr => "tp_getattr", Self::TpGetattro => "tp_getattro", Self::TpHash => "tp_hash", Self::TpInit => "tp_init", Self::TpIsGc => "tp_is_gc", Self::TpIter => "tp_iter", Self::TpIternext => "tp_iternext", Self::TpMethods => "tp_methods", Self::TpNew => "tp_new", Self::TpRepr => "tp_repr", Self::TpRichcompare => "tp_richcompare", Self::TpSetattr => "tp_setattr", Self::TpSetattro => "tp_setattro", Self::TpStr => "tp_str", Self::TpTraverse => "tp_traverse", Self::TpMembers => "tp_members", Self::TpGetset => "tp_getset", Self::TpFree => "tp_free", Self::NbMatrixMultiply => "nb_matrix_multiply", Self::NbInplaceMatrixMultiply => "nb_inplace_matrix_multiply", Self::AmAwait => "am_await", Self::AmAiter => "am_aiter", Self::AmAnext => "am_anext", Self::TpFinalize => "tp_finalize", Self::AmSend => "am_send", } } /// Extract the raw function pointer from a SlotFunc if it matches this accessor's type pub fn extract_from_slot_func(&self, slot_func: &SlotFunc) -> bool { match self { // Type slots Self::TpHash => matches!(slot_func, SlotFunc::Hash(_)), Self::TpRepr => matches!(slot_func, SlotFunc::Repr(_)), Self::TpStr => matches!(slot_func, SlotFunc::Str(_)), Self::TpCall => matches!(slot_func, SlotFunc::Call(_)), Self::TpIter => matches!(slot_func, SlotFunc::Iter(_)), Self::TpIternext => matches!(slot_func, SlotFunc::IterNext(_)), Self::TpInit => matches!(slot_func, SlotFunc::Init(_)), Self::TpDel => matches!(slot_func, SlotFunc::Del(_)), Self::TpGetattro => matches!(slot_func, SlotFunc::GetAttro(_)), Self::TpSetattro => { matches!(slot_func, SlotFunc::SetAttro(_) | SlotFunc::DelAttro(_)) } Self::TpDescrGet => matches!(slot_func, SlotFunc::DescrGet(_)), Self::TpDescrSet => { matches!(slot_func, SlotFunc::DescrSet(_) | SlotFunc::DescrDel(_)) } Self::TpRichcompare => matches!(slot_func, SlotFunc::RichCompare(_, _)), // Number - Power (ternary) Self::NbPower | Self::NbInplacePower => { matches!(slot_func, SlotFunc::NumTernary(_)) } // Number - Boolean Self::NbBool => matches!(slot_func, SlotFunc::NumBoolean(_)), // Number - Unary Self::NbNegative | Self::NbPositive | Self::NbAbsolute | Self::NbInvert | Self::NbInt | Self::NbFloat | Self::NbIndex => matches!(slot_func, SlotFunc::NumUnary(_)), // Number - Binary Self::NbAdd | Self::NbSubtract | Self::NbMultiply | Self::NbRemainder | Self::NbDivmod | Self::NbLshift | Self::NbRshift | Self::NbAnd | Self::NbXor | Self::NbOr | Self::NbFloorDivide | Self::NbTrueDivide | Self::NbMatrixMultiply | Self::NbInplaceAdd | Self::NbInplaceSubtract | Self::NbInplaceMultiply | Self::NbInplaceRemainder | Self::NbInplaceLshift | Self::NbInplaceRshift | Self::NbInplaceAnd | Self::NbInplaceXor | Self::NbInplaceOr | Self::NbInplaceFloorDivide | Self::NbInplaceTrueDivide | Self::NbInplaceMatrixMultiply => matches!(slot_func, SlotFunc::NumBinary(_)), // Sequence Self::SqLength => matches!(slot_func, SlotFunc::SeqLength(_)), Self::SqConcat | Self::SqInplaceConcat => matches!(slot_func, SlotFunc::SeqConcat(_)), Self::SqRepeat | Self::SqInplaceRepeat => matches!(slot_func, SlotFunc::SeqRepeat(_)), Self::SqItem => matches!(slot_func, SlotFunc::SeqItem(_)), Self::SqAssItem => { matches!(slot_func, SlotFunc::SeqSetItem(_) | SlotFunc::SeqDelItem(_)) } Self::SqContains => matches!(slot_func, SlotFunc::SeqContains(_)), // Mapping Self::MpLength => matches!(slot_func, SlotFunc::MapLength(_)), Self::MpSubscript => matches!(slot_func, SlotFunc::MapSubscript(_)), Self::MpAssSubscript => { matches!( slot_func, SlotFunc::MapSetSubscript(_) | SlotFunc::MapDelSubscript(_) ) } // New and reserved slots Self::TpNew => false, _ => false, // Reserved slots } } /// Inherit slot value from MRO pub fn inherit_from_mro(&self, typ: &crate::builtins::PyType) { // mro[0] is self, so skip it let mro_guard = typ.mro.read(); let mro = &mro_guard[1..]; macro_rules! inherit_main { ($slot:ident) => {{ let inherited = mro.iter().find_map(|cls| cls.slots.$slot.load()); typ.slots.$slot.store(inherited); }}; } macro_rules! inherit_number { ($slot:ident) => {{ let inherited = mro.iter().find_map(|cls| cls.slots.as_number.$slot.load()); typ.slots.as_number.$slot.store(inherited); }}; } macro_rules! inherit_sequence { ($slot:ident) => {{ let inherited = mro .iter() .find_map(|cls| cls.slots.as_sequence.$slot.load()); typ.slots.as_sequence.$slot.store(inherited); }}; } macro_rules! inherit_mapping { ($slot:ident) => {{ let inherited = mro.iter().find_map(|cls| cls.slots.as_mapping.$slot.load()); typ.slots.as_mapping.$slot.store(inherited); }}; } match self { // Type slots Self::TpHash => inherit_main!(hash), Self::TpRepr => inherit_main!(repr), Self::TpStr => inherit_main!(str), Self::TpCall => inherit_main!(call), Self::TpIter => inherit_main!(iter), Self::TpIternext => inherit_main!(iternext), Self::TpInit => inherit_main!(init), Self::TpNew => inherit_main!(new), Self::TpDel => inherit_main!(del), Self::TpGetattro => inherit_main!(getattro), Self::TpSetattro => inherit_main!(setattro), Self::TpDescrGet => inherit_main!(descr_get), Self::TpDescrSet => inherit_main!(descr_set), Self::TpRichcompare => inherit_main!(richcompare), // Number slots Self::NbAdd => inherit_number!(add), Self::NbSubtract => inherit_number!(subtract), Self::NbMultiply => inherit_number!(multiply), Self::NbRemainder => inherit_number!(remainder), Self::NbDivmod => inherit_number!(divmod), Self::NbPower => inherit_number!(power), Self::NbLshift => inherit_number!(lshift), Self::NbRshift => inherit_number!(rshift), Self::NbAnd => inherit_number!(and), Self::NbXor => inherit_number!(xor), Self::NbOr => inherit_number!(or), Self::NbFloorDivide => inherit_number!(floor_divide), Self::NbTrueDivide => inherit_number!(true_divide), Self::NbMatrixMultiply => inherit_number!(matrix_multiply), Self::NbInplaceAdd => inherit_number!(inplace_add), Self::NbInplaceSubtract => inherit_number!(inplace_subtract), Self::NbInplaceMultiply => inherit_number!(inplace_multiply), Self::NbInplaceRemainder => inherit_number!(inplace_remainder), Self::NbInplacePower => inherit_number!(inplace_power), Self::NbInplaceLshift => inherit_number!(inplace_lshift), Self::NbInplaceRshift => inherit_number!(inplace_rshift), Self::NbInplaceAnd => inherit_number!(inplace_and), Self::NbInplaceXor => inherit_number!(inplace_xor), Self::NbInplaceOr => inherit_number!(inplace_or), Self::NbInplaceFloorDivide => inherit_number!(inplace_floor_divide), Self::NbInplaceTrueDivide => inherit_number!(inplace_true_divide), Self::NbInplaceMatrixMultiply => inherit_number!(inplace_matrix_multiply), // Number unary Self::NbNegative => inherit_number!(negative), Self::NbPositive => inherit_number!(positive), Self::NbAbsolute => inherit_number!(absolute), Self::NbInvert => inherit_number!(invert), Self::NbBool => inherit_number!(boolean), Self::NbInt => inherit_number!(int), Self::NbFloat => inherit_number!(float), Self::NbIndex => inherit_number!(index), // Sequence slots Self::SqLength => inherit_sequence!(length), Self::SqConcat => inherit_sequence!(concat), Self::SqRepeat => inherit_sequence!(repeat), Self::SqItem => inherit_sequence!(item), Self::SqAssItem => inherit_sequence!(ass_item), Self::SqContains => inherit_sequence!(contains), Self::SqInplaceConcat => inherit_sequence!(inplace_concat), Self::SqInplaceRepeat => inherit_sequence!(inplace_repeat), // Mapping slots Self::MpLength => inherit_mapping!(length), Self::MpSubscript => inherit_mapping!(subscript), Self::MpAssSubscript => inherit_mapping!(ass_subscript), // Reserved slots - no-op _ => {} } } /// Copy slot from base type if self's slot is None pub fn copyslot_if_none(&self, typ: &crate::builtins::PyType, base: &crate::builtins::PyType) { macro_rules! copy_main { ($slot:ident) => {{ if typ.slots.$slot.load().is_none() { if let Some(base_val) = base.slots.$slot.load() { typ.slots.$slot.store(Some(base_val)); } } }}; } macro_rules! copy_number { ($slot:ident) => {{ if typ.slots.as_number.$slot.load().is_none() { if let Some(base_val) = base.slots.as_number.$slot.load() { typ.slots.as_number.$slot.store(Some(base_val)); } } }}; } macro_rules! copy_sequence { ($slot:ident) => {{ if typ.slots.as_sequence.$slot.load().is_none() { if let Some(base_val) = base.slots.as_sequence.$slot.load() { typ.slots.as_sequence.$slot.store(Some(base_val)); } } }}; } macro_rules! copy_mapping { ($slot:ident) => {{ if typ.slots.as_mapping.$slot.load().is_none() { if let Some(base_val) = base.slots.as_mapping.$slot.load() { typ.slots.as_mapping.$slot.store(Some(base_val)); } } }}; } match self { // Type slots Self::TpHash => copy_main!(hash), Self::TpRepr => copy_main!(repr), Self::TpStr => copy_main!(str), Self::TpCall => copy_main!(call), Self::TpIter => copy_main!(iter), Self::TpIternext => copy_main!(iternext), Self::TpInit => { // SLOTDEFINED check for multiple inheritance support if typ.slots.init.load().is_none() && let Some(base_val) = base.slots.init.load() { let slot_defined = base.base.as_ref().is_none_or(|bb| { bb.slots.init.load().map(|v| v as usize) != Some(base_val as usize) }); if slot_defined { typ.slots.init.store(Some(base_val)); } } } Self::TpNew => {} // handled by set_new() Self::TpDel => copy_main!(del), Self::TpGetattro => copy_main!(getattro), Self::TpSetattro => copy_main!(setattro), Self::TpDescrGet => copy_main!(descr_get), Self::TpDescrSet => copy_main!(descr_set), Self::TpRichcompare => copy_main!(richcompare), // Number slots Self::NbAdd => copy_number!(add), Self::NbSubtract => copy_number!(subtract), Self::NbMultiply => copy_number!(multiply), Self::NbRemainder => copy_number!(remainder), Self::NbDivmod => copy_number!(divmod), Self::NbPower => copy_number!(power), Self::NbLshift => copy_number!(lshift), Self::NbRshift => copy_number!(rshift), Self::NbAnd => copy_number!(and), Self::NbXor => copy_number!(xor), Self::NbOr => copy_number!(or), Self::NbFloorDivide => copy_number!(floor_divide), Self::NbTrueDivide => copy_number!(true_divide), Self::NbMatrixMultiply => copy_number!(matrix_multiply), Self::NbInplaceAdd => copy_number!(inplace_add), Self::NbInplaceSubtract => copy_number!(inplace_subtract), Self::NbInplaceMultiply => copy_number!(inplace_multiply), Self::NbInplaceRemainder => copy_number!(inplace_remainder), Self::NbInplacePower => copy_number!(inplace_power), Self::NbInplaceLshift => copy_number!(inplace_lshift), Self::NbInplaceRshift => copy_number!(inplace_rshift), Self::NbInplaceAnd => copy_number!(inplace_and), Self::NbInplaceXor => copy_number!(inplace_xor), Self::NbInplaceOr => copy_number!(inplace_or), Self::NbInplaceFloorDivide => copy_number!(inplace_floor_divide), Self::NbInplaceTrueDivide => copy_number!(inplace_true_divide), Self::NbInplaceMatrixMultiply => copy_number!(inplace_matrix_multiply), // Number unary Self::NbNegative => copy_number!(negative), Self::NbPositive => copy_number!(positive), Self::NbAbsolute => copy_number!(absolute), Self::NbInvert => copy_number!(invert), Self::NbBool => copy_number!(boolean), Self::NbInt => copy_number!(int), Self::NbFloat => copy_number!(float), Self::NbIndex => copy_number!(index), // Sequence slots Self::SqLength => copy_sequence!(length), Self::SqConcat => copy_sequence!(concat), Self::SqRepeat => copy_sequence!(repeat), Self::SqItem => copy_sequence!(item), Self::SqAssItem => copy_sequence!(ass_item), Self::SqContains => copy_sequence!(contains), Self::SqInplaceConcat => copy_sequence!(inplace_concat), Self::SqInplaceRepeat => copy_sequence!(inplace_repeat), // Mapping slots Self::MpLength => copy_mapping!(length), Self::MpSubscript => copy_mapping!(subscript), Self::MpAssSubscript => copy_mapping!(ass_subscript), // Reserved slots - no-op _ => {} } } /// Get the SlotFunc from type slots for this accessor pub fn get_slot_func(&self, slots: &PyTypeSlots) -> Option<SlotFunc> { match self { // Type slots Self::TpHash => slots.hash.load().map(SlotFunc::Hash), Self::TpRepr => slots.repr.load().map(SlotFunc::Repr), Self::TpStr => slots.str.load().map(SlotFunc::Str), Self::TpCall => slots.call.load().map(SlotFunc::Call), Self::TpIter => slots.iter.load().map(SlotFunc::Iter), Self::TpIternext => slots.iternext.load().map(SlotFunc::IterNext), Self::TpInit => slots.init.load().map(SlotFunc::Init), Self::TpNew => None, // __new__ handled separately Self::TpDel => slots.del.load().map(SlotFunc::Del), Self::TpGetattro => slots.getattro.load().map(SlotFunc::GetAttro), Self::TpSetattro => slots.setattro.load().map(SlotFunc::SetAttro), Self::TpDescrGet => slots.descr_get.load().map(SlotFunc::DescrGet), Self::TpDescrSet => slots.descr_set.load().map(SlotFunc::DescrSet), Self::TpRichcompare => slots .richcompare .load() .map(|f| SlotFunc::RichCompare(f, PyComparisonOp::Eq)), // Number binary slots Self::NbAdd => slots.as_number.add.load().map(SlotFunc::NumBinary), Self::NbSubtract => slots.as_number.subtract.load().map(SlotFunc::NumBinary), Self::NbMultiply => slots.as_number.multiply.load().map(SlotFunc::NumBinary), Self::NbRemainder => slots.as_number.remainder.load().map(SlotFunc::NumBinary), Self::NbDivmod => slots.as_number.divmod.load().map(SlotFunc::NumBinary), Self::NbPower => slots.as_number.power.load().map(SlotFunc::NumTernary), Self::NbLshift => slots.as_number.lshift.load().map(SlotFunc::NumBinary), Self::NbRshift => slots.as_number.rshift.load().map(SlotFunc::NumBinary), Self::NbAnd => slots.as_number.and.load().map(SlotFunc::NumBinary), Self::NbXor => slots.as_number.xor.load().map(SlotFunc::NumBinary), Self::NbOr => slots.as_number.or.load().map(SlotFunc::NumBinary), Self::NbFloorDivide => slots.as_number.floor_divide.load().map(SlotFunc::NumBinary), Self::NbTrueDivide => slots.as_number.true_divide.load().map(SlotFunc::NumBinary), Self::NbMatrixMultiply => slots .as_number .matrix_multiply .load() .map(SlotFunc::NumBinary), // Number inplace slots Self::NbInplaceAdd => slots.as_number.inplace_add.load().map(SlotFunc::NumBinary), Self::NbInplaceSubtract => slots .as_number .inplace_subtract .load() .map(SlotFunc::NumBinary), Self::NbInplaceMultiply => slots .as_number .inplace_multiply .load() .map(SlotFunc::NumBinary), Self::NbInplaceRemainder => slots .as_number .inplace_remainder .load() .map(SlotFunc::NumBinary), Self::NbInplacePower => slots .as_number .inplace_power .load() .map(SlotFunc::NumTernary), Self::NbInplaceLshift => slots .as_number .inplace_lshift .load() .map(SlotFunc::NumBinary), Self::NbInplaceRshift => slots .as_number .inplace_rshift .load() .map(SlotFunc::NumBinary), Self::NbInplaceAnd => slots.as_number.inplace_and.load().map(SlotFunc::NumBinary), Self::NbInplaceXor => slots.as_number.inplace_xor.load().map(SlotFunc::NumBinary), Self::NbInplaceOr => slots.as_number.inplace_or.load().map(SlotFunc::NumBinary), Self::NbInplaceFloorDivide => slots .as_number .inplace_floor_divide .load() .map(SlotFunc::NumBinary), Self::NbInplaceTrueDivide => slots .as_number .inplace_true_divide .load() .map(SlotFunc::NumBinary), Self::NbInplaceMatrixMultiply => slots .as_number .inplace_matrix_multiply .load() .map(SlotFunc::NumBinary), // Number unary slots Self::NbNegative => slots.as_number.negative.load().map(SlotFunc::NumUnary), Self::NbPositive => slots.as_number.positive.load().map(SlotFunc::NumUnary), Self::NbAbsolute => slots.as_number.absolute.load().map(SlotFunc::NumUnary), Self::NbInvert => slots.as_number.invert.load().map(SlotFunc::NumUnary), Self::NbBool => slots.as_number.boolean.load().map(SlotFunc::NumBoolean), Self::NbInt => slots.as_number.int.load().map(SlotFunc::NumUnary), Self::NbFloat => slots.as_number.float.load().map(SlotFunc::NumUnary), Self::NbIndex => slots.as_number.index.load().map(SlotFunc::NumUnary), // Sequence slots Self::SqLength => slots.as_sequence.length.load().map(SlotFunc::SeqLength), Self::SqConcat => slots.as_sequence.concat.load().map(SlotFunc::SeqConcat), Self::SqRepeat => slots.as_sequence.repeat.load().map(SlotFunc::SeqRepeat), Self::SqItem => slots.as_sequence.item.load().map(SlotFunc::SeqItem), Self::SqAssItem => slots.as_sequence.ass_item.load().map(SlotFunc::SeqSetItem), Self::SqContains => slots.as_sequence.contains.load().map(SlotFunc::SeqContains), Self::SqInplaceConcat => slots .as_sequence .inplace_concat .load() .map(SlotFunc::SeqConcat), Self::SqInplaceRepeat => slots .as_sequence .inplace_repeat .load() .map(SlotFunc::SeqRepeat), // Mapping slots Self::MpLength => slots.as_mapping.length.load().map(SlotFunc::MapLength), Self::MpSubscript => slots .as_mapping .subscript .load() .map(SlotFunc::MapSubscript), Self::MpAssSubscript => slots .as_mapping .ass_subscript .load() .map(SlotFunc::MapSetSubscript), // Reserved slots _ => None, } } /// Get slot function considering SlotOp for right-hand and delete operations pub fn get_slot_func_with_op( &self, slots: &PyTypeSlots, op: Option<SlotOp>, ) -> Option<SlotFunc> { // For Delete operations, return the delete variant if op == Some(SlotOp::Delete) { match self { Self::TpSetattro => return slots.setattro.load().map(SlotFunc::DelAttro), Self::TpDescrSet => return slots.descr_set.load().map(SlotFunc::DescrDel), Self::SqAssItem => { return slots.as_sequence.ass_item.load().map(SlotFunc::SeqDelItem); } Self::MpAssSubscript => { return slots .as_mapping .ass_subscript .load() .map(SlotFunc::MapDelSubscript); } _ => {} } } // For Right operations on binary number slots, use right_* fields with swapped args if op == Some(SlotOp::Right) { match self { Self::NbAdd => { return slots .as_number .right_add
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/vm/compile.rs
crates/vm/src/vm/compile.rs
//! Python code compilation functions. //! //! For code execution functions, see python_run.rs use crate::{ PyRef, VirtualMachine, builtins::PyCode, compiler::{self, CompileError, CompileOpts}, }; impl VirtualMachine { pub fn compile( &self, source: &str, mode: compiler::Mode, source_path: String, ) -> Result<PyRef<PyCode>, CompileError> { self.compile_with_opts(source, mode, source_path, self.compile_opts()) } pub fn compile_with_opts( &self, source: &str, mode: compiler::Mode, source_path: String, opts: CompileOpts, ) -> Result<PyRef<PyCode>, CompileError> { compiler::compile(source, mode, &source_path, opts).map(|code| self.ctx.new_code(code)) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/vm/python_run.rs
crates/vm/src/vm/python_run.rs
//! Python code execution functions. use crate::{ Py, PyResult, VirtualMachine, builtins::{PyCode, PyDict}, compiler::{self}, scope::Scope, }; impl VirtualMachine { /// _PyRun_AnyFileObject (internal) /// /// Execute a Python file. Currently always delegates to run_simple_file /// (interactive mode is handled separately in shell.rs). /// /// Note: This is an internal function. Use `run_file` for the public interface. #[doc(hidden)] pub fn run_any_file(&self, scope: Scope, path: &str) -> PyResult<()> { let path = if path.is_empty() { "???" } else { path }; self.run_simple_file(scope, path) } /// _PyRun_SimpleFileObject /// /// Execute a Python file with __main__ module setup. /// Sets __file__ and __cached__ before execution, removes them after. fn run_simple_file(&self, scope: Scope, path: &str) -> PyResult<()> { self.with_simple_run(path, |module_dict| { self.run_simple_file_inner(module_dict, scope, path) }) } fn run_simple_file_inner( &self, module_dict: &Py<PyDict>, scope: Scope, path: &str, ) -> PyResult<()> { let pyc = maybe_pyc_file(path); if pyc { // pyc file execution set_main_loader(module_dict, path, "SourcelessFileLoader", self)?; let loader = module_dict.get_item("__loader__", self)?; let get_code = loader.get_attr("get_code", self)?; let code_obj = get_code.call((identifier!(self, __main__).to_owned(),), self)?; let code = code_obj .downcast::<PyCode>() .map_err(|_| self.new_runtime_error("Bad code object in .pyc file".to_owned()))?; self.run_code_obj(code, scope)?; } else { if path != "<stdin>" { set_main_loader(module_dict, path, "SourceFileLoader", self)?; } match std::fs::read_to_string(path) { Ok(source) => { let code_obj = self .compile(&source, compiler::Mode::Exec, path.to_owned()) .map_err(|err| self.new_syntax_error(&err, Some(&source)))?; self.run_code_obj(code_obj, scope)?; } Err(err) => { return Err(self.new_os_error(err.to_string())); } } } Ok(()) } /// PyRun_SimpleString /// /// Execute a string of Python code in a new scope with builtins. pub fn run_simple_string(&self, source: &str) -> PyResult { let scope = self.new_scope_with_builtins(); self.run_string(scope, source, "<string>".to_owned()) } /// PyRun_String /// /// Execute a string of Python code with explicit scope and source path. pub fn run_string(&self, scope: Scope, source: &str, source_path: String) -> PyResult { let code_obj = self .compile(source, compiler::Mode::Exec, source_path) .map_err(|err| self.new_syntax_error(&err, Some(source)))?; self.run_code_obj(code_obj, scope) } #[deprecated(note = "use run_string instead")] pub fn run_code_string(&self, scope: Scope, source: &str, source_path: String) -> PyResult { self.run_string(scope, source, source_path) } // #[deprecated(note = "use rustpython::run_file instead; if this changes causes problems, please report an issue.")] pub fn run_script(&self, scope: Scope, path: &str) -> PyResult<()> { self.run_any_file(scope, path) } pub fn run_block_expr(&self, scope: Scope, source: &str) -> PyResult { let code_obj = self .compile(source, compiler::Mode::BlockExpr, "<embedded>".to_owned()) .map_err(|err| self.new_syntax_error(&err, Some(source)))?; self.run_code_obj(code_obj, scope) } } fn set_main_loader( module_dict: &Py<PyDict>, filename: &str, loader_name: &str, vm: &VirtualMachine, ) -> PyResult<()> { vm.import("importlib.machinery", 0)?; let sys_modules = vm.sys_module.get_attr(identifier!(vm, modules), vm)?; let machinery = sys_modules.get_item("importlib.machinery", vm)?; let loader_name = vm.ctx.new_str(loader_name); let loader_class = machinery.get_attr(&loader_name, vm)?; let loader = loader_class.call((identifier!(vm, __main__).to_owned(), filename), vm)?; module_dict.set_item("__loader__", loader, vm)?; Ok(()) } /// Check whether a file is maybe a pyc file. /// /// Detection is performed by: /// 1. Checking if the filename ends with ".pyc" /// 2. If not, reading the first 2 bytes and comparing with the magic number fn maybe_pyc_file(path: &str) -> bool { if path.ends_with(".pyc") { return true; } maybe_pyc_file_with_magic(path).unwrap_or(false) } fn maybe_pyc_file_with_magic(path: &str) -> std::io::Result<bool> { let path_obj = std::path::Path::new(path); if !path_obj.is_file() { return Ok(false); } let mut file = std::fs::File::open(path)?; let mut buf = [0u8; 2]; use std::io::Read; if file.read(&mut buf)? != 2 { return Ok(false); } // Read only two bytes of the magic. If the file was opened in // text mode, the bytes 3 and 4 of the magic (\r\n) might not // be read as they are on disk. Ok(crate::import::check_pyc_magic_number_bytes(&buf)) }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/vm/mod.rs
crates/vm/src/vm/mod.rs
//! Implement virtual machine to run instructions. //! //! See also: //! <https://github.com/ProgVal/pythonvm-rust/blob/master/src/processor/mod.rs> #[cfg(feature = "rustpython-compiler")] mod compile; mod context; mod interpreter; mod method; #[cfg(feature = "rustpython-compiler")] mod python_run; mod setting; pub mod thread; mod vm_new; mod vm_object; mod vm_ops; use crate::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, builtins::{ PyBaseExceptionRef, PyDict, PyDictRef, PyInt, PyList, PyModule, PyStr, PyStrInterned, PyStrRef, PyTypeRef, code::PyCode, pystr::AsPyStr, tuple::PyTuple, }, codecs::CodecsRegistry, common::{hash::HashSecret, lock::PyMutex, rc::PyRc}, convert::ToPyObject, exceptions::types::PyBaseException, frame::{ExecutionResult, Frame, FrameRef}, frozen::FrozenModule, function::{ArgMapping, FuncArgs, PySetterValue}, import, protocol::PyIterIter, scope::Scope, signal, stdlib, warn::WarningsState, }; use alloc::borrow::Cow; use core::{ cell::{Cell, Ref, RefCell}, sync::atomic::AtomicBool, }; use crossbeam_utils::atomic::AtomicCell; #[cfg(unix)] use nix::{ sys::signal::{SaFlags, SigAction, SigSet, Signal::SIGINT, kill, sigaction}, unistd::getpid, }; use std::{ collections::{HashMap, HashSet}, ffi::{OsStr, OsString}, }; pub use context::Context; pub use interpreter::Interpreter; pub(crate) use method::PyMethod; pub use setting::{CheckHashPycsMode, Paths, PyConfig, Settings}; pub const MAX_MEMORY_SIZE: usize = isize::MAX as usize; // Objects are live when they are on stack, or referenced by a name (for now) /// Top level container of a python virtual machine. In theory you could /// create more instances of this struct and have them operate fully isolated. /// /// To construct this, please refer to the [`Interpreter`] pub struct VirtualMachine { pub builtins: PyRef<PyModule>, pub sys_module: PyRef<PyModule>, pub ctx: PyRc<Context>, pub frames: RefCell<Vec<FrameRef>>, pub wasm_id: Option<String>, exceptions: RefCell<ExceptionStack>, pub import_func: PyObjectRef, pub profile_func: RefCell<PyObjectRef>, pub trace_func: RefCell<PyObjectRef>, pub use_tracing: Cell<bool>, pub recursion_limit: Cell<usize>, pub(crate) signal_handlers: Option<Box<RefCell<[Option<PyObjectRef>; signal::NSIG]>>>, pub(crate) signal_rx: Option<signal::UserSignalReceiver>, pub repr_guards: RefCell<HashSet<usize>>, pub state: PyRc<PyGlobalState>, pub initialized: bool, recursion_depth: Cell<usize>, } #[derive(Debug, Default)] struct ExceptionStack { exc: Option<PyBaseExceptionRef>, prev: Option<Box<ExceptionStack>>, } pub struct PyGlobalState { pub config: PyConfig, pub module_inits: stdlib::StdlibMap, pub frozen: HashMap<&'static str, FrozenModule, ahash::RandomState>, pub stacksize: AtomicCell<usize>, pub thread_count: AtomicCell<usize>, pub hash_secret: HashSecret, pub atexit_funcs: PyMutex<Vec<(PyObjectRef, FuncArgs)>>, pub codec_registry: CodecsRegistry, pub finalizing: AtomicBool, pub warnings: WarningsState, pub override_frozen_modules: AtomicCell<isize>, pub before_forkers: PyMutex<Vec<PyObjectRef>>, pub after_forkers_child: PyMutex<Vec<PyObjectRef>>, pub after_forkers_parent: PyMutex<Vec<PyObjectRef>>, pub int_max_str_digits: AtomicCell<usize>, pub switch_interval: AtomicCell<f64>, } pub fn process_hash_secret_seed() -> u32 { use std::sync::OnceLock; static SEED: OnceLock<u32> = OnceLock::new(); // os_random is expensive, but this is only ever called once *SEED.get_or_init(|| u32::from_ne_bytes(rustpython_common::rand::os_random())) } impl VirtualMachine { /// Create a new `VirtualMachine` structure. fn new(config: PyConfig, ctx: PyRc<Context>) -> Self { flame_guard!("new VirtualMachine"); // make a new module without access to the vm; doesn't // set __spec__, __loader__, etc. attributes let new_module = |def| { PyRef::new_ref( PyModule::from_def(def), ctx.types.module_type.to_owned(), Some(ctx.new_dict()), ) }; // Hard-core modules: let builtins = new_module(stdlib::builtins::__module_def(&ctx)); let sys_module = new_module(stdlib::sys::__module_def(&ctx)); let import_func = ctx.none(); let profile_func = RefCell::new(ctx.none()); let trace_func = RefCell::new(ctx.none()); let signal_handlers = Some(Box::new( // putting it in a const optimizes better, prevents linear initialization of the array const { RefCell::new([const { None }; signal::NSIG]) }, )); let module_inits = stdlib::get_module_inits(); let seed = match config.settings.hash_seed { Some(seed) => seed, None => process_hash_secret_seed(), }; let hash_secret = HashSecret::new(seed); let codec_registry = CodecsRegistry::new(&ctx); let warnings = WarningsState::init_state(&ctx); let int_max_str_digits = AtomicCell::new(match config.settings.int_max_str_digits { -1 => 4300, other => other, } as usize); let mut vm = Self { builtins, sys_module, ctx, frames: RefCell::new(vec![]), wasm_id: None, exceptions: RefCell::default(), import_func, profile_func, trace_func, use_tracing: Cell::new(false), recursion_limit: Cell::new(if cfg!(debug_assertions) { 256 } else { 1000 }), signal_handlers, signal_rx: None, repr_guards: RefCell::default(), state: PyRc::new(PyGlobalState { config, module_inits, frozen: HashMap::default(), stacksize: AtomicCell::new(0), thread_count: AtomicCell::new(0), hash_secret, atexit_funcs: PyMutex::default(), codec_registry, finalizing: AtomicBool::new(false), warnings, override_frozen_modules: AtomicCell::new(0), before_forkers: PyMutex::default(), after_forkers_child: PyMutex::default(), after_forkers_parent: PyMutex::default(), int_max_str_digits, switch_interval: AtomicCell::new(0.005), }), initialized: false, recursion_depth: Cell::new(0), }; if vm.state.hash_secret.hash_str("") != vm .ctx .interned_str("") .expect("empty str must be interned") .hash(&vm) { panic!("Interpreters in same process must share the hash seed"); } let frozen = core_frozen_inits().collect(); PyRc::get_mut(&mut vm.state).unwrap().frozen = frozen; vm.builtins.init_dict( vm.ctx.intern_str("builtins"), Some(vm.ctx.intern_str(stdlib::builtins::DOC.unwrap()).to_owned()), &vm, ); vm.sys_module.init_dict( vm.ctx.intern_str("sys"), Some(vm.ctx.intern_str(stdlib::sys::DOC.unwrap()).to_owned()), &vm, ); // let name = vm.sys_module.get_attr("__name__", &vm).unwrap(); vm } /// set up the encodings search function /// init_importlib must be called before this call #[cfg(feature = "encodings")] fn import_encodings(&mut self) -> PyResult<()> { self.import("encodings", 0).map_err(|import_err| { let rustpythonpath_env = std::env::var("RUSTPYTHONPATH").ok(); let pythonpath_env = std::env::var("PYTHONPATH").ok(); let env_set = rustpythonpath_env.as_ref().is_some() || pythonpath_env.as_ref().is_some(); let path_contains_env = self.state.config.paths.module_search_paths.iter().any(|s| { Some(s.as_str()) == rustpythonpath_env.as_deref() || Some(s.as_str()) == pythonpath_env.as_deref() }); let guide_message = if cfg!(feature = "freeze-stdlib") { "`rustpython_pylib` maybe not set while using `freeze-stdlib` feature. Try using `rustpython::InterpreterConfig::init_stdlib` or manually call `vm.add_frozen(rustpython_pylib::FROZEN_STDLIB)` in `rustpython_vm::Interpreter::with_init`." } else if !env_set { "Neither RUSTPYTHONPATH nor PYTHONPATH is set. Try setting one of them to the stdlib directory." } else if path_contains_env { "RUSTPYTHONPATH or PYTHONPATH is set, but it doesn't contain the encodings library. If you are customizing the RustPython vm/interpreter, try adding the stdlib directory to the path. If you are developing the RustPython interpreter, it might be a bug during development." } else { "RUSTPYTHONPATH or PYTHONPATH is set, but it wasn't loaded to `PyConfig::paths::module_search_paths`. If you are going to customize the RustPython vm/interpreter, those environment variables are not loaded in the Settings struct by default. Please try creating a customized instance of the Settings struct. If you are developing the RustPython interpreter, it might be a bug during development." }; let mut msg = format!( "RustPython could not import the encodings module. It usually means something went wrong. Please carefully read the following messages and follow the steps.\n\ \n\ {guide_message}"); if !cfg!(feature = "freeze-stdlib") { msg += "\n\ If you don't have access to a consistent external environment (e.g. targeting wasm, embedding \ rustpython in another application), try enabling the `freeze-stdlib` feature.\n\ If this is intended and you want to exclude the encodings module from your interpreter, please remove the `encodings` feature from `rustpython-vm` crate."; } let err = self.new_runtime_error(msg); err.set___cause__(Some(import_err)); err })?; Ok(()) } fn import_ascii_utf8_encodings(&mut self) -> PyResult<()> { import::import_frozen(self, "codecs")?; // Use dotted names when freeze-stdlib is enabled (modules come from Lib/encodings/), // otherwise use underscored names (modules come from core_modules/). let (ascii_module_name, utf8_module_name) = if cfg!(feature = "freeze-stdlib") { ("encodings.ascii", "encodings.utf_8") } else { ("encodings_ascii", "encodings_utf_8") }; // Register ascii encoding let ascii_module = import::import_frozen(self, ascii_module_name)?; let getregentry = ascii_module.get_attr("getregentry", self)?; let codec_info = getregentry.call((), self)?; self.state .codec_registry .register_manual("ascii", codec_info.try_into_value(self)?)?; // Register utf-8 encoding let utf8_module = import::import_frozen(self, utf8_module_name)?; let getregentry = utf8_module.get_attr("getregentry", self)?; let codec_info = getregentry.call((), self)?; self.state .codec_registry .register_manual("utf-8", codec_info.try_into_value(self)?)?; Ok(()) } fn initialize(&mut self) { flame_guard!("init VirtualMachine"); if self.initialized { panic!("Double Initialize Error"); } stdlib::builtins::init_module(self, &self.builtins); stdlib::sys::init_module(self, &self.sys_module, &self.builtins); let mut essential_init = || -> PyResult { import::import_builtin(self, "_typing")?; #[cfg(not(target_arch = "wasm32"))] import::import_builtin(self, "_signal")?; #[cfg(any(feature = "parser", feature = "compiler"))] import::import_builtin(self, "_ast")?; #[cfg(not(feature = "threading"))] import::import_frozen(self, "_thread")?; let importlib = import::init_importlib_base(self)?; self.import_ascii_utf8_encodings()?; #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] { let io = import::import_builtin(self, "_io")?; #[cfg(feature = "stdio")] let make_stdio = |name, fd, write| { let buffered_stdio = self.state.config.settings.buffered_stdio; let unbuffered = write && !buffered_stdio; let buf = crate::stdlib::io::open( self.ctx.new_int(fd).into(), Some(if write { "wb" } else { "rb" }), crate::stdlib::io::OpenArgs { buffering: if unbuffered { 0 } else { -1 }, ..Default::default() }, self, )?; let raw = if unbuffered { buf.clone() } else { buf.get_attr("raw", self)? }; raw.set_attr("name", self.ctx.new_str(format!("<{name}>")), self)?; let isatty = self.call_method(&raw, "isatty", ())?.is_true(self)?; let write_through = !buffered_stdio; let line_buffering = buffered_stdio && (isatty || fd == 2); let newline = if cfg!(windows) { None } else { Some("\n") }; let encoding = self.state.config.settings.stdio_encoding.as_deref(); // stderr always uses backslashreplace (ignores stdio_errors) let errors = if fd == 2 { Some("backslashreplace") } else { self.state.config.settings.stdio_errors.as_deref() }; let stdio = self.call_method( &io, "TextIOWrapper", ( buf, encoding, errors, newline, line_buffering, write_through, ), )?; let mode = if write { "w" } else { "r" }; stdio.set_attr("mode", self.ctx.new_str(mode), self)?; Ok(stdio) }; #[cfg(not(feature = "stdio"))] let make_stdio = |_name, _fd, _write| Ok(crate::builtins::PyNone.into_pyobject(self)); let set_stdio = |name, fd, write| { let stdio = make_stdio(name, fd, write)?; let dunder_name = self.ctx.intern_str(format!("__{name}__")); self.sys_module.set_attr( dunder_name, // e.g. __stdin__ stdio.clone(), self, )?; self.sys_module.set_attr(name, stdio, self)?; Ok(()) }; set_stdio("stdin", 0, false)?; set_stdio("stdout", 1, true)?; set_stdio("stderr", 2, true)?; let io_open = io.get_attr("open", self)?; self.builtins.set_attr("open", io_open, self)?; } Ok(importlib) }; let res = essential_init(); let importlib = self.expect_pyresult(res, "essential initialization failed"); if self.state.config.settings.allow_external_library && cfg!(feature = "rustpython-compiler") && let Err(e) = import::init_importlib_package(self, importlib) { eprintln!( "importlib initialization failed. This is critical for many complicated packages." ); self.print_exception(e); } let _expect_stdlib = cfg!(feature = "freeze-stdlib") || !self.state.config.paths.module_search_paths.is_empty(); #[cfg(feature = "encodings")] if _expect_stdlib { if let Err(e) = self.import_encodings() { eprintln!( "encodings initialization failed. Only utf-8 encoding will be supported." ); self.print_exception(e); } } else { // Here may not be the best place to give general `path_list` advice, // but bare rustpython_vm::VirtualMachine users skipped proper settings must hit here while properly setup vm never enters here. eprintln!( "feature `encodings` is enabled but `paths.module_search_paths` is empty. \ Please add the library path to `settings.path_list`. If you intended to disable the entire standard library (including the `encodings` feature), please also make sure to disable the `encodings` feature.\n\ Tip: You may also want to add `\"\"` to `settings.path_list` in order to enable importing from the current working directory." ); } self.initialized = true; } fn state_mut(&mut self) -> &mut PyGlobalState { PyRc::get_mut(&mut self.state) .expect("there should not be multiple threads while a user has a mut ref to a vm") } /// Can only be used in the initialization closure passed to [`Interpreter::with_init`] pub fn add_native_module<S>(&mut self, name: S, module: stdlib::StdlibInitFunc) where S: Into<Cow<'static, str>>, { self.state_mut().module_inits.insert(name.into(), module); } pub fn add_native_modules<I>(&mut self, iter: I) where I: IntoIterator<Item = (Cow<'static, str>, stdlib::StdlibInitFunc)>, { self.state_mut().module_inits.extend(iter); } /// Can only be used in the initialization closure passed to [`Interpreter::with_init`] pub fn add_frozen<I>(&mut self, frozen: I) where I: IntoIterator<Item = (&'static str, FrozenModule)>, { self.state_mut().frozen.extend(frozen); } /// Set the custom signal channel for the interpreter pub fn set_user_signal_channel(&mut self, signal_rx: signal::UserSignalReceiver) { self.signal_rx = Some(signal_rx); } /// Execute Python bytecode (`.pyc`) from an in-memory buffer. /// /// When the RustPython CLI is available, `.pyc` files are normally executed by /// invoking `rustpython <input>.pyc`. This method provides an alternative for /// environments where the binary is unavailable or file I/O is restricted /// (e.g. WASM). /// /// ## Preparing a `.pyc` file /// /// First, compile a Python source file into bytecode: /// /// ```sh /// # Generate a .pyc file /// $ rustpython -m py_compile <input>.py /// ``` /// /// ## Running the bytecode /// /// Load the resulting `.pyc` file into memory and execute it using the VM: /// /// ```no_run /// use rustpython_vm::Interpreter; /// Interpreter::without_stdlib(Default::default()).enter(|vm| { /// let bytes = std::fs::read("__pycache__/<input>.rustpython-313.pyc").unwrap(); /// let main_scope = vm.new_scope_with_main().unwrap(); /// vm.run_pyc_bytes(&bytes, main_scope); /// }); /// ``` pub fn run_pyc_bytes(&self, pyc_bytes: &[u8], scope: Scope) -> PyResult<()> { let code = PyCode::from_pyc(pyc_bytes, Some("<pyc_bytes>"), None, None, self)?; self.with_simple_run("<source>", |_module_dict| { self.run_code_obj(code, scope)?; Ok(()) }) } pub fn run_code_obj(&self, code: PyRef<PyCode>, scope: Scope) -> PyResult { use crate::builtins::PyFunction; // Create a function object for module code, similar to CPython's PyEval_EvalCode let func = PyFunction::new(code.clone(), scope.globals.clone(), self)?; let func_obj = func.into_ref(&self.ctx).into(); let frame = Frame::new(code, scope, self.builtins.dict(), &[], Some(func_obj), self) .into_ref(&self.ctx); self.run_frame(frame) } #[cold] pub fn run_unraisable(&self, e: PyBaseExceptionRef, msg: Option<String>, object: PyObjectRef) { let sys_module = self.import("sys", 0).unwrap(); let unraisablehook = sys_module.get_attr("unraisablehook", self).unwrap(); let exc_type = e.class().to_owned(); let exc_traceback = e.__traceback__().to_pyobject(self); // TODO: actual traceback let exc_value = e.into(); let args = stdlib::sys::UnraisableHookArgsData { exc_type, exc_value, exc_traceback, err_msg: self.new_pyobj(msg), object, }; if let Err(e) = unraisablehook.call((args,), self) { println!("{}", e.as_object().repr(self).unwrap()); } } #[inline(always)] pub fn run_frame(&self, frame: FrameRef) -> PyResult { match self.with_frame(frame, |f| f.run(self))? { ExecutionResult::Return(value) => Ok(value), _ => panic!("Got unexpected result from function"), } } /// Run `run` with main scope. fn with_simple_run( &self, path: &str, run: impl FnOnce(&Py<PyDict>) -> PyResult<()>, ) -> PyResult<()> { let sys_modules = self.sys_module.get_attr(identifier!(self, modules), self)?; let main_module = sys_modules.get_item(identifier!(self, __main__), self)?; let module_dict = main_module.dict().expect("main module must have __dict__"); // Track whether we set __file__ (for cleanup) let set_file_name = !module_dict.contains_key(identifier!(self, __file__), self); if set_file_name { module_dict.set_item( identifier!(self, __file__), self.ctx.new_str(path).into(), self, )?; module_dict.set_item(identifier!(self, __cached__), self.ctx.none(), self)?; } let result = run(&module_dict); self.flush_io(); // Cleanup __file__ and __cached__ after execution if set_file_name { let _ = module_dict.del_item(identifier!(self, __file__), self); let _ = module_dict.del_item(identifier!(self, __cached__), self); } result } /// flush_io /// /// Flush stdout and stderr. Errors are silently ignored. fn flush_io(&self) { if let Ok(stdout) = self.sys_module.get_attr("stdout", self) { let _ = self.call_method(&stdout, identifier!(self, flush).as_str(), ()); } if let Ok(stderr) = self.sys_module.get_attr("stderr", self) { let _ = self.call_method(&stderr, identifier!(self, flush).as_str(), ()); } } pub fn current_recursion_depth(&self) -> usize { self.recursion_depth.get() } /// Used to run the body of a (possibly) recursive function. It will raise a /// RecursionError if recursive functions are nested far too many times, /// preventing a stack overflow. pub fn with_recursion<R, F: FnOnce() -> PyResult<R>>(&self, _where: &str, f: F) -> PyResult<R> { self.check_recursive_call(_where)?; self.recursion_depth.set(self.recursion_depth.get() + 1); let result = f(); self.recursion_depth.set(self.recursion_depth.get() - 1); result } pub fn with_frame<R, F: FnOnce(FrameRef) -> PyResult<R>>( &self, frame: FrameRef, f: F, ) -> PyResult<R> { self.with_recursion("", || { self.frames.borrow_mut().push(frame.clone()); // Push a new exception context for frame isolation // Each frame starts with no active exception (None) // This prevents exceptions from leaking between function calls self.push_exception(None); let result = f(frame); // Pop the exception context - restores caller's exception state self.pop_exception(); // defer dec frame let _popped = self.frames.borrow_mut().pop(); result }) } /// Returns a basic CompileOpts instance with options accurate to the vm. Used /// as the CompileOpts for `vm.compile()`. #[cfg(feature = "rustpython-codegen")] pub fn compile_opts(&self) -> crate::compiler::CompileOpts { crate::compiler::CompileOpts { optimize: self.state.config.settings.optimize, debug_ranges: self.state.config.settings.code_debug_ranges, } } // To be called right before raising the recursion depth. fn check_recursive_call(&self, _where: &str) -> PyResult<()> { if self.recursion_depth.get() >= self.recursion_limit.get() { Err(self.new_recursion_error(format!("maximum recursion depth exceeded {_where}"))) } else { Ok(()) } } pub fn current_frame(&self) -> Option<Ref<'_, FrameRef>> { let frames = self.frames.borrow(); if frames.is_empty() { None } else { Some(Ref::map(self.frames.borrow(), |frames| { frames.last().unwrap() })) } } pub fn current_locals(&self) -> PyResult<ArgMapping> { self.current_frame() .expect("called current_locals but no frames on the stack") .locals(self) } pub fn current_globals(&self) -> Ref<'_, PyDictRef> { let frame = self .current_frame() .expect("called current_globals but no frames on the stack"); Ref::map(frame, |f| &f.globals) } pub fn try_class(&self, module: &'static str, class: &'static str) -> PyResult<PyTypeRef> { let class = self .import(module, 0)? .get_attr(class, self)? .downcast() .expect("not a class"); Ok(class) } pub fn class(&self, module: &'static str, class: &'static str) -> PyTypeRef { let module = self .import(module, 0) .unwrap_or_else(|_| panic!("unable to import {module}")); let class = module .get_attr(class, self) .unwrap_or_else(|_| panic!("module {module:?} has no class {class}")); class.downcast().expect("not a class") } /// Call Python __import__ function without from_list. /// Roughly equivalent to `import module_name` or `import top.submodule`. /// /// See also [`VirtualMachine::import_from`] for more advanced import. /// See also [`rustpython_vm::import::import_source`] and other primitive import functions. #[inline] pub fn import<'a>(&self, module_name: impl AsPyStr<'a>, level: usize) -> PyResult { let module_name = module_name.as_pystr(&self.ctx); let from_list = self.ctx.empty_tuple_typed(); self.import_inner(module_name, from_list, level) } /// Call Python __import__ function caller with from_list. /// Roughly equivalent to `from module_name import item1, item2` or `from top.submodule import item1, item2` #[inline] pub fn import_from<'a>( &self, module_name: impl AsPyStr<'a>, from_list: &Py<PyTuple<PyStrRef>>, level: usize, ) -> PyResult { let module_name = module_name.as_pystr(&self.ctx); self.import_inner(module_name, from_list, level) } fn import_inner( &self, module: &Py<PyStr>, from_list: &Py<PyTuple<PyStrRef>>, level: usize, ) -> PyResult { // if the import inputs seem weird, e.g a package import or something, rather than just // a straight `import ident` let weird = module.as_str().contains('.') || level != 0 || !from_list.is_empty(); let cached_module = if weird { None } else { let sys_modules = self.sys_module.get_attr("modules", self)?; sys_modules.get_item(module, self).ok() }; match cached_module { Some(cached_module) => { if self.is_none(&cached_module) { Err(self.new_import_error( format!("import of {module} halted; None in sys.modules"), module.to_owned(), )) } else { Ok(cached_module) } } None => { let import_func = self .builtins .get_attr(identifier!(self, __import__), self) .map_err(|_| { self.new_import_error("__import__ not found", module.to_owned()) })?; let (locals, globals) = if let Some(frame) = self.current_frame() { (Some(frame.locals.clone()), Some(frame.globals.clone())) } else { (None, None) }; let from_list: PyObjectRef = from_list.to_owned().into(); import_func .call((module.to_owned(), globals, locals, from_list, level), self) .inspect_err(|exc| import::remove_importlib_frames(self, exc)) } } } pub fn extract_elements_with<T, F>(&self, value: &PyObject, func: F) -> PyResult<Vec<T>> where F: Fn(PyObjectRef) -> PyResult<T>, { // Extract elements from item, if possible: let cls = value.class(); let list_borrow; let slice = if cls.is(self.ctx.types.tuple_type) { value.downcast_ref::<PyTuple>().unwrap().as_slice() } else if cls.is(self.ctx.types.list_type) { list_borrow = value.downcast_ref::<PyList>().unwrap().borrow_vec(); &list_borrow } else { return self.map_py_iter(value, func); }; slice.iter().map(|obj| func(obj.clone())).collect() } pub fn map_iterable_object<F, R>(&self, obj: &PyObject, mut f: F) -> PyResult<PyResult<Vec<R>>> where F: FnMut(PyObjectRef) -> PyResult<R>, { match_class!(match obj { ref l @ PyList => { let mut i: usize = 0; let mut results = Vec::with_capacity(l.borrow_vec().len()); loop { let elem = { let elements = &*l.borrow_vec(); if i >= elements.len() { results.shrink_to_fit(); return Ok(Ok(results)); } else { elements[i].clone() } // free the lock }; match f(elem) { Ok(result) => results.push(result), Err(err) => return Ok(Err(err)), } i += 1; } } ref t @ PyTuple => Ok(t.iter().cloned().map(f).collect()), // TODO: put internal iterable type obj => { Ok(self.map_py_iter(obj, f)) } }) } fn map_py_iter<F, R>(&self, value: &PyObject, mut f: F) -> PyResult<Vec<R>> where F: FnMut(PyObjectRef) -> PyResult<R>, { let iter = value.to_owned().get_iter(self)?; let cap = match self.length_hint_opt(value.to_owned()) { Err(e) if e.class().is(self.ctx.exceptions.runtime_error) => return Err(e), Ok(Some(value)) => Some(value), // Use a power of 2 as a default capacity. _ => None, }; // TODO: fix extend to do this check (?), see test_extend in Lib/test/list_tests.py, // https://github.com/python/cpython/blob/v3.9.0/Objects/listobject.c#L922-L928 if let Some(cap) = cap && cap >= isize::MAX as usize { return Ok(Vec::new()); } let mut results = PyIterIter::new(self, iter.as_ref(), cap) .map(|element| f(element?)) .collect::<PyResult<Vec<_>>>()?; results.shrink_to_fit();
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
true
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/vm/method.rs
crates/vm/src/vm/method.rs
//! This module will be replaced once #3100 is done //! Do not expose this type to outside of this crate use super::VirtualMachine; use crate::{ builtins::{PyBaseObject, PyStr, PyStrInterned}, function::IntoFuncArgs, object::{AsObject, Py, PyObject, PyObjectRef, PyResult}, types::PyTypeFlags, }; #[derive(Debug)] pub enum PyMethod { Function { target: PyObjectRef, func: PyObjectRef, }, Attribute(PyObjectRef), } impl PyMethod { pub fn get(obj: PyObjectRef, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult<Self> { let cls = obj.class(); let getattro = cls.slots.getattro.load().unwrap(); if getattro as usize != PyBaseObject::getattro as usize { return obj.get_attr(name, vm).map(Self::Attribute); } // any correct method name is always interned already. let interned_name = vm.ctx.interned_str(name); let mut is_method = false; let cls_attr = match interned_name.and_then(|name| cls.get_attr(name)) { Some(descr) => { let descr_cls = descr.class(); let descr_get = if descr_cls .slots .flags .has_feature(PyTypeFlags::METHOD_DESCRIPTOR) { is_method = true; None } else { let descr_get = descr_cls.slots.descr_get.load(); if let Some(descr_get) = descr_get && descr_cls.slots.descr_set.load().is_some() { let cls = cls.to_owned().into(); return descr_get(descr, Some(obj), Some(cls), vm).map(Self::Attribute); } descr_get }; Some((descr, descr_get)) } None => None, }; if let Some(dict) = obj.dict() && let Some(attr) = dict.get_item_opt(name, vm)? { return Ok(Self::Attribute(attr)); } if let Some((attr, descr_get)) = cls_attr { match descr_get { None if is_method => Ok(Self::Function { target: obj, func: attr, }), Some(descr_get) => { let cls = cls.to_owned().into(); descr_get(attr, Some(obj), Some(cls), vm).map(Self::Attribute) } None => Ok(Self::Attribute(attr)), } } else if let Some(getter) = cls.get_attr(identifier!(vm, __getattr__)) { getter.call((obj, name.to_owned()), vm).map(Self::Attribute) } else { Err(vm.new_no_attribute_error(obj.clone(), name.to_owned())) } } pub(crate) fn get_special<const DIRECT: bool>( obj: &PyObject, name: &'static PyStrInterned, vm: &VirtualMachine, ) -> PyResult<Option<Self>> { let obj_cls = obj.class(); let attr = if DIRECT { obj_cls.get_direct_attr(name) } else { obj_cls.get_attr(name) }; let func = match attr { Some(f) => f, None => { return Ok(None); } }; let meth = if func .class() .slots .flags .has_feature(PyTypeFlags::METHOD_DESCRIPTOR) { Self::Function { target: obj.to_owned(), func, } } else { let obj_cls = obj_cls.to_owned().into(); let attr = vm .call_get_descriptor_specific(&func, Some(obj.to_owned()), Some(obj_cls)) .unwrap_or(Ok(func))?; Self::Attribute(attr) }; Ok(Some(meth)) } pub fn invoke(self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult { let (func, args) = match self { Self::Function { target, func } => (func, args.into_method_args(target, vm)), Self::Attribute(func) => (func, args.into_args(vm)), }; func.call(args, vm) } #[allow(dead_code)] pub fn invoke_ref(&self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult { let (func, args) = match self { Self::Function { target, func } => (func, args.into_method_args(target.clone(), vm)), Self::Attribute(func) => (func, args.into_args(vm)), }; func.call(args, vm) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/vm/interpreter.rs
crates/vm/src/vm/interpreter.rs
use super::{Context, PyConfig, VirtualMachine, setting::Settings, thread}; use crate::{PyResult, getpath, stdlib::atexit, vm::PyBaseExceptionRef}; use core::sync::atomic::Ordering; /// The general interface for the VM /// /// # Examples /// Runs a simple embedded hello world program. /// ``` /// use rustpython_vm::Interpreter; /// use rustpython_vm::compiler::Mode; /// Interpreter::without_stdlib(Default::default()).enter(|vm| { /// let scope = vm.new_scope_with_builtins(); /// let source = r#"print("Hello World!")"#; /// let code_obj = vm.compile( /// source, /// Mode::Exec, /// "<embedded>".to_owned(), /// ).map_err(|err| vm.new_syntax_error(&err, Some(source))).unwrap(); /// vm.run_code_obj(code_obj, scope).unwrap(); /// }); /// ``` pub struct Interpreter { vm: VirtualMachine, } impl Interpreter { /// This is a bare unit to build up an interpreter without the standard library. /// To create an interpreter with the standard library with the `rustpython` crate, use `rustpython::InterpreterConfig`. /// To create an interpreter without the `rustpython` crate, but only with `rustpython-vm`, /// try to build one from the source code of `InterpreterConfig`. It will not be a one-liner but it also will not be too hard. pub fn without_stdlib(settings: Settings) -> Self { Self::with_init(settings, |_| {}) } /// Create with initialize function taking mutable vm reference. /// ``` /// use rustpython_vm::Interpreter; /// Interpreter::with_init(Default::default(), |vm| { /// // put this line to add stdlib to the vm /// // vm.add_native_modules(rustpython_stdlib::get_module_inits()); /// }).enter(|vm| { /// vm.run_code_string(vm.new_scope_with_builtins(), "print(1)", "<...>".to_owned()); /// }); /// ``` pub fn with_init<F>(settings: Settings, init: F) -> Self where F: FnOnce(&mut VirtualMachine), { // Compute path configuration from settings let paths = getpath::init_path_config(&settings); let config = PyConfig::new(settings, paths); let ctx = Context::genesis(); crate::types::TypeZoo::extend(ctx); crate::exceptions::ExceptionZoo::extend(ctx); let mut vm = VirtualMachine::new(config, ctx.clone()); init(&mut vm); vm.initialize(); Self { vm } } /// Run a function with the main virtual machine and return a PyResult of the result. /// /// To enter vm context multiple times or to avoid buffer/exception management, this function is preferred. /// `enter` is lightweight and it returns a python object in PyResult. /// You can stop or continue the execution multiple times by calling `enter`. /// /// To finalize the vm once all desired `enter`s are called, calling `finalize` will be helpful. /// /// See also [`Interpreter::run`] for managed way to run the interpreter. pub fn enter<F, R>(&self, f: F) -> R where F: FnOnce(&VirtualMachine) -> R, { thread::enter_vm(&self.vm, || f(&self.vm)) } /// Run [`Interpreter::enter`] and call [`VirtualMachine::expect_pyresult`] for the result. /// /// This function is useful when you want to expect a result from the function, /// but also print useful panic information when exception raised. /// /// See also [`Interpreter::enter`] and [`VirtualMachine::expect_pyresult`] for more information. pub fn enter_and_expect<F, R>(&self, f: F, msg: &str) -> R where F: FnOnce(&VirtualMachine) -> PyResult<R>, { self.enter(|vm| { let result = f(vm); vm.expect_pyresult(result, msg) }) } /// Run a function with the main virtual machine and return exit code. /// /// To enter vm context only once and safely terminate the vm, this function is preferred. /// Unlike [`Interpreter::enter`], `run` calls finalize and returns exit code. /// You will not be able to obtain Python exception in this way. /// /// See [`Interpreter::finalize`] for the finalization steps. /// See also [`Interpreter::enter`] for pure function call to obtain Python exception. pub fn run<F>(self, f: F) -> u32 where F: FnOnce(&VirtualMachine) -> PyResult<()>, { let res = self.enter(|vm| f(vm)); self.finalize(res.err()) } /// Finalize vm and turns an exception to exit code. /// /// Finalization steps including 4 steps: /// 1. Flush stdout and stderr. /// 1. Handle exit exception and turn it to exit code. /// 1. Run atexit exit functions. /// 1. Mark vm as finalized. /// /// Note that calling `finalize` is not necessary by purpose though. pub fn finalize(self, exc: Option<PyBaseExceptionRef>) -> u32 { self.enter(|vm| { vm.flush_std(); // See if any exception leaked out: let exit_code = if let Some(exc) = exc { vm.handle_exit_exception(exc) } else { 0 }; atexit::_run_exitfuncs(vm); vm.state.finalizing.store(true, Ordering::Release); vm.flush_std(); exit_code }) } } #[cfg(test)] mod tests { use super::*; use crate::{ PyObjectRef, builtins::{PyStr, int}, }; use malachite_bigint::ToBigInt; #[test] fn test_add_py_integers() { Interpreter::without_stdlib(Default::default()).enter(|vm| { let a: PyObjectRef = vm.ctx.new_int(33_i32).into(); let b: PyObjectRef = vm.ctx.new_int(12_i32).into(); let res = vm._add(&a, &b).unwrap(); let value = int::get_value(&res); assert_eq!(*value, 45_i32.to_bigint().unwrap()); }) } #[test] fn test_multiply_str() { Interpreter::without_stdlib(Default::default()).enter(|vm| { let a = vm.new_pyobj(crate::common::ascii!("Hello ")); let b = vm.new_pyobj(4_i32); let res = vm._mul(&a, &b).unwrap(); let value = res.downcast_ref::<PyStr>().unwrap(); assert_eq!(value.as_str(), "Hello Hello Hello Hello ") }) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/vm/vm_object.rs
crates/vm/src/vm/vm_object.rs
use super::PyMethod; use crate::{ builtins::{PyBaseExceptionRef, PyList, PyStrInterned, pystr::AsPyStr}, function::IntoFuncArgs, object::{AsObject, PyObject, PyObjectRef, PyResult}, stdlib::sys, vm::VirtualMachine, }; /// PyObject support impl VirtualMachine { #[track_caller] #[cold] fn _py_panic_failed(&self, exc: PyBaseExceptionRef, msg: &str) -> ! { #[cfg(not(all( target_arch = "wasm32", not(any(target_os = "emscripten", target_os = "wasi")), )))] { self.print_exception(exc); self.flush_std(); panic!("{msg}") } #[cfg(all( target_arch = "wasm32", feature = "wasmbind", not(any(target_os = "emscripten", target_os = "wasi")), ))] #[cfg(all(target_arch = "wasm32", not(target_os = "wasi"), feature = "wasmbind"))] { use wasm_bindgen::prelude::*; #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console)] fn error(s: &str); } let mut s = String::new(); self.write_exception(&mut s, &exc).unwrap(); error(&s); panic!("{msg}; exception backtrace above") } #[cfg(all( target_arch = "wasm32", not(feature = "wasmbind"), not(any(target_os = "emscripten", target_os = "wasi")), ))] { use crate::convert::ToPyObject; let err_string: String = exc.to_pyobject(self).repr(self).unwrap().to_string(); eprintln!("{err_string}"); panic!("{msg}; python exception not available") } } pub(crate) fn flush_std(&self) { let vm = self; if let Ok(stdout) = sys::get_stdout(vm) { let _ = vm.call_method(&stdout, identifier!(vm, flush).as_str(), ()); } if let Ok(stderr) = sys::get_stderr(vm) { let _ = vm.call_method(&stderr, identifier!(vm, flush).as_str(), ()); } } #[track_caller] pub fn unwrap_pyresult<T>(&self, result: PyResult<T>) -> T { match result { Ok(x) => x, Err(exc) => { self._py_panic_failed(exc, "called `vm.unwrap_pyresult()` on an `Err` value") } } } #[track_caller] pub fn expect_pyresult<T>(&self, result: PyResult<T>, msg: &str) -> T { match result { Ok(x) => x, Err(exc) => self._py_panic_failed(exc, msg), } } /// Test whether a python object is `None`. pub fn is_none(&self, obj: &PyObject) -> bool { obj.is(&self.ctx.none) } pub fn option_if_none(&self, obj: PyObjectRef) -> Option<PyObjectRef> { if self.is_none(&obj) { None } else { Some(obj) } } pub fn unwrap_or_none(&self, obj: Option<PyObjectRef>) -> PyObjectRef { obj.unwrap_or_else(|| self.ctx.none()) } pub fn call_get_descriptor_specific( &self, descr: &PyObject, obj: Option<PyObjectRef>, cls: Option<PyObjectRef>, ) -> Option<PyResult> { let descr_get = descr.class().slots.descr_get.load()?; Some(descr_get(descr.to_owned(), obj, cls, self)) } pub fn call_get_descriptor(&self, descr: &PyObject, obj: PyObjectRef) -> Option<PyResult> { let cls = obj.class().to_owned().into(); self.call_get_descriptor_specific(descr, Some(obj), Some(cls)) } pub fn call_if_get_descriptor(&self, attr: &PyObject, obj: PyObjectRef) -> PyResult { self.call_get_descriptor(attr, obj) .unwrap_or_else(|| Ok(attr.to_owned())) } #[inline] pub fn call_method<T>(&self, obj: &PyObject, method_name: &str, args: T) -> PyResult where T: IntoFuncArgs, { flame_guard!(format!("call_method({:?})", method_name)); let dynamic_name; let name = match self.ctx.interned_str(method_name) { Some(name) => name.as_pystr(&self.ctx), None => { dynamic_name = self.ctx.new_str(method_name); &dynamic_name } }; PyMethod::get(obj.to_owned(), name, self)?.invoke(args, self) } pub fn dir(&self, obj: Option<PyObjectRef>) -> PyResult<PyList> { let seq = match obj { Some(obj) => self .get_special_method(&obj, identifier!(self, __dir__))? .ok_or_else(|| self.new_type_error("object does not provide __dir__"))? .invoke((), self)?, None => self.call_method( self.current_locals()?.as_object(), identifier!(self, keys).as_str(), (), )?, }; let items: Vec<_> = seq.try_to_value(self)?; let lst = PyList::from(items); lst.sort(Default::default(), self)?; Ok(lst) } #[inline] pub(crate) fn get_special_method( &self, obj: &PyObject, method: &'static PyStrInterned, ) -> PyResult<Option<PyMethod>> { PyMethod::get_special::<false>(obj, method, self) } /// NOT PUBLIC API #[doc(hidden)] pub fn call_special_method( &self, obj: &PyObject, method: &'static PyStrInterned, args: impl IntoFuncArgs, ) -> PyResult { self.get_special_method(obj, method)? .ok_or_else(|| self.new_attribute_error(method.as_str().to_owned()))? .invoke(args, self) } /// Same as __builtins__.print in Python. /// A convenience function to provide a simple way to print objects for debug purpose. // NOTE: Keep the interface simple. pub fn print(&self, args: impl IntoFuncArgs) -> PyResult<()> { let ret = self.builtins.get_attr("print", self)?.call(args, self)?; debug_assert!(self.is_none(&ret)); Ok(()) } #[deprecated(note = "in favor of `obj.call(args, vm)`")] pub fn invoke(&self, obj: &impl AsObject, args: impl IntoFuncArgs) -> PyResult { obj.as_object().call(args, self) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/vm/setting.rs
crates/vm/src/vm/setting.rs
#[cfg(feature = "flame-it")] use std::ffi::OsString; /// Path configuration computed at runtime (like PyConfig path outputs) #[derive(Debug, Clone, Default)] pub struct Paths { /// sys.executable pub executable: String, /// sys._base_executable (original interpreter in venv) pub base_executable: String, /// sys.prefix pub prefix: String, /// sys.base_prefix pub base_prefix: String, /// sys.exec_prefix pub exec_prefix: String, /// sys.base_exec_prefix pub base_exec_prefix: String, /// Computed module_search_paths (complete sys.path) pub module_search_paths: Vec<String>, } /// Combined configuration: user settings + computed paths /// CPython directly exposes every fields under both of them. /// We separate them to maintain better ownership discipline. pub struct PyConfig { pub settings: Settings, pub paths: Paths, } impl PyConfig { pub fn new(settings: Settings, paths: Paths) -> Self { Self { settings, paths } } } /// User-configurable settings for the python vm. #[non_exhaustive] pub struct Settings { /// -I pub isolated: bool, // int use_environment /// -Xdev pub dev_mode: bool, /// Not set SIGINT handler(i.e. for embedded mode) pub install_signal_handlers: bool, /// PYTHONHASHSEED=x /// None means use_hash_seed = 0 in CPython pub hash_seed: Option<u32>, /// -X faulthandler, PYTHONFAULTHANDLER pub faulthandler: bool, // int tracemalloc; // int perf_profiling; // int import_time; /// -X no_debug_ranges: disable column info in bytecode pub code_debug_ranges: bool, // int show_ref_count; // int dump_refs; // wchar_t *dump_refs_file; // int malloc_stats; // wchar_t *filesystem_encoding; // wchar_t *filesystem_errors; // wchar_t *pycache_prefix; // int parse_argv; // PyWideStringList orig_argv; /// sys.argv pub argv: Vec<String>, // spell-checker:ignore Xfoo /// -Xfoo[=bar] pub xoptions: Vec<(String, Option<String>)>, // spell-checker:ignore Wfoo /// -Wfoo pub warnoptions: Vec<String>, /// -S pub import_site: bool, /// -b pub bytes_warning: u64, /// -X warn_default_encoding, PYTHONWARNDEFAULTENCODING pub warn_default_encoding: bool, /// -i pub inspect: bool, /// -i, with no script pub interactive: bool, // int optimization_level; // int parser_debug; /// -B pub write_bytecode: bool, /// verbosity level (-v switch) pub verbose: u8, /// -q pub quiet: bool, /// -s pub user_site_directory: bool, // int configure_c_stdio; /// -u, PYTHONUNBUFFERED=x pub buffered_stdio: bool, /// PYTHONIOENCODING - stdio encoding pub stdio_encoding: Option<String>, /// PYTHONIOENCODING - stdio error handler pub stdio_errors: Option<String>, pub utf8_mode: u8, /// --check-hash-based-pycs pub check_hash_pycs_mode: CheckHashPycsMode, // int use_frozen_modules; /// -P pub safe_path: bool, /// -X int_max_str_digits pub int_max_str_digits: i64, // /* --- Path configuration inputs ------------ */ // int pathconfig_warnings; // wchar_t *program_name; /// Environment PYTHONPATH (and RUSTPYTHONPATH) pub path_list: Vec<String>, // wchar_t *home; // wchar_t *platlibdir; /// -d command line switch pub debug: u8, /// -O optimization switch counter pub optimize: u8, /// -E pub ignore_environment: bool, /// false for wasm. Not a command-line option pub allow_external_library: bool, #[cfg(feature = "flame-it")] pub profile_output: Option<OsString>, #[cfg(feature = "flame-it")] pub profile_format: Option<String>, } #[derive(Debug, Default, Copy, Clone, strum_macros::Display, strum_macros::EnumString)] #[strum(serialize_all = "lowercase")] pub enum CheckHashPycsMode { #[default] Default, Always, Never, } impl Settings { pub fn with_path(mut self, path: String) -> Self { self.path_list.push(path); self } } /// Sensible default settings. impl Default for Settings { fn default() -> Self { Self { debug: 0, inspect: false, interactive: false, optimize: 0, install_signal_handlers: true, user_site_directory: true, import_site: true, ignore_environment: false, verbose: 0, quiet: false, write_bytecode: true, safe_path: false, bytes_warning: 0, xoptions: vec![], isolated: false, dev_mode: false, warn_default_encoding: false, warnoptions: vec![], path_list: vec![], argv: vec![], hash_seed: None, faulthandler: false, code_debug_ranges: true, buffered_stdio: true, check_hash_pycs_mode: CheckHashPycsMode::Default, allow_external_library: cfg!(feature = "importlib"), stdio_encoding: None, stdio_errors: None, utf8_mode: 1, int_max_str_digits: 4300, #[cfg(feature = "flame-it")] profile_output: None, #[cfg(feature = "flame-it")] profile_format: None, } } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/vm/context.rs
crates/vm/src/vm/context.rs
use crate::{ PyResult, VirtualMachine, builtins::{ PyByteArray, PyBytes, PyComplex, PyDict, PyDictRef, PyEllipsis, PyFloat, PyFrozenSet, PyInt, PyIntRef, PyList, PyListRef, PyNone, PyNotImplemented, PyStr, PyStrInterned, PyTuple, PyTupleRef, PyType, PyTypeRef, bool_::PyBool, code::{self, PyCode}, descriptor::{ MemberGetter, MemberKind, MemberSetter, MemberSetterFunc, PyDescriptorOwned, PyMemberDef, PyMemberDescriptor, }, getset::PyGetSet, object, pystr, type_::PyAttributes, }, class::StaticType, common::rc::PyRc, exceptions, function::{ HeapMethodDef, IntoPyGetterFunc, IntoPyNativeFn, IntoPySetterFunc, PyMethodDef, PyMethodFlags, }, intern::{InternableString, MaybeInternedString, StringPool}, object::{Py, PyObjectPayload, PyObjectRef, PyPayload, PyRef}, types::{PyTypeFlags, PyTypeSlots, TypeZoo}, }; use malachite_bigint::BigInt; use num_complex::Complex64; use num_traits::ToPrimitive; use rustpython_common::lock::PyRwLock; #[derive(Debug)] pub struct Context { pub true_value: PyRef<PyBool>, pub false_value: PyRef<PyBool>, pub none: PyRef<PyNone>, pub empty_tuple: PyTupleRef, pub empty_frozenset: PyRef<PyFrozenSet>, pub empty_str: &'static PyStrInterned, pub empty_bytes: PyRef<PyBytes>, pub ellipsis: PyRef<PyEllipsis>, pub not_implemented: PyRef<PyNotImplemented>, pub typing_no_default: PyRef<crate::stdlib::typing::NoDefault>, pub types: TypeZoo, pub exceptions: exceptions::ExceptionZoo, pub int_cache_pool: Vec<PyIntRef>, // there should only be exact objects of str in here, no non-str objects and no subclasses pub(crate) string_pool: StringPool, pub(crate) slot_new_wrapper: PyMethodDef, pub names: ConstName, } macro_rules! declare_const_name { ($($name:ident$(: $s:literal)?,)*) => { #[derive(Debug, Clone, Copy)] #[allow(non_snake_case)] pub struct ConstName { $(pub $name: &'static PyStrInterned,)* } impl ConstName { unsafe fn new(pool: &StringPool, typ: &Py<PyType>) -> Self { Self { $($name: unsafe { pool.intern(declare_const_name!(@string $name $($s)?), typ.to_owned()) },)* } } } }; (@string $name:ident) => { stringify!($name) }; (@string $name:ident $string:literal) => { $string }; } declare_const_name! { True, False, None, NotImplemented, Ellipsis, // magic methods __abs__, __abstractmethods__, __add__, __aenter__, __aexit__, __aiter__, __alloc__, __all__, __and__, __anext__, __annotations__, __args__, __await__, __bases__, __bool__, __build_class__, __builtins__, __bytes__, __cached__, __call__, __ceil__, __cformat__, __class__, __class_getitem__, __classcell__, __complex__, __contains__, __copy__, __deepcopy__, __del__, __delattr__, __delete__, __delitem__, __dict__, __dir__, __div__, __divmod__, __doc__, __enter__, __eq__, __exit__, __file__, __float__, __floor__, __floordiv__, __format__, __fspath__, __ge__, __get__, __getattr__, __getattribute__, __getformat__, __getitem__, __getnewargs__, __getstate__, __gt__, __hash__, __iadd__, __iand__, __idiv__, __ifloordiv__, __ilshift__, __imatmul__, __imod__, __import__, __imul__, __index__, __init__, __init_subclass__, __instancecheck__, __int__, __invert__, __ior__, __ipow__, __irshift__, __isub__, __iter__, __itruediv__, __ixor__, __jit__, // RustPython dialect __le__, __len__, __length_hint__, __lshift__, __lt__, __main__, __match_args__, __matmul__, __missing__, __mod__, __module__, __mro_entries__, __mul__, __name__, __ne__, __neg__, __new__, __next__, __objclass__, __or__, __orig_bases__, __orig_class__, __origin__, __parameters__, __pos__, __pow__, __prepare__, __qualname__, __radd__, __rand__, __rdiv__, __rdivmod__, __reduce__, __reduce_ex__, __repr__, __reversed__, __rfloordiv__, __rlshift__, __rmatmul__, __rmod__, __rmul__, __ror__, __round__, __rpow__, __rrshift__, __rshift__, __rsub__, __rtruediv__, __rxor__, __set__, __setattr__, __setitem__, __setstate__, __set_name__, __slots__, __slotnames__, __str__, __sub__, __subclasscheck__, __subclasshook__, __subclasses__, __sizeof__, __truediv__, __trunc__, __type_params__, __typing_subst__, __typing_is_unpacked_typevartuple__, __typing_prepare_subst__, __typing_unpacked_tuple_args__, __xor__, // common names _attributes, _fields, _showwarnmsg, backslashreplace, close, copy, decode, encode, flush, ignore, items, keys, modules, n_fields, n_sequence_fields, n_unnamed_fields, namereplace, replace, strict, surrogateescape, surrogatepass, update, utf_8: "utf-8", values, version, WarningMessage, xmlcharrefreplace, } // Basic objects: impl Context { pub const INT_CACHE_POOL_RANGE: core::ops::RangeInclusive<i32> = (-5)..=256; const INT_CACHE_POOL_MIN: i32 = *Self::INT_CACHE_POOL_RANGE.start(); pub fn genesis() -> &'static PyRc<Self> { rustpython_common::static_cell! { static CONTEXT: PyRc<Context>; } CONTEXT.get_or_init(|| PyRc::new(Self::init_genesis())) } fn init_genesis() -> Self { flame_guard!("init Context"); let types = TypeZoo::init(); let exceptions = exceptions::ExceptionZoo::init(); #[inline] fn create_object<T: PyObjectPayload>(payload: T, cls: &'static Py<PyType>) -> PyRef<T> { PyRef::new_ref(payload, cls.to_owned(), None) } let none = create_object(PyNone, PyNone::static_type()); let ellipsis = create_object(PyEllipsis, PyEllipsis::static_type()); let not_implemented = create_object(PyNotImplemented, PyNotImplemented::static_type()); let typing_no_default = create_object( crate::stdlib::typing::NoDefault, crate::stdlib::typing::NoDefault::static_type(), ); let int_cache_pool = Self::INT_CACHE_POOL_RANGE .map(|v| { PyRef::new_ref( PyInt::from(BigInt::from(v)), types.int_type.to_owned(), None, ) }) .collect(); let true_value = create_object(PyBool(PyInt::from(1)), types.bool_type); let false_value = create_object(PyBool(PyInt::from(0)), types.bool_type); let empty_tuple = create_object( PyTuple::new_unchecked(Vec::new().into_boxed_slice()), types.tuple_type, ); let empty_frozenset = PyRef::new_ref( PyFrozenSet::default(), types.frozenset_type.to_owned(), None, ); let string_pool = StringPool::default(); let names = unsafe { ConstName::new(&string_pool, types.str_type) }; let slot_new_wrapper = PyMethodDef::new_const( names.__new__.as_str(), PyType::__new__, PyMethodFlags::METHOD, None, ); let empty_str = unsafe { string_pool.intern("", types.str_type.to_owned()) }; let empty_bytes = create_object(PyBytes::from(Vec::new()), types.bytes_type); Self { true_value, false_value, none, empty_tuple, empty_frozenset, empty_str, empty_bytes, ellipsis, not_implemented, typing_no_default, types, exceptions, int_cache_pool, string_pool, slot_new_wrapper, names, } } pub fn intern_str<S: InternableString>(&self, s: S) -> &'static PyStrInterned { unsafe { self.string_pool.intern(s, self.types.str_type.to_owned()) } } pub fn interned_str<S: MaybeInternedString + ?Sized>( &self, s: &S, ) -> Option<&'static PyStrInterned> { self.string_pool.interned(s) } #[inline(always)] pub fn none(&self) -> PyObjectRef { self.none.clone().into() } #[inline(always)] pub fn not_implemented(&self) -> PyObjectRef { self.not_implemented.clone().into() } #[inline] pub fn empty_tuple_typed<T>(&self) -> &Py<PyTuple<T>> { let py: &Py<PyTuple> = &self.empty_tuple; unsafe { core::mem::transmute(py) } } // universal pyref constructor pub fn new_pyref<T, P>(&self, value: T) -> PyRef<P> where T: Into<P>, P: PyPayload + core::fmt::Debug, { value.into().into_ref(self) } // shortcuts for common type #[inline] pub fn new_int<T: Into<BigInt> + ToPrimitive>(&self, i: T) -> PyIntRef { if let Some(i) = i.to_i32() && Self::INT_CACHE_POOL_RANGE.contains(&i) { let inner_idx = (i - Self::INT_CACHE_POOL_MIN) as usize; return self.int_cache_pool[inner_idx].clone(); } PyInt::from(i).into_ref(self) } #[inline] pub fn new_bigint(&self, i: &BigInt) -> PyIntRef { if let Some(i) = i.to_i32() && Self::INT_CACHE_POOL_RANGE.contains(&i) { let inner_idx = (i - Self::INT_CACHE_POOL_MIN) as usize; return self.int_cache_pool[inner_idx].clone(); } PyInt::from(i.clone()).into_ref(self) } #[inline] pub fn new_float(&self, value: f64) -> PyRef<PyFloat> { PyFloat::from(value).into_ref(self) } #[inline] pub fn new_complex(&self, value: Complex64) -> PyRef<PyComplex> { PyComplex::from(value).into_ref(self) } #[inline] pub fn new_str(&self, s: impl Into<pystr::PyStr>) -> PyRef<PyStr> { s.into().into_ref(self) } pub fn interned_or_new_str<S, M>(&self, s: S) -> PyRef<PyStr> where S: Into<PyStr> + AsRef<M>, M: MaybeInternedString, { match self.interned_str(s.as_ref()) { Some(s) => s.to_owned(), None => self.new_str(s), } } #[inline] pub fn new_bytes(&self, data: Vec<u8>) -> PyRef<PyBytes> { PyBytes::from(data).into_ref(self) } #[inline] pub fn new_bytearray(&self, data: Vec<u8>) -> PyRef<PyByteArray> { PyByteArray::from(data).into_ref(self) } #[inline(always)] pub fn new_bool(&self, b: bool) -> PyRef<PyBool> { let value = if b { &self.true_value } else { &self.false_value }; value.to_owned() } #[inline(always)] pub fn new_tuple(&self, elements: Vec<PyObjectRef>) -> PyTupleRef { PyTuple::new_ref(elements, self) } #[inline(always)] pub fn new_list(&self, elements: Vec<PyObjectRef>) -> PyListRef { PyList::from(elements).into_ref(self) } #[inline(always)] pub fn new_dict(&self) -> PyDictRef { PyDict::default().into_ref(self) } pub fn new_class( &self, module: Option<&str>, name: &str, base: PyTypeRef, slots: PyTypeSlots, ) -> PyTypeRef { let mut attrs = PyAttributes::default(); if let Some(module) = module { attrs.insert(identifier!(self, __module__), self.new_str(module).into()); }; PyType::new_heap( name, vec![base], attrs, slots, self.types.type_type.to_owned(), self, ) .unwrap() } pub fn new_exception_type( &self, module: &str, name: &str, bases: Option<Vec<PyTypeRef>>, ) -> PyTypeRef { let bases = if let Some(bases) = bases { bases } else { vec![self.exceptions.exception_type.to_owned()] }; let mut attrs = PyAttributes::default(); attrs.insert(identifier!(self, __module__), self.new_str(module).into()); let interned_name = self.intern_str(name); let slots = PyTypeSlots { name: interned_name.as_str(), basicsize: 0, flags: PyTypeFlags::heap_type_flags() | PyTypeFlags::HAS_DICT, ..PyTypeSlots::default() }; PyType::new_heap( name, bases, attrs, slots, self.types.type_type.to_owned(), self, ) .unwrap() } pub fn new_method_def<F, FKind>( &self, name: &'static str, f: F, flags: PyMethodFlags, doc: Option<&'static str>, ) -> PyRef<HeapMethodDef> where F: IntoPyNativeFn<FKind>, { let def = PyMethodDef { name, func: Box::leak(Box::new(f.into_func())), flags, doc, }; let payload = HeapMethodDef::new(def); PyRef::new_ref(payload, self.types.method_def.to_owned(), None) } #[inline] pub fn new_member( &self, name: &str, member_kind: MemberKind, getter: fn(&VirtualMachine, PyObjectRef) -> PyResult, setter: MemberSetterFunc, class: &'static Py<PyType>, ) -> PyRef<PyMemberDescriptor> { let member_def = PyMemberDef { name: name.to_owned(), kind: member_kind, getter: MemberGetter::Getter(getter), setter: MemberSetter::Setter(setter), doc: None, }; let member_descriptor = PyMemberDescriptor { common: PyDescriptorOwned { typ: class.to_owned(), name: self.intern_str(name), qualname: PyRwLock::new(None), }, member: member_def, }; member_descriptor.into_ref(self) } pub fn new_readonly_getset<F, T>( &self, name: impl Into<String>, class: &'static Py<PyType>, f: F, ) -> PyRef<PyGetSet> where F: IntoPyGetterFunc<T>, { let name = name.into(); let getset = PyGetSet::new(name, class).with_get(f); PyRef::new_ref(getset, self.types.getset_type.to_owned(), None) } pub fn new_static_getset<G, S, T, U>( &self, name: impl Into<String>, class: &'static Py<PyType>, g: G, s: S, ) -> PyRef<PyGetSet> where G: IntoPyGetterFunc<T>, S: IntoPySetterFunc<U>, { let name = name.into(); let getset = PyGetSet::new(name, class).with_get(g).with_set(s); PyRef::new_ref(getset, self.types.getset_type.to_owned(), None) } /// Creates a new `PyGetSet` with a heap type. /// /// # Safety /// In practice, this constructor is safe because a getset is always owned by its `class` type. /// However, it can be broken if used unconventionally. pub unsafe fn new_getset<G, S, T, U>( &self, name: impl Into<String>, class: &Py<PyType>, g: G, s: S, ) -> PyRef<PyGetSet> where G: IntoPyGetterFunc<T>, S: IntoPySetterFunc<U>, { let class = unsafe { &*(class as *const _) }; self.new_static_getset(name, class, g, s) } pub fn new_base_object(&self, class: PyTypeRef, dict: Option<PyDictRef>) -> PyObjectRef { debug_assert_eq!( class.slots.flags.contains(PyTypeFlags::HAS_DICT), dict.is_some() ); PyRef::new_ref(object::PyBaseObject, class, dict).into() } pub fn new_code(&self, code: impl code::IntoCodeObject) -> PyRef<PyCode> { let code = code.into_code_object(self); PyRef::new_ref(PyCode { code }, self.types.code_type.to_owned(), None) } } impl AsRef<Self> for Context { fn as_ref(&self) -> &Self { self } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/vm/vm_ops.rs
crates/vm/src/vm/vm_ops.rs
use super::VirtualMachine; use crate::stdlib::warnings; use crate::{ PyRef, builtins::{PyInt, PyStr, PyStrRef, PyUtf8Str}, object::{AsObject, PyObject, PyObjectRef, PyResult}, protocol::{PyNumberBinaryOp, PyNumberTernaryOp}, types::PyComparisonOp, }; use num_traits::ToPrimitive; macro_rules! binary_func { ($fn:ident, $op_slot:ident, $op:expr) => { pub fn $fn(&self, a: &PyObject, b: &PyObject) -> PyResult { self.binary_op(a, b, PyNumberBinaryOp::$op_slot, $op) } }; } macro_rules! ternary_func { ($fn:ident, $op_slot:ident, $op:expr) => { pub fn $fn(&self, a: &PyObject, b: &PyObject, c: &PyObject) -> PyResult { self.ternary_op(a, b, c, PyNumberTernaryOp::$op_slot, $op) } }; } macro_rules! inplace_binary_func { ($fn:ident, $iop_slot:ident, $op_slot:ident, $op:expr) => { pub fn $fn(&self, a: &PyObject, b: &PyObject) -> PyResult { self.binary_iop( a, b, PyNumberBinaryOp::$iop_slot, PyNumberBinaryOp::$op_slot, $op, ) } }; } macro_rules! inplace_ternary_func { ($fn:ident, $iop_slot:ident, $op_slot:ident, $op:expr) => { pub fn $fn(&self, a: &PyObject, b: &PyObject, c: &PyObject) -> PyResult { self.ternary_iop( a, b, c, PyNumberTernaryOp::$iop_slot, PyNumberTernaryOp::$op_slot, $op, ) } }; } /// Collection of operators impl VirtualMachine { #[inline] pub fn bool_eq(&self, a: &PyObject, b: &PyObject) -> PyResult<bool> { a.rich_compare_bool(b, PyComparisonOp::Eq, self) } pub fn identical_or_equal(&self, a: &PyObject, b: &PyObject) -> PyResult<bool> { if a.is(b) { Ok(true) } else { self.bool_eq(a, b) } } pub fn bool_seq_lt(&self, a: &PyObject, b: &PyObject) -> PyResult<Option<bool>> { let value = if a.rich_compare_bool(b, PyComparisonOp::Lt, self)? { Some(true) } else if !self.bool_eq(a, b)? { Some(false) } else { None }; Ok(value) } pub fn bool_seq_gt(&self, a: &PyObject, b: &PyObject) -> PyResult<Option<bool>> { let value = if a.rich_compare_bool(b, PyComparisonOp::Gt, self)? { Some(true) } else if !self.bool_eq(a, b)? { Some(false) } else { None }; Ok(value) } pub fn length_hint_opt(&self, iter: PyObjectRef) -> PyResult<Option<usize>> { match iter.length(self) { Ok(len) => return Ok(Some(len)), Err(e) => { if !e.fast_isinstance(self.ctx.exceptions.type_error) { return Err(e); } } } let hint = match self.get_method(iter, identifier!(self, __length_hint__)) { Some(hint) => hint?, None => return Ok(None), }; let result = match hint.call((), self) { Ok(res) => { if res.is(&self.ctx.not_implemented) { return Ok(None); } res } Err(e) => { return if e.fast_isinstance(self.ctx.exceptions.type_error) { Ok(None) } else { Err(e) }; } }; let hint = result .downcast_ref::<PyInt>() .ok_or_else(|| { self.new_type_error(format!( "'{}' object cannot be interpreted as an integer", result.class().name() )) })? .try_to_primitive::<isize>(self)?; if hint.is_negative() { Err(self.new_value_error("__length_hint__() should return >= 0")) } else { Ok(Some(hint as usize)) } } /// Checks that the multiplication is able to be performed. On Ok returns the /// index as a usize for sequences to be able to use immediately. pub fn check_repeat_or_overflow_error(&self, length: usize, n: isize) -> PyResult<usize> { if n <= 0 { Ok(0) } else { let n = n as usize; if length > crate::stdlib::sys::MAXSIZE as usize / n { Err(self.new_overflow_error("repeated value are too long")) } else { Ok(n) } } } /// Calling scheme used for binary operations: /// /// Order operations are tried until either a valid result or error: /// `b.rop(b,a)[*], a.op(a,b), b.rop(b,a)` /// /// `[*]` - only when Py_TYPE(a) != Py_TYPE(b) && Py_TYPE(b) is a subclass of Py_TYPE(a) pub fn binary_op1(&self, a: &PyObject, b: &PyObject, op_slot: PyNumberBinaryOp) -> PyResult { let class_a = a.class(); let class_b = b.class(); // Number slots are inherited, direct access is O(1) let slot_a = class_a.slots.as_number.left_binary_op(op_slot); let mut slot_b = None; if !class_a.is(class_b) { let slot_bb = class_b.slots.as_number.right_binary_op(op_slot); if slot_bb.map(|x| x as usize) != slot_a.map(|x| x as usize) { slot_b = slot_bb; } } if let Some(slot_a) = slot_a { if let Some(slot_bb) = slot_b && class_b.fast_issubclass(class_a) { let ret = slot_bb(a, b, self)?; if !ret.is(&self.ctx.not_implemented) { return Ok(ret); } slot_b = None; } let ret = slot_a(a, b, self)?; if !ret.is(&self.ctx.not_implemented) { return Ok(ret); } } if let Some(slot_b) = slot_b { let ret = slot_b(a, b, self)?; if !ret.is(&self.ctx.not_implemented) { return Ok(ret); } } Ok(self.ctx.not_implemented()) } pub fn binary_op( &self, a: &PyObject, b: &PyObject, op_slot: PyNumberBinaryOp, op: &str, ) -> PyResult { let result = self.binary_op1(a, b, op_slot)?; if !result.is(&self.ctx.not_implemented) { return Ok(result); } Err(self.new_unsupported_bin_op_error(a, b, op)) } /// Binary in-place operators /// /// The in-place operators are defined to fall back to the 'normal', /// non in-place operations, if the in-place methods are not in place. /// /// - If the left hand object has the appropriate struct members, and /// they are filled, call the appropriate function and return the /// result. No coercion is done on the arguments; the left-hand object /// is the one the operation is performed on, and it's up to the /// function to deal with the right-hand object. /// /// - Otherwise, in-place modification is not supported. Handle it exactly as /// a non in-place operation of the same kind. fn binary_iop1( &self, a: &PyObject, b: &PyObject, iop_slot: PyNumberBinaryOp, op_slot: PyNumberBinaryOp, ) -> PyResult { if let Some(slot) = a.class().slots.as_number.left_binary_op(iop_slot) { let x = slot(a, b, self)?; if !x.is(&self.ctx.not_implemented) { return Ok(x); } } self.binary_op1(a, b, op_slot) } fn binary_iop( &self, a: &PyObject, b: &PyObject, iop_slot: PyNumberBinaryOp, op_slot: PyNumberBinaryOp, op: &str, ) -> PyResult { let result = self.binary_iop1(a, b, iop_slot, op_slot)?; if !result.is(&self.ctx.not_implemented) { return Ok(result); } Err(self.new_unsupported_bin_op_error(a, b, op)) } fn ternary_op( &self, a: &PyObject, b: &PyObject, c: &PyObject, op_slot: PyNumberTernaryOp, op_str: &str, ) -> PyResult { let class_a = a.class(); let class_b = b.class(); let class_c = c.class(); // Number slots are inherited, direct access is O(1) let slot_a = class_a.slots.as_number.left_ternary_op(op_slot); let mut slot_b = None; if !class_a.is(class_b) { let slot_bb = class_b.slots.as_number.right_ternary_op(op_slot); if slot_bb.map(|x| x as usize) != slot_a.map(|x| x as usize) { slot_b = slot_bb; } } if let Some(slot_a) = slot_a { if let Some(slot_bb) = slot_b && class_b.fast_issubclass(class_a) { let ret = slot_bb(a, b, c, self)?; if !ret.is(&self.ctx.not_implemented) { return Ok(ret); } slot_b = None; } let ret = slot_a(a, b, c, self)?; if !ret.is(&self.ctx.not_implemented) { return Ok(ret); } } if let Some(slot_b) = slot_b { let ret = slot_b(a, b, c, self)?; if !ret.is(&self.ctx.not_implemented) { return Ok(ret); } } if let Some(slot_c) = class_c.slots.as_number.left_ternary_op(op_slot) && slot_a.is_some_and(|slot_a| !core::ptr::fn_addr_eq(slot_a, slot_c)) && slot_b.is_some_and(|slot_b| !core::ptr::fn_addr_eq(slot_b, slot_c)) { let ret = slot_c(a, b, c, self)?; if !ret.is(&self.ctx.not_implemented) { return Ok(ret); } } Err(if self.is_none(c) { self.new_type_error(format!( "unsupported operand type(s) for {}: \ '{}' and '{}'", op_str, a.class(), b.class() )) } else { self.new_type_error(format!( "unsupported operand type(s) for {}: \ '{}' and '{}', '{}'", op_str, a.class(), b.class(), c.class() )) }) } fn ternary_iop( &self, a: &PyObject, b: &PyObject, c: &PyObject, iop_slot: PyNumberTernaryOp, op_slot: PyNumberTernaryOp, op_str: &str, ) -> PyResult { if let Some(slot) = a.class().slots.as_number.left_ternary_op(iop_slot) { let x = slot(a, b, c, self)?; if !x.is(&self.ctx.not_implemented) { return Ok(x); } } self.ternary_op(a, b, c, op_slot, op_str) } binary_func!(_sub, Subtract, "-"); binary_func!(_mod, Remainder, "%"); binary_func!(_divmod, Divmod, "divmod"); binary_func!(_lshift, Lshift, "<<"); binary_func!(_rshift, Rshift, ">>"); binary_func!(_and, And, "&"); binary_func!(_xor, Xor, "^"); binary_func!(_or, Or, "|"); binary_func!(_floordiv, FloorDivide, "//"); binary_func!(_truediv, TrueDivide, "/"); binary_func!(_matmul, MatrixMultiply, "@"); inplace_binary_func!(_isub, InplaceSubtract, Subtract, "-="); inplace_binary_func!(_imod, InplaceRemainder, Remainder, "%="); inplace_binary_func!(_ilshift, InplaceLshift, Lshift, "<<="); inplace_binary_func!(_irshift, InplaceRshift, Rshift, ">>="); inplace_binary_func!(_iand, InplaceAnd, And, "&="); inplace_binary_func!(_ixor, InplaceXor, Xor, "^="); inplace_binary_func!(_ior, InplaceOr, Or, "|="); inplace_binary_func!(_ifloordiv, InplaceFloorDivide, FloorDivide, "//="); inplace_binary_func!(_itruediv, InplaceTrueDivide, TrueDivide, "/="); inplace_binary_func!(_imatmul, InplaceMatrixMultiply, MatrixMultiply, "@="); ternary_func!(_pow, Power, "** or pow()"); inplace_ternary_func!(_ipow, InplacePower, Power, "**="); pub fn _add(&self, a: &PyObject, b: &PyObject) -> PyResult { let result = self.binary_op1(a, b, PyNumberBinaryOp::Add)?; if !result.is(&self.ctx.not_implemented) { return Ok(result); } if let Ok(seq_a) = a.try_sequence(self) { let result = seq_a.concat(b, self)?; if !result.is(&self.ctx.not_implemented) { return Ok(result); } } Err(self.new_unsupported_bin_op_error(a, b, "+")) } pub fn _iadd(&self, a: &PyObject, b: &PyObject) -> PyResult { let result = self.binary_iop1(a, b, PyNumberBinaryOp::InplaceAdd, PyNumberBinaryOp::Add)?; if !result.is(&self.ctx.not_implemented) { return Ok(result); } if let Ok(seq_a) = a.try_sequence(self) { let result = seq_a.inplace_concat(b, self)?; if !result.is(&self.ctx.not_implemented) { return Ok(result); } } Err(self.new_unsupported_bin_op_error(a, b, "+=")) } pub fn _mul(&self, a: &PyObject, b: &PyObject) -> PyResult { let result = self.binary_op1(a, b, PyNumberBinaryOp::Multiply)?; if !result.is(&self.ctx.not_implemented) { return Ok(result); } if let Ok(seq_a) = a.try_sequence(self) { let n = b .try_index(self)? .as_bigint() .to_isize() .ok_or_else(|| self.new_overflow_error("repeated bytes are too long"))?; return seq_a.repeat(n, self); } else if let Ok(seq_b) = b.try_sequence(self) { let n = a .try_index(self)? .as_bigint() .to_isize() .ok_or_else(|| self.new_overflow_error("repeated bytes are too long"))?; return seq_b.repeat(n, self); } Err(self.new_unsupported_bin_op_error(a, b, "*")) } pub fn _imul(&self, a: &PyObject, b: &PyObject) -> PyResult { let result = self.binary_iop1( a, b, PyNumberBinaryOp::InplaceMultiply, PyNumberBinaryOp::Multiply, )?; if !result.is(&self.ctx.not_implemented) { return Ok(result); } if let Ok(seq_a) = a.try_sequence(self) { let n = b .try_index(self)? .as_bigint() .to_isize() .ok_or_else(|| self.new_overflow_error("repeated bytes are too long"))?; return seq_a.inplace_repeat(n, self); } else if let Ok(seq_b) = b.try_sequence(self) { let n = a .try_index(self)? .as_bigint() .to_isize() .ok_or_else(|| self.new_overflow_error("repeated bytes are too long"))?; /* Note that the right hand operand should not be * mutated in this case so inplace_repeat is not * used. */ return seq_b.repeat(n, self); } Err(self.new_unsupported_bin_op_error(a, b, "*=")) } pub fn _abs(&self, a: &PyObject) -> PyResult<PyObjectRef> { self.get_special_method(a, identifier!(self, __abs__))? .ok_or_else(|| self.new_unsupported_unary_error(a, "abs()"))? .invoke((), self) } pub fn _pos(&self, a: &PyObject) -> PyResult { self.get_special_method(a, identifier!(self, __pos__))? .ok_or_else(|| self.new_unsupported_unary_error(a, "unary +"))? .invoke((), self) } pub fn _neg(&self, a: &PyObject) -> PyResult { self.get_special_method(a, identifier!(self, __neg__))? .ok_or_else(|| self.new_unsupported_unary_error(a, "unary -"))? .invoke((), self) } pub fn _invert(&self, a: &PyObject) -> PyResult { const STR: &str = "Bitwise inversion '~' on bool is deprecated and will be removed in Python 3.16. \ This returns the bitwise inversion of the underlying int object and is usually not what you expect from negating a bool. \ Use the 'not' operator for boolean negation or ~int(x) if you really want the bitwise inversion of the underlying int."; if a.fast_isinstance(self.ctx.types.bool_type) { warnings::warn( self.ctx.exceptions.deprecation_warning, STR.to_owned(), 1, self, )?; } self.get_special_method(a, identifier!(self, __invert__))? .ok_or_else(|| self.new_unsupported_unary_error(a, "unary ~"))? .invoke((), self) } // PyObject_Format pub fn format(&self, obj: &PyObject, format_spec: PyStrRef) -> PyResult<PyStrRef> { if format_spec.is_empty() { let obj = match obj.to_owned().downcast_exact::<PyStr>(self) { Ok(s) => return Ok(s.into_pyref()), Err(obj) => obj, }; if obj.class().is(self.ctx.types.int_type) { return obj.str(self); } } let bound_format = self .get_special_method(obj, identifier!(self, __format__))? .ok_or_else(|| { self.new_type_error(format!( "Type {} doesn't define __format__", obj.class().name() )) })?; let formatted = bound_format.invoke((format_spec,), self)?; formatted.downcast().map_err(|result| { self.new_type_error(format!( "__format__ must return a str, not {}", &result.class().name() )) }) } pub fn format_utf8(&self, obj: &PyObject, format_spec: PyStrRef) -> PyResult<PyRef<PyUtf8Str>> { self.format(obj, format_spec)?.try_into_utf8(self) } pub fn _contains(&self, haystack: &PyObject, needle: &PyObject) -> PyResult<bool> { let seq = haystack.sequence_unchecked(); seq.contains(needle, self) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/vm/thread.rs
crates/vm/src/vm/thread.rs
use crate::{AsObject, PyObject, PyObjectRef, VirtualMachine}; use core::{ cell::{Cell, RefCell}, ptr::NonNull, }; use itertools::Itertools; use std::thread_local; thread_local! { pub(super) static VM_STACK: RefCell<Vec<NonNull<VirtualMachine>>> = Vec::with_capacity(1).into(); pub(crate) static COROUTINE_ORIGIN_TRACKING_DEPTH: Cell<u32> = const { Cell::new(0) }; pub(crate) static ASYNC_GEN_FINALIZER: RefCell<Option<PyObjectRef>> = const { RefCell::new(None) }; pub(crate) static ASYNC_GEN_FIRSTITER: RefCell<Option<PyObjectRef>> = const { RefCell::new(None) }; } scoped_tls::scoped_thread_local!(static VM_CURRENT: VirtualMachine); pub fn with_current_vm<R>(f: impl FnOnce(&VirtualMachine) -> R) -> R { if !VM_CURRENT.is_set() { panic!("call with_current_vm() but VM_CURRENT is null"); } VM_CURRENT.with(f) } pub fn enter_vm<R>(vm: &VirtualMachine, f: impl FnOnce() -> R) -> R { VM_STACK.with(|vms| { vms.borrow_mut().push(vm.into()); scopeguard::defer! { vms.borrow_mut().pop(); } VM_CURRENT.set(vm, f) }) } pub fn with_vm<F, R>(obj: &PyObject, f: F) -> Option<R> where F: Fn(&VirtualMachine) -> R, { let vm_owns_obj = |interp: NonNull<VirtualMachine>| { // SAFETY: all references in VM_STACK should be valid let vm = unsafe { interp.as_ref() }; obj.fast_isinstance(vm.ctx.types.object_type) }; VM_STACK.with(|vms| { let interp = match vms.borrow().iter().copied().exactly_one() { Ok(x) => { debug_assert!(vm_owns_obj(x)); x } Err(mut others) => others.find(|x| vm_owns_obj(*x))?, }; // SAFETY: all references in VM_STACK should be valid, and should not be changed or moved // at least until this function returns and the stack unwinds to an enter_vm() call let vm = unsafe { interp.as_ref() }; Some(VM_CURRENT.set(vm, || f(vm))) }) } #[must_use = "ThreadedVirtualMachine does nothing unless you move it to another thread and call .run()"] #[cfg(feature = "threading")] pub struct ThreadedVirtualMachine { pub(super) vm: VirtualMachine, } #[cfg(feature = "threading")] impl ThreadedVirtualMachine { /// Create a `FnOnce()` that can easily be passed to a function like [`std::thread::Builder::spawn`] /// /// # Note /// /// If you return a `PyObjectRef` (or a type that contains one) from `F`, and don't `join()` /// on the thread this `FnOnce` runs in, there is a possibility that that thread will panic /// as `PyObjectRef`'s `Drop` implementation tries to run the `__del__` destructor of a /// Python object but finds that it's not in the context of any vm. pub fn make_spawn_func<F, R>(self, f: F) -> impl FnOnce() -> R where F: FnOnce(&VirtualMachine) -> R, { move || self.run(f) } /// Run a function in this thread context /// /// # Note /// /// If you return a `PyObjectRef` (or a type that contains one) from `F`, and don't return the object /// to the parent thread and then `join()` on the `JoinHandle` (or similar), there is a possibility that /// the current thread will panic as `PyObjectRef`'s `Drop` implementation tries to run the `__del__` /// destructor of a python object but finds that it's not in the context of any vm. pub fn run<F, R>(&self, f: F) -> R where F: FnOnce(&VirtualMachine) -> R, { let vm = &self.vm; enter_vm(vm, || f(vm)) } } impl VirtualMachine { /// Start a new thread with access to the same interpreter. /// /// # Note /// /// If you return a `PyObjectRef` (or a type that contains one) from `F`, and don't `join()` /// on the thread, there is a possibility that that thread will panic as `PyObjectRef`'s `Drop` /// implementation tries to run the `__del__` destructor of a python object but finds that it's /// not in the context of any vm. #[cfg(feature = "threading")] pub fn start_thread<F, R>(&self, f: F) -> std::thread::JoinHandle<R> where F: FnOnce(&Self) -> R, F: Send + 'static, R: Send + 'static, { let func = self.new_thread().make_spawn_func(f); std::thread::spawn(func) } /// Create a new VM thread that can be passed to a function like [`std::thread::spawn`] /// to use the same interpreter on a different thread. Note that if you just want to /// use this with `thread::spawn`, you can use /// [`vm.start_thread()`](`VirtualMachine::start_thread`) as a convenience. /// /// # Usage /// /// ``` /// # rustpython_vm::Interpreter::without_stdlib(Default::default()).enter(|vm| { /// use std::thread::Builder; /// let handle = Builder::new() /// .name("my thread :)".into()) /// .spawn(vm.new_thread().make_spawn_func(|vm| vm.ctx.none())) /// .expect("couldn't spawn thread"); /// let returned_obj = handle.join().expect("thread panicked"); /// assert!(vm.is_none(&returned_obj)); /// # }) /// ``` /// /// Note: this function is safe, but running the returned ThreadedVirtualMachine in the same /// thread context (i.e. with the same thread-local storage) doesn't have any /// specific guaranteed behavior. #[cfg(feature = "threading")] pub fn new_thread(&self) -> ThreadedVirtualMachine { let vm = Self { builtins: self.builtins.clone(), sys_module: self.sys_module.clone(), ctx: self.ctx.clone(), frames: RefCell::new(vec![]), wasm_id: self.wasm_id.clone(), exceptions: RefCell::default(), import_func: self.import_func.clone(), profile_func: RefCell::new(self.ctx.none()), trace_func: RefCell::new(self.ctx.none()), use_tracing: Cell::new(false), recursion_limit: self.recursion_limit.clone(), signal_handlers: None, signal_rx: None, repr_guards: RefCell::default(), state: self.state.clone(), initialized: self.initialized, recursion_depth: Cell::new(0), }; ThreadedVirtualMachine { vm } } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/vm/vm_new.rs
crates/vm/src/vm/vm_new.rs
use crate::{ AsObject, Py, PyObject, PyObjectRef, PyRef, PyResult, builtins::{ PyBaseException, PyBaseExceptionRef, PyBytesRef, PyDictRef, PyModule, PyOSError, PyStrRef, PyType, PyTypeRef, builtin_func::PyNativeFunction, descriptor::PyMethodDescriptor, tuple::{IntoPyTuple, PyTupleRef}, }, convert::{ToPyException, ToPyObject}, exceptions::OSErrorBuilder, function::{IntoPyNativeFn, PyMethodFlags}, scope::Scope, vm::VirtualMachine, }; use rustpython_compiler_core::SourceLocation; macro_rules! define_exception_fn { ( fn $fn_name:ident, $attr:ident, $python_repr:ident ) => { #[doc = concat!( "Create a new python ", stringify!($python_repr), " object.\nUseful for raising errors from python functions implemented in rust." )] pub fn $fn_name(&self, msg: impl Into<String>) -> PyBaseExceptionRef { let err = self.ctx.exceptions.$attr.to_owned(); self.new_exception_msg(err, msg.into()) } }; } /// Collection of object creation helpers impl VirtualMachine { /// Create a new python object pub fn new_pyobj(&self, value: impl ToPyObject) -> PyObjectRef { value.to_pyobject(self) } pub fn new_tuple(&self, value: impl IntoPyTuple) -> PyTupleRef { value.into_pytuple(self) } pub fn new_module( &self, name: &str, dict: PyDictRef, doc: Option<PyStrRef>, ) -> PyRef<PyModule> { let module = PyRef::new_ref( PyModule::new(), self.ctx.types.module_type.to_owned(), Some(dict), ); module.init_dict(self.ctx.intern_str(name), doc, self); module } pub fn new_scope_with_builtins(&self) -> Scope { Scope::with_builtins(None, self.ctx.new_dict(), self) } pub fn new_scope_with_main(&self) -> PyResult<Scope> { let scope = self.new_scope_with_builtins(); let main_module = self.new_module("__main__", scope.globals.clone(), None); main_module .dict() .set_item("__annotations__", self.ctx.new_dict().into(), self) .expect("Failed to initialize __main__.__annotations__"); self.sys_module.get_attr("modules", self)?.set_item( "__main__", main_module.into(), self, )?; Ok(scope) } pub fn new_function<F, FKind>(&self, name: &'static str, f: F) -> PyRef<PyNativeFunction> where F: IntoPyNativeFn<FKind>, { let def = self .ctx .new_method_def(name, f, PyMethodFlags::empty(), None); def.build_function(self) } pub fn new_method<F, FKind>( &self, name: &'static str, class: &'static Py<PyType>, f: F, ) -> PyRef<PyMethodDescriptor> where F: IntoPyNativeFn<FKind>, { let def = self .ctx .new_method_def(name, f, PyMethodFlags::METHOD, None); def.build_method(class, self) } /// Instantiate an exception with arguments. /// This function should only be used with builtin exception types; if a user-defined exception /// type is passed in, it may not be fully initialized; try using /// [`vm.invoke_exception()`][Self::invoke_exception] or /// [`exceptions::ExceptionCtor`][crate::exceptions::ExceptionCtor] instead. pub fn new_exception(&self, exc_type: PyTypeRef, args: Vec<PyObjectRef>) -> PyBaseExceptionRef { debug_assert_eq!( exc_type.slots.basicsize, core::mem::size_of::<PyBaseException>(), "vm.new_exception() is only for exception types without additional payload. The given type '{}' is not allowed.", exc_type.class().name() ); PyRef::new_ref( PyBaseException::new(args, self), exc_type, Some(self.ctx.new_dict()), ) } pub fn new_os_error(&self, msg: impl ToPyObject) -> PyRef<PyBaseException> { self.new_os_subtype_error(self.ctx.exceptions.os_error.to_owned(), None, msg) .upcast() } pub fn new_os_subtype_error( &self, exc_type: PyTypeRef, errno: Option<i32>, msg: impl ToPyObject, ) -> PyRef<PyOSError> { debug_assert_eq!(exc_type.slots.basicsize, core::mem::size_of::<PyOSError>()); OSErrorBuilder::with_subtype(exc_type, errno, msg, self).build(self) } /// Instantiate an exception with no arguments. /// This function should only be used with builtin exception types; if a user-defined exception /// type is passed in, it may not be fully initialized; try using /// [`vm.invoke_exception()`][Self::invoke_exception] or /// [`exceptions::ExceptionCtor`][crate::exceptions::ExceptionCtor] instead. pub fn new_exception_empty(&self, exc_type: PyTypeRef) -> PyBaseExceptionRef { self.new_exception(exc_type, vec![]) } /// Instantiate an exception with `msg` as the only argument. /// This function should only be used with builtin exception types; if a user-defined exception /// type is passed in, it may not be fully initialized; try using /// [`vm.invoke_exception()`][Self::invoke_exception] or /// [`exceptions::ExceptionCtor`][crate::exceptions::ExceptionCtor] instead. pub fn new_exception_msg(&self, exc_type: PyTypeRef, msg: String) -> PyBaseExceptionRef { self.new_exception(exc_type, vec![self.ctx.new_str(msg).into()]) } /// Instantiate an exception with `msg` as the only argument and `dict` for object /// This function should only be used with builtin exception types; if a user-defined exception /// type is passed in, it may not be fully initialized; try using /// [`vm.invoke_exception()`][Self::invoke_exception] or /// [`exceptions::ExceptionCtor`][crate::exceptions::ExceptionCtor] instead. pub fn new_exception_msg_dict( &self, exc_type: PyTypeRef, msg: String, dict: PyDictRef, ) -> PyBaseExceptionRef { PyRef::new_ref( // TODO: this constructor might be invalid, because multiple // exception (even builtin ones) are using custom constructors, // see `OSError` as an example: PyBaseException::new(vec![self.ctx.new_str(msg).into()], self), exc_type, Some(dict), ) } pub fn new_no_attribute_error(&self, obj: PyObjectRef, name: PyStrRef) -> PyBaseExceptionRef { let msg = format!( "'{}' object has no attribute '{}'", obj.class().name(), name ); let attribute_error = self.new_attribute_error(msg); // Use existing set_attribute_error_context function self.set_attribute_error_context(&attribute_error, obj, name); attribute_error } pub fn new_name_error(&self, msg: impl Into<String>, name: PyStrRef) -> PyBaseExceptionRef { let name_error_type = self.ctx.exceptions.name_error.to_owned(); let name_error = self.new_exception_msg(name_error_type, msg.into()); name_error.as_object().set_attr("name", name, self).unwrap(); name_error } pub fn new_unsupported_unary_error(&self, a: &PyObject, op: &str) -> PyBaseExceptionRef { self.new_type_error(format!( "bad operand type for {}: '{}'", op, a.class().name() )) } pub fn new_unsupported_bin_op_error( &self, a: &PyObject, b: &PyObject, op: &str, ) -> PyBaseExceptionRef { self.new_type_error(format!( "'{}' not supported between instances of '{}' and '{}'", op, a.class().name(), b.class().name() )) } pub fn new_unsupported_ternary_op_error( &self, a: &PyObject, b: &PyObject, c: &PyObject, op: &str, ) -> PyBaseExceptionRef { self.new_type_error(format!( "Unsupported operand types for '{}': '{}', '{}', and '{}'", op, a.class().name(), b.class().name(), c.class().name() )) } /// Create a new OSError from the last OS error. /// /// On windows, windows-sys errors are expected to be handled by this function. /// This is identical to `new_last_errno_error` on non-Windows platforms. pub fn new_last_os_error(&self) -> PyBaseExceptionRef { let err = std::io::Error::last_os_error(); err.to_pyexception(self) } /// Create a new OSError from the last POSIX errno. /// /// On windows, CRT errno are expected to be handled by this function. /// This is identical to `new_last_os_error` on non-Windows platforms. pub fn new_last_errno_error(&self) -> PyBaseExceptionRef { let err = crate::common::os::errno_io_error(); err.to_pyexception(self) } pub fn new_errno_error(&self, errno: i32, msg: impl ToPyObject) -> PyRef<PyOSError> { let exc_type = crate::exceptions::errno_to_exc_type(errno, self) .unwrap_or(self.ctx.exceptions.os_error); self.new_os_subtype_error(exc_type.to_owned(), Some(errno), msg) } pub fn new_unicode_decode_error_real( &self, encoding: PyStrRef, object: PyBytesRef, start: usize, end: usize, reason: PyStrRef, ) -> PyBaseExceptionRef { let start = self.ctx.new_int(start); let end = self.ctx.new_int(end); let exc = self.new_exception( self.ctx.exceptions.unicode_decode_error.to_owned(), vec![ encoding.clone().into(), object.clone().into(), start.clone().into(), end.clone().into(), reason.clone().into(), ], ); exc.as_object() .set_attr("encoding", encoding, self) .unwrap(); exc.as_object().set_attr("object", object, self).unwrap(); exc.as_object().set_attr("start", start, self).unwrap(); exc.as_object().set_attr("end", end, self).unwrap(); exc.as_object().set_attr("reason", reason, self).unwrap(); exc } pub fn new_unicode_encode_error_real( &self, encoding: PyStrRef, object: PyStrRef, start: usize, end: usize, reason: PyStrRef, ) -> PyBaseExceptionRef { let start = self.ctx.new_int(start); let end = self.ctx.new_int(end); let exc = self.new_exception( self.ctx.exceptions.unicode_encode_error.to_owned(), vec![ encoding.clone().into(), object.clone().into(), start.clone().into(), end.clone().into(), reason.clone().into(), ], ); exc.as_object() .set_attr("encoding", encoding, self) .unwrap(); exc.as_object().set_attr("object", object, self).unwrap(); exc.as_object().set_attr("start", start, self).unwrap(); exc.as_object().set_attr("end", end, self).unwrap(); exc.as_object().set_attr("reason", reason, self).unwrap(); exc } // TODO: don't take ownership should make the success path faster pub fn new_key_error(&self, obj: PyObjectRef) -> PyBaseExceptionRef { let key_error = self.ctx.exceptions.key_error.to_owned(); self.new_exception(key_error, vec![obj]) } #[cfg(any(feature = "parser", feature = "compiler"))] pub fn new_syntax_error_maybe_incomplete( &self, error: &crate::compiler::CompileError, source: Option<&str>, allow_incomplete: bool, ) -> PyBaseExceptionRef { let syntax_error_type = match &error { #[cfg(feature = "parser")] // FIXME: this condition will cause TabError even when the matching actual error is IndentationError crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { error: ruff_python_parser::ParseErrorType::Lexical( ruff_python_parser::LexicalErrorType::IndentationError, ), .. }) => self.ctx.exceptions.tab_error, #[cfg(feature = "parser")] crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { error: ruff_python_parser::ParseErrorType::UnexpectedIndentation, .. }) => self.ctx.exceptions.indentation_error, #[cfg(feature = "parser")] crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { error: ruff_python_parser::ParseErrorType::Lexical( ruff_python_parser::LexicalErrorType::Eof, ), .. }) => { if allow_incomplete { self.ctx.exceptions.incomplete_input_error } else { self.ctx.exceptions.syntax_error } } #[cfg(feature = "parser")] crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { error: ruff_python_parser::ParseErrorType::Lexical( ruff_python_parser::LexicalErrorType::FStringError( ruff_python_parser::InterpolatedStringErrorType::UnterminatedTripleQuotedString, ), ), .. }) => { if allow_incomplete { self.ctx.exceptions.incomplete_input_error } else { self.ctx.exceptions.syntax_error } } #[cfg(feature = "parser")] crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { error: ruff_python_parser::ParseErrorType::Lexical( ruff_python_parser::LexicalErrorType::UnclosedStringError, ), raw_location, .. }) => { if allow_incomplete { let mut is_incomplete = false; if let Some(source) = source { let loc = raw_location.start().to_usize(); let mut iter = source.chars(); if let Some(quote) = iter.nth(loc) && iter.next() == Some(quote) && iter.next() == Some(quote) { is_incomplete = true; } } if is_incomplete { self.ctx.exceptions.incomplete_input_error } else { self.ctx.exceptions.syntax_error } } else { self.ctx.exceptions.syntax_error } } #[cfg(feature = "parser")] crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { error: ruff_python_parser::ParseErrorType::OtherError(s), raw_location, .. }) => { if s.starts_with("Expected an indented block after") { if allow_incomplete { // Check that all chars in the error are whitespace, if so, the source is // incomplete. Otherwise, we've found code that might violates // indentation rules. let mut is_incomplete = true; if let Some(source) = source { let start = raw_location.start().to_usize(); let end = raw_location.end().to_usize(); let mut iter = source.chars(); iter.nth(start); for _ in start..end { if let Some(c) = iter.next() { if !c.is_ascii_whitespace() { is_incomplete = false; } } else { break; } } } if is_incomplete { self.ctx.exceptions.incomplete_input_error } else { self.ctx.exceptions.indentation_error } } else { self.ctx.exceptions.indentation_error } } else { self.ctx.exceptions.syntax_error } } _ => self.ctx.exceptions.syntax_error, } .to_owned(); // TODO: replace to SourceCode fn get_statement(source: &str, loc: Option<SourceLocation>) -> Option<String> { let line = source .split('\n') .nth(loc?.line.to_zero_indexed())? .to_owned(); Some(line + "\n") } let statement = if let Some(source) = source { get_statement(source, error.location()) } else { None }; let mut msg = error.to_string(); if let Some(msg) = msg.get_mut(..1) { msg.make_ascii_lowercase(); } match error { #[cfg(feature = "parser")] crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { error: ruff_python_parser::ParseErrorType::FStringError(_) | ruff_python_parser::ParseErrorType::UnexpectedExpressionToken, .. }) => msg.insert_str(0, "invalid syntax: "), _ => {} } let syntax_error = self.new_exception_msg(syntax_error_type, msg); let (lineno, offset) = error.python_location(); let lineno = self.ctx.new_int(lineno); let offset = self.ctx.new_int(offset); syntax_error .as_object() .set_attr("lineno", lineno, self) .unwrap(); syntax_error .as_object() .set_attr("offset", offset, self) .unwrap(); syntax_error .as_object() .set_attr("text", statement.to_pyobject(self), self) .unwrap(); syntax_error .as_object() .set_attr("filename", self.ctx.new_str(error.source_path()), self) .unwrap(); syntax_error } #[cfg(any(feature = "parser", feature = "compiler"))] pub fn new_syntax_error( &self, error: &crate::compiler::CompileError, source: Option<&str>, ) -> PyBaseExceptionRef { self.new_syntax_error_maybe_incomplete(error, source, false) } pub fn new_import_error(&self, msg: impl Into<String>, name: PyStrRef) -> PyBaseExceptionRef { let import_error = self.ctx.exceptions.import_error.to_owned(); let exc = self.new_exception_msg(import_error, msg.into()); exc.as_object().set_attr("name", name, self).unwrap(); exc } pub fn new_stop_iteration(&self, value: Option<PyObjectRef>) -> PyBaseExceptionRef { let dict = self.ctx.new_dict(); let args = if let Some(value) = value { // manually set `value` attribute like StopIteration.__init__ dict.set_item("value", value.clone(), self) .expect("dict.__setitem__ never fails"); vec![value] } else { Vec::new() }; PyRef::new_ref( PyBaseException::new(args, self), self.ctx.exceptions.stop_iteration.to_owned(), Some(dict), ) } fn new_downcast_error( &self, msg: &'static str, error_type: &'static Py<PyType>, class: &Py<PyType>, obj: &PyObject, // the impl Borrow allows to pass PyObjectRef or &PyObject ) -> PyBaseExceptionRef { let actual_class = obj.class(); let actual_type = &*actual_class.name(); let expected_type = &*class.name(); let msg = format!("Expected {msg} '{expected_type}' but '{actual_type}' found."); #[cfg(debug_assertions)] let msg = if class.get_id() == actual_class.get_id() { let mut msg = msg; msg += " It might mean this type doesn't support subclassing very well. e.g. Did you forget to add `#[pyclass(with(Constructor))]`?"; msg } else { msg }; self.new_exception_msg(error_type.to_owned(), msg) } pub(crate) fn new_downcast_runtime_error( &self, class: &Py<PyType>, obj: &impl AsObject, ) -> PyBaseExceptionRef { self.new_downcast_error( "payload", self.ctx.exceptions.runtime_error, class, obj.as_object(), ) } pub(crate) fn new_downcast_type_error( &self, class: &Py<PyType>, obj: &impl AsObject, ) -> PyBaseExceptionRef { self.new_downcast_error( "type", self.ctx.exceptions.type_error, class, obj.as_object(), ) } define_exception_fn!(fn new_lookup_error, lookup_error, LookupError); define_exception_fn!(fn new_eof_error, eof_error, EOFError); define_exception_fn!(fn new_attribute_error, attribute_error, AttributeError); define_exception_fn!(fn new_type_error, type_error, TypeError); define_exception_fn!(fn new_system_error, system_error, SystemError); // TODO: remove & replace with new_unicode_decode_error_real define_exception_fn!(fn new_unicode_decode_error, unicode_decode_error, UnicodeDecodeError); // TODO: remove & replace with new_unicode_encode_error_real define_exception_fn!(fn new_unicode_encode_error, unicode_encode_error, UnicodeEncodeError); define_exception_fn!(fn new_value_error, value_error, ValueError); define_exception_fn!(fn new_buffer_error, buffer_error, BufferError); define_exception_fn!(fn new_index_error, index_error, IndexError); define_exception_fn!( fn new_not_implemented_error, not_implemented_error, NotImplementedError ); define_exception_fn!(fn new_recursion_error, recursion_error, RecursionError); define_exception_fn!(fn new_zero_division_error, zero_division_error, ZeroDivisionError); define_exception_fn!(fn new_overflow_error, overflow_error, OverflowError); define_exception_fn!(fn new_runtime_error, runtime_error, RuntimeError); define_exception_fn!(fn new_python_finalization_error, python_finalization_error, PythonFinalizationError); define_exception_fn!(fn new_memory_error, memory_error, MemoryError); }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/function/argument.rs
crates/vm/src/function/argument.rs
use crate::{ AsObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, builtins::{PyBaseExceptionRef, PyTupleRef, PyTypeRef}, convert::ToPyObject, object::{Traverse, TraverseFn}, }; use core::ops::RangeInclusive; use indexmap::IndexMap; use itertools::Itertools; pub trait IntoFuncArgs: Sized { fn into_args(self, vm: &VirtualMachine) -> FuncArgs; fn into_method_args(self, obj: PyObjectRef, vm: &VirtualMachine) -> FuncArgs { let mut args = self.into_args(vm); args.prepend_arg(obj); args } } impl<T> IntoFuncArgs for T where T: Into<FuncArgs>, { fn into_args(self, _vm: &VirtualMachine) -> FuncArgs { self.into() } } // A tuple of values that each implement `ToPyObject` represents a sequence of // arguments that can be bound and passed to a built-in function. macro_rules! into_func_args_from_tuple { ($(($n:tt, $T:ident)),*) => { impl<$($T,)*> IntoFuncArgs for ($($T,)*) where $($T: ToPyObject,)* { #[inline] fn into_args(self, vm: &VirtualMachine) -> FuncArgs { let ($($n,)*) = self; PosArgs::new(vec![$($n.to_pyobject(vm),)*]).into() } #[inline] fn into_method_args(self, obj: PyObjectRef, vm: &VirtualMachine) -> FuncArgs { let ($($n,)*) = self; PosArgs::new(vec![obj, $($n.to_pyobject(vm),)*]).into() } } }; } into_func_args_from_tuple!((v1, T1)); into_func_args_from_tuple!((v1, T1), (v2, T2)); into_func_args_from_tuple!((v1, T1), (v2, T2), (v3, T3)); into_func_args_from_tuple!((v1, T1), (v2, T2), (v3, T3), (v4, T4)); into_func_args_from_tuple!((v1, T1), (v2, T2), (v3, T3), (v4, T4), (v5, T5)); into_func_args_from_tuple!((v1, T1), (v2, T2), (v3, T3), (v4, T4), (v5, T5), (v6, T6)); // We currently allows only 6 unnamed positional arguments. // Please use `#[derive(FromArgs)]` and a struct for more complex argument parsing. // The number of limitation came from: // https://rust-lang.github.io/rust-clippy/master/index.html#too_many_arguments /// The `FuncArgs` struct is one of the most used structs then creating /// a rust function that can be called from python. It holds both positional /// arguments, as well as keyword arguments passed to the function. #[derive(Debug, Default, Clone, Traverse)] pub struct FuncArgs { pub args: Vec<PyObjectRef>, // sorted map, according to https://www.python.org/dev/peps/pep-0468/ pub kwargs: IndexMap<String, PyObjectRef>, } unsafe impl Traverse for IndexMap<String, PyObjectRef> { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { self.values().for_each(|v| v.traverse(tracer_fn)); } } /// Conversion from vector of python objects to function arguments. impl<A> From<A> for FuncArgs where A: Into<PosArgs>, { fn from(args: A) -> Self { Self { args: args.into().into_vec(), kwargs: IndexMap::new(), } } } impl From<KwArgs> for FuncArgs { fn from(kwargs: KwArgs) -> Self { Self { args: Vec::new(), kwargs: kwargs.0, } } } impl FromArgs for FuncArgs { fn from_args(_vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> { Ok(core::mem::take(args)) } } impl FuncArgs { pub fn new<A, K>(args: A, kwargs: K) -> Self where A: Into<PosArgs>, K: Into<KwArgs>, { let PosArgs(args) = args.into(); let KwArgs(kwargs) = kwargs.into(); Self { args, kwargs } } pub fn with_kwargs_names<A, KW>(mut args: A, kwarg_names: KW) -> Self where A: ExactSizeIterator<Item = PyObjectRef>, KW: ExactSizeIterator<Item = String>, { // last `kwarg_names.len()` elements of args in order of appearance in the call signature let total_argc = args.len(); let kwarg_count = kwarg_names.len(); let pos_arg_count = total_argc - kwarg_count; let pos_args = args.by_ref().take(pos_arg_count).collect(); let kwargs = kwarg_names.zip_eq(args).collect::<IndexMap<_, _>>(); Self { args: pos_args, kwargs, } } pub fn is_empty(&self) -> bool { self.args.is_empty() && self.kwargs.is_empty() } pub fn prepend_arg(&mut self, item: PyObjectRef) { self.args.reserve_exact(1); self.args.insert(0, item) } pub fn shift(&mut self) -> PyObjectRef { self.args.remove(0) } pub fn get_kwarg(&self, key: &str, default: PyObjectRef) -> PyObjectRef { self.kwargs .get(key) .cloned() .unwrap_or_else(|| default.clone()) } pub fn get_optional_kwarg(&self, key: &str) -> Option<PyObjectRef> { self.kwargs.get(key).cloned() } pub fn get_optional_kwarg_with_type( &self, key: &str, ty: PyTypeRef, vm: &VirtualMachine, ) -> PyResult<Option<PyObjectRef>> { match self.get_optional_kwarg(key) { Some(kwarg) => { if kwarg.fast_isinstance(&ty) { Ok(Some(kwarg)) } else { let expected_ty_name = &ty.name(); let kwarg_class = kwarg.class(); let actual_ty_name = &kwarg_class.name(); Err(vm.new_type_error(format!( "argument of type {expected_ty_name} is required for named parameter `{key}` (got: {actual_ty_name})" ))) } } None => Ok(None), } } pub fn take_positional(&mut self) -> Option<PyObjectRef> { if self.args.is_empty() { None } else { Some(self.args.remove(0)) } } pub fn take_positional_keyword(&mut self, name: &str) -> Option<PyObjectRef> { self.take_positional().or_else(|| self.take_keyword(name)) } pub fn take_keyword(&mut self, name: &str) -> Option<PyObjectRef> { self.kwargs.swap_remove(name) } pub fn remaining_keywords(&mut self) -> impl Iterator<Item = (String, PyObjectRef)> + '_ { self.kwargs.drain(..) } /// Binds these arguments to their respective values. /// /// If there is an insufficient number of arguments, there are leftover /// arguments after performing the binding, or if an argument is not of /// the expected type, a TypeError is raised. /// /// If the given `FromArgs` includes any conversions, exceptions raised /// during the conversion will halt the binding and return the error. pub fn bind<T: FromArgs>(mut self, vm: &VirtualMachine) -> PyResult<T> { let given_args = self.args.len(); let bound = T::from_args(vm, &mut self) .map_err(|e| e.into_exception(T::arity(), given_args, vm))?; if !self.args.is_empty() { Err(vm.new_type_error(format!( "expected at most {} arguments, got {}", T::arity().end(), given_args, ))) } else if let Some(err) = self.check_kwargs_empty(vm) { Err(err) } else { Ok(bound) } } pub fn check_kwargs_empty(&self, vm: &VirtualMachine) -> Option<PyBaseExceptionRef> { self.kwargs .keys() .next() .map(|k| vm.new_type_error(format!("Unexpected keyword argument {k}"))) } } /// An error encountered while binding arguments to the parameters of a Python /// function call. pub enum ArgumentError { /// The call provided fewer positional arguments than the function requires. TooFewArgs, /// The call provided more positional arguments than the function accepts. TooManyArgs, /// The function doesn't accept a keyword argument with the given name. InvalidKeywordArgument(String), /// The function require a keyword argument with the given name, but one wasn't provided RequiredKeywordArgument(String), /// An exception was raised while binding arguments to the function /// parameters. Exception(PyBaseExceptionRef), } impl From<PyBaseExceptionRef> for ArgumentError { fn from(ex: PyBaseExceptionRef) -> Self { Self::Exception(ex) } } impl ArgumentError { fn into_exception( self, arity: RangeInclusive<usize>, num_given: usize, vm: &VirtualMachine, ) -> PyBaseExceptionRef { match self { Self::TooFewArgs => vm.new_type_error(format!( "expected at least {} arguments, got {}", arity.start(), num_given )), Self::TooManyArgs => vm.new_type_error(format!( "expected at most {} arguments, got {}", arity.end(), num_given )), Self::InvalidKeywordArgument(name) => { vm.new_type_error(format!("{name} is an invalid keyword argument")) } Self::RequiredKeywordArgument(name) => { vm.new_type_error(format!("Required keyword only argument {name}")) } Self::Exception(ex) => ex, } } } /// Implemented by any type that can be accepted as a parameter to a built-in /// function. /// pub trait FromArgs: Sized { /// The range of positional arguments permitted by the function signature. /// /// Returns an empty range if not applicable. fn arity() -> RangeInclusive<usize> { 0..=0 } /// Extracts this item from the next argument(s). fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError>; } pub trait FromArgOptional { type Inner: TryFromObject; fn from_inner(x: Self::Inner) -> Self; } impl<T: TryFromObject> FromArgOptional for OptionalArg<T> { type Inner = T; fn from_inner(x: T) -> Self { Self::Present(x) } } impl<T: TryFromObject> FromArgOptional for T { type Inner = Self; fn from_inner(x: Self) -> Self { x } } /// A map of keyword arguments to their values. /// /// A built-in function with a `KwArgs` parameter is analogous to a Python /// function with `**kwargs`. All remaining keyword arguments are extracted /// (and hence the function will permit an arbitrary number of them). /// /// `KwArgs` optionally accepts a generic type parameter to allow type checks /// or conversions of each argument. /// /// Note: /// /// KwArgs is only for functions that accept arbitrary keyword arguments. For /// functions that accept only *specific* named arguments, a rust struct with /// an appropriate FromArgs implementation must be created. #[derive(Clone)] pub struct KwArgs<T = PyObjectRef>(IndexMap<String, T>); unsafe impl<T> Traverse for KwArgs<T> where T: Traverse, { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { self.0.iter().map(|(_, v)| v.traverse(tracer_fn)).count(); } } impl<T> KwArgs<T> { pub const fn new(map: IndexMap<String, T>) -> Self { Self(map) } pub fn pop_kwarg(&mut self, name: &str) -> Option<T> { self.0.swap_remove(name) } pub fn is_empty(self) -> bool { self.0.is_empty() } } impl<T> FromIterator<(String, T)> for KwArgs<T> { fn from_iter<I: IntoIterator<Item = (String, T)>>(iter: I) -> Self { Self(iter.into_iter().collect()) } } impl<T> Default for KwArgs<T> { fn default() -> Self { Self(IndexMap::new()) } } impl<T> FromArgs for KwArgs<T> where T: TryFromObject, { fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> { let mut kwargs = IndexMap::new(); for (name, value) in args.remaining_keywords() { kwargs.insert(name, value.try_into_value(vm)?); } Ok(Self(kwargs)) } } impl<T> IntoIterator for KwArgs<T> { type Item = (String, T); type IntoIter = indexmap::map::IntoIter<String, T>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } /// A list of positional argument values. /// /// A built-in function with a `PosArgs` parameter is analogous to a Python /// function with `*args`. All remaining positional arguments are extracted /// (and hence the function will permit an arbitrary number of them). /// /// `PosArgs` optionally accepts a generic type parameter to allow type checks /// or conversions of each argument. #[derive(Clone)] pub struct PosArgs<T = PyObjectRef>(Vec<T>); unsafe impl<T> Traverse for PosArgs<T> where T: Traverse, { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { self.0.traverse(tracer_fn) } } impl<T> PosArgs<T> { pub const fn new(args: Vec<T>) -> Self { Self(args) } pub fn into_vec(self) -> Vec<T> { self.0 } pub fn iter(&self) -> core::slice::Iter<'_, T> { self.0.iter() } } impl<T> From<Vec<T>> for PosArgs<T> { fn from(v: Vec<T>) -> Self { Self(v) } } impl From<()> for PosArgs<PyObjectRef> { fn from(_args: ()) -> Self { Self(Vec::new()) } } impl<T> AsRef<[T]> for PosArgs<T> { fn as_ref(&self) -> &[T] { &self.0 } } impl<T: PyPayload> PosArgs<PyRef<T>> { pub fn into_tuple(self, vm: &VirtualMachine) -> PyTupleRef { vm.ctx .new_tuple(self.0.into_iter().map(Into::into).collect()) } } impl<T> FromArgs for PosArgs<T> where T: TryFromObject, { fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> { let mut varargs = Vec::new(); while let Some(value) = args.take_positional() { varargs.push(value.try_into_value(vm)?); } Ok(Self(varargs)) } } impl<T> IntoIterator for PosArgs<T> { type Item = T; type IntoIter = alloc::vec::IntoIter<T>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } impl<T> FromArgs for T where T: TryFromObject, { fn arity() -> RangeInclusive<usize> { 1..=1 } fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> { let value = args.take_positional().ok_or(ArgumentError::TooFewArgs)?; Ok(value.try_into_value(vm)?) } } /// An argument that may or may not be provided by the caller. /// /// This style of argument is not possible in pure Python. #[derive(Debug, result_like::OptionLike, is_macro::Is)] pub enum OptionalArg<T = PyObjectRef> { Present(T), Missing, } unsafe impl<T> Traverse for OptionalArg<T> where T: Traverse, { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { match self { Self::Present(o) => o.traverse(tracer_fn), Self::Missing => (), } } } impl OptionalArg<PyObjectRef> { pub fn unwrap_or_none(self, vm: &VirtualMachine) -> PyObjectRef { self.unwrap_or_else(|| vm.ctx.none()) } } pub type OptionalOption<T = PyObjectRef> = OptionalArg<Option<T>>; impl<T> OptionalOption<T> { #[inline] pub fn flatten(self) -> Option<T> { self.into_option().flatten() } } impl<T> FromArgs for OptionalArg<T> where T: TryFromObject, { fn arity() -> RangeInclusive<usize> { 0..=1 } fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> { let r = if let Some(value) = args.take_positional() { Self::Present(value.try_into_value(vm)?) } else { Self::Missing }; Ok(r) } } // For functions that accept no arguments. Implemented explicitly instead of via // macro below to avoid unused warnings. impl FromArgs for () { fn from_args(_vm: &VirtualMachine, _args: &mut FuncArgs) -> Result<Self, ArgumentError> { Ok(()) } } // A tuple of types that each implement `FromArgs` represents a sequence of // arguments that can be bound and passed to a built-in function. // // Technically, a tuple can contain tuples, which can contain tuples, and so on, // so this actually represents a tree of values to be bound from arguments, but // in practice this is only used for the top-level parameters. macro_rules! tuple_from_py_func_args { ($($T:ident),+) => { impl<$($T),+> FromArgs for ($($T,)+) where $($T: FromArgs),+ { fn arity() -> RangeInclusive<usize> { let mut min = 0; let mut max = 0; $( let (start, end) = $T::arity().into_inner(); min += start; max += end; )+ min..=max } fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result<Self, ArgumentError> { Ok(($($T::from_args(vm, args)?,)+)) } } }; } // Implement `FromArgs` for up to 7-tuples, allowing built-in functions to bind // up to 7 top-level parameters (note that `PosArgs`, `KwArgs`, nested tuples, etc. // count as 1, so this should actually be more than enough). tuple_from_py_func_args!(A); tuple_from_py_func_args!(A, B); tuple_from_py_func_args!(A, B, C); tuple_from_py_func_args!(A, B, C, D); tuple_from_py_func_args!(A, B, C, D, E); tuple_from_py_func_args!(A, B, C, D, E, F); tuple_from_py_func_args!(A, B, C, D, E, F, G); tuple_from_py_func_args!(A, B, C, D, E, F, G, H);
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/function/arithmetic.rs
crates/vm/src/function/arithmetic.rs
use crate::{ VirtualMachine, convert::{ToPyObject, TryFromObject}, object::{AsObject, PyObjectRef, PyResult}, }; #[derive(result_like::OptionLike)] pub enum PyArithmeticValue<T> { Implemented(T), NotImplemented, } impl PyArithmeticValue<PyObjectRef> { pub fn from_object(vm: &VirtualMachine, obj: PyObjectRef) -> Self { if obj.is(&vm.ctx.not_implemented) { Self::NotImplemented } else { Self::Implemented(obj) } } } impl<T: TryFromObject> TryFromObject for PyArithmeticValue<T> { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { PyArithmeticValue::from_object(vm, obj) .map(|x| T::try_from_object(vm, x)) .transpose() } } impl<T> ToPyObject for PyArithmeticValue<T> where T: ToPyObject, { fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { match self { Self::Implemented(v) => v.to_pyobject(vm), Self::NotImplemented => vm.ctx.not_implemented(), } } } pub type PyComparisonValue = PyArithmeticValue<bool>;
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/function/number.rs
crates/vm/src/function/number.rs
use super::argument::OptionalArg; use crate::{AsObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, builtins::PyIntRef}; use core::ops::Deref; use malachite_bigint::BigInt; use num_complex::Complex64; use num_traits::PrimInt; /// A Python complex-like object. /// /// `ArgIntoComplex` implements `FromArgs` so that a built-in function can accept /// any object that can be transformed into a complex. /// /// If the object is not a Python complex object but has a `__complex__()` /// method, this method will first be called to convert the object into a float. /// If `__complex__()` is not defined then it falls back to `__float__()`. If /// `__float__()` is not defined it falls back to `__index__()`. #[derive(Debug, PartialEq)] #[repr(transparent)] pub struct ArgIntoComplex { value: Complex64, } impl ArgIntoComplex { #[inline] pub fn into_complex(self) -> Complex64 { self.value } } impl From<ArgIntoComplex> for Complex64 { fn from(arg: ArgIntoComplex) -> Self { arg.value } } impl TryFromObject for ArgIntoComplex { // Equivalent to PyComplex_AsCComplex fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { // We do not care if it was already a complex. let (value, _) = obj.try_complex(vm)?.ok_or_else(|| { vm.new_type_error(format!("must be real number, not {}", obj.class().name())) })?; Ok(Self { value }) } } /// A Python float-like object. /// /// `ArgIntoFloat` implements `FromArgs` so that a built-in function can accept /// any object that can be transformed into a float. /// /// If the object is not a Python floating point object but has a `__float__()` /// method, this method will first be called to convert the object into a float. /// If `__float__()` is not defined then it falls back to `__index__()`. #[derive(Debug, PartialEq)] #[repr(transparent)] pub struct ArgIntoFloat { value: f64, } impl ArgIntoFloat { #[inline] pub fn into_float(self) -> f64 { self.value } pub fn vec_into_f64(v: Vec<Self>) -> Vec<f64> { // TODO: Vec::into_raw_parts once stabilized let mut v = core::mem::ManuallyDrop::new(v); let (p, l, c) = (v.as_mut_ptr(), v.len(), v.capacity()); // SAFETY: IntoPyFloat is repr(transparent) over f64 unsafe { Vec::from_raw_parts(p.cast(), l, c) } } } impl From<ArgIntoFloat> for f64 { fn from(arg: ArgIntoFloat) -> Self { arg.value } } impl TryFromObject for ArgIntoFloat { // Equivalent to PyFloat_AsDouble. fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { let value = obj.try_float(vm)?.to_f64(); Ok(Self { value }) } } /// A Python bool-like object. /// /// `ArgIntoBool` implements `FromArgs` so that a built-in function can accept /// any object that can be transformed into a boolean. /// /// By default an object is considered true unless its class defines either a /// `__bool__()` method that returns False or a `__len__()` method that returns /// zero, when called with the object. #[derive(Debug, Default, PartialEq, Eq)] pub struct ArgIntoBool { value: bool, } impl ArgIntoBool { pub const TRUE: Self = Self { value: true }; pub const FALSE: Self = Self { value: false }; #[inline] pub fn into_bool(self) -> bool { self.value } } impl From<ArgIntoBool> for bool { fn from(arg: ArgIntoBool) -> Self { arg.value } } impl TryFromObject for ArgIntoBool { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { Ok(Self { value: obj.try_to_bool(vm)?, }) } } // Implement ArgIndex to separate between "true" int and int generated by index #[derive(Debug, Traverse)] #[repr(transparent)] pub struct ArgIndex { value: PyIntRef, } impl ArgIndex { #[inline] pub fn into_int_ref(self) -> PyIntRef { self.value } } impl AsRef<PyIntRef> for ArgIndex { fn as_ref(&self) -> &PyIntRef { &self.value } } impl From<ArgIndex> for PyIntRef { fn from(arg: ArgIndex) -> Self { arg.value } } impl TryFromObject for ArgIndex { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { Ok(Self { value: obj.try_index(vm)?, }) } } #[derive(Debug, Copy, Clone)] #[repr(transparent)] pub struct ArgPrimitiveIndex<T> { pub value: T, } impl<T> OptionalArg<ArgPrimitiveIndex<T>> { pub fn into_primitive(self) -> OptionalArg<T> { self.map(|x| x.value) } } impl<T> Deref for ArgPrimitiveIndex<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.value } } impl<T> TryFromObject for ArgPrimitiveIndex<T> where T: PrimInt + for<'a> TryFrom<&'a BigInt>, { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { Ok(Self { value: obj.try_index(vm)?.try_to_primitive(vm)?, }) } } pub type ArgSize = ArgPrimitiveIndex<isize>; impl From<ArgSize> for isize { fn from(arg: ArgSize) -> Self { arg.value } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/function/either.rs
crates/vm/src/function/either.rs
use crate::{ AsObject, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, convert::ToPyObject, }; use core::borrow::Borrow; pub enum Either<A, B> { A(A), B(B), } impl<A: Borrow<PyObject>, B: Borrow<PyObject>> Borrow<PyObject> for Either<A, B> { #[inline(always)] fn borrow(&self) -> &PyObject { match self { Self::A(a) => a.borrow(), Self::B(b) => b.borrow(), } } } impl<A: AsRef<PyObject>, B: AsRef<PyObject>> AsRef<PyObject> for Either<A, B> { #[inline(always)] fn as_ref(&self) -> &PyObject { match self { Self::A(a) => a.as_ref(), Self::B(b) => b.as_ref(), } } } impl<A: Into<Self>, B: Into<Self>> From<Either<A, B>> for PyObjectRef { #[inline(always)] fn from(value: Either<A, B>) -> Self { match value { Either::A(a) => a.into(), Either::B(b) => b.into(), } } } impl<A: ToPyObject, B: ToPyObject> ToPyObject for Either<A, B> { #[inline(always)] fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { match self { Self::A(a) => a.to_pyobject(vm), Self::B(b) => b.to_pyobject(vm), } } } /// This allows a builtin method to accept arguments that may be one of two /// types, raising a `TypeError` if it is neither. /// /// # Example /// /// ``` /// use rustpython_vm::VirtualMachine; /// use rustpython_vm::builtins::{PyStrRef, PyIntRef}; /// use rustpython_vm::function::Either; /// /// fn do_something(arg: Either<PyIntRef, PyStrRef>, vm: &VirtualMachine) { /// match arg { /// Either::A(int)=> { /// // do something with int /// } /// Either::B(string) => { /// // do something with string /// } /// } /// } /// ``` impl<A, B> TryFromObject for Either<A, B> where A: TryFromObject, B: TryFromObject, { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { A::try_from_object(vm, obj.clone()) .map(Either::A) .or_else(|_| B::try_from_object(vm, obj.clone()).map(Either::B)) .map_err(|_| vm.new_type_error(format!("unexpected type {}", obj.class()))) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/function/fspath.rs
crates/vm/src/function/fspath.rs
use crate::{ PyObjectRef, PyResult, TryFromObject, VirtualMachine, builtins::{PyBytes, PyBytesRef, PyStrRef}, convert::{IntoPyException, ToPyObject}, function::PyStr, protocol::PyBuffer, }; use alloc::borrow::Cow; use std::{ffi::OsStr, path::PathBuf}; /// Helper to implement os.fspath() #[derive(Clone)] pub enum FsPath { Str(PyStrRef), Bytes(PyBytesRef), } impl FsPath { pub fn try_from_path_like( obj: PyObjectRef, check_for_nul: bool, vm: &VirtualMachine, ) -> PyResult<Self> { Self::try_from( obj, check_for_nul, "expected str, bytes or os.PathLike object", vm, ) } // PyOS_FSPath pub fn try_from( obj: PyObjectRef, check_for_nul: bool, msg: &'static str, vm: &VirtualMachine, ) -> PyResult<Self> { let check_nul = |b: &[u8]| { if !check_for_nul || memchr::memchr(b'\0', b).is_none() { Ok(()) } else { Err(crate::exceptions::cstring_error(vm)) } }; let match1 = |obj: PyObjectRef| { let pathlike = match_class!(match obj { s @ PyStr => { check_nul(s.as_bytes())?; Self::Str(s) } b @ PyBytes => { check_nul(&b)?; Self::Bytes(b) } obj => return Ok(Err(obj)), }); Ok(Ok(pathlike)) }; let obj = match match1(obj)? { Ok(pathlike) => return Ok(pathlike), Err(obj) => obj, }; let not_pathlike_error = || format!("{msg}, not {}", obj.class().name()); let method = vm.get_method_or_type_error( obj.clone(), identifier!(vm, __fspath__), not_pathlike_error, )?; // If __fspath__ is explicitly set to None, treat it as if it doesn't have __fspath__ if vm.is_none(&method) { return Err(vm.new_type_error(not_pathlike_error())); } let result = method.call((), vm)?; match1(result)?.map_err(|result| { vm.new_type_error(format!( "expected {}.__fspath__() to return str or bytes, not {}", obj.class().name(), result.class().name(), )) }) } pub fn as_os_str(&self, vm: &VirtualMachine) -> PyResult<Cow<'_, OsStr>> { // TODO: FS encodings match self { Self::Str(s) => vm.fsencode(s), Self::Bytes(b) => Self::bytes_as_os_str(b.as_bytes(), vm).map(Cow::Borrowed), } } pub fn as_bytes(&self) -> &[u8] { // TODO: FS encodings match self { Self::Str(s) => s.as_bytes(), Self::Bytes(b) => b.as_bytes(), } } pub fn to_string_lossy(&self) -> Cow<'_, str> { match self { Self::Str(s) => s.to_string_lossy(), Self::Bytes(s) => String::from_utf8_lossy(s), } } pub fn to_path_buf(&self, vm: &VirtualMachine) -> PyResult<PathBuf> { let path = match self { Self::Str(s) => PathBuf::from(s.as_str()), Self::Bytes(b) => PathBuf::from(Self::bytes_as_os_str(b, vm)?), }; Ok(path) } pub fn to_cstring(&self, vm: &VirtualMachine) -> PyResult<alloc::ffi::CString> { alloc::ffi::CString::new(self.as_bytes()).map_err(|e| e.into_pyexception(vm)) } #[cfg(windows)] pub fn to_wide_cstring(&self, vm: &VirtualMachine) -> PyResult<widestring::WideCString> { widestring::WideCString::from_os_str(self.as_os_str(vm)?) .map_err(|err| err.into_pyexception(vm)) } pub fn bytes_as_os_str<'a>(b: &'a [u8], vm: &VirtualMachine) -> PyResult<&'a std::ffi::OsStr> { rustpython_common::os::bytes_as_os_str(b) .map_err(|_| vm.new_unicode_decode_error("can't decode path for utf-8")) } } impl ToPyObject for FsPath { fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { match self { Self::Str(s) => s.into(), Self::Bytes(b) => b.into(), } } } impl TryFromObject for FsPath { // PyUnicode_FSDecoder in CPython fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { let obj = match obj.try_to_value::<PyBuffer>(vm) { Ok(buffer) => { let mut bytes = vec![]; buffer.append_to(&mut bytes); vm.ctx.new_bytes(bytes).into() } Err(_) => obj, }; Self::try_from_path_like(obj, true, vm) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/function/getset.rs
crates/vm/src/function/getset.rs
/*! Python `attribute` descriptor class. (PyGetSet) */ use crate::{ Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, convert::ToPyResult, function::{BorrowedParam, OwnedParam, RefParam}, object::PyThreadingConstraint, }; #[derive(result_like::OptionLike, is_macro::Is, Debug)] pub enum PySetterValue<T = PyObjectRef> { Assign(T), Delete, } impl PySetterValue { pub fn unwrap_or_none(self, vm: &VirtualMachine) -> PyObjectRef { match self { Self::Assign(value) => value, Self::Delete => vm.ctx.none(), } } } trait FromPySetterValue where Self: Sized, { fn from_setter_value(vm: &VirtualMachine, obj: PySetterValue) -> PyResult<Self>; } impl<T> FromPySetterValue for T where T: Sized + TryFromObject, { #[inline] fn from_setter_value(vm: &VirtualMachine, obj: PySetterValue) -> PyResult<Self> { let obj = obj.ok_or_else(|| vm.new_type_error("can't delete attribute"))?; T::try_from_object(vm, obj) } } impl<T> FromPySetterValue for PySetterValue<T> where T: Sized + TryFromObject, { #[inline] fn from_setter_value(vm: &VirtualMachine, obj: PySetterValue) -> PyResult<Self> { obj.map(|obj| T::try_from_object(vm, obj)).transpose() } } pub type PyGetterFunc = Box<py_dyn_fn!(dyn Fn(&VirtualMachine, PyObjectRef) -> PyResult)>; pub type PySetterFunc = Box<py_dyn_fn!(dyn Fn(&VirtualMachine, PyObjectRef, PySetterValue) -> PyResult<()>)>; pub trait IntoPyGetterFunc<T>: PyThreadingConstraint + Sized + 'static { fn get(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult; fn into_getter(self) -> PyGetterFunc { Box::new(move |vm, obj| self.get(obj, vm)) } } impl<F, T, R> IntoPyGetterFunc<(OwnedParam<T>, R, VirtualMachine)> for F where F: Fn(T, &VirtualMachine) -> R + 'static + Send + Sync, T: TryFromObject, R: ToPyResult, { fn get(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { let obj = T::try_from_object(vm, obj)?; (self)(obj, vm).to_pyresult(vm) } } impl<F, S, R> IntoPyGetterFunc<(BorrowedParam<S>, R, VirtualMachine)> for F where F: Fn(&Py<S>, &VirtualMachine) -> R + 'static + Send + Sync, S: PyPayload, R: ToPyResult, { fn get(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { let zelf = PyRef::<S>::try_from_object(vm, obj)?; (self)(&zelf, vm).to_pyresult(vm) } } impl<F, S, R> IntoPyGetterFunc<(RefParam<S>, R, VirtualMachine)> for F where F: Fn(&S, &VirtualMachine) -> R + 'static + Send + Sync, S: PyPayload, R: ToPyResult, { fn get(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { let zelf = PyRef::<S>::try_from_object(vm, obj)?; (self)(&zelf, vm).to_pyresult(vm) } } impl<F, T, R> IntoPyGetterFunc<(OwnedParam<T>, R)> for F where F: Fn(T) -> R + 'static + Send + Sync, T: TryFromObject, R: ToPyResult, { fn get(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { let obj = T::try_from_object(vm, obj)?; (self)(obj).to_pyresult(vm) } } impl<F, S, R> IntoPyGetterFunc<(BorrowedParam<S>, R)> for F where F: Fn(&Py<S>) -> R + 'static + Send + Sync, S: PyPayload, R: ToPyResult, { fn get(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { let zelf = PyRef::<S>::try_from_object(vm, obj)?; (self)(&zelf).to_pyresult(vm) } } impl<F, S, R> IntoPyGetterFunc<(RefParam<S>, R)> for F where F: Fn(&S) -> R + 'static + Send + Sync, S: PyPayload, R: ToPyResult, { fn get(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { let zelf = PyRef::<S>::try_from_object(vm, obj)?; (self)(&zelf).to_pyresult(vm) } } pub trait IntoPyNoResult { fn into_noresult(self) -> PyResult<()>; } impl IntoPyNoResult for () { #[inline] fn into_noresult(self) -> PyResult<()> { Ok(()) } } impl IntoPyNoResult for PyResult<()> { #[inline] fn into_noresult(self) -> PyResult<()> { self } } pub trait IntoPySetterFunc<T>: PyThreadingConstraint + Sized + 'static { fn set(&self, obj: PyObjectRef, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()>; fn into_setter(self) -> PySetterFunc { Box::new(move |vm, obj, value| self.set(obj, value, vm)) } } impl<F, T, V, R> IntoPySetterFunc<(OwnedParam<T>, V, R, VirtualMachine)> for F where F: Fn(T, V, &VirtualMachine) -> R + 'static + Send + Sync, T: TryFromObject, V: FromPySetterValue, R: IntoPyNoResult, { fn set(&self, obj: PyObjectRef, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { let obj = T::try_from_object(vm, obj)?; let value = V::from_setter_value(vm, value)?; (self)(obj, value, vm).into_noresult() } } impl<F, S, V, R> IntoPySetterFunc<(BorrowedParam<S>, V, R, VirtualMachine)> for F where F: Fn(&Py<S>, V, &VirtualMachine) -> R + 'static + Send + Sync, S: PyPayload, V: FromPySetterValue, R: IntoPyNoResult, { fn set(&self, obj: PyObjectRef, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { let zelf = PyRef::<S>::try_from_object(vm, obj)?; let value = V::from_setter_value(vm, value)?; (self)(&zelf, value, vm).into_noresult() } } impl<F, S, V, R> IntoPySetterFunc<(RefParam<S>, V, R, VirtualMachine)> for F where F: Fn(&S, V, &VirtualMachine) -> R + 'static + Send + Sync, S: PyPayload, V: FromPySetterValue, R: IntoPyNoResult, { fn set(&self, obj: PyObjectRef, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { let zelf = PyRef::<S>::try_from_object(vm, obj)?; let value = V::from_setter_value(vm, value)?; (self)(&zelf, value, vm).into_noresult() } } impl<F, T, V, R> IntoPySetterFunc<(OwnedParam<T>, V, R)> for F where F: Fn(T, V) -> R + 'static + Send + Sync, T: TryFromObject, V: FromPySetterValue, R: IntoPyNoResult, { fn set(&self, obj: PyObjectRef, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { let obj = T::try_from_object(vm, obj)?; let value = V::from_setter_value(vm, value)?; (self)(obj, value).into_noresult() } } impl<F, S, V, R> IntoPySetterFunc<(BorrowedParam<S>, V, R)> for F where F: Fn(&Py<S>, V) -> R + 'static + Send + Sync, S: PyPayload, V: FromPySetterValue, R: IntoPyNoResult, { fn set(&self, obj: PyObjectRef, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { let zelf = PyRef::<S>::try_from_object(vm, obj)?; let value = V::from_setter_value(vm, value)?; (self)(&zelf, value).into_noresult() } } impl<F, S, V, R> IntoPySetterFunc<(RefParam<S>, V, R)> for F where F: Fn(&S, V) -> R + 'static + Send + Sync, S: PyPayload, V: FromPySetterValue, R: IntoPyNoResult, { fn set(&self, obj: PyObjectRef, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { let zelf = PyRef::<S>::try_from_object(vm, obj)?; let value = V::from_setter_value(vm, value)?; (self)(&zelf, value).into_noresult() } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/function/mod.rs
crates/vm/src/function/mod.rs
mod argument; mod arithmetic; mod buffer; mod builtin; mod either; mod fspath; mod getset; mod method; mod number; mod protocol; pub use argument::{ ArgumentError, FromArgOptional, FromArgs, FuncArgs, IntoFuncArgs, KwArgs, OptionalArg, OptionalOption, PosArgs, }; pub use arithmetic::{PyArithmeticValue, PyComparisonValue}; pub use buffer::{ArgAsciiBuffer, ArgBytesLike, ArgMemoryBuffer, ArgStrOrBytesLike}; pub use builtin::{IntoPyNativeFn, PyNativeFn, static_func, static_raw_func}; pub use either::Either; pub use fspath::FsPath; pub use getset::PySetterValue; pub(super) use getset::{IntoPyGetterFunc, IntoPySetterFunc, PyGetterFunc, PySetterFunc}; pub use method::{HeapMethodDef, PyMethodDef, PyMethodFlags}; pub use number::{ArgIndex, ArgIntoBool, ArgIntoComplex, ArgIntoFloat, ArgPrimitiveIndex, ArgSize}; pub use protocol::{ArgCallable, ArgIterable, ArgMapping, ArgSequence}; use crate::{PyObject, PyResult, VirtualMachine, builtins::PyStr, convert::TryFromBorrowedObject}; use builtin::{BorrowedParam, OwnedParam, RefParam}; #[derive(Clone, Copy, PartialEq, Eq)] pub enum ArgByteOrder { Big, Little, } impl<'a> TryFromBorrowedObject<'a> for ArgByteOrder { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> { obj.try_value_with( |s: &PyStr| match s.as_str() { "big" => Ok(Self::Big), "little" => Ok(Self::Little), _ => Err(vm.new_value_error("byteorder must be either 'little' or 'big'")), }, vm, ) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/function/method.rs
crates/vm/src/function/method.rs
use crate::{ Context, Py, PyObjectRef, PyPayload, PyRef, VirtualMachine, builtins::{ PyType, builtin_func::{PyNativeFunction, PyNativeMethod}, descriptor::PyMethodDescriptor, }, function::{IntoPyNativeFn, PyNativeFn}, }; bitflags::bitflags! { // METH_XXX flags in CPython #[derive(Copy, Clone, Debug, PartialEq)] pub struct PyMethodFlags: u32 { // const VARARGS = 0x0001; // const KEYWORDS = 0x0002; // METH_NOARGS and METH_O must not be combined with the flags above. // const NOARGS = 0x0004; // const O = 0x0008; // METH_CLASS and METH_STATIC are a little different; these control // the construction of methods for a class. These cannot be used for // functions in modules. const CLASS = 0x0010; const STATIC = 0x0020; // METH_COEXIST allows a method to be entered even though a slot has // already filled the entry. When defined, the flag allows a separate // method, "__contains__" for example, to coexist with a defined // slot like sq_contains. // const COEXIST = 0x0040; // if not Py_LIMITED_API // const FASTCALL = 0x0080; // This bit is preserved for Stackless Python // const STACKLESS = 0x0100; // METH_METHOD means the function stores an // additional reference to the class that defines it; // both self and class are passed to it. // It uses PyCMethodObject instead of PyCFunctionObject. // May not be combined with METH_NOARGS, METH_O, METH_CLASS or METH_STATIC. const METHOD = 0x0200; } } impl PyMethodFlags { // FIXME: macro temp pub const EMPTY: Self = Self::empty(); } #[macro_export] macro_rules! define_methods { // TODO: more flexible syntax ($($name:literal => $func:ident as $flags:ident),+) => { vec![ $( $crate::function::PyMethodDef { name: $name, func: $crate::function::static_func($func), flags: $crate::function::PyMethodFlags::$flags, doc: None, }),+ ] }; } #[derive(Clone)] pub struct PyMethodDef { pub name: &'static str, // TODO: interned pub func: &'static dyn PyNativeFn, pub flags: PyMethodFlags, pub doc: Option<&'static str>, // TODO: interned } impl PyMethodDef { #[inline] pub const fn new_const<Kind>( name: &'static str, func: impl IntoPyNativeFn<Kind>, flags: PyMethodFlags, doc: Option<&'static str>, ) -> Self { Self { name, func: super::static_func(func), flags, doc, } } #[inline] pub const fn new_raw_const( name: &'static str, func: impl PyNativeFn, flags: PyMethodFlags, doc: Option<&'static str>, ) -> Self { Self { name, func: super::static_raw_func(func), flags, doc, } } pub fn to_proper_method( &'static self, class: &'static Py<PyType>, ctx: &Context, ) -> PyObjectRef { if self.flags.contains(PyMethodFlags::METHOD) { self.build_method(ctx, class).into() } else if self.flags.contains(PyMethodFlags::CLASS) { self.build_classmethod(ctx, class).into() } else if self.flags.contains(PyMethodFlags::STATIC) { self.build_staticmethod(ctx, class).into() } else { unreachable!() } } pub const fn to_function(&'static self) -> PyNativeFunction { PyNativeFunction { zelf: None, value: self, module: None, } } pub fn to_method( &'static self, class: &'static Py<PyType>, ctx: &Context, ) -> PyMethodDescriptor { PyMethodDescriptor::new(self, class, ctx) } pub const fn to_bound_method( &'static self, obj: PyObjectRef, class: &'static Py<PyType>, ) -> PyNativeMethod { PyNativeMethod { func: PyNativeFunction { zelf: Some(obj), value: self, module: None, }, class, } } pub fn build_function(&'static self, ctx: &Context) -> PyRef<PyNativeFunction> { self.to_function().into_ref(ctx) } pub fn build_bound_function( &'static self, ctx: &Context, obj: PyObjectRef, ) -> PyRef<PyNativeFunction> { let function = PyNativeFunction { zelf: Some(obj), value: self, module: None, }; PyRef::new_ref( function, ctx.types.builtin_function_or_method_type.to_owned(), None, ) } pub fn build_method( &'static self, ctx: &Context, class: &'static Py<PyType>, ) -> PyRef<PyMethodDescriptor> { debug_assert!(self.flags.contains(PyMethodFlags::METHOD)); let method = self.to_method(class, ctx); PyRef::new_ref(method, ctx.types.method_descriptor_type.to_owned(), None) } pub fn build_bound_method( &'static self, ctx: &Context, obj: PyObjectRef, class: &'static Py<PyType>, ) -> PyRef<PyNativeMethod> { PyRef::new_ref( self.to_bound_method(obj, class), ctx.types.builtin_method_type.to_owned(), None, ) } pub fn build_classmethod( &'static self, ctx: &Context, class: &'static Py<PyType>, ) -> PyRef<PyMethodDescriptor> { PyRef::new_ref( self.to_method(class, ctx), ctx.types.method_descriptor_type.to_owned(), None, ) } pub fn build_staticmethod( &'static self, ctx: &Context, class: &'static Py<PyType>, ) -> PyRef<PyNativeMethod> { debug_assert!(self.flags.contains(PyMethodFlags::STATIC)); let func = self.to_function(); PyNativeMethod { func, class }.into_ref(ctx) } #[doc(hidden)] pub const fn __const_concat_arrays<const SUM_LEN: usize>( method_groups: &[&[Self]], ) -> [Self; SUM_LEN] { const NULL_METHOD: PyMethodDef = PyMethodDef { name: "", func: &|_, _| unreachable!(), flags: PyMethodFlags::empty(), doc: None, }; let mut all_methods = [NULL_METHOD; SUM_LEN]; let mut all_idx = 0; let mut group_idx = 0; while group_idx < method_groups.len() { let group = method_groups[group_idx]; let mut method_idx = 0; while method_idx < group.len() { all_methods[all_idx] = group[method_idx].const_copy(); method_idx += 1; all_idx += 1; } group_idx += 1; } all_methods } const fn const_copy(&self) -> Self { Self { name: self.name, func: self.func, flags: self.flags, doc: self.doc, } } } impl core::fmt::Debug for PyMethodDef { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyMethodDef") .field("name", &self.name) .field( "func", &(unsafe { core::mem::transmute::<&dyn PyNativeFn, [usize; 2]>(self.func)[1] as *const u8 }), ) .field("flags", &self.flags) .field("doc", &self.doc) .finish() } } // This is not a part of CPython API. // But useful to support dynamically generated methods #[pyclass(name, module = false, ctx = "method_def")] #[derive(Debug)] pub struct HeapMethodDef { method: PyMethodDef, } impl HeapMethodDef { pub const fn new(method: PyMethodDef) -> Self { Self { method } } } impl Py<HeapMethodDef> { pub(crate) unsafe fn method(&self) -> &'static PyMethodDef { unsafe { &*(&self.method as *const _) } } pub fn build_function(&self, vm: &VirtualMachine) -> PyRef<PyNativeFunction> { let function = unsafe { self.method() }.to_function(); let dict = vm.ctx.new_dict(); dict.set_item("__method_def__", self.to_owned().into(), vm) .unwrap(); PyRef::new_ref( function, vm.ctx.types.builtin_function_or_method_type.to_owned(), Some(dict), ) } pub fn build_method( &self, class: &'static Py<PyType>, vm: &VirtualMachine, ) -> PyRef<PyMethodDescriptor> { let function = unsafe { self.method() }.to_method(class, &vm.ctx); let dict = vm.ctx.new_dict(); dict.set_item("__method_def__", self.to_owned().into(), vm) .unwrap(); PyRef::new_ref( function, vm.ctx.types.method_descriptor_type.to_owned(), Some(dict), ) } } #[pyclass] impl HeapMethodDef {}
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/function/protocol.rs
crates/vm/src/function/protocol.rs
use super::IntoFuncArgs; use crate::{ AsObject, PyObject, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine, builtins::{PyDictRef, iter::PySequenceIterator}, convert::ToPyObject, object::{Traverse, TraverseFn}, protocol::{PyIter, PyIterIter, PyMapping}, types::GenericMethod, }; use core::{borrow::Borrow, marker::PhantomData}; #[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 core::fmt::Debug for ArgCallable { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::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) -> Self { 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(Self { 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, iter_fn: 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.iter_fn { 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 cls = obj.class(); let iter_fn = cls.slots.iter.load(); if iter_fn.is_none() && !cls.has_attr(identifier!(vm, __getitem__)) { return Err(vm.new_type_error(format!("'{}' object is not iterable", cls.name()))); } Ok(Self { iterable: obj, iter_fn, _item: PhantomData, }) } } #[derive(Debug, Clone, Traverse)] pub struct ArgMapping { obj: PyObjectRef, } impl ArgMapping { #[inline] pub const fn new(obj: PyObjectRef) -> Self { Self { obj } } #[inline(always)] pub fn from_dict_exact(dict: PyDictRef) -> Self { Self { obj: dict.into() } } #[inline(always)] pub fn obj(&self) -> &PyObject { &self.obj } #[inline(always)] pub fn mapping(&self) -> PyMapping<'_> { self.obj.mapping_unchecked() } } 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 From<ArgMapping> for PyObjectRef { #[inline(always)] fn from(value: ArgMapping) -> Self { 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 = obj.try_mapping(vm)?; Ok(Self { obj }) } } // 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> core::ops::Deref for ArgSequence<T> { type Target = [T]; #[inline(always)] fn deref(&self) -> &[T] { self.as_slice() } } impl<'a, T> IntoIterator for &'a ArgSequence<T> { type Item = &'a T; type IntoIter = core::slice::Iter<'a, T>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl<T> IntoIterator for ArgSequence<T> { type Item = T; type IntoIter = alloc::vec::IntoIter<T>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } impl<T: TryFromObject> TryFromObject for ArgSequence<T> { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { obj.try_to_value(vm).map(Self) } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false
RustPython/RustPython
https://github.com/RustPython/RustPython/blob/e1b22f19e62d47485bdb55c9f3a4698221374f5b/crates/vm/src/function/buffer.rs
crates/vm/src/function/buffer.rs
use crate::{ AsObject, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine, builtins::{PyStr, PyStrRef}, common::borrow::{BorrowedValue, BorrowedValueMut}, protocol::PyBuffer, }; // Python/getargs.c /// any bytes-like object. Like the `y*` format code for `PyArg_Parse` in CPython. #[derive(Debug, Traverse)] pub struct ArgBytesLike(PyBuffer); impl PyObject { pub fn try_bytes_like<R>( &self, vm: &VirtualMachine, f: impl FnOnce(&[u8]) -> R, ) -> PyResult<R> { let buffer = PyBuffer::try_from_borrowed_object(vm, self)?; buffer .as_contiguous() .map(|x| f(&x)) .ok_or_else(|| vm.new_buffer_error("non-contiguous buffer is not a bytes-like object")) } pub fn try_rw_bytes_like<R>( &self, vm: &VirtualMachine, f: impl FnOnce(&mut [u8]) -> R, ) -> PyResult<R> { let buffer = PyBuffer::try_from_borrowed_object(vm, self)?; buffer .as_contiguous_mut() .map(|mut x| f(&mut x)) .ok_or_else(|| vm.new_type_error("buffer is not a read-write bytes-like object")) } } impl ArgBytesLike { pub fn borrow_buf(&self) -> BorrowedValue<'_, [u8]> { unsafe { self.0.contiguous_unchecked() } } pub fn with_ref<F, R>(&self, f: F) -> R where F: FnOnce(&[u8]) -> R, { f(&self.borrow_buf()) } pub const fn len(&self) -> usize { self.0.desc.len } pub const fn is_empty(&self) -> bool { self.len() == 0 } pub fn as_object(&self) -> &PyObject { &self.0.obj } } impl From<ArgBytesLike> for PyBuffer { fn from(buffer: ArgBytesLike) -> Self { buffer.0 } } impl From<ArgBytesLike> for PyObjectRef { fn from(buffer: ArgBytesLike) -> Self { buffer.as_object().to_owned() } } impl<'a> TryFromBorrowedObject<'a> for ArgBytesLike { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> { let buffer = PyBuffer::try_from_borrowed_object(vm, obj)?; if buffer.desc.is_contiguous() { Ok(Self(buffer)) } else { Err(vm.new_buffer_error("non-contiguous buffer is not a bytes-like object")) } } } /// A memory buffer, read-write access. Like the `w*` format code for `PyArg_Parse` in CPython. #[derive(Debug, Traverse)] pub struct ArgMemoryBuffer(PyBuffer); impl ArgMemoryBuffer { pub fn borrow_buf_mut(&self) -> BorrowedValueMut<'_, [u8]> { unsafe { self.0.contiguous_mut_unchecked() } } pub fn with_ref<F, R>(&self, f: F) -> R where F: FnOnce(&mut [u8]) -> R, { f(&mut self.borrow_buf_mut()) } pub const fn len(&self) -> usize { self.0.desc.len } pub const fn is_empty(&self) -> bool { self.len() == 0 } } impl From<ArgMemoryBuffer> for PyBuffer { fn from(buffer: ArgMemoryBuffer) -> Self { buffer.0 } } impl<'a> TryFromBorrowedObject<'a> for ArgMemoryBuffer { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult<Self> { let buffer = PyBuffer::try_from_borrowed_object(vm, obj)?; if !buffer.desc.is_contiguous() { Err(vm.new_buffer_error("non-contiguous buffer is not a bytes-like object")) } else if buffer.desc.readonly { Err(vm.new_type_error("buffer is not a read-write bytes-like object")) } else { Ok(Self(buffer)) } } } /// A text string or bytes-like object. Like the `s*` format code for `PyArg_Parse` in CPython. pub enum ArgStrOrBytesLike { Buf(ArgBytesLike), Str(PyStrRef), } impl ArgStrOrBytesLike { pub fn as_object(&self) -> &PyObject { match self { Self::Buf(b) => b.as_object(), Self::Str(s) => s.as_object(), } } } impl TryFromObject for ArgStrOrBytesLike { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { obj.downcast() .map(Self::Str) .or_else(|obj| ArgBytesLike::try_from_object(vm, obj).map(Self::Buf)) } } impl ArgStrOrBytesLike { pub fn borrow_bytes(&self) -> BorrowedValue<'_, [u8]> { match self { Self::Buf(b) => b.borrow_buf(), Self::Str(s) => s.as_bytes().into(), } } } #[derive(Debug)] pub enum ArgAsciiBuffer { String(PyStrRef), Buffer(ArgBytesLike), } impl TryFromObject for ArgAsciiBuffer { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> { match obj.downcast::<PyStr>() { Ok(string) => { if string.as_str().is_ascii() { Ok(Self::String(string)) } else { Err(vm.new_value_error("string argument should contain only ASCII characters")) } } Err(obj) => ArgBytesLike::try_from_object(vm, obj).map(ArgAsciiBuffer::Buffer), } } } impl ArgAsciiBuffer { pub fn len(&self) -> usize { match self { Self::String(s) => s.as_str().len(), Self::Buffer(buffer) => buffer.len(), } } pub fn is_empty(&self) -> bool { self.len() == 0 } #[inline] pub fn with_ref<R>(&self, f: impl FnOnce(&[u8]) -> R) -> R { match self { Self::String(s) => f(s.as_bytes()), Self::Buffer(buffer) => buffer.with_ref(f), } } }
rust
MIT
e1b22f19e62d47485bdb55c9f3a4698221374f5b
2026-01-04T15:39:39.834879Z
false