PyString -> PyStr

This commit is contained in:
Jeong YunWon committed 2020-09-26 00:20:02 +09:00
1 parent c5011038e0
commit f81ad04ce3
58 files changed
+401 -443

No files matched your search

+3 -6
View File
@@ -1,4 +1,4 @@
use rustpython_vm::obj::objstr::PyStringRef;
use rustpython_vm::obj::objstr::PyStrRef;
use rustpython_vm::pyobject::{BorrowValue, PyIterable, PyResult, TryFromObject};
use rustpython_vm::scope::{NameProtocol, Scope};
use rustpython_vm::VirtualMachine;
@@ -59,16 +59,13 @@ impl<'vm> ShellHelper<'vm> {
fn get_available_completions<'w>(
&self,
words: &'w [String],
) -> Option<(
&'w str,
Box<dyn Iterator<Item = PyResult<PyStringRef>> + 'vm>,
)> {
) -> Option<(&'w str, Box<dyn Iterator<Item = PyResult<PyStrRef>> + 'vm>)> {
// the very first word and then all the ones after the dot
let (first, rest) = words.split_first().unwrap();
let str_iter_method = |obj, name| {
let iter = self.vm.call_method(obj, name, vec![])?;
PyIterable::<PyStringRef>::try_from_object(self.vm, iter)?.iter(self.vm)
PyIterable::<PyStrRef>::try_from_object(self.vm, iter)?.iter(self.vm)
};
if let Some((last, parents)) = rest.split_last() {
+23 -25
View File
@@ -29,7 +29,7 @@ mod decl {
use crate::obj::objiter;
use crate::obj::objlist::{PyList, SortOptions};
use crate::obj::objsequence;
use crate::obj::objstr::{PyString, PyStringRef};
use crate::obj::objstr::{PyStr, PyStrRef};
use crate::obj::objtype::{self, PyClassRef};
use crate::pyobject::{
BorrowValue, Either, IdProtocol, ItemProtocol, PyCallable, PyIterable, PyObjectRef,
@@ -108,11 +108,11 @@ mod decl {
#[allow(dead_code)]
struct CompileArgs {
#[pyarg(positional_only, optional = false)]
source: Either<PyStringRef, PyBytesRef>,
source: Either<PyStrRef, PyBytesRef>,
#[pyarg(positional_only, optional = false)]
filename: PyStringRef,
filename: PyStrRef,
#[pyarg(positional_only, optional = false)]
mode: PyStringRef,
mode: PyStrRef,
#[pyarg(positional_or_keyword, optional = true)]
flags: OptionalArg<PyIntRef>,
#[pyarg(positional_or_keyword, optional = true)]
@@ -162,7 +162,7 @@ mod decl {
}
#[pyfunction]
fn delattr(obj: PyObjectRef, attr: PyStringRef, vm: &VirtualMachine) -> PyResult<()> {
fn delattr(obj: PyObjectRef, attr: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
vm.del_attr(&obj, attr.into_object())
}
@@ -200,7 +200,7 @@ mod decl {
#[cfg(feature = "rustpython-compiler")]
#[pyfunction]
fn eval(
source: Either<PyStringRef, PyCodeRef>,
source: Either<PyStrRef, PyCodeRef>,
scope: ScopeArgs,
vm: &VirtualMachine,
) -> PyResult {
@@ -212,7 +212,7 @@ mod decl {
#[cfg(feature = "rustpython-compiler")]
#[pyfunction]
fn exec(
source: Either<PyStringRef, PyCodeRef>,
source: Either<PyStrRef, PyCodeRef>,
scope: ScopeArgs,
vm: &VirtualMachine,
) -> PyResult {
@@ -222,7 +222,7 @@ mod decl {
#[cfg(feature = "rustpython-compiler")]
fn run_code(
vm: &VirtualMachine,
source: Either<PyStringRef, PyCodeRef>,
source: Either<PyStrRef, PyCodeRef>,
scope: ScopeArgs,
mode: compile::Mode,
) -> PyResult {
@@ -272,12 +272,12 @@ mod decl {
#[pyfunction]
fn format(
value: PyObjectRef,
format_spec: OptionalArg<PyStringRef>,
format_spec: OptionalArg<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult<PyStringRef> {
) -> PyResult<PyStrRef> {
let format_spec = format_spec
.into_option()
.unwrap_or_else(|| PyString::from("").into_ref(vm));
.unwrap_or_else(|| PyStr::from("").into_ref(vm));
vm.call_method(&value, "__format__", vec![format_spec.into_object()])?
.downcast()
@@ -304,7 +304,7 @@ mod decl {
#[pyfunction]
fn getattr(
obj: PyObjectRef,
attr: PyStringRef,
attr: PyStrRef,
default: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult {
@@ -322,7 +322,7 @@ mod decl {
}
#[pyfunction]
fn hasattr(obj: PyObjectRef, attr: PyStringRef, vm: &VirtualMachine) -> PyResult<bool> {
fn hasattr(obj: PyObjectRef, attr: PyStrRef, vm: &VirtualMachine) -> PyResult<bool> {
if let Err(ex) = vm.get_attribute(obj, attr) {
catch_attr_exception(ex, false, vm)
} else {
@@ -355,7 +355,7 @@ mod decl {
}
#[pyfunction]
fn input(prompt: OptionalArg<PyStringRef>, vm: &VirtualMachine) -> PyResult {
fn input(prompt: OptionalArg<PyStrRef>, vm: &VirtualMachine) -> PyResult {
let stdin = sysmodule::get_stdin(vm)?;
let stdout = sysmodule::get_stdout(vm)?;
let stderr = sysmodule::get_stderr(vm)?;
@@ -590,7 +590,7 @@ mod decl {
}
#[pyfunction]
fn ord(string: Either<PyBytesLike, PyStringRef>, vm: &VirtualMachine) -> PyResult<u32> {
fn ord(string: Either<PyBytesLike, PyStrRef>, vm: &VirtualMachine) -> PyResult<u32> {
match string {
Either::A(bytes) => bytes.with_ref(|bytes| {
let bytes_len = bytes.len();
@@ -670,9 +670,9 @@ mod decl {
#[derive(Debug, Default, FromArgs)]
pub struct PrintOptions {
#[pyarg(keyword_only, default = "None")]
sep: Option<PyStringRef>,
sep: Option<PyStrRef>,
#[pyarg(keyword_only, default = "None")]
end: Option<PyStringRef>,
end: Option<PyStrRef>,
#[pyarg(keyword_only, default = "IntoPyBool::FALSE")]
flush: IntoPyBool,
#[pyarg(keyword_only, default = "None")]
@@ -685,11 +685,9 @@ mod decl {
Some(f) => f,
None => sysmodule::get_stdout(vm)?,
};
let write = |obj: PyStringRef| vm.call_method(&file, "write", vec![obj.into_object()]);
let write = |obj: PyStrRef| vm.call_method(&file, "write", vec![obj.into_object()]);
let sep = options
.sep
.unwrap_or_else(|| PyString::from(" ").into_ref(vm));
let sep = options.sep.unwrap_or_else(|| PyStr::from(" ").into_ref(vm));
let mut first = true;
for object in objects {
@@ -704,7 +702,7 @@ mod decl {
let end = options
.end
.unwrap_or_else(|| PyString::from("\n").into_ref(vm));
.unwrap_or_else(|| PyStr::from("\n").into_ref(vm));
write(end)?;
if options.flush.to_bool() {
@@ -715,7 +713,7 @@ mod decl {
}
#[pyfunction]
fn repr(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStringRef> {
fn repr(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
vm.to_repr(&obj)
}
@@ -759,7 +757,7 @@ mod decl {
#[pyfunction]
fn setattr(
obj: PyObjectRef,
attr: PyStringRef,
attr: PyStrRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
@@ -804,7 +802,7 @@ mod decl {
#[pyfunction]
pub fn __build_class__(
function: PyFunctionRef,
qualified_name: PyStringRef,
qualified_name: PyStrRef,
bases: Args<PyClassRef>,
mut kwargs: KwArgs,
vm: &VirtualMachine,
+8 -8
View File
@@ -15,7 +15,7 @@ use crate::obj::objsequence::{
};
use crate::obj::objsingletons::PyNoneRef;
use crate::obj::objslice::PySliceRef;
use crate::obj::objstr::{self, PyString, PyStringRef};
use crate::obj::objstr::{self, PyStr, PyStrRef};
use crate::pyobject::{
BorrowValue, Either, PyComparisonValue, PyIterable, PyIterator, PyObjectRef, PyResult,
TryFromObject, TypeProtocol,
@@ -67,9 +67,9 @@ pub struct ByteInnerNewOptions {
#[pyarg(positional_or_keyword, optional = true)]
source: OptionalArg<PyObjectRef>,
#[pyarg(positional_or_keyword, optional = true)]
encoding: OptionalArg<PyStringRef>,
encoding: OptionalArg<PyStrRef>,
#[pyarg(positional_or_keyword, optional = true)]
errors: OptionalArg<PyStringRef>,
errors: OptionalArg<PyStrRef>,
}
impl ByteInnerNewOptions {
@@ -87,7 +87,7 @@ impl ByteInnerNewOptions {
}
}
OptionalArg::Present(obj) => {
match obj.downcast::<PyString>() {
match obj.downcast::<PyStr>() {
Ok(s) => {
// Handle bytes(string, encoding[, errors])
if let OptionalArg::Present(enc) = self.encoding {
@@ -1188,19 +1188,19 @@ impl<'s> PyCommonString<'s, u8> for [u8] {
#[derive(FromArgs)]
pub struct DecodeArgs {
#[pyarg(positional_or_keyword, default = "None")]
encoding: Option<PyStringRef>,
encoding: Option<PyStrRef>,
#[pyarg(positional_or_keyword, default = "None")]
errors: Option<PyStringRef>,
errors: Option<PyStrRef>,
}
pub fn bytes_decode(
zelf: PyObjectRef,
args: DecodeArgs,
vm: &VirtualMachine,
) -> PyResult<PyStringRef> {
) -> PyResult<PyStrRef> {
let DecodeArgs { encoding, errors } = args;
vm.decode(zelf, encoding.clone(), errors)?
.downcast::<PyString>()
.downcast::<PyStr>()
.map_err(|obj| {
vm.new_type_error(format!(
"'{}' decoder returned '{}' instead of 'str'; use codecs.encode() to \
+5 -5
View File
@@ -3,7 +3,7 @@
/// And: https://www.youtube.com/watch?v=p33CVV29OG8
/// And: http://code.activestate.com/recipes/578375/
use crate::common::cell::{PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard};
use crate::obj::objstr::{PyString, PyStringRef};
use crate::obj::objstr::{PyStr, PyStrRef};
use crate::pyobject::{BorrowValue, IdProtocol, IntoPyObject, PyObjectRef, PyResult};
use crate::vm::VirtualMachine;
use rustpython_common::hash;
@@ -455,7 +455,7 @@ impl DictKey for PyObjectRef {
}
}
impl DictKey for PyStringRef {
impl DictKey for PyStrRef {
fn key_hash(&self, vm: &VirtualMachine) -> PyResult<HashValue> {
Ok(self.hash(vm))
}
@@ -467,7 +467,7 @@ impl DictKey for PyStringRef {
fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObjectRef) -> PyResult<bool> {
if self.is(other_key) {
Ok(true)
} else if let Some(py_str_value) = other_key.payload::<PyString>() {
} else if let Some(py_str_value) = other_key.payload::<PyStr>() {
Ok(py_str_value.borrow_value() == self.borrow_value())
} else {
vm.bool_eq(self.clone().into_object(), other_key.clone())
@@ -481,7 +481,7 @@ impl DictKey for PyStringRef {
/// to index dictionaries.
impl DictKey for &str {
fn key_hash(&self, vm: &VirtualMachine) -> PyResult<HashValue> {
// follow a similar route as the hashing of PyStringRef
// follow a similar route as the hashing of PyStrRef
Ok(vm.state.hash_secret.hash_str(*self))
}
@@ -492,7 +492,7 @@ impl DictKey for &str {
}
fn key_eq(&self, vm: &VirtualMachine, other_key: &PyObjectRef) -> PyResult<bool> {
if let Some(py_str_value) = other_key.payload::<PyString>() {
if let Some(py_str_value) = other_key.payload::<PyStr>() {
Ok(py_str_value.borrow_value() == *self)
} else {
// Fall back to PyObjectRef implementation.
+9 -9
View File
@@ -1,7 +1,7 @@
use crate::common::cell::PyRwLock;
use crate::function::PyFuncArgs;
use crate::obj::objsingletons::{PyNone, PyNoneRef};
use crate::obj::objstr::{PyString, PyStringRef};
use crate::obj::objstr::{PyStr, PyStrRef};
use crate::obj::objtraceback::PyTracebackRef;
use crate::obj::objtuple::{PyTuple, PyTupleRef};
use crate::obj::objtype::{self, PyClass, PyClassRef};
@@ -131,12 +131,12 @@ impl PyBaseException {
}
#[pymethod(name = "__str__")]
fn str(&self, vm: &VirtualMachine) -> PyStringRef {
fn str(&self, vm: &VirtualMachine) -> PyStrRef {
let str_args = exception_args_as_string(vm, self.args(), true);
match str_args.into_iter().exactly_one() {
Err(i) if i.len() == 0 => PyString::from("").into_ref(vm),
Err(i) if i.len() == 0 => PyStr::from("").into_ref(vm),
Ok(s) => s,
Err(i) => PyString::from(format!("({})", i.format(", "))).into_ref(vm),
Err(i) => PyStr::from(format!("({})", i.format(", "))).into_ref(vm),
}
}
@@ -269,17 +269,17 @@ fn exception_args_as_string(
vm: &VirtualMachine,
varargs: PyTupleRef,
str_single: bool,
) -> Vec<PyStringRef> {
) -> Vec<PyStrRef> {
let varargs = varargs.borrow_value();
match varargs.len() {
0 => vec![],
1 => {
let args0_repr = if str_single {
vm.to_str(&varargs[0])
.unwrap_or_else(|_| PyString::from("<element str() failed>").into_ref(vm))
.unwrap_or_else(|_| PyStr::from("<element str() failed>").into_ref(vm))
} else {
vm.to_repr(&varargs[0])
.unwrap_or_else(|_| PyString::from("<element repr() failed>").into_ref(vm))
.unwrap_or_else(|_| PyStr::from("<element repr() failed>").into_ref(vm))
};
vec![args0_repr]
}
@@ -287,7 +287,7 @@ fn exception_args_as_string(
.iter()
.map(|vararg| {
vm.to_repr(vararg)
.unwrap_or_else(|_| PyString::from("<element repr() failed>").into_ref(vm))
.unwrap_or_else(|_| PyStr::from("<element repr() failed>").into_ref(vm))
})
.collect(),
}
@@ -644,7 +644,7 @@ fn make_arg_getter(idx: usize) -> impl Fn(PyBaseExceptionRef) -> Option<PyObject
move |exc| exc.args.read().borrow_value().get(idx).cloned()
}
fn key_error_str(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyStringRef {
fn key_error_str(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyStrRef {
let args = exc.args();
if args.borrow_value().len() == 1 {
exception_args_as_string(vm, args, false)
+22 -21
View File
@@ -19,7 +19,7 @@ use crate::obj::objgenerator::PyGenerator;
use crate::obj::objiter;
use crate::obj::objlist;
use crate::obj::objslice::PySlice;
use crate::obj::objstr::{self, PyString, PyStringRef};
use crate::obj::objstr::{self, PyStr, PyStrRef};
use crate::obj::objtraceback::PyTraceback;
use crate::obj::objtuple::PyTuple;
use crate::obj::objtype::{self, PyClassRef};
@@ -797,7 +797,7 @@ impl ExecutingFrame<'_> {
if let Some(dict) = module.dict() {
let filter_pred: Box<dyn Fn(&str) -> bool> =
if let Ok(all) = dict.get_item("__all__", vm) {
let all: Vec<PyStringRef> = vm.extract_elements(&all)?;
let all: Vec<PyStrRef> = vm.extract_elements(&all)?;
let all: Vec<String> = all
.into_iter()
.map(|name| name.as_ref().to_owned())
@@ -807,7 +807,7 @@ impl ExecutingFrame<'_> {
Box::new(|name| !name.starts_with('_'))
};
for (k, v) in &dict {
let k = PyStringRef::try_from_object(vm, k)?;
let k = PyStrRef::try_from_object(vm, k)?;
let k = k.as_ref();
if filter_pred(k) {
self.scope.store_name(&vm, k, v);
@@ -1063,23 +1063,24 @@ impl ExecutingFrame<'_> {
PyFuncArgs::new(args, kwarg_names)
}
bytecode::CallType::Ex(has_kwargs) => {
let kwargs =
if *has_kwargs {
let kw_dict: PyDictRef = self.pop_value().downcast().map_err(|_| {
// TODO: check collections.abc.Mapping
vm.new_type_error("Kwargs must be a dict.".to_owned())
})?;
let mut kwargs = IndexMap::new();
for (key, value) in kw_dict.into_iter() {
let key = key.payload_if_subclass::<objstr::PyString>(vm).ok_or_else(
|| vm.new_type_error("keywords must be strings".to_owned()),
)?;
kwargs.insert(key.borrow_value().to_owned(), value);
}
kwargs
} else {
IndexMap::new()
};
let kwargs = if *has_kwargs {
let kw_dict: PyDictRef = self.pop_value().downcast().map_err(|_| {
// TODO: check collections.abc.Mapping
vm.new_type_error("Kwargs must be a dict.".to_owned())
})?;
let mut kwargs = IndexMap::new();
for (key, value) in kw_dict.into_iter() {
let key =
key.payload_if_subclass::<objstr::PyStr>(vm)
.ok_or_else(|| {
vm.new_type_error("keywords must be strings".to_owned())
})?;
kwargs.insert(key.borrow_value().to_owned(), value);
}
kwargs
} else {
IndexMap::new()
};
let args = self.pop_value();
let args = vm.extract_elements(&args)?;
PyFuncArgs { args, kwargs }
@@ -1243,7 +1244,7 @@ impl ExecutingFrame<'_> {
fn execute_make_function(&mut self, vm: &VirtualMachine) -> FrameResult {
let qualified_name = self
.pop_value()
.downcast::<PyString>()
.downcast::<PyStr>()
.expect("qualified name to be a string");
let code_obj: PyCodeRef = self
.pop_value()
+1 -1
View File
@@ -487,7 +487,7 @@ pub type PyNativeFunc = Box<py_dyn_fn!(dyn Fn(&VirtualMachine, PyFuncArgs) -> Py
///
/// For example, anything from `Fn()` to `Fn(vm: &VirtualMachine) -> u32` to
/// `Fn(PyIntRef, PyIntRef) -> String` to
/// `Fn(&self, PyStringRef, FooOptions, vm: &VirtualMachine) -> PyResult<PyInt>`
/// `Fn(&self, PyStrRef, FooOptions, vm: &VirtualMachine) -> PyResult<PyInt>`
/// is `IntoPyNativeFunc`. If you do want a really general function signature, e.g.
/// to forward the args to another function, you can define a function like
/// `Fn(PyFuncArgs [, &VirtualMachine]) -> ...`
+2 -6
View File
@@ -9,7 +9,7 @@ use crate::pyobject::{
use crate::vm::VirtualMachine;
use super::objint::PyInt;
use super::objstr::PyStringRef;
use super::objstr::PyStrRef;
use super::objtype;
impl IntoPyObject for bool {
@@ -92,11 +92,7 @@ impl PyBool {
}
#[pymethod(magic)]
fn format(
obj: PyObjectRef,
format_spec: PyStringRef,
vm: &VirtualMachine,
) -> PyResult<PyStringRef> {
fn format(obj: PyObjectRef, format_spec: PyStrRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
if format_spec.borrow_value().is_empty() {
vm.to_str(&obj)
} else {
+8 -8
View File
@@ -2,7 +2,7 @@ use std::fmt;
use super::objclassmethod::PyClassMethod;
use crate::function::{PyFuncArgs, PyNativeFunc};
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{
PyClassImpl, PyContext, PyObject, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol,
@@ -12,8 +12,8 @@ use crate::vm::VirtualMachine;
pub struct PyFuncDef {
pub func: PyNativeFunc,
pub name: Option<PyStringRef>,
pub doc: Option<PyStringRef>,
pub name: Option<PyStrRef>,
pub doc: Option<PyStrRef>,
}
impl From<PyNativeFunc> for PyFuncDef {
@@ -119,11 +119,11 @@ impl PyBuiltinFunction {
vm.unwrap_or_none(self.module.clone())
}
#[pyproperty(magic)]
fn name(&self) -> Option<PyStringRef> {
fn name(&self) -> Option<PyStrRef> {
self.value.name.clone()
}
#[pyproperty(magic)]
fn doc(&self) -> Option<PyStringRef> {
fn doc(&self) -> Option<PyStrRef> {
self.value.doc.clone()
}
}
@@ -152,7 +152,7 @@ impl From<PyFuncDef> for PyBuiltinMethod {
}
impl PyBuiltinMethod {
pub fn new_with_name(func: PyNativeFunc, name: PyStringRef) -> Self {
pub fn new_with_name(func: PyNativeFunc, name: PyStrRef) -> Self {
Self {
value: PyFuncDef {
func,
@@ -195,11 +195,11 @@ impl Callable for PyBuiltinMethod {
#[pyimpl(with(SlotDescriptor, Callable))]
impl PyBuiltinMethod {
#[pyproperty(magic)]
fn name(&self) -> Option<PyStringRef> {
fn name(&self) -> Option<PyStrRef> {
self.value.name.clone()
}
#[pyproperty(magic)]
fn doc(&self) -> Option<PyStringRef> {
fn doc(&self) -> Option<PyStrRef> {
self.value.doc.clone()
}
}
+3 -3
View File
@@ -6,7 +6,7 @@ use std::mem::size_of;
use super::objint::PyIntRef;
use super::objiter;
use super::objsequence::SequenceIndex;
use super::objstr::PyStringRef;
use super::objstr::PyStrRef;
use super::objtype::PyClassRef;
use crate::bytesinner::{
bytes_decode, ByteInnerFindOptions, ByteInnerNewOptions, ByteInnerPaddingOptions,
@@ -246,7 +246,7 @@ impl PyByteArray {
}
#[pymethod]
fn fromhex(string: PyStringRef, vm: &VirtualMachine) -> PyResult<PyByteArray> {
fn fromhex(string: PyStrRef, vm: &VirtualMachine) -> PyResult<PyByteArray> {
Ok(PyBytesInner::fromhex(string.borrow_value(), vm)?.into())
}
@@ -528,7 +528,7 @@ impl PyByteArray {
}
#[pymethod]
fn decode(zelf: PyRef<Self>, args: DecodeArgs, vm: &VirtualMachine) -> PyResult<PyStringRef> {
fn decode(zelf: PyRef<Self>, args: DecodeArgs, vm: &VirtualMachine) -> PyResult<PyStrRef> {
bytes_decode(zelf.into_object(), args, vm)
}
+3 -3
View File
@@ -6,7 +6,7 @@ use std::ops::Deref;
use super::objint::PyIntRef;
use super::objiter;
use super::objsequence::SequenceIndex;
use super::objstr::PyStringRef;
use super::objstr::PyStrRef;
use super::objtype::PyClassRef;
use crate::bytesinner::{
bytes_decode, ByteInnerFindOptions, ByteInnerNewOptions, ByteInnerPaddingOptions,
@@ -209,7 +209,7 @@ impl PyBytes {
}
#[pymethod]
fn fromhex(string: PyStringRef, vm: &VirtualMachine) -> PyResult<PyBytes> {
fn fromhex(string: PyStrRef, vm: &VirtualMachine) -> PyResult<PyBytes> {
Ok(PyBytesInner::fromhex(string.borrow_value(), vm)?.into())
}
@@ -440,7 +440,7 @@ impl PyBytes {
/// see https://docs.python.org/3/library/codecs.html#standard-encodings
/// currently, only 'utf-8' and 'ascii' emplemented
#[pymethod]
fn decode(zelf: PyRef<Self>, args: DecodeArgs, vm: &VirtualMachine) -> PyResult<PyStringRef> {
fn decode(zelf: PyRef<Self>, args: DecodeArgs, vm: &VirtualMachine) -> PyResult<PyStrRef> {
bytes_decode(zelf.into_object(), args, vm)
}
+2 -2
View File
@@ -2,7 +2,7 @@ use num_complex::Complex64;
use num_traits::Zero;
use super::objfloat;
use super::objstr::PyString;
use super::objstr::PyStr;
use super::objtype::{self, PyClassRef};
use crate::pyobject::{
BorrowValue, IntoPyObject, Never, PyArithmaticValue, PyClassImpl, PyComparisonValue, PyContext,
@@ -229,7 +229,7 @@ impl PyComplex {
Some(obj) => {
if let Some(c) = try_complex(&obj, vm)? {
c
} else if let Some(s) = obj.payload_if_subclass::<PyString>(vm) {
} else if let Some(s) = obj.payload_if_subclass::<PyStr>(vm) {
if args.imag.is_some() {
return Err(vm.new_type_error(
"complex() can't take second arg if first is a string".to_owned(),
+2 -2
View File
@@ -1,6 +1,6 @@
use super::objcode::PyCodeRef;
use super::objcoroinner::{Coro, Variant};
use super::objstr::PyStringRef;
use super::objstr::PyStrRef;
use super::objtype::PyClassRef;
use crate::frame::FrameRef;
use crate::function::OptionalArg;
@@ -90,7 +90,7 @@ impl PyCoroutine {
// TODO: coroutine origin tracking:
// https://docs.python.org/3/library/sys.html#sys.set_coroutine_origin_tracking_depth
#[pyproperty]
fn cr_origin(&self, _vm: &VirtualMachine) -> Option<(PyStringRef, usize, PyStringRef)> {
fn cr_origin(&self, _vm: &VirtualMachine) -> Option<(PyStrRef, usize, PyStrRef)> {
None
}
}
+1 -1
View File
@@ -467,7 +467,7 @@ impl PyDictRef {
// Test if this object is a true dict, or mabye a subclass?
// If it is a dict, we can directly invoke inner_get_item_option,
// and prevent the creation of the KeyError exception.
// Also note, that we prevent the creation of a full PyString object
// Also note, that we prevent the creation of a full PyStr object
// if we lookup local names (which happens all of the time).
if self.lease_class().is(&vm.ctx.types.dict_type) {
// We can take the short path here!
+4 -4
View File
@@ -5,7 +5,7 @@ use num_traits::{pow, ToPrimitive, Zero};
use super::objbytes::PyBytes;
use super::objint::{self, PyInt, PyIntRef};
use super::objstr::{PyString, PyStringRef};
use super::objstr::{PyStr, PyStrRef};
use super::objtype::PyClassRef;
use crate::format::FormatSpec;
use crate::function::{OptionalArg, OptionalOption};
@@ -149,7 +149,7 @@ impl PyFloat {
}
#[pymethod(name = "__format__")]
fn format(&self, spec: PyStringRef, vm: &VirtualMachine) -> PyResult<String> {
fn format(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
match FormatSpec::parse(spec.borrow_value())
.and_then(|format_spec| format_spec.format_float(self.value))
{
@@ -432,7 +432,7 @@ impl PyFloat {
}
#[pymethod]
fn fromhex(repr: PyStringRef, vm: &VirtualMachine) -> PyResult<f64> {
fn fromhex(repr: PyStrRef, vm: &VirtualMachine) -> PyResult<f64> {
float_ops::from_hex(repr.borrow_value().trim()).ok_or_else(|| {
vm.new_value_error("invalid hexadecimal floating-point string".to_owned())
})
@@ -496,7 +496,7 @@ fn to_float(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<f64> {
float.value
} else if let Some(int) = obj.payload_if_subclass::<PyInt>(vm) {
objint::try_float(int.borrow_value(), vm)?
} else if let Some(s) = obj.payload_if_subclass::<PyString>(vm) {
} else if let Some(s) = obj.payload_if_subclass::<PyStr>(vm) {
float_ops::parse_str(s.borrow_value().trim()).ok_or_else(|| {
vm.new_value_error(format!("could not convert string to float: '{}'", s))
})?
+2 -2
View File
@@ -4,7 +4,7 @@
use super::objcode::PyCodeRef;
use super::objdict::PyDictRef;
use super::objstr::PyStringRef;
use super::objstr::PyStrRef;
use crate::frame::FrameRef;
use crate::pyobject::{IdProtocol, PyClassImpl, PyContext, PyObjectRef, PyResult};
use crate::vm::VirtualMachine;
@@ -26,7 +26,7 @@ impl FrameRef {
}
#[pymethod(name = "__delattr__")]
fn delattr(self, value: PyStringRef, vm: &VirtualMachine) {
fn delattr(self, value: PyStrRef, vm: &VirtualMachine) {
// CPython' Frame.f_trace is set to None when deleted.
// The strange behavior is mimicked here make bdb.py happy about it.
if value.to_string() == "f_trace" {
+2 -2
View File
@@ -3,7 +3,7 @@ mod jitfunc;
use super::objcode::PyCodeRef;
use super::objdict::PyDictRef;
use super::objstr::PyStringRef;
use super::objstr::PyStrRef;
use super::objtuple::PyTupleRef;
use super::objtype::PyClassRef;
use crate::bytecode;
@@ -377,7 +377,7 @@ impl PyBoundMethod {
}
#[pymethod(magic)]
fn getattribute(zelf: PyRef<Self>, name: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn getattribute(zelf: PyRef<Self>, name: PyStrRef, vm: &VirtualMachine) -> PyResult {
if let Some(obj) = zelf.get_class_attr(name.borrow_value()) {
return vm.call_if_get_descriptor(obj, zelf.into_object());
}
+6 -6
View File
@@ -12,7 +12,7 @@ use super::objbytearray::PyByteArray;
use super::objbytes::PyBytes;
use super::objfloat;
use super::objmemory::PyMemoryView;
use super::objstr::{PyString, PyStringRef};
use super::objstr::{PyStr, PyStrRef};
use super::objtype::PyClassRef;
use crate::bytesinner::PyBytesInner;
use crate::format::FormatSpec;
@@ -518,7 +518,7 @@ impl PyInt {
}
#[pymethod(name = "__format__")]
fn format(&self, spec: PyStringRef, vm: &VirtualMachine) -> PyResult<String> {
fn format(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
match FormatSpec::parse(spec.borrow_value())
.and_then(|format_spec| format_spec.format_int(&self.value))
{
@@ -702,7 +702,7 @@ struct IntFromByteArgs {
#[pyarg(positional_or_keyword)]
bytes: PyBytesInner,
#[pyarg(positional_or_keyword)]
byteorder: PyStringRef,
byteorder: PyStrRef,
#[pyarg(keyword_only, optional = true)]
signed: OptionalArg<IntoPyBool>,
}
@@ -712,7 +712,7 @@ struct IntToByteArgs {
#[pyarg(positional_or_keyword)]
length: PyIntRef,
#[pyarg(positional_or_keyword)]
byteorder: PyStringRef,
byteorder: PyStrRef,
#[pyarg(keyword_only, optional = true)]
signed: OptionalArg<IntoPyBool>,
}
@@ -721,7 +721,7 @@ struct IntToByteArgs {
pub(crate) fn to_int(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<BigInt> {
let base = 10;
let opt = match_class!(match obj.clone() {
string @ PyString => {
string @ PyStr => {
let s = string.borrow_value();
bytes_to_int(s.as_bytes(), base)
}
@@ -774,7 +774,7 @@ fn to_int_radix(vm: &VirtualMachine, obj: &PyObjectRef, base: u32) -> PyResult<B
debug_assert!(base == 0 || (2..=36).contains(&base));
let opt = match_class!(match obj.clone() {
string @ PyString => {
string @ PyStr => {
let s = string.borrow_value();
bytes_to_int(s.as_bytes(), base)
}
+3 -3
View File
@@ -1,6 +1,6 @@
use super::objdict::PyDict;
use super::objiter;
use super::objstr::PyStringRef;
use super::objstr::PyStrRef;
use super::objtype::PyClassRef;
use crate::function::OptionalArg;
use crate::pyobject::{
@@ -48,7 +48,7 @@ impl PyMappingProxy {
fn get_inner(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<Option<PyObjectRef>> {
let opt = match &self.mapping {
MappingProxyInner::Class(class) => {
let key = PyStringRef::try_from_object(vm, key)?;
let key = PyStrRef::try_from_object(vm, key)?;
class.get_attr(key.borrow_value())
}
MappingProxyInner::Dict(obj) => obj.get_item(key, vm).ok(),
@@ -78,7 +78,7 @@ impl PyMappingProxy {
pub fn contains(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult {
match &self.mapping {
MappingProxyInner::Class(class) => {
let key = PyStringRef::try_from_object(vm, key)?;
let key = PyStrRef::try_from_object(vm, key)?;
Ok(vm.ctx.new_bool(class.has_attr(key.borrow_value())))
}
MappingProxyInner::Dict(obj) => vm._membership(obj.clone(), key),
+6 -9
View File
@@ -1,5 +1,5 @@
use super::objdict::PyDictRef;
use super::objstr::{PyString, PyStringRef};
use super::objstr::{PyStr, PyStrRef};
use super::objtype::PyClassRef;
use crate::function::{OptionalOption, PyFuncArgs};
use crate::pyobject::{
@@ -52,8 +52,8 @@ impl PyModuleRef {
#[pymethod(magic)]
fn init(
self,
name: PyStringRef,
doc: OptionalOption<PyStringRef>,
name: PyStrRef,
doc: OptionalOption<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
debug_assert!(crate::pyobject::TypeProtocol::lease_class(self.as_object())
@@ -72,18 +72,15 @@ impl PyModuleRef {
fn name(self, vm: &VirtualMachine) -> Option<String> {
vm.generic_getattribute_opt(
self.as_object().clone(),
PyString::from("__name__").into_ref(vm),
PyStr::from("__name__").into_ref(vm),
None,
)
.unwrap_or(None)
.and_then(|obj| {
obj.payload::<PyString>()
.map(|s| s.borrow_value().to_owned())
})
.and_then(|obj| obj.payload::<PyStr>().map(|s| s.borrow_value().to_owned()))
}
#[pymethod(magic)]
fn getattribute(self, name: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn getattribute(self, name: PyStrRef, vm: &VirtualMachine) -> PyResult {
vm.generic_getattribute_opt(self.as_object().clone(), name.clone(), None)?
.ok_or_else(|| {
let module_name = if let Some(name) = self.name(vm) {
+6 -10
View File
@@ -1,7 +1,7 @@
use super::objbool;
use super::objdict::{PyDict, PyDictRef};
use super::objlist::PyList;
use super::objstr::PyStringRef;
use super::objstr::PyStrRef;
use super::objtype::PyClassRef;
use crate::common::hash::PyHash;
use crate::function::{OptionalArg, PyFuncArgs};
@@ -132,7 +132,7 @@ impl PyBaseObject {
#[pymethod(magic)]
pub(crate) fn setattr(
obj: PyObjectRef,
attr_name: PyStringRef,
attr_name: PyStrRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
@@ -140,7 +140,7 @@ impl PyBaseObject {
}
#[pymethod(magic)]
fn delattr(obj: PyObjectRef, attr_name: PyStringRef, vm: &VirtualMachine) -> PyResult<()> {
fn delattr(obj: PyObjectRef, attr_name: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
if let Some(attr) = obj.get_class_attr(attr_name.borrow_value()) {
if let Some(descriptor) = attr.get_class_attr("__delete__") {
return vm.invoke(&descriptor, vec![attr, obj]).map(|_| ());
@@ -198,11 +198,7 @@ impl PyBaseObject {
}
#[pymethod(magic)]
fn format(
obj: PyObjectRef,
format_spec: PyStringRef,
vm: &VirtualMachine,
) -> PyResult<PyStringRef> {
fn format(obj: PyObjectRef, format_spec: PyStrRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
if format_spec.borrow_value().is_empty() {
vm.to_str(&obj)
} else {
@@ -245,7 +241,7 @@ impl PyBaseObject {
}
#[pymethod(magic)]
fn getattribute(obj: PyObjectRef, name: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn getattribute(obj: PyObjectRef, name: PyStrRef, vm: &VirtualMachine) -> PyResult {
vm_trace!("object.__getattribute__({:?}, {:?})", obj, name);
vm.generic_getattribute(obj, name)
}
@@ -289,7 +285,7 @@ pub fn object_set_dict(obj: PyObjectRef, dict: PyDictRef, vm: &VirtualMachine) -
#[cfg_attr(feature = "flame-it", flame)]
pub(crate) fn setattr(
obj: PyObjectRef,
attr_name: PyStringRef,
attr_name: PyStrRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
+71 -71
View File
@@ -44,13 +44,13 @@ use rustpython_common::hash;
/// errors defaults to 'strict'."
#[pyclass(module = false, name = "str")]
#[derive(Debug)]
pub struct PyString {
pub struct PyStr {
value: String,
hash: AtomicCell<Option<hash::PyHash>>,
len: AtomicCell<Option<usize>>,
}
impl<'a> BorrowValue<'a> for PyString {
impl<'a> BorrowValue<'a> for PyStr {
type Borrowed = &'a str;
fn borrow_value(&'a self) -> Self::Borrowed {
@@ -58,24 +58,24 @@ impl<'a> BorrowValue<'a> for PyString {
}
}
impl AsRef<str> for PyString {
impl AsRef<str> for PyStr {
fn as_ref(&self) -> &str {
&self.value
}
}
impl<T> From<&T> for PyString
impl<T> From<&T> for PyStr
where
T: AsRef<str> + ?Sized,
{
fn from(s: &T) -> PyString {
fn from(s: &T) -> PyStr {
s.as_ref().to_owned().into()
}
}
impl From<String> for PyString {
fn from(s: String) -> PyString {
PyString {
impl From<String> for PyStr {
fn from(s: String) -> PyStr {
PyStr {
value: s,
hash: AtomicCell::default(),
len: AtomicCell::default(),
@@ -83,30 +83,30 @@ impl From<String> for PyString {
}
}
pub type PyStringRef = PyRef<PyString>;
pub type PyStrRef = PyRef<PyStr>;
impl fmt::Display for PyString {
impl fmt::Display for PyStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.value, f)
}
}
impl TryIntoRef<PyString> for String {
fn try_into_ref(self, vm: &VirtualMachine) -> PyResult<PyRef<PyString>> {
Ok(PyString::from(self).into_ref(vm))
impl TryIntoRef<PyStr> for String {
fn try_into_ref(self, vm: &VirtualMachine) -> PyResult<PyRef<PyStr>> {
Ok(PyStr::from(self).into_ref(vm))
}
}
impl TryIntoRef<PyString> for &str {
fn try_into_ref(self, vm: &VirtualMachine) -> PyResult<PyRef<PyString>> {
Ok(PyString::from(self).into_ref(vm))
impl TryIntoRef<PyStr> for &str {
fn try_into_ref(self, vm: &VirtualMachine) -> PyResult<PyRef<PyStr>> {
Ok(PyStr::from(self).into_ref(vm))
}
}
#[pyclass(module = false, name = "str_iterator")]
#[derive(Debug)]
pub struct PyStringIterator {
pub string: PyStringRef,
pub string: PyStrRef,
position: AtomicCell<usize>,
}
@@ -140,7 +140,7 @@ impl PyStringIterator {
#[derive(Debug)]
pub struct PyStringReverseIterator {
pub position: AtomicCell<isize>,
pub string: PyStringRef,
pub string: PyStrRef,
}
impl PyValue for PyStringReverseIterator {
@@ -173,16 +173,16 @@ struct StrArgs {
#[pyarg(positional_or_keyword, optional = true)]
object: OptionalArg<PyObjectRef>,
#[pyarg(positional_or_keyword, optional = true)]
encoding: OptionalArg<PyStringRef>,
encoding: OptionalArg<PyStrRef>,
#[pyarg(positional_or_keyword, optional = true)]
errors: OptionalArg<PyStringRef>,
errors: OptionalArg<PyStrRef>,
}
#[pyimpl(flags(BASETYPE), with(Hashable, Comparable))]
impl PyString {
impl PyStr {
#[pyslot]
fn tp_new(cls: PyClassRef, args: StrArgs, vm: &VirtualMachine) -> PyResult<PyStringRef> {
let string: PyStringRef = match args.object {
fn tp_new(cls: PyClassRef, args: StrArgs, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let string: PyStrRef = match args.object {
OptionalArg::Present(input) => {
if let OptionalArg::Present(enc) = args.encoding {
vm.decode(input, Some(enc.clone()), args.errors.into_option())?
@@ -200,13 +200,13 @@ impl PyString {
}
}
OptionalArg::Missing => {
PyString::from(String::new()).into_ref_with_type(vm, cls.clone())?
PyStr::from(String::new()).into_ref_with_type(vm, cls.clone())?
}
};
if string.class().is(&cls) {
Ok(string)
} else {
PyString::from(string.borrow_value()).into_ref_with_type(vm, cls)
PyStr::from(string.borrow_value()).into_ref_with_type(vm, cls)
}
}
@@ -225,7 +225,7 @@ impl PyString {
}
#[pymethod(name = "__contains__")]
fn contains(&self, needle: PyStringRef) -> bool {
fn contains(&self, needle: PyStrRef) -> bool {
self.value.contains(&needle.value)
}
@@ -282,7 +282,7 @@ impl PyString {
}
#[pymethod(name = "__str__")]
fn str(zelf: PyRef<Self>) -> PyStringRef {
fn str(zelf: PyRef<Self>) -> PyStrRef {
zelf
}
@@ -435,7 +435,7 @@ impl PyString {
}
#[pymethod]
fn strip(&self, chars: OptionalOption<PyStringRef>) -> String {
fn strip(&self, chars: OptionalOption<PyStrRef>) -> String {
self.value
.py_strip(
chars,
@@ -446,7 +446,7 @@ impl PyString {
}
#[pymethod]
fn lstrip(&self, chars: OptionalOption<PyStringRef>) -> String {
fn lstrip(&self, chars: OptionalOption<PyStrRef>) -> String {
self.value
.py_strip(
chars,
@@ -457,7 +457,7 @@ impl PyString {
}
#[pymethod]
fn rstrip(&self, chars: OptionalOption<PyStringRef>) -> String {
fn rstrip(&self, chars: OptionalOption<PyStrRef>) -> String {
self.value
.py_strip(
chars,
@@ -473,7 +473,7 @@ impl PyString {
args,
"endswith",
"str",
|s, x: &PyStringRef| s.ends_with(x.borrow_value()),
|s, x: &PyStrRef| s.ends_with(x.borrow_value()),
vm,
)
}
@@ -484,7 +484,7 @@ impl PyString {
args,
"startswith",
"str",
|s, x: &PyStringRef| s.starts_with(x.borrow_value()),
|s, x: &PyStrRef| s.starts_with(x.borrow_value()),
vm,
)
}
@@ -497,7 +497,7 @@ impl PyString {
/// If the string starts with the prefix string, return string[len(prefix):]
/// Otherwise, return a copy of the original string.
#[pymethod]
fn removeprefix(&self, pref: PyStringRef) -> String {
fn removeprefix(&self, pref: PyStrRef) -> String {
self.value
.py_removeprefix(&pref.value, pref.value.len(), |s, p| s.starts_with(p))
.to_owned()
@@ -511,7 +511,7 @@ impl PyString {
/// If the string ends with the suffix string, return string[:len(suffix)]
/// Otherwise, return a copy of the original string.
#[pymethod]
fn removesuffix(&self, suff: PyStringRef) -> String {
fn removesuffix(&self, suff: PyStrRef) -> String {
self.value
.py_removesuffix(&suff.value, suff.value.len(), |s, p| s.ends_with(p))
.to_owned()
@@ -579,7 +579,7 @@ impl PyString {
}
#[pymethod(name = "__format__")]
fn format_str(&self, spec: PyStringRef, vm: &VirtualMachine) -> PyResult<String> {
fn format_str(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
match FormatSpec::parse(spec.borrow_value())
.and_then(|format_spec| format_spec.format_string(&self.value))
{
@@ -639,7 +639,7 @@ impl PyString {
}
#[pymethod]
fn replace(&self, old: PyStringRef, new: PyStringRef, count: OptionalArg<isize>) -> String {
fn replace(&self, old: PyStrRef, new: PyStrRef, count: OptionalArg<isize>) -> String {
match count {
OptionalArg::Present(maxcount) if maxcount >= 0 => {
if maxcount == 0 || self.value.is_empty() {
@@ -711,7 +711,7 @@ impl PyString {
}
#[pymethod]
fn join(&self, iterable: PyIterable<PyStringRef>, vm: &VirtualMachine) -> PyResult<String> {
fn join(&self, iterable: PyIterable<PyStrRef>, vm: &VirtualMachine) -> PyResult<String> {
let iter = iterable.iter(vm)?;
self.value.py_join(iter)
}
@@ -750,7 +750,7 @@ impl PyString {
}
#[pymethod]
fn partition(&self, sep: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn partition(&self, sep: PyStrRef, vm: &VirtualMachine) -> PyResult {
let (front, has_mid, back) =
self.value
.py_partition(&sep.value, || self.value.splitn(2, &sep.value), vm)?;
@@ -766,7 +766,7 @@ impl PyString {
}
#[pymethod]
fn rpartition(&self, sep: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn rpartition(&self, sep: PyStrRef, vm: &VirtualMachine) -> PyResult {
let (back, has_mid, front) =
self.value
.py_partition(&sep.value, || self.value.rsplitn(2, &sep.value), vm)?;
@@ -828,7 +828,7 @@ impl PyString {
fn _pad(
&self,
width: isize,
fillchar: OptionalArg<PyStringRef>,
fillchar: OptionalArg<PyStrRef>,
pad: fn(&str, usize, char, usize) -> String,
vm: &VirtualMachine,
) -> PyResult<String> {
@@ -851,7 +851,7 @@ impl PyString {
fn center(
&self,
width: isize,
fillchar: OptionalArg<PyStringRef>,
fillchar: OptionalArg<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult<String> {
self._pad(width, fillchar, PyCommonString::<char>::py_center, vm)
@@ -861,7 +861,7 @@ impl PyString {
fn ljust(
&self,
width: isize,
fillchar: OptionalArg<PyStringRef>,
fillchar: OptionalArg<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult<String> {
self._pad(width, fillchar, PyCommonString::<char>::py_ljust, vm)
@@ -871,7 +871,7 @@ impl PyString {
fn rjust(
&self,
width: isize,
fillchar: OptionalArg<PyStringRef>,
fillchar: OptionalArg<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult<String> {
self._pad(width, fillchar, PyCommonString::<char>::py_rjust, vm)
@@ -927,7 +927,7 @@ impl PyString {
for c in self.value.chars() {
match table.get_item((c as u32).into_pyobject(vm), vm) {
Ok(value) => {
if let Some(text) = value.payload::<PyString>() {
if let Some(text) = value.payload::<PyStr>() {
translated.push_str(&text.value);
} else if let Some(bigint) = value.payload::<PyInt>() {
let ch = bigint
@@ -955,13 +955,13 @@ impl PyString {
#[pymethod]
fn maketrans(
dict_or_str: PyObjectRef,
to_str: OptionalArg<PyStringRef>,
none_str: OptionalArg<PyStringRef>,
to_str: OptionalArg<PyStrRef>,
none_str: OptionalArg<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult {
let new_dict = vm.ctx.new_dict();
if let OptionalArg::Present(to_str) = to_str {
match dict_or_str.downcast::<PyString>() {
match dict_or_str.downcast::<PyStr>() {
Ok(from_str) => {
if to_str.len() == from_str.len() {
for (c1, c2) in from_str.value.chars().zip(to_str.value.chars()) {
@@ -999,7 +999,7 @@ impl PyString {
val,
vm,
)?;
} else if let Some(string) = key.payload::<PyString>() {
} else if let Some(string) = key.payload::<PyStr>() {
if string.len() == 1 {
let num_value = string.value.chars().next().unwrap() as u32;
new_dict.set_item(num_value.into_pyobject(vm), val, vm)?;
@@ -1043,13 +1043,13 @@ impl PyString {
}
}
impl Hashable for PyString {
impl Hashable for PyStr {
fn hash(zelf: &PyRef<Self>, vm: &VirtualMachine) -> PyResult<hash::PyHash> {
Ok(zelf.hash(vm))
}
}
impl Comparable for PyString {
impl Comparable for PyStr {
fn cmp(
zelf: PyRef<Self>,
other: PyObjectRef,
@@ -1069,15 +1069,15 @@ impl Comparable for PyString {
#[derive(FromArgs)]
struct EncodeArgs {
#[pyarg(positional_or_keyword, default = "None")]
encoding: Option<PyStringRef>,
encoding: Option<PyStrRef>,
#[pyarg(positional_or_keyword, default = "None")]
errors: Option<PyStringRef>,
errors: Option<PyStrRef>,
}
pub(crate) fn encode_string(
s: PyStringRef,
encoding: Option<PyStringRef>,
errors: Option<PyStringRef>,
s: PyStrRef,
encoding: Option<PyStrRef>,
errors: Option<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult<PyBytesRef> {
vm.encode(s.into_object(), encoding.clone(), errors)?
@@ -1092,7 +1092,7 @@ pub(crate) fn encode_string(
})
}
impl PyValue for PyString {
impl PyValue for PyStr {
fn class(vm: &VirtualMachine) -> PyClassRef {
vm.ctx.types.str_type.clone()
}
@@ -1118,7 +1118,7 @@ impl IntoPyObject for &String {
impl TryFromObject for std::ffi::CString {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
let s = PyStringRef::try_from_object(vm, obj)?;
let s = PyStrRef::try_from_object(vm, obj)?;
Self::new(s.borrow_value().to_owned())
.map_err(|_| vm.new_value_error("embedded null character".to_owned()))
}
@@ -1128,17 +1128,17 @@ impl TryFromObject for std::ffi::OsString {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
use std::str::FromStr;
let s = PyStringRef::try_from_object(vm, obj)?;
let s = PyStrRef::try_from_object(vm, obj)?;
Ok(std::ffi::OsString::from_str(s.borrow_value()).unwrap())
}
}
type SplitArgs<'a> = pystr::SplitArgs<'a, PyStringRef, str, char>;
type SplitArgs<'a> = pystr::SplitArgs<'a, PyStrRef, str, char>;
#[derive(FromArgs)]
pub struct FindArgs {
#[pyarg(positional_only, optional = false)]
sub: PyStringRef,
sub: PyStrRef,
#[pyarg(positional_only, default = "None")]
start: Option<PyIntRef>,
#[pyarg(positional_only, default = "None")]
@@ -1146,28 +1146,28 @@ pub struct FindArgs {
}
impl FindArgs {
fn get_value(self, len: usize) -> (PyStringRef, std::ops::Range<usize>) {
fn get_value(self, len: usize) -> (PyStrRef, std::ops::Range<usize>) {
let range = adjust_indices(self.start, self.end, len);
(self.sub, range)
}
}
pub fn init(ctx: &PyContext) {
PyString::extend_class(ctx, &ctx.types.str_type);
PyStr::extend_class(ctx, &ctx.types.str_type);
PyStringIterator::extend_class(ctx, &ctx.types.str_iterator_type);
PyStringReverseIterator::extend_class(ctx, &ctx.types.str_reverseiterator_type);
}
pub fn clone_value(obj: &PyObjectRef) -> String {
obj.payload::<PyString>().unwrap().value.clone()
obj.payload::<PyStr>().unwrap().value.clone()
}
pub fn borrow_value(obj: &PyObjectRef) -> &str {
&obj.payload::<PyString>().unwrap().value
&obj.payload::<PyStr>().unwrap().value
}
impl PySliceableSequence for PyString {
impl PySliceableSequence for PyStr {
type Sliced = String;
fn do_slice(&self, range: Range<usize>) -> Self::Sliced {
@@ -1253,7 +1253,7 @@ mod tests {
("Greek ῼitlecases ...", "greek ῳitlecases ..."),
];
for (title, input) in tests {
assert_eq!(PyString::from(input).title().as_str(), title);
assert_eq!(PyStr::from(input).title().as_str(), title);
}
}
@@ -1269,7 +1269,7 @@ mod tests {
];
for s in pos {
assert!(PyString::from(s).istitle());
assert!(PyStr::from(s).istitle());
}
let neg = vec![
@@ -1282,7 +1282,7 @@ mod tests {
"NOT",
];
for s in neg {
assert!(!PyString::from(s).istitle());
assert!(!PyStr::from(s).istitle());
}
}
@@ -1293,14 +1293,14 @@ mod tests {
table.set_item("a", vm.ctx.new_str("🎅"), &vm).unwrap();
table.set_item("b", vm.ctx.none(), &vm).unwrap();
table.set_item("c", vm.ctx.new_str("xda"), &vm).unwrap();
let translated = PyString::maketrans(
let translated = PyStr::maketrans(
table.into_object(),
OptionalArg::Missing,
OptionalArg::Missing,
&vm,
)
.unwrap();
let text = PyString::from("abc");
let text = PyStr::from("abc");
let translated = text.translate(translated, &vm).unwrap();
assert_eq!(translated, "🎅xda".to_owned());
let translated = text.translate(vm.ctx.new_int(3), &vm);
@@ -1312,7 +1312,7 @@ mod tests {
}
}
impl PyCommonStringWrapper<str> for PyStringRef {
impl PyCommonStringWrapper<str> for PyStrRef {
fn as_ref(&self) -> &str {
self.value.as_str()
}
+2 -2
View File
@@ -6,7 +6,7 @@ https://github.com/python/cpython/blob/50b48572d9a90c5bb36e2bef6179548ea927a35a/
*/
use super::objstr::PyStringRef;
use super::objstr::PyStrRef;
use super::objtype::{self, PyClass, PyClassRef};
use crate::function::OptionalArg;
use crate::pyobject::{
@@ -56,7 +56,7 @@ impl PySuper {
}
#[pymethod(name = "__getattribute__")]
fn getattribute(zelf: PyRef<Self>, name: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn getattribute(zelf: PyRef<Self>, name: PyStrRef, vm: &VirtualMachine) -> PyResult {
let (inst, obj_type) = match zelf.obj.clone() {
Some(o) => o,
None => return vm.generic_getattribute(zelf.into_object(), name),
+7 -7
View File
@@ -9,7 +9,7 @@ use super::objlist::PyList;
use super::objmappingproxy::PyMappingProxy;
use super::objobject;
use super::objstaticmethod::PyStaticMethod;
use super::objstr::PyStringRef;
use super::objstr::PyStrRef;
use super::objtuple::PyTuple;
use super::objweakref::PyWeak;
use crate::function::{KwArgs, PyFuncArgs};
@@ -63,7 +63,7 @@ impl PyClassRef {
let module = zelf.attributes.read().get("__module__").cloned();
let new_name = if let Some(module) = module {
// FIXME: "unknown" case is a bug.
let module_str = PyStringRef::try_from_object(vm, module)
let module_str = PyStrRef::try_from_object(vm, module)
.map_or("<unknown>".to_owned(), |m| m.borrow_value().to_owned());
format!("{}.{}", module_str, &zelf.name)
} else {
@@ -261,12 +261,12 @@ impl PyClass {
}
#[pymethod(magic)]
fn prepare(_name: PyStringRef, _bases: PyObjectRef, vm: &VirtualMachine) -> PyDictRef {
fn prepare(_name: PyStrRef, _bases: PyObjectRef, vm: &VirtualMachine) -> PyDictRef {
vm.ctx.new_dict()
}
#[pymethod(magic)]
fn getattribute(zelf: PyRef<Self>, name_ref: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn getattribute(zelf: PyRef<Self>, name_ref: PyStrRef, vm: &VirtualMachine) -> PyResult {
let name = name_ref.borrow_value();
vm_trace!("type.__getattribute__({:?}, {:?})", zelf, name);
let mcl = zelf.lease_class();
@@ -315,7 +315,7 @@ impl PyClass {
#[pymethod(magic)]
fn setattr(
zelf: PyRef<Self>,
attr_name: PyStringRef,
attr_name: PyStrRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
@@ -334,7 +334,7 @@ impl PyClass {
}
#[pymethod(magic)]
fn delattr(zelf: PyRef<Self>, attr_name: PyStringRef, vm: &VirtualMachine) -> PyResult<()> {
fn delattr(zelf: PyRef<Self>, attr_name: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
if let Some(attr) = zelf.get_class_attr(attr_name.borrow_value()) {
if let Some(ref descriptor) = attr.get_class_attr("__delete__") {
return vm
@@ -389,7 +389,7 @@ impl PyClass {
}));
}
let (name, bases, dict, kwargs): (PyStringRef, PyIterable<PyClassRef>, PyDictRef, KwArgs) =
let (name, bases, dict, kwargs): (PyStrRef, PyIterable<PyClassRef>, PyDictRef, KwArgs) =
args.clone().bind(vm)?;
let bases: Vec<PyClassRef> = bases.iter(vm)?.collect::<Result<Vec<_>, _>>()?;
+2 -2
View File
@@ -1,6 +1,6 @@
use crate::exceptions::PyBaseExceptionRef;
use crate::obj::objbytes::PyBytes;
use crate::obj::objstr::PyString;
use crate::obj::objstr::PyStr;
use crate::pyobject::{BorrowValue, PyObjectRef, PyResult};
use crate::VirtualMachine;
use std::{fmt, io};
@@ -41,7 +41,7 @@ pub fn file_readline(obj: &PyObjectRef, size: Option<usize>, vm: &VirtualMachine
)
};
let ret = match_class!(match ret {
s @ PyString => {
s @ PyStr => {
let sval = s.borrow_value();
if sval.is_empty() {
return Err(eof_err());
+5 -5
View File
@@ -214,7 +214,7 @@ impl PyContext {
pub fn new_str<S>(&self, s: S) -> PyObjectRef
where
S: Into<objstr::PyString>,
S: Into<objstr::PyStr>,
{
PyObject::new(s.into(), self.types.str_type.clone(), None)
}
@@ -288,8 +288,8 @@ impl PyContext {
PyFuncDef::from(f.into_func()).build_function(self)
}
pub(crate) fn new_stringref(&self, s: String) -> objstr::PyStringRef {
PyRef::new_ref(objstr::PyString::from(s), self.types.str_type.clone(), None)
pub(crate) fn new_stringref(&self, s: String) -> objstr::PyStrRef {
PyRef::new_ref(objstr::PyStr::from(s), self.types.str_type.clone(), None)
}
pub fn new_function_named<F, FKind>(&self, f: F, name: String) -> PyFuncDef
@@ -1222,10 +1222,10 @@ impl<A: IntoPyObject, B: IntoPyObject> IntoPyObject for Either<A, B> {
///
/// ```
/// use rustpython_vm::VirtualMachine;
/// use rustpython_vm::obj::{objstr::PyStringRef, objint::PyIntRef};
/// use rustpython_vm::obj::{objstr::PyStrRef, objint::PyIntRef};
/// use rustpython_vm::pyobject::Either;
///
/// fn do_something(arg: Either<PyIntRef, PyStringRef>, vm: &VirtualMachine) {
/// fn do_something(arg: Either<PyIntRef, PyStrRef>, vm: &VirtualMachine) {
/// match arg {
/// Either::A(int)=> {
/// // do something with int
+2 -2
View File
@@ -9,7 +9,7 @@ use crate::obj::objiter;
use crate::obj::objlist::PyList;
use crate::obj::objsequence::{get_saturated_pos, PySliceableSequence, PySliceableSequenceMut};
use crate::obj::objslice::PySliceRef;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{
BorrowValue, Either, IdProtocol, IntoPyObject, PyClassImpl, PyComparisonValue, PyIterable,
@@ -479,7 +479,7 @@ impl PyArray {
#[pyslot]
fn tp_new(
cls: PyClassRef,
spec: PyStringRef,
spec: PyStrRef,
init: OptionalArg<PyIterable>,
vm: &VirtualMachine,
) -> PyResult<PyArrayRef> {
+3 -3
View File
@@ -6,7 +6,7 @@ mod decl {
use crate::function::OptionalArg;
use crate::obj::objbytearray::{PyByteArray, PyByteArrayRef};
use crate::obj::objbytes::{PyBytes, PyBytesRef};
use crate::obj::objstr::{PyString, PyStringRef};
use crate::obj::objstr::{PyStr, PyStrRef};
use crate::pyobject::{BorrowValue, PyObjectRef, PyResult, TryFromObject, TypeProtocol};
use crate::vm::VirtualMachine;
use crc::{crc32, Hasher32};
@@ -15,7 +15,7 @@ mod decl {
enum SerializedData {
Bytes(PyBytesRef),
Buffer(PyByteArrayRef),
Ascii(PyStringRef),
Ascii(PyStrRef),
}
impl TryFromObject for SerializedData {
@@ -23,7 +23,7 @@ mod decl {
match_class!(match obj {
b @ PyBytes => Ok(SerializedData::Bytes(b)),
b @ PyByteArray => Ok(SerializedData::Buffer(b)),
a @ PyString => {
a @ PyStr => {
if a.borrow_value().is_ascii() {
Ok(SerializedData::Ascii(a))
} else {
+2 -2
View File
@@ -5,7 +5,7 @@ use std::fmt::{self, Debug, Formatter};
use crate::common::cell::PyRwLock;
use crate::function::PyFuncArgs;
use crate::obj::objiter;
use crate::obj::objstr::{self, PyString};
use crate::obj::objstr::{self, PyStr};
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{
BorrowValue, IntoPyObject, PyClassImpl, PyIterable, PyObjectRef, PyRef, PyResult, PyValue,
@@ -77,7 +77,7 @@ fn into_strings(iterable: &PyIterable<PyObjectRef>, vm: &VirtualMachine) -> PyRe
.iter(vm)?
.map(|py_obj_ref| {
match_class!(match py_obj_ref? {
py_str @ PyString => Ok(py_str.borrow_value().trim().to_owned()),
py_str @ PyStr => Ok(py_str.borrow_value().trim().to_owned()),
obj => {
let msg = format!(
"iterator should return strings, not {} (did you open the file in text mode?)",
+2 -2
View File
@@ -5,7 +5,7 @@ mod decl {
use crate::bytecode::CodeFlags;
use crate::obj::objcode::PyCodeRef;
use crate::obj::objdict::PyDictRef;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::pyobject::{BorrowValue, ItemProtocol, PyObjectRef, PyResult, TryFromObject};
use crate::vm::VirtualMachine;
use rustpython_compiler::compile;
@@ -15,7 +15,7 @@ mod decl {
let co = if let Ok(co) = vm.get_attribute(obj.clone(), "__code__") {
// Method or function:
co
} else if let Ok(co_str) = PyStringRef::try_from_object(vm, obj.clone()) {
} else if let Ok(co_str) = PyStrRef::try_from_object(vm, obj.clone()) {
// String:
vm.compile(
co_str.borrow_value(),
+2 -2
View File
@@ -5,7 +5,7 @@ mod hashlib {
use crate::common::cell::{PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard};
use crate::function::{OptionalArg, PyFuncArgs};
use crate::obj::objbytes::{PyBytes, PyBytesRef};
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{BorrowValue, PyClassImpl, PyResult, PyValue};
use crate::vm::VirtualMachine;
@@ -94,7 +94,7 @@ mod hashlib {
#[pyfunction(name = "new")]
fn hashlib_new(
name: PyStringRef,
name: PyStrRef,
data: OptionalArg<PyBytesRef>,
vm: &VirtualMachine,
) -> PyResult<PyHasher> {
+7 -7
View File
@@ -3,7 +3,7 @@ use crate::obj::objbytes::PyBytesRef;
use crate::obj::objcode::PyCode;
use crate::obj::objmodule::PyModuleRef;
use crate::obj::objstr;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::pyobject::{BorrowValue, ItemProtocol, PyObjectRef, PyResult};
use crate::vm::VirtualMachine;
@@ -49,11 +49,11 @@ fn _imp_extension_suffixes(vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.new_list(vec![]))
}
fn _imp_is_builtin(name: PyStringRef, vm: &VirtualMachine) -> bool {
fn _imp_is_builtin(name: PyStrRef, vm: &VirtualMachine) -> bool {
vm.state.stdlib_inits.contains_key(name.borrow_value())
}
fn _imp_is_frozen(name: PyStringRef, vm: &VirtualMachine) -> bool {
fn _imp_is_frozen(name: PyStrRef, vm: &VirtualMachine) -> bool {
vm.state.frozen.contains_key(name.borrow_value())
}
@@ -76,7 +76,7 @@ fn _imp_exec_builtin(_mod: PyModuleRef) -> i32 {
0
}
fn _imp_get_frozen_object(name: PyStringRef, vm: &VirtualMachine) -> PyResult<PyCode> {
fn _imp_get_frozen_object(name: PyStrRef, vm: &VirtualMachine) -> PyResult<PyCode> {
let name = name.borrow_value();
vm.state
.frozen
@@ -89,11 +89,11 @@ fn _imp_get_frozen_object(name: PyStringRef, vm: &VirtualMachine) -> PyResult<Py
.ok_or_else(|| vm.new_import_error(format!("No such frozen object named {}", name), name))
}
fn _imp_init_frozen(name: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn _imp_init_frozen(name: PyStrRef, vm: &VirtualMachine) -> PyResult {
import::import_frozen(vm, name.borrow_value())
}
fn _imp_is_frozen_package(name: PyStringRef, vm: &VirtualMachine) -> PyResult<bool> {
fn _imp_is_frozen_package(name: PyStrRef, vm: &VirtualMachine) -> PyResult<bool> {
let name = name.borrow_value();
vm.state
.frozen
@@ -102,7 +102,7 @@ fn _imp_is_frozen_package(name: PyStringRef, vm: &VirtualMachine) -> PyResult<bo
.ok_or_else(|| vm.new_import_error(format!("No such frozen object named {}", name), name))
}
fn _imp_fix_co_filename(_code: PyObjectRef, _path: PyStringRef) {
fn _imp_fix_co_filename(_code: PyObjectRef, _path: PyStrRef) {
// TODO:
}
+16 -16
View File
@@ -26,7 +26,7 @@ mod _io {
use crate::obj::objbytes::PyBytesRef;
use crate::obj::objint;
use crate::obj::objiter;
use crate::obj::objstr::{self, PyString, PyStringRef};
use crate::obj::objstr::{self, PyStr, PyStrRef};
use crate::obj::objtype::{self, PyClassRef};
use crate::pyobject::{
BorrowValue, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue,
@@ -610,11 +610,11 @@ mod _io {
#[pyarg(positional_or_keyword, optional = false)]
buffer: PyObjectRef,
#[pyarg(positional_or_keyword, default = "None")]
encoding: Option<PyStringRef>,
encoding: Option<PyStrRef>,
#[pyarg(positional_or_keyword, default = "None")]
errors: Option<PyStringRef>,
errors: Option<PyStrRef>,
#[pyarg(positional_or_keyword, default = "None")]
newline: Option<PyStringRef>,
newline: Option<PyStrRef>,
}
impl TextIOWrapperArgs {
@@ -645,14 +645,14 @@ mod _io {
) -> PyResult<()> {
args.validate_newline(vm)?;
let mut encoding: Option<PyStringRef> = args.encoding.clone();
let mut encoding: Option<PyStrRef> = args.encoding.clone();
let mut self_encoding = None; // TODO: Try os.device_encoding(fileno)
if let (None, None) = (&encoding, &self_encoding) {
// TODO: locale module
self_encoding = Some("utf-8");
}
if let Some(self_encoding) = self_encoding {
encoding = Some(PyString::from(self_encoding).into_ref(vm));
encoding = Some(PyStr::from(self_encoding).into_ref(vm));
} else if let Some(ref encoding) = encoding {
self_encoding = Some(encoding.borrow_value())
} else {
@@ -741,7 +741,7 @@ mod _io {
}
#[pymethod]
fn write(instance: PyObjectRef, obj: PyStringRef, vm: &VirtualMachine) -> PyResult<usize> {
fn write(instance: PyObjectRef, obj: PyStrRef, vm: &VirtualMachine) -> PyResult<usize> {
use std::str::from_utf8;
let buffered_writer_class = vm.try_class("_io", "BufferedWriter")?;
@@ -798,7 +798,7 @@ mod _io {
#[pyarg(positional_or_keyword, default = "None")]
#[allow(dead_code)]
// TODO: use this
newline: Option<PyStringRef>,
newline: Option<PyStrRef>,
}
#[pyclass(name = "StringIO", noattr)]
@@ -864,7 +864,7 @@ mod _io {
impl StringIORef {
//write string to underlying vector
#[pymethod]
fn write(self, data: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn write(self, data: PyStrRef, vm: &VirtualMachine) -> PyResult {
let bytes = data.borrow_value().as_bytes();
match self.buffer(vm)?.write(bytes) {
@@ -1112,7 +1112,7 @@ mod _io {
#[pyfunction]
fn open(
file: PyObjectRef,
mode: OptionalArg<PyStringRef>,
mode: OptionalArg<PyStrRef>,
opts: OpenArgs,
vm: &VirtualMachine,
) -> PyResult {
@@ -1136,11 +1136,11 @@ mod _io {
#[pyarg(positional_or_keyword, default = "-1")]
buffering: isize,
#[pyarg(positional_or_keyword, default = "None")]
encoding: Option<PyStringRef>,
encoding: Option<PyStrRef>,
#[pyarg(positional_or_keyword, default = "None")]
errors: Option<PyStringRef>,
errors: Option<PyStrRef>,
#[pyarg(positional_or_keyword, default = "None")]
newline: Option<PyStringRef>,
newline: Option<PyStrRef>,
#[pyarg(positional_or_keyword, default = "true")]
closefd: bool,
#[pyarg(positional_or_keyword, default = "None")]
@@ -1407,7 +1407,7 @@ mod fileio {
use crate::function::{OptionalArg, PyFuncArgs};
use crate::obj::objbytearray::PyByteArray;
use crate::obj::objint;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{
BorrowValue, BufferProtocol, Either, PyClassImpl, PyObjectRef, PyRef, PyResult, PyValue,
@@ -1451,9 +1451,9 @@ mod fileio {
#[derive(FromArgs)]
struct FileIOArgs {
#[pyarg(positional_only)]
name: Either<PyStringRef, i64>,
name: Either<PyStrRef, i64>,
#[pyarg(positional_or_keyword, default = "None")]
mode: Option<PyStringRef>,
mode: Option<PyStrRef>,
#[pyarg(positional_or_keyword, default = "true")]
closefd: bool,
#[pyarg(positional_or_keyword, default = "None")]
+6 -11
View File
@@ -5,7 +5,7 @@ mod machinery;
mod _json {
use crate::function::PyFuncArgs;
use crate::obj::objiter;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::{objbool, objtype::PyClassRef};
use crate::pyobject::{
BorrowValue, IdProtocol, PyClassImpl, PyObjectRef, PyRef, PyResult, PyValue,
@@ -73,7 +73,7 @@ mod _json {
fn parse(
&self,
s: &str,
pystr: PyStringRef,
pystr: PyStrRef,
idx: usize,
scan_once: PyObjectRef,
vm: &VirtualMachine,
@@ -196,12 +196,7 @@ mod _json {
Some((ret, buf.len()))
}
fn call(
zelf: &PyRef<Self>,
pystr: PyStringRef,
idx: isize,
vm: &VirtualMachine,
) -> PyResult {
fn call(zelf: &PyRef<Self>, pystr: PyStrRef, idx: isize, vm: &VirtualMachine) -> PyResult {
if idx < 0 {
return Err(vm.new_value_error("idx cannot be negative".to_owned()));
}
@@ -224,7 +219,7 @@ mod _json {
impl Callable for JsonScanner {
fn call(zelf: &PyRef<Self>, args: PyFuncArgs, vm: &VirtualMachine) -> PyResult {
let (pystr, idx) = args.bind::<(PyStringRef, isize)>(vm)?;
let (pystr, idx) = args.bind::<(PyStrRef, isize)>(vm)?;
JsonScanner::call(zelf, pystr, idx, vm)
}
}
@@ -239,12 +234,12 @@ mod _json {
}
#[pyfunction]
fn encode_basestring(s: PyStringRef) -> String {
fn encode_basestring(s: PyStrRef) -> String {
encode_string(s.borrow_value(), false)
}
#[pyfunction]
fn encode_basestring_ascii(s: PyStringRef) -> String {
fn encode_basestring_ascii(s: PyStrRef) -> String {
encode_string(s.borrow_value(), true)
}
}
+2 -2
View File
@@ -5,12 +5,12 @@ pub(crate) use decl::make_module;
mod decl {
use rustpython_parser::lexer;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::pyobject::{BorrowValue, PyObjectRef, PyResult};
use crate::vm::VirtualMachine;
#[pyfunction]
fn iskeyword(s: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn iskeyword(s: PyStrRef, vm: &VirtualMachine) -> PyResult {
let keywords = lexer::get_keywords();
let value = keywords.contains_key(s.borrow_value());
let value = vm.ctx.new_bool(value);
+2 -2
View File
@@ -1,6 +1,6 @@
use super::os::errno_err;
use crate::obj::objbytes::PyBytesRef;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::pyobject::{BorrowValue, PyObjectRef, PyResult};
use crate::VirtualMachine;
@@ -40,7 +40,7 @@ fn msvcrt_putch(b: PyBytesRef, vm: &VirtualMachine) -> PyResult<()> {
unsafe { suppress_iph!(_putch(c.into())) };
Ok(())
}
fn msvcrt_putwch(s: PyStringRef, vm: &VirtualMachine) -> PyResult<()> {
fn msvcrt_putwch(s: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
let c = s.borrow_value().chars().exactly_one().map_err(|_| {
vm.new_type_error("putch() argument must be a string of length 1".to_owned())
})?;
+3 -3
View File
@@ -1,6 +1,6 @@
use crate::byteslike::PyBytesLike;
use crate::function::OptionalArg;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::{objiter, objtype};
use crate::pyobject::{BorrowValue, Either, PyObjectRef, PyResult, TypeProtocol};
use crate::VirtualMachine;
@@ -70,8 +70,8 @@ fn timing_safe_cmp(a: &[u8], b: &[u8]) -> bool {
}
fn _operator_compare_digest(
a: Either<PyStringRef, PyBytesLike>,
b: Either<PyStringRef, PyBytesLike>,
a: Either<PyStrRef, PyBytesLike>,
b: Either<PyStrRef, PyBytesLike>,
vm: &VirtualMachine,
) -> PyResult<bool> {
let res = match (a, b) {
+12 -12
View File
@@ -19,7 +19,7 @@ use crate::obj::objdict::PyDictRef;
use crate::obj::objint::{PyInt, PyIntRef};
use crate::obj::objiter;
use crate::obj::objset::PySet;
use crate::obj::objstr::{PyString, PyStringRef};
use crate::obj::objstr::{PyStr, PyStrRef};
use crate::obj::objtuple::PyTupleRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{
@@ -94,7 +94,7 @@ impl TryFromObject for PyPathLike {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
let match1 = |obj: &PyObjectRef| {
let pathlike = match_class!(match obj {
ref l @ PyString => PyPathLike {
ref l @ PyStr => PyPathLike {
path: l.borrow_value().into(),
mode: OutputMode::String,
},
@@ -339,7 +339,7 @@ mod _os {
}
#[pyfunction]
fn error(message: OptionalArg<PyStringRef>, vm: &VirtualMachine) -> PyResult {
fn error(message: OptionalArg<PyStrRef>, vm: &VirtualMachine) -> PyResult {
let msg = message.map_or("".to_owned(), |msg| msg.borrow_value().to_owned());
Err(vm.new_os_error(msg))
@@ -398,7 +398,7 @@ mod _os {
}
#[pyfunction]
fn mkdirs(path: PyStringRef, vm: &VirtualMachine) -> PyResult<()> {
fn mkdirs(path: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
fs::create_dir_all(path.borrow_value()).map_err(|err| err.into_pyexception(vm))
}
@@ -422,8 +422,8 @@ mod _os {
#[pyfunction]
fn putenv(
key: Either<PyStringRef, PyBytesRef>,
value: Either<PyStringRef, PyBytesRef>,
key: Either<PyStrRef, PyBytesRef>,
value: Either<PyStrRef, PyBytesRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
let key: &ffi::OsStr = match key {
@@ -439,7 +439,7 @@ mod _os {
}
#[pyfunction]
fn unsetenv(key: Either<PyStringRef, PyBytesRef>, vm: &VirtualMachine) -> PyResult<()> {
fn unsetenv(key: Either<PyStrRef, PyBytesRef>, vm: &VirtualMachine) -> PyResult<()> {
let key: &ffi::OsStr = match key {
Either::A(ref s) => s.borrow_value().as_ref(),
Either::B(ref b) => bytes_as_osstr(b.borrow_value(), vm)?,
@@ -1478,7 +1478,7 @@ mod posix {
}
#[pyfunction]
fn system(command: PyStringRef) -> PyResult<i32> {
fn system(command: PyStrRef) -> PyResult<i32> {
use std::ffi::CString;
let rstr = command.borrow_value();
@@ -1508,7 +1508,7 @@ mod posix {
#[pyfunction]
fn execv(
path: PyStringRef,
path: PyStrRef,
argv: Either<PyListRef, PyTupleRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
@@ -1856,7 +1856,7 @@ mod posix {
target_os = "openbsd"
))]
#[pyfunction]
fn initgroups(user_name: PyStringRef, gid: u32, vm: &VirtualMachine) -> PyResult<()> {
fn initgroups(user_name: PyStrRef, gid: u32, vm: &VirtualMachine) -> PyResult<()> {
let user = ffi::CString::new(user_name.borrow_value()).unwrap();
let gid = Gid::from_raw(gid);
unistd::initgroups(&user, gid).map_err(|err| err.into_pyexception(vm))
@@ -2506,7 +2506,7 @@ mod nt {
#[cfg(target_env = "msvc")]
#[pyfunction]
fn execv(
path: PyStringRef,
path: PyStrRef,
argv: Either<PyListRef, PyTupleRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
@@ -2589,7 +2589,7 @@ mod minor {
}
#[pyfunction]
pub(super) fn access(_path: PyStringRef, _mode: u8, vm: &VirtualMachine) -> PyResult<bool> {
pub(super) fn access(_path: PyStrRef, _mode: u8, vm: &VirtualMachine) -> PyResult<bool> {
os_unimpl("os.access", vm)
}
+2 -2
View File
@@ -1,6 +1,6 @@
use crate::exceptions::IntoPyException;
use crate::obj::objint::PyIntRef;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::pyobject::{BorrowValue, PyClassImpl, PyObjectRef, PyResult, PyStructSequence};
use crate::vm::VirtualMachine;
use std::convert::TryFrom;
@@ -46,7 +46,7 @@ impl From<User> for Passwd {
}
}
fn pwd_getpwnam(name: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn pwd_getpwnam(name: PyStrRef, vm: &VirtualMachine) -> PyResult {
match User::from_name(name.borrow_value()).map_err(|err| err.into_pyexception(vm))? {
Some(user) => Ok(Passwd::from(user)
.into_struct_sequence(vm, vm.try_class("pwd", "struct_passwd")?)?
+12 -12
View File
@@ -26,7 +26,7 @@ mod _struct {
use crate::exceptions::PyBaseExceptionRef;
use crate::function::Args;
use crate::obj::{
objbool::IntoPyBool, objbytes::PyBytesRef, objiter, objstr::PyString, objstr::PyStringRef,
objbool::IntoPyBool, objbytes::PyBytesRef, objiter, objstr::PyStr, objstr::PyStrRef,
objtuple::PyTuple, objtype::PyClassRef,
};
use crate::pyobject::{
@@ -90,7 +90,7 @@ mod _struct {
impl FormatSpec {
fn decode_and_parse(
vm: &VirtualMachine,
fmt: &Either<PyStringRef, PyBytesRef>,
fmt: &Either<PyStrRef, PyBytesRef>,
) -> PyResult<FormatSpec> {
let decoded_fmt = match fmt {
Either::A(string) => string.borrow_value(),
@@ -532,7 +532,7 @@ mod _struct {
#[pyfunction]
fn pack(
fmt: Either<PyStringRef, PyBytesRef>,
fmt: Either<PyStrRef, PyBytesRef>,
args: Args,
vm: &VirtualMachine,
) -> PyResult<Vec<u8>> {
@@ -542,7 +542,7 @@ mod _struct {
#[pyfunction]
fn pack_into(
fmt: Either<PyStringRef, PyBytesRef>,
fmt: Either<PyStrRef, PyBytesRef>,
buffer: PyRwBytesLike,
offset: isize,
args: Args,
@@ -711,7 +711,7 @@ mod _struct {
#[pyfunction]
fn unpack(
fmt: Either<PyStringRef, PyBytesRef>,
fmt: Either<PyStrRef, PyBytesRef>,
buffer: PyBytesLike,
vm: &VirtualMachine,
) -> PyResult<PyTuple> {
@@ -775,7 +775,7 @@ mod _struct {
#[pyfunction]
fn unpack_from(
fmt: Either<PyStringRef, PyBytesRef>,
fmt: Either<PyStrRef, PyBytesRef>,
args: UpdateFromArgs,
vm: &VirtualMachine,
) -> PyResult<PyTuple> {
@@ -857,7 +857,7 @@ mod _struct {
#[pyfunction]
fn iter_unpack(
fmt: Either<PyStringRef, PyBytesRef>,
fmt: Either<PyStrRef, PyBytesRef>,
buffer: PyBytesLike,
vm: &VirtualMachine,
) -> PyResult<UnpackIterator> {
@@ -866,7 +866,7 @@ mod _struct {
}
#[pyfunction]
fn calcsize(fmt: Either<PyStringRef, PyBytesRef>, vm: &VirtualMachine) -> PyResult<usize> {
fn calcsize(fmt: Either<PyStrRef, PyBytesRef>, vm: &VirtualMachine) -> PyResult<usize> {
let format_spec = FormatSpec::decode_and_parse(vm, &fmt)?;
Ok(format_spec.size())
}
@@ -876,7 +876,7 @@ mod _struct {
#[derive(Debug)]
struct PyStruct {
spec: FormatSpec,
fmt_str: PyStringRef,
fmt_str: PyStrRef,
}
impl PyValue for PyStruct {
@@ -890,20 +890,20 @@ mod _struct {
#[pyslot]
fn tp_new(
cls: PyClassRef,
fmt: Either<PyStringRef, PyBytesRef>,
fmt: Either<PyStrRef, PyBytesRef>,
vm: &VirtualMachine,
) -> PyResult<PyRef<Self>> {
let spec = FormatSpec::decode_and_parse(vm, &fmt)?;
let fmt_str = match fmt {
Either::A(s) => s,
Either::B(b) => PyString::from(std::str::from_utf8(b.borrow_value()).unwrap())
Either::B(b) => PyStr::from(std::str::from_utf8(b.borrow_value()).unwrap())
.into_ref_with_type(vm, vm.ctx.types.str_type.clone())?,
};
PyStruct { spec, fmt_str }.into_ref_with_type(vm, cls)
}
#[pyproperty]
fn format(&self) -> PyStringRef {
fn format(&self) -> PyStrRef {
self.fmt_str.clone()
}
+28 -33
View File
@@ -11,7 +11,7 @@ use std::ops::Range;
use crate::function::{Args, OptionalArg};
use crate::obj::objint::{PyInt, PyIntRef};
use crate::obj::objstr::{PyString, PyStringRef};
use crate::obj::objstr::{PyStr, PyStrRef};
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{
BorrowValue, IntoPyObject, PyClassImpl, PyObjectRef, PyResult, PyValue, TryFromObject,
@@ -73,7 +73,7 @@ impl PyValue for PyPattern {
/// Inner data for a match object.
#[pyclass(module = "re", name = "Match")]
struct PyMatch {
haystack: PyStringRef,
haystack: PyStrRef,
captures: Vec<Option<Range<usize>>>,
}
@@ -93,8 +93,8 @@ impl PyValue for PyMatch {
// type PyMatchRef = PyRef<PyMatch>;
fn re_match(
pattern: PyStringRef,
string: PyStringRef,
pattern: PyStrRef,
string: PyStrRef,
flags: OptionalArg<usize>,
vm: &VirtualMachine,
) -> PyResult<Option<PyMatch>> {
@@ -104,8 +104,8 @@ fn re_match(
}
fn re_search(
pattern: PyStringRef,
string: PyStringRef,
pattern: PyStrRef,
string: PyStrRef,
flags: OptionalArg<usize>,
vm: &VirtualMachine,
) -> PyResult<Option<PyMatch>> {
@@ -115,9 +115,9 @@ fn re_search(
}
fn re_sub(
pattern: PyStringRef,
repl: PyStringRef,
string: PyStringRef,
pattern: PyStrRef,
repl: PyStrRef,
string: PyStrRef,
count: OptionalArg<usize>,
flags: OptionalArg<usize>,
vm: &VirtualMachine,
@@ -129,8 +129,8 @@ fn re_sub(
}
fn re_findall(
pattern: PyStringRef,
string: PyStringRef,
pattern: PyStrRef,
string: PyStrRef,
flags: OptionalArg<usize>,
vm: &VirtualMachine,
) -> PyResult {
@@ -140,8 +140,8 @@ fn re_findall(
}
fn re_split(
pattern: PyStringRef,
string: PyStringRef,
pattern: PyStrRef,
string: PyStrRef,
maxsplit: OptionalArg<PyIntRef>,
flags: OptionalArg<usize>,
vm: &VirtualMachine,
@@ -151,12 +151,7 @@ fn re_split(
do_split(vm, &regex, string, maxsplit.into_option())
}
fn do_sub(
pattern: &PyPattern,
repl: PyStringRef,
search_text: PyStringRef,
limit: usize,
) -> String {
fn do_sub(pattern: &PyPattern, repl: PyStrRef, search_text: PyStrRef, limit: usize) -> String {
let out = pattern.regex.replacen(
search_text.borrow_value().as_bytes(),
limit,
@@ -165,7 +160,7 @@ fn do_sub(
String::from_utf8_lossy(&out).into_owned()
}
fn do_match(pattern: &PyPattern, search_text: PyStringRef) -> Option<PyMatch> {
fn do_match(pattern: &PyPattern, search_text: PyStrRef) -> Option<PyMatch> {
// I really wish there was a better way to do this; I don't think there is
let mut regex_text = r"\A".to_owned();
regex_text.push_str(pattern.regex.as_str());
@@ -175,14 +170,14 @@ fn do_match(pattern: &PyPattern, search_text: PyStringRef) -> Option<PyMatch> {
.map(|captures| create_match(search_text.clone(), captures))
}
fn do_search(regex: &PyPattern, search_text: PyStringRef) -> Option<PyMatch> {
fn do_search(regex: &PyPattern, search_text: PyStrRef) -> Option<PyMatch> {
regex
.regex
.captures(search_text.borrow_value().as_bytes())
.map(|captures| create_match(search_text.clone(), captures))
}
fn do_findall(vm: &VirtualMachine, pattern: &PyPattern, search_text: PyStringRef) -> PyResult {
fn do_findall(vm: &VirtualMachine, pattern: &PyPattern, search_text: PyStrRef) -> PyResult {
let out = pattern
.regex
.captures_iter(search_text.borrow_value().as_bytes())
@@ -218,7 +213,7 @@ fn do_findall(vm: &VirtualMachine, pattern: &PyPattern, search_text: PyStringRef
fn do_split(
vm: &VirtualMachine,
pattern: &PyPattern,
search_text: PyStringRef,
search_text: PyStrRef,
maxsplit: Option<PyIntRef>,
) -> PyResult {
if maxsplit
@@ -283,7 +278,7 @@ fn make_regex(vm: &VirtualMachine, pattern: &str, flags: PyRegexFlags) -> PyResu
}
/// Take a found regular expression and convert it to proper match object.
fn create_match(haystack: PyStringRef, captures: Captures) -> PyMatch {
fn create_match(haystack: PyStrRef, captures: Captures) -> PyMatch {
let captures = captures
.iter()
.map(|opt| opt.map(|m| m.start()..m.end()))
@@ -299,7 +294,7 @@ fn extract_flags(flags: OptionalArg<usize>) -> PyRegexFlags {
}
fn re_compile(
pattern: PyStringRef,
pattern: PyStrRef,
flags: OptionalArg<usize>,
vm: &VirtualMachine,
) -> PyResult<PyPattern> {
@@ -307,7 +302,7 @@ fn re_compile(
make_regex(vm, pattern.borrow_value(), flags)
}
fn re_escape(pattern: PyStringRef) -> String {
fn re_escape(pattern: PyStrRef) -> String {
regex::escape(pattern.borrow_value())
}
@@ -316,17 +311,17 @@ fn re_purge(_vm: &VirtualMachine) {}
#[pyimpl]
impl PyPattern {
#[pymethod(name = "match")]
fn match_(&self, text: PyStringRef) -> Option<PyMatch> {
fn match_(&self, text: PyStrRef) -> Option<PyMatch> {
do_match(self, text)
}
#[pymethod(name = "search")]
fn search(&self, text: PyStringRef) -> Option<PyMatch> {
fn search(&self, text: PyStrRef) -> Option<PyMatch> {
do_search(self, text)
}
#[pymethod(name = "sub")]
fn sub(&self, repl: PyStringRef, text: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn sub(&self, repl: PyStrRef, text: PyStrRef, vm: &VirtualMachine) -> PyResult {
let replaced_text = self.regex.replace_all(
text.borrow_value().as_bytes(),
repl.borrow_value().as_bytes(),
@@ -336,7 +331,7 @@ impl PyPattern {
}
#[pymethod(name = "subn")]
fn subn(&self, repl: PyStringRef, text: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn subn(&self, repl: PyStrRef, text: PyStrRef, vm: &VirtualMachine) -> PyResult {
self.sub(repl, text, vm)
}
@@ -348,7 +343,7 @@ impl PyPattern {
#[pymethod]
fn split(
&self,
search_text: PyStringRef,
search_text: PyStrRef,
maxsplit: OptionalArg<PyIntRef>,
vm: &VirtualMachine,
) -> PyResult {
@@ -356,7 +351,7 @@ impl PyPattern {
}
#[pymethod]
fn findall(&self, search_text: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn findall(&self, search_text: PyStrRef, vm: &VirtualMachine) -> PyResult {
do_findall(vm, self, search_text)
}
}
@@ -395,7 +390,7 @@ impl PyMatch {
.ok_or_else(|| vm.new_index_error("No such group".to_owned()))?;
Ok(capture.clone())
}
_s @ PyString => unimplemented!(),
_s @ PyStr => unimplemented!(),
_ => Err(vm.new_index_error("No such group".to_owned())),
})
}
+13 -13
View File
@@ -15,7 +15,7 @@ use crate::exceptions::{IntoPyException, PyBaseExceptionRef};
use crate::function::{OptionalArg, PyFuncArgs};
use crate::obj::objbytearray::PyByteArrayRef;
use crate::obj::objbytes::PyBytesRef;
use crate::obj::objstr::{PyString, PyStringRef};
use crate::obj::objstr::{PyStr, PyStrRef};
use crate::obj::objtuple::PyTupleRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{
@@ -428,7 +428,7 @@ impl io::Write for PySocketRef {
}
struct Address {
host: PyStringRef,
host: PyStrRef,
port: u16,
}
@@ -445,9 +445,9 @@ impl TryFromObject for Address {
if tuple.borrow_value().len() != 2 {
Err(vm.new_type_error("Address tuple should have only 2 values".to_owned()))
} else {
let host = PyStringRef::try_from_object(vm, tuple.borrow_value()[0].clone())?;
let host = PyStrRef::try_from_object(vm, tuple.borrow_value()[0].clone())?;
let host = if host.borrow_value().is_empty() {
PyString::from("0.0.0.0").into_ref(vm)
PyStr::from("0.0.0.0").into_ref(vm)
} else {
host
};
@@ -478,11 +478,11 @@ fn socket_gethostname(vm: &VirtualMachine) -> PyResult {
}
#[cfg(all(unix, not(target_os = "redox")))]
fn socket_sethostname(hostname: PyStringRef, vm: &VirtualMachine) -> PyResult<()> {
fn socket_sethostname(hostname: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
sethostname(hostname.borrow_value()).map_err(|err| err.into_pyexception(vm))
}
fn socket_inet_aton(ip_string: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn socket_inet_aton(ip_string: PyStrRef, vm: &VirtualMachine) -> PyResult {
ip_string
.borrow_value()
.parse::<Ipv4Addr>()
@@ -501,9 +501,9 @@ fn socket_inet_ntoa(packed_ip: PyBytesRef, vm: &VirtualMachine) -> PyResult {
#[derive(FromArgs)]
struct GAIOptions {
#[pyarg(positional_only)]
host: Option<PyStringRef>,
host: Option<PyStrRef>,
#[pyarg(positional_only)]
port: Option<Either<PyStringRef, i32>>,
port: Option<Either<PyStrRef, i32>>,
#[pyarg(positional_only, default = "0")]
family: i32,
@@ -557,7 +557,7 @@ fn socket_getaddrinfo(opts: GAIOptions, vm: &VirtualMachine) -> PyResult {
#[cfg(not(target_os = "redox"))]
fn socket_gethostbyaddr(
addr: PyStringRef,
addr: PyStrRef,
vm: &VirtualMachine,
) -> PyResult<(String, PyObjectRef, PyObjectRef)> {
// TODO: figure out how to do this properly
@@ -577,10 +577,10 @@ fn socket_gethostbyaddr(
}
#[cfg(not(target_os = "redox"))]
fn socket_gethostbyname(name: PyStringRef, vm: &VirtualMachine) -> PyResult<String> {
fn socket_gethostbyname(name: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
match socket_gethostbyaddr(name, vm) {
Ok((_, _, hosts)) => {
let lst = vm.extract_elements::<PyStringRef>(&hosts)?;
let lst = vm.extract_elements::<PyStrRef>(&hosts)?;
Ok(lst.get(0).unwrap().to_string())
}
Err(_) => {
@@ -593,7 +593,7 @@ fn socket_gethostbyname(name: PyStringRef, vm: &VirtualMachine) -> PyResult<Stri
}
}
fn socket_inet_pton(af_inet: i32, ip_string: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn socket_inet_pton(af_inet: i32, ip_string: PyStrRef, vm: &VirtualMachine) -> PyResult {
match af_inet {
c::AF_INET => ip_string
.borrow_value()
@@ -643,7 +643,7 @@ fn socket_inet_ntop(af_inet: i32, packed_ip: PyBytesRef, vm: &VirtualMachine) ->
}
}
fn socket_getprotobyname(name: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn socket_getprotobyname(name: PyStrRef, vm: &VirtualMachine) -> PyResult {
use std::ffi::CString;
let cstr = CString::new(name.borrow_value())
.map_err(|_| vm.new_value_error("embedded null character".to_owned()))?;
+8 -8
View File
@@ -4,7 +4,7 @@ use crate::common::cell::{PyRwLock, PyRwLockWriteGuard};
use crate::exceptions::{IntoPyException, PyBaseExceptionRef};
use crate::function::OptionalArg;
use crate::obj::objbytearray::PyByteArrayRef;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::{objtype::PyClassRef, objweakref::PyWeak};
use crate::pyobject::{
BorrowValue, Either, IntoPyObject, ItemProtocol, PyClassImpl, PyObjectRef, PyRef, PyResult,
@@ -112,7 +112,7 @@ fn obj2py(obj: &Asn1ObjectRef) -> PyNid {
}
#[cfg(windows)]
fn ssl_enum_certificates(store_name: PyStringRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
fn ssl_enum_certificates(store_name: PyStrRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
use crate::obj::objset::PyFrozenSet;
use schannel::{cert_context::ValidUses, cert_store::CertStore, RawPointer};
use winapi::um::wincrypt;
@@ -194,7 +194,7 @@ fn ssl_rand_status() -> i32 {
unsafe { sys::RAND_status() }
}
fn ssl_rand_add(string: Either<PyStringRef, PyBytesLike>, entropy: f64) {
fn ssl_rand_add(string: Either<PyStrRef, PyBytesLike>, entropy: f64) {
let f = |b: &[u8]| {
for buf in b.chunks(libc::c_int::max_value() as usize) {
unsafe { sys::RAND_add(buf.as_ptr() as *const _, buf.len() as _, entropy) }
@@ -315,7 +315,7 @@ impl PySslContext {
}
#[pymethod]
fn set_ciphers(&self, cipherlist: PyStringRef, vm: &VirtualMachine) -> PyResult<()> {
fn set_ciphers(&self, cipherlist: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
let ciphers = cipherlist.borrow_value();
if ciphers.contains('\0') {
return Err(vm.new_value_error("embedded null character".to_owned()));
@@ -487,7 +487,7 @@ struct WrapSocketArgs {
#[pyarg(positional_or_keyword)]
server_side: bool,
#[pyarg(positional_or_keyword, default = "None")]
server_hostname: Option<PyStringRef>,
server_hostname: Option<PyStrRef>,
#[pyarg(keyword_only, default = "None")]
owner: Option<PyObjectRef>,
#[pyarg(keyword_only, default = "None")]
@@ -501,7 +501,7 @@ struct LoadVerifyLocationsArgs {
#[pyarg(positional_or_keyword, default = "None")]
capath: Option<CString>,
#[pyarg(positional_or_keyword, default = "None")]
cadata: Option<Either<PyStringRef, PyBytesLike>>,
cadata: Option<Either<PyStrRef, PyBytesLike>>,
}
#[pyclass(module = "ssl", name = "_SSLSocket")]
@@ -509,7 +509,7 @@ struct PySslSocket {
ctx: PyRef<PySslContext>,
stream: PyRwLock<Option<ssl::SslStreamBuilder<PySocketRef>>>,
socket_type: SslServerOrClient,
server_hostname: Option<PyStringRef>,
server_hostname: Option<PyStrRef>,
owner: PyRwLock<Option<PyWeak>>,
}
@@ -560,7 +560,7 @@ impl PySslSocket {
self.ctx.clone()
}
#[pyproperty]
fn server_hostname(&self) -> Option<PyStringRef> {
fn server_hostname(&self) -> Option<PyStrRef> {
self.server_hostname.clone()
}
+3 -3
View File
@@ -12,7 +12,7 @@ mod _string {
FieldName, FieldNamePart, FieldType, FormatPart, FormatString, FromTemplate,
};
use crate::obj::objlist::PyList;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::pyobject::{BorrowValue, IntoPyObject, PyObjectRef, PyResult};
use crate::vm::VirtualMachine;
@@ -33,7 +33,7 @@ mod _string {
}
#[pyfunction]
fn formatter_parser(text: PyStringRef, vm: &VirtualMachine) -> PyResult<PyList> {
fn formatter_parser(text: PyStrRef, vm: &VirtualMachine) -> PyResult<PyList> {
let format_string =
FormatString::from_str(text.borrow_value()).map_err(|e| e.into_pyexception(vm))?;
@@ -71,7 +71,7 @@ mod _string {
#[pyfunction]
fn formatter_field_name_split(
text: PyStringRef,
text: PyStrRef,
vm: &VirtualMachine,
) -> PyResult<(PyObjectRef, PyList)> {
let field_name =
+5 -5
View File
@@ -4,7 +4,7 @@ pub(crate) use decl::make_module;
mod decl {
use std::fmt;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{BorrowValue, PyClassImpl, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;
@@ -15,9 +15,9 @@ mod decl {
/// See docs: https://docs.python.org/3/library/symtable.html?highlight=symtable#symtable.symtable
#[pyfunction]
fn symtable(
source: PyStringRef,
filename: PyStringRef,
mode: PyStringRef,
source: PyStrRef,
filename: PyStrRef,
mode: PyStrRef,
vm: &VirtualMachine,
) -> PyResult<PySymbolTableRef> {
let mode = mode
@@ -106,7 +106,7 @@ mod decl {
}
#[pymethod(name = "lookup")]
fn lookup(&self, name: PyStringRef, vm: &VirtualMachine) -> PyResult<PySymbolRef> {
fn lookup(&self, name: PyStrRef, vm: &VirtualMachine) -> PyResult<PySymbolRef> {
let name = name.borrow_value();
if let Some(symbol) = self.symtable.symbols.get(name) {
Ok(PySymbol {
+4 -4
View File
@@ -2,7 +2,7 @@
use crate::exceptions::{self, IntoPyException};
use crate::function::{Args, KwArgs, OptionalArg, PyFuncArgs};
use crate::obj::objdict::PyDictRef;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::objtuple::PyTupleRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{
@@ -311,7 +311,7 @@ impl PyLocal {
}
#[pymethod(magic)]
fn getattribute(zelf: PyRef<Self>, attr: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn getattribute(zelf: PyRef<Self>, attr: PyStrRef, vm: &VirtualMachine) -> PyResult {
let ldict = zelf.ldict(vm);
if attr.borrow_value() == "__dict__" {
Ok(ldict.into_object())
@@ -327,7 +327,7 @@ impl PyLocal {
#[pymethod(magic)]
fn setattr(
zelf: PyRef<Self>,
attr: PyStringRef,
attr: PyStrRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
@@ -343,7 +343,7 @@ impl PyLocal {
}
#[pymethod(magic)]
fn delattr(zelf: PyRef<Self>, attr: PyStringRef, vm: &VirtualMachine) -> PyResult<()> {
fn delattr(zelf: PyRef<Self>, attr: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
if attr.borrow_value() == "__dict__" {
Err(vm.new_attribute_error(format!(
"{} attribute '__dict__' is read-only",
+3 -11
View File
@@ -8,7 +8,7 @@ use chrono::naive::{NaiveDate, NaiveDateTime, NaiveTime};
use chrono::{Datelike, Timelike};
use crate::function::OptionalArg;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::objtuple::PyTupleRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{
@@ -144,11 +144,7 @@ fn time_ctime(secs: OptionalArg<Either<f64, i64>>, vm: &VirtualMachine) -> PyRes
Ok(instant.format(&CFMT).to_string())
}
fn time_strftime(
format: PyStringRef,
t: OptionalArg<PyStructTime>,
vm: &VirtualMachine,
) -> PyResult {
fn time_strftime(format: PyStrRef, t: OptionalArg<PyStructTime>, vm: &VirtualMachine) -> PyResult {
let default = chrono::offset::Local::now().naive_local();
let instant = match t {
OptionalArg::Present(t) => t.to_date_time(vm)?,
@@ -158,11 +154,7 @@ fn time_strftime(
Ok(vm.ctx.new_str(formatted_time))
}
fn time_strptime(
string: PyStringRef,
format: OptionalArg<PyStringRef>,
vm: &VirtualMachine,
) -> PyResult {
fn time_strptime(string: PyStrRef, format: OptionalArg<PyStrRef>, vm: &VirtualMachine) -> PyResult {
let format = match format {
OptionalArg::Present(ref format) => format.borrow_value(),
OptionalArg::Missing => "%a %b %H:%M:%S %Y",
+2 -2
View File
@@ -8,13 +8,13 @@ pub(crate) use decl::make_module;
mod decl {
use std::iter::FromIterator;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::pyobject::{BorrowValue, PyResult};
use crate::vm::VirtualMachine;
use rustpython_parser::lexer;
#[pyfunction]
fn tokenize(s: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn tokenize(s: PyStrRef, vm: &VirtualMachine) -> PyResult {
let source = s.borrow_value();
// TODO: implement generator when the time has come.
+7 -12
View File
@@ -3,7 +3,7 @@
*/
use crate::function::OptionalArg;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{BorrowValue, PyClassImpl, PyObject, PyObjectRef, PyResult, PyValue};
use crate::vm::VirtualMachine;
@@ -81,7 +81,7 @@ impl PyUCD {
Age::of(c).map_or(false, |age| age.actual() <= self.unic_version)
}
fn extract_char(&self, character: PyStringRef, vm: &VirtualMachine) -> PyResult<Option<char>> {
fn extract_char(&self, character: PyStrRef, vm: &VirtualMachine) -> PyResult<Option<char>> {
let c = character
.borrow_value()
.chars()
@@ -98,7 +98,7 @@ impl PyUCD {
}
#[pymethod]
fn category(&self, character: PyStringRef, vm: &VirtualMachine) -> PyResult<String> {
fn category(&self, character: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
Ok(self
.extract_char(character, vm)?
.map_or(GeneralCategory::Unassigned, GeneralCategory::of)
@@ -107,7 +107,7 @@ impl PyUCD {
}
#[pymethod]
fn lookup(&self, name: PyStringRef, vm: &VirtualMachine) -> PyResult<String> {
fn lookup(&self, name: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
if let Some(character) = unicode_names2::character(name.borrow_value()) {
if self.check_age(character) {
return Ok(character.to_string());
@@ -119,7 +119,7 @@ impl PyUCD {
#[pymethod]
fn name(
&self,
character: PyStringRef,
character: PyStrRef,
default: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult {
@@ -139,7 +139,7 @@ impl PyUCD {
}
#[pymethod]
fn bidirectional(&self, character: PyStringRef, vm: &VirtualMachine) -> PyResult<String> {
fn bidirectional(&self, character: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
let bidi = match self.extract_char(character, vm)? {
Some(c) => BidiClass::of(c).abbr_name(),
None => "",
@@ -148,12 +148,7 @@ impl PyUCD {
}
#[pymethod]
fn normalize(
&self,
form: PyStringRef,
unistr: PyStringRef,
vm: &VirtualMachine,
) -> PyResult<String> {
fn normalize(&self, form: PyStrRef, unistr: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
let text = unistr.borrow_value();
let normalized_text = match form.borrow_value() {
"NFC" => text.nfc().collect::<String>(),
+2 -2
View File
@@ -3,7 +3,7 @@ pub(crate) use _warnings::make_module;
#[pymodule]
mod _warnings {
use crate::function::OptionalArg;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::objtype::{self, PyClassRef};
use crate::pyobject::{PyResult, TypeProtocol};
use crate::vm::VirtualMachine;
@@ -11,7 +11,7 @@ mod _warnings {
#[derive(FromArgs)]
struct WarnArgs {
#[pyarg(positional_only, optional = false)]
message: PyStringRef,
message: PyStrRef,
#[pyarg(positional_or_keyword, optional = true)]
category: OptionalArg<PyClassRef>,
#[pyarg(positional_or_keyword, optional = true)]
+7 -7
View File
@@ -12,7 +12,7 @@ use winapi::um::{
use super::os::errno_err;
use crate::function::OptionalArg;
use crate::obj::objdict::{PyDictRef, PyMapping};
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::pyobject::{BorrowValue, PyObjectRef, PyResult, PySequence, TryFromObject};
use crate::VirtualMachine;
@@ -107,9 +107,9 @@ fn _winapi_GetFileType(h: usize, vm: &VirtualMachine) -> PyResult<u32> {
#[derive(FromArgs)]
struct CreateProcessArgs {
#[pyarg(positional_only)]
name: Option<PyStringRef>,
name: Option<PyStrRef>,
#[pyarg(positional_only)]
command_line: Option<PyStringRef>,
command_line: Option<PyStrRef>,
#[pyarg(positional_only)]
_proc_attrs: PyObjectRef,
#[pyarg(positional_only)]
@@ -121,7 +121,7 @@ struct CreateProcessArgs {
#[pyarg(positional_only)]
env_mapping: Option<PyMapping>,
#[pyarg(positional_only)]
current_dir: Option<PyStringRef>,
current_dir: Option<PyStrRef>,
#[pyarg(positional_only)]
startup_info: PyObjectRef,
}
@@ -169,7 +169,7 @@ fn _winapi_CreateProcess(
.as_mut()
.map_or_else(null_mut, |l| l.attrlist.as_mut_ptr() as _);
let wstr = |s: PyStringRef| {
let wstr = |s: PyStrRef| {
if s.borrow_value().contains('\0') {
Err(vm.new_value_error("embedded null character".to_owned()))
} else {
@@ -226,9 +226,9 @@ fn _winapi_CreateProcess(
fn getenvironment(env: PyDictRef, vm: &VirtualMachine) -> PyResult<Vec<u16>> {
let mut out = vec![];
for (k, v) in env {
let k = PyStringRef::try_from_object(vm, k)?;
let k = PyStrRef::try_from_object(vm, k)?;
let k = k.borrow_value();
let v = PyStringRef::try_from_object(vm, v)?;
let v = PyStrRef::try_from_object(vm, v)?;
let v = v.borrow_value();
if k.contains('\0') || v.contains('\0') {
return Err(vm.new_value_error("embedded null character".to_owned()));
+4 -8
View File
@@ -2,7 +2,7 @@
use crate::common::cell::{PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard};
use crate::exceptions::IntoPyException;
use crate::function::OptionalArg;
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{
BorrowValue, PyClassImpl, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject,
@@ -102,7 +102,7 @@ impl Hkey {
fn winreg_OpenKey(
key: Hkey,
subkey: Option<PyStringRef>,
subkey: Option<PyStrRef>,
reserved: OptionalArg<i32>,
access: OptionalArg<u32>,
vm: &VirtualMachine,
@@ -122,11 +122,7 @@ fn winreg_OpenKey(
Ok(PyHKEY::new(key))
}
fn winreg_QueryValue(
key: Hkey,
subkey: Option<PyStringRef>,
vm: &VirtualMachine,
) -> PyResult<String> {
fn winreg_QueryValue(key: Hkey, subkey: Option<PyStrRef>, vm: &VirtualMachine) -> PyResult<String> {
let subkey = subkey.as_ref().map_or("", |s| s.borrow_value());
key.with_key(|k| k.get_value(subkey))
.map_err(|e| e.into_pyexception(vm))
@@ -134,7 +130,7 @@ fn winreg_QueryValue(
fn winreg_QueryValueEx(
key: Hkey,
subkey: Option<PyStringRef>,
subkey: Option<PyStrRef>,
vm: &VirtualMachine,
) -> PyResult<(PyObjectRef, usize)> {
let subkey = subkey.as_ref().map_or("", |s| s.borrow_value());
+2 -2
View File
@@ -4,7 +4,7 @@ use std::{env, mem, path};
use crate::common::hash::{PyHash, PyUHash};
use crate::frame::FrameRef;
use crate::function::{Args, OptionalArg, PyFuncArgs};
use crate::obj::objstr::PyStringRef;
use crate::obj::objstr::PyStrRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{
IntoPyObject, ItemProtocol, PyClassImpl, PyContext, PyObjectRc, PyObjectRef, PyResult,
@@ -213,7 +213,7 @@ fn sys_setrecursionlimit(recursion_limit: i32, vm: &VirtualMachine) -> PyResult<
}
// TODO implement string interning, this will be key for performance
fn sys_intern(value: PyStringRef) -> PyStringRef {
fn sys_intern(value: PyStrRef) -> PyStrRef {
value
}
+1 -1
View File
@@ -189,7 +189,7 @@ impl TypeZoo {
set_iterator_type: create_type!(objset::PySetIterator),
slice_type: create_type!(objslice::PySlice),
staticmethod_type: create_type!(objstaticmethod::PyStaticMethod),
str_type: create_type!(objstr::PyString),
str_type: create_type!(objstr::PyStr),
str_iterator_type: create_type!(objstr::PyStringIterator),
str_reverseiterator_type: create_type!(objstr::PyStringReverseIterator),
super_type: create_type!(objsuper::PySuper),
+16 -16
View File
@@ -33,7 +33,7 @@ use crate::obj::objiter;
use crate::obj::objlist::PyList;
use crate::obj::objmodule::{self, PyModule};
use crate::obj::objobject;
use crate::obj::objstr::{PyString, PyStringRef};
use crate::obj::objstr::{PyStr, PyStrRef};
use crate::obj::objtuple::PyTuple;
use crate::obj::objtype::{self, PyClassRef};
use crate::pyobject::{
@@ -708,12 +708,12 @@ impl VirtualMachine {
}
// Container of the virtual machine state:
pub fn to_str(&self, obj: &PyObjectRef) -> PyResult<PyStringRef> {
pub fn to_str(&self, obj: &PyObjectRef) -> PyResult<PyStrRef> {
if obj.lease_class().is(&self.ctx.types.str_type) {
Ok(obj.clone().downcast().unwrap())
} else {
let s = self.call_method(&obj, "__str__", vec![])?;
PyStringRef::try_from_object(self, s)
PyStrRef::try_from_object(self, s)
}
}
@@ -722,14 +722,14 @@ impl VirtualMachine {
Ok(py_str_obj.borrow_value().to_owned())
}
pub fn to_repr(&self, obj: &PyObjectRef) -> PyResult<PyStringRef> {
pub fn to_repr(&self, obj: &PyObjectRef) -> PyResult<PyStrRef> {
let repr = self.call_method(obj, "__repr__", vec![])?;
TryFromObject::try_from_object(self, repr)
}
pub fn to_ascii(&self, obj: &PyObjectRef) -> PyResult {
let repr = self.call_method(obj, "__repr__", vec![])?;
let repr: PyStringRef = TryFromObject::try_from_object(self, repr)?;
let repr: PyStrRef = TryFromObject::try_from_object(self, repr)?;
let ascii = to_ascii(repr.borrow_value());
Ok(self.ctx.new_str(ascii))
}
@@ -971,7 +971,7 @@ impl VirtualMachine {
#[cfg_attr(feature = "flame-it", flame("VirtualMachine"))]
pub fn get_attribute<T>(&self, obj: PyObjectRef, attr_name: T) -> PyResult
where
T: TryIntoRef<PyString>,
T: TryIntoRef<PyStr>,
{
let attr_name = attr_name.try_into_ref(self)?;
vm_trace!("vm.__getattribute__: {:?} {:?}", obj, attr_name);
@@ -980,7 +980,7 @@ impl VirtualMachine {
pub fn set_attr<K, V>(&self, obj: &PyObjectRef, attr_name: K, attr_value: V) -> PyResult
where
K: TryIntoRef<PyString>,
K: TryIntoRef<PyStr>,
V: Into<PyObjectRef>,
{
let attr_name = attr_name.try_into_ref(self)?;
@@ -1072,7 +1072,7 @@ impl VirtualMachine {
})
}
pub fn generic_getattribute(&self, obj: PyObjectRef, name: PyStringRef) -> PyResult {
pub fn generic_getattribute(&self, obj: PyObjectRef, name: PyStrRef) -> PyResult {
self.generic_getattribute_opt(obj.clone(), name.clone(), None)?
.ok_or_else(|| self.new_attribute_error(format!("{} has no attribute '{}'", obj, name)))
}
@@ -1081,7 +1081,7 @@ impl VirtualMachine {
pub fn generic_getattribute_opt(
&self,
obj: PyObjectRef,
name_str: PyStringRef,
name_str: PyStrRef,
dict: Option<PyDictRef>,
) -> PyResult<Option<PyObjectRef>> {
let name = name_str.borrow_value();
@@ -1174,8 +1174,8 @@ impl VirtualMachine {
&self,
func: &str,
obj: PyObjectRef,
encoding: Option<PyStringRef>,
errors: Option<PyStringRef>,
encoding: Option<PyStrRef>,
errors: Option<PyStrRef>,
) -> PyResult {
let codecsmodule = self.import("_codecs", &[], 0)?;
let func = self.get_attribute(codecsmodule, func)?;
@@ -1189,8 +1189,8 @@ impl VirtualMachine {
pub fn decode(
&self,
obj: PyObjectRef,
encoding: Option<PyStringRef>,
errors: Option<PyStringRef>,
encoding: Option<PyStrRef>,
errors: Option<PyStrRef>,
) -> PyResult {
self.call_codec_func("decode", obj, encoding, errors)
}
@@ -1198,8 +1198,8 @@ impl VirtualMachine {
pub fn encode(
&self,
obj: PyObjectRef,
encoding: Option<PyStringRef>,
errors: Option<PyStringRef>,
encoding: Option<PyStrRef>,
errors: Option<PyStrRef>,
) -> PyResult {
self.call_codec_func("encode", obj, encoding, errors)
}
@@ -1533,7 +1533,7 @@ impl VirtualMachine {
pub fn __module_set_attr(
&self,
module: &PyObjectRef,
attr_name: impl TryIntoRef<PyString>,
attr_name: impl TryIntoRef<PyStr>,
attr_value: impl Into<PyObjectRef>,
) -> PyResult<()> {
let val = attr_value.into();
+9 -9
View File
@@ -7,7 +7,7 @@ use wasm_bindgen_futures::{future_to_promise, JsFuture};
use rustpython_vm::common::rc::PyRc;
use rustpython_vm::function::{OptionalArg, PyFuncArgs};
use rustpython_vm::import::import_file;
use rustpython_vm::obj::{objdict::PyDictRef, objstr::PyStringRef, objtype::PyClassRef};
use rustpython_vm::obj::{objdict::PyDictRef, objstr::PyStrRef, objtype::PyClassRef};
use rustpython_vm::pyobject::{
BorrowValue, IntoPyObject, PyCallable, PyClassImpl, PyObject, PyObjectRef, PyRef, PyResult,
PyValue,
@@ -43,18 +43,18 @@ impl FetchResponseFormat {
#[derive(FromArgs)]
struct FetchArgs {
#[pyarg(keyword_only, default = "None")]
response_format: Option<PyStringRef>,
response_format: Option<PyStrRef>,
#[pyarg(keyword_only, default = "None")]
method: Option<PyStringRef>,
method: Option<PyStrRef>,
#[pyarg(keyword_only, default = "None")]
headers: Option<PyDictRef>,
#[pyarg(keyword_only, default = "None")]
body: Option<PyObjectRef>,
#[pyarg(keyword_only, default = "None")]
content_type: Option<PyStringRef>,
content_type: Option<PyStrRef>,
}
fn browser_fetch(url: PyStringRef, args: FetchArgs, vm: &VirtualMachine) -> PyResult {
fn browser_fetch(url: PyStrRef, args: FetchArgs, vm: &VirtualMachine) -> PyResult {
let FetchArgs {
response_format,
method,
@@ -267,7 +267,7 @@ impl PyValue for Document {
#[pyimpl]
impl Document {
#[pymethod]
fn query(&self, query: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn query(&self, query: PyStrRef, vm: &VirtualMachine) -> PyResult {
let elem = self
.doc
.query_selector(query.borrow_value())
@@ -295,7 +295,7 @@ impl Element {
#[pymethod]
fn get_attr(
&self,
attr: PyStringRef,
attr: PyStrRef,
default: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> PyObjectRef {
@@ -306,14 +306,14 @@ impl Element {
}
#[pymethod]
fn set_attr(&self, attr: PyStringRef, value: PyStringRef, vm: &VirtualMachine) -> PyResult<()> {
fn set_attr(&self, attr: PyStrRef, value: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
self.elem
.set_attribute(attr.borrow_value(), value.borrow_value())
.map_err(|err| convert::js_py_typeerror(vm, err))
}
}
fn browser_load_module(module: PyStringRef, path: PyStringRef, vm: &VirtualMachine) -> PyResult {
fn browser_load_module(module: PyStrRef, path: PyStrRef, vm: &VirtualMachine) -> PyResult {
let weak_vm = weak_vm(vm);
let mut opts = web_sys::RequestInit::new();
+4 -4
View File
@@ -2,7 +2,7 @@ use js_sys::{Array, Object, Reflect};
use rustpython_vm::common::rc::PyRc;
use rustpython_vm::exceptions::PyBaseExceptionRef;
use rustpython_vm::function::Args;
use rustpython_vm::obj::{objfloat::PyFloatRef, objstr::PyStringRef, objtype::PyClassRef};
use rustpython_vm::obj::{objfloat::PyFloatRef, objstr::PyStrRef, objtype::PyClassRef};
use rustpython_vm::pyobject::{
BorrowValue, PyClassImpl, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject,
};
@@ -48,13 +48,13 @@ impl PyValue for PyJsValue {
}
enum JsProperty {
Str(PyStringRef),
Str(PyStrRef),
Js(PyJsValueRef),
}
impl TryFromObject for JsProperty {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
PyStringRef::try_from_object(vm, obj.clone())
PyStrRef::try_from_object(vm, obj.clone())
.map(JsProperty::Str)
.or_else(|_| PyJsValueRef::try_from_object(vm, obj).map(JsProperty::Js))
}
@@ -89,7 +89,7 @@ impl PyJsValue {
}
#[pymethod]
fn new_from_str(&self, s: PyStringRef) -> PyJsValue {
fn new_from_str(&self, s: PyStrRef) -> PyJsValue {
PyJsValue::new(s.borrow_value())
}
+2 -2
View File
@@ -6,7 +6,7 @@
use web_sys::{self, console};
use rustpython_vm::obj::objstr::PyStringRef;
use rustpython_vm::obj::objstr::PyStrRef;
use rustpython_vm::pyobject::{BorrowValue, PyObjectRef, PyResult};
use rustpython_vm::VirtualMachine;
@@ -25,7 +25,7 @@ pub fn make_stdout_object(
) -> PyObjectRef {
let ctx = &vm.ctx;
let write_method = ctx.new_method(
move |_self: PyObjectRef, data: PyStringRef, vm: &VirtualMachine| -> PyResult<()> {
move |_self: PyObjectRef, data: PyStrRef, vm: &VirtualMachine| -> PyResult<()> {
write_f(data.borrow_value(), vm)
},
);