mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-29 03:04:38 +08:00
Merge pull request #2078 from youknowone/new-object
vm.new_pystr and vm.ctx.new_str
This commit is contained in:
44 files changed
+268
-283
No files matched your search
+7
-3
@@ -395,7 +395,7 @@ fn _run_string(vm: &VirtualMachine, scope: Scope, source: &str, source_path: Str
|
||||
// trace!("Code object: {:?}", code_obj.borrow());
|
||||
scope
|
||||
.globals
|
||||
.set_item("__file__", vm.new_str(source_path), vm)?;
|
||||
.set_item("__file__", vm.ctx.new_str(source_path), vm)?;
|
||||
vm.run_code_obj(code_obj, scope)
|
||||
}
|
||||
|
||||
@@ -409,7 +409,7 @@ fn run_module(vm: &VirtualMachine, module: &str) -> PyResult<()> {
|
||||
debug!("Running module {}", module);
|
||||
let runpy = vm.import("runpy", &[], 0)?;
|
||||
let run_module_as_main = vm.get_attribute(runpy, "_run_module_as_main")?;
|
||||
vm.invoke(&run_module_as_main, vec![vm.new_str(module.to_owned())])?;
|
||||
vm.invoke(&run_module_as_main, vec![vm.ctx.new_str(module)])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -440,7 +440,11 @@ fn run_script(vm: &VirtualMachine, scope: Scope, script_file: &str) -> PyResult<
|
||||
|
||||
let dir = file_path.parent().unwrap().to_str().unwrap().to_owned();
|
||||
let sys_path = vm.get_attribute(vm.sys_module.clone(), "path").unwrap();
|
||||
vm.call_method(&sys_path, "insert", vec![vm.new_int(0), vm.new_str(dir)])?;
|
||||
vm.call_method(
|
||||
&sys_path,
|
||||
"insert",
|
||||
vec![vm.ctx.new_int(0), vm.ctx.new_str(dir)],
|
||||
)?;
|
||||
|
||||
match util::read_file(&file_path) {
|
||||
Ok(source) => {
|
||||
|
||||
+5
-5
@@ -345,7 +345,7 @@ mod decl {
|
||||
format!("0x{:x}", n)
|
||||
};
|
||||
|
||||
Ok(vm.new_str(s))
|
||||
Ok(vm.ctx.new_str(s))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -551,7 +551,7 @@ mod decl {
|
||||
format!("0o{:o}", n)
|
||||
};
|
||||
|
||||
Ok(vm.new_str(s))
|
||||
Ok(vm.ctx.new_str(s))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -621,14 +621,14 @@ mod decl {
|
||||
return Err(vm.new_value_error("pow() 3rd argument cannot be 0".to_owned()));
|
||||
}
|
||||
let x = objint::get_value(&x);
|
||||
Ok(vm.new_int(x.modpow(&y, &m)))
|
||||
Ok(vm.ctx.new_int(x.modpow(&y, &m)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
pub fn exit(exit_code_arg: OptionalArg<PyObjectRef>, vm: &VirtualMachine) -> PyResult {
|
||||
let code = exit_code_arg.unwrap_or_else(|| vm.new_int(0));
|
||||
let code = exit_code_arg.unwrap_or_else(|| vm.ctx.new_int(0));
|
||||
Err(vm.new_exception(vm.ctx.exceptions.system_exit.clone(), vec![code]))
|
||||
}
|
||||
|
||||
@@ -784,7 +784,7 @@ mod decl {
|
||||
.split('.')
|
||||
.next_back()
|
||||
.unwrap();
|
||||
let name_obj = vm.new_str(name.to_owned());
|
||||
let name_obj = vm.ctx.new_str(name);
|
||||
|
||||
let mut metaclass = if let Some(metaclass) = kwargs.pop_kwarg("metaclass") {
|
||||
PyClassRef::try_from_object(vm, metaclass)?
|
||||
|
||||
@@ -313,7 +313,7 @@ impl PyBytesInner {
|
||||
match needle {
|
||||
SequenceIndex::Int(int) => {
|
||||
if let Some(idx) = self.elements.get_pos(int) {
|
||||
Ok(vm.new_int(self.elements[idx]))
|
||||
Ok(vm.ctx.new_int(self.elements[idx]))
|
||||
} else {
|
||||
Err(vm.new_index_error("index out of range".to_owned()))
|
||||
}
|
||||
@@ -338,7 +338,7 @@ impl PyBytesInner {
|
||||
});
|
||||
let value = result?;
|
||||
self.elements[idx] = value;
|
||||
Ok(vm.new_int(value))
|
||||
Ok(vm.ctx.new_int(value))
|
||||
} else {
|
||||
Err(vm.new_index_error("index out of range".to_owned()))
|
||||
}
|
||||
|
||||
@@ -491,13 +491,13 @@ mod tests {
|
||||
let dict = Dict::default();
|
||||
assert_eq!(0, dict.len());
|
||||
|
||||
let key1 = vm.new_bool(true);
|
||||
let value1 = vm.new_str("abc".to_owned());
|
||||
let key1 = vm.ctx.new_bool(true);
|
||||
let value1 = vm.ctx.new_str("abc");
|
||||
dict.insert(&vm, key1.clone(), value1.clone()).unwrap();
|
||||
assert_eq!(1, dict.len());
|
||||
|
||||
let key2 = vm.new_str("x".to_owned());
|
||||
let value2 = vm.new_str("def".to_owned());
|
||||
let key2 = vm.ctx.new_str("x");
|
||||
let value2 = vm.ctx.new_str("def");
|
||||
dict.insert(&vm, key2.clone(), value2.clone()).unwrap();
|
||||
assert_eq!(2, dict.len());
|
||||
|
||||
@@ -537,7 +537,7 @@ mod tests {
|
||||
fn check_hash_equivalence(text: &str) {
|
||||
let vm: VirtualMachine = Default::default();
|
||||
let value1 = text;
|
||||
let value2 = vm.new_str(value1.to_owned());
|
||||
let value2 = vm.ctx.new_str(value1.to_owned());
|
||||
|
||||
let hash1 = value1.key_hash(&vm).expect("Hash should not fail.");
|
||||
let hash2 = value2.key_hash(&vm).expect("Hash should not fail.");
|
||||
|
||||
+8
-8
@@ -1291,7 +1291,7 @@ impl ExecutingFrame<'_> {
|
||||
.split('.')
|
||||
.next_back()
|
||||
.unwrap();
|
||||
vm.set_attr(&func_obj, "__name__", vm.new_str(name.to_owned()))?;
|
||||
vm.set_attr(&func_obj, "__name__", vm.ctx.new_str(name))?;
|
||||
vm.set_attr(&func_obj, "__qualname__", qualified_name)?;
|
||||
let module = self
|
||||
.scope
|
||||
@@ -1416,12 +1416,12 @@ impl ExecutingFrame<'_> {
|
||||
bytecode::ComparisonOperator::LessOrEqual => vm._le(a, b)?,
|
||||
bytecode::ComparisonOperator::Greater => vm._gt(a, b)?,
|
||||
bytecode::ComparisonOperator::GreaterOrEqual => vm._ge(a, b)?,
|
||||
bytecode::ComparisonOperator::Is => vm.new_bool(self._is(a, b)),
|
||||
bytecode::ComparisonOperator::IsNot => vm.new_bool(self._is_not(a, b)),
|
||||
bytecode::ComparisonOperator::In => vm.new_bool(self._in(vm, a, b)?),
|
||||
bytecode::ComparisonOperator::NotIn => vm.new_bool(self._not_in(vm, a, b)?),
|
||||
bytecode::ComparisonOperator::Is => vm.ctx.new_bool(self._is(a, b)),
|
||||
bytecode::ComparisonOperator::IsNot => vm.ctx.new_bool(self._is_not(a, b)),
|
||||
bytecode::ComparisonOperator::In => vm.ctx.new_bool(self._in(vm, a, b)?),
|
||||
bytecode::ComparisonOperator::NotIn => vm.ctx.new_bool(self._not_in(vm, a, b)?),
|
||||
bytecode::ComparisonOperator::ExceptionMatch => {
|
||||
vm.new_bool(builtin_isinstance(a, b, vm)?)
|
||||
vm.ctx.new_bool(builtin_isinstance(a, b, vm)?)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1439,13 +1439,13 @@ impl ExecutingFrame<'_> {
|
||||
fn store_attr(&mut self, vm: &VirtualMachine, attr_name: &str) -> FrameResult {
|
||||
let parent = self.pop_value();
|
||||
let value = self.pop_value();
|
||||
vm.set_attr(&parent, vm.new_str(attr_name.to_owned()), value)?;
|
||||
vm.set_attr(&parent, vm.ctx.new_str(attr_name), value)?;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn delete_attr(&mut self, vm: &VirtualMachine, attr_name: &str) -> FrameResult {
|
||||
let parent = self.pop_value();
|
||||
let name = vm.ctx.new_str(attr_name.to_owned());
|
||||
let name = vm.ctx.new_str(attr_name);
|
||||
vm.del_attr(&parent, name)?;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
+2
-2
@@ -106,9 +106,9 @@ pub fn import_codeobj(
|
||||
set_file_attr: bool,
|
||||
) -> PyResult {
|
||||
let attrs = vm.ctx.new_dict();
|
||||
attrs.set_item("__name__", vm.new_str(module_name.to_owned()), vm)?;
|
||||
attrs.set_item("__name__", vm.ctx.new_str(module_name), vm)?;
|
||||
if set_file_attr {
|
||||
attrs.set_item("__file__", vm.new_str(code_obj.source_path.to_owned()), vm)?;
|
||||
attrs.set_item("__file__", vm.ctx.new_str(&code_obj.source_path), vm)?;
|
||||
}
|
||||
let module = vm.new_module(module_name, attrs.clone());
|
||||
|
||||
|
||||
@@ -166,7 +166,7 @@ impl PyBool {
|
||||
OptionalArg::Present(val) => boolval(vm, val.clone())?,
|
||||
OptionalArg::Missing => false,
|
||||
};
|
||||
Ok(vm.new_bool(val))
|
||||
Ok(vm.ctx.new_bool(val))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -108,11 +108,7 @@ impl PyCodeRef {
|
||||
|
||||
#[pyproperty]
|
||||
fn co_varnames(self, vm: &VirtualMachine) -> PyObjectRef {
|
||||
let varnames = self
|
||||
.code
|
||||
.varnames()
|
||||
.map(|s| vm.new_str(s.to_owned()))
|
||||
.collect();
|
||||
let varnames = self.code.varnames().map(|s| vm.ctx.new_str(s)).collect();
|
||||
vm.ctx.new_tuple(varnames)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ impl PyDictRef {
|
||||
}
|
||||
|
||||
for (key, value) in kwargs.into_iter() {
|
||||
dict.insert(vm, vm.new_str(key), value)?;
|
||||
dict.insert(vm, vm.ctx.new_str(key), value)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -392,7 +392,7 @@ impl PyDictRef {
|
||||
if let Some((key, value)) = self.entries.pop_front() {
|
||||
Ok(vm.ctx.new_tuple(vec![key, value]))
|
||||
} else {
|
||||
let err_msg = vm.new_str("popitem(): dictionary is empty".to_owned());
|
||||
let err_msg = vm.ctx.new_str("popitem(): dictionary is empty");
|
||||
Err(vm.new_key_error(err_msg))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,12 +71,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoPyObject for BigInt {
|
||||
fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
|
||||
vm.ctx.new_int(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl PyValue for PyInt {
|
||||
fn class(vm: &VirtualMachine) -> PyClassRef {
|
||||
vm.ctx.int_type()
|
||||
@@ -110,7 +104,7 @@ macro_rules! impl_into_pyobject_int {
|
||||
)*};
|
||||
}
|
||||
|
||||
impl_into_pyobject_int!(isize i8 i16 i32 i64 usize u8 u16 u32 u64);
|
||||
impl_into_pyobject_int!(isize i8 i16 i32 i64 usize u8 u16 u32 u64 BigInt);
|
||||
|
||||
macro_rules! impl_try_from_object_int {
|
||||
($(($t:ty, $to_prim:ident),)*) => {$(
|
||||
|
||||
@@ -186,7 +186,7 @@ impl PySequenceIterator {
|
||||
let step: isize = if self.reversed { -1 } else { 1 };
|
||||
let pos = self.position.fetch_add(step);
|
||||
if pos >= 0 {
|
||||
match vm.call_method(&self.obj, "__getitem__", vec![vm.new_int(pos)]) {
|
||||
match vm.call_method(&self.obj, "__getitem__", vec![vm.ctx.new_int(pos)]) {
|
||||
Err(ref e) if objtype::isinstance(&e, &vm.ctx.exceptions.index_error) => {
|
||||
Err(new_stop_iteration(vm))
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ impl PyMappingProxy {
|
||||
match &self.mapping {
|
||||
MappingProxyInner::Class(class) => {
|
||||
let key = PyStringRef::try_from_object(vm, key)?;
|
||||
Ok(vm.new_bool(class.has_attr(key.borrow_value())))
|
||||
Ok(vm.ctx.new_bool(class.has_attr(key.borrow_value())))
|
||||
}
|
||||
MappingProxyInner::Dict(obj) => vm._membership(obj.clone(), key),
|
||||
}
|
||||
|
||||
@@ -295,6 +295,6 @@ fn common_reduce(obj: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResul
|
||||
} else {
|
||||
let copyreg = vm.import("copyreg", &[], 0)?;
|
||||
let reduce_ex = vm.get_attribute(copyreg, "_reduce_ex")?;
|
||||
vm.invoke(&reduce_ex, vec![obj, vm.new_int(proto)])
|
||||
vm.invoke(&reduce_ex, vec![obj, vm.ctx.new_int(proto)])
|
||||
}
|
||||
}
|
||||
@@ -281,7 +281,7 @@ impl PySetInner {
|
||||
if let Some((key, _)) = self.content.pop_front() {
|
||||
Ok(key)
|
||||
} else {
|
||||
let err_msg = vm.new_str("pop from an empty set".to_owned());
|
||||
let err_msg = vm.ctx.new_str("pop from an empty set");
|
||||
Err(vm.new_key_error(err_msg))
|
||||
}
|
||||
}
|
||||
@@ -342,8 +342,8 @@ impl PySetInner {
|
||||
macro_rules! try_set_cmp {
|
||||
($vm:expr, $other:expr, $op:expr) => {
|
||||
Ok(match_class!(match ($other) {
|
||||
set @ PySet => ($vm.new_bool($op(&set.inner)?)),
|
||||
frozen @ PyFrozenSet => ($vm.new_bool($op(&frozen.inner)?)),
|
||||
set @ PySet => ($vm.ctx.new_bool($op(&set.inner)?)),
|
||||
frozen @ PyFrozenSet => ($vm.ctx.new_bool($op(&frozen.inner)?)),
|
||||
_ => $vm.ctx.not_implemented(),
|
||||
}));
|
||||
};
|
||||
@@ -518,7 +518,7 @@ impl PySet {
|
||||
} else {
|
||||
"set(...)".to_owned()
|
||||
};
|
||||
Ok(vm.new_str(s))
|
||||
Ok(vm.ctx.new_str(s))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -788,7 +788,7 @@ impl PyFrozenSet {
|
||||
} else {
|
||||
"frozenset(...)".to_owned()
|
||||
};
|
||||
Ok(vm.new_str(s))
|
||||
Ok(vm.ctx.new_str(s))
|
||||
}
|
||||
|
||||
#[pymethod(name = "__hash__")]
|
||||
|
||||
@@ -309,9 +309,11 @@ impl PySlice {
|
||||
fn indices(&self, length: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
if let Some(length) = length.payload::<PyInt>() {
|
||||
let (start, stop, step) = self.inner_indices(length.borrow_value(), vm)?;
|
||||
Ok(vm
|
||||
.ctx
|
||||
.new_tuple(vec![vm.new_int(start), vm.new_int(stop), vm.new_int(step)]))
|
||||
Ok(vm.ctx.new_tuple(vec![
|
||||
vm.ctx.new_int(start),
|
||||
vm.ctx.new_int(stop),
|
||||
vm.ctx.new_int(step),
|
||||
]))
|
||||
} else {
|
||||
Ok(vm.ctx.not_implemented())
|
||||
}
|
||||
|
||||
+21
-18
@@ -64,9 +64,12 @@ impl AsRef<str> for PyString {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for PyString {
|
||||
fn from(s: &str) -> PyString {
|
||||
s.to_owned().into()
|
||||
impl<T> From<&T> for PyString
|
||||
where
|
||||
T: AsRef<str> + ?Sized,
|
||||
{
|
||||
fn from(s: &T) -> PyString {
|
||||
s.as_ref().to_owned().into()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -224,7 +227,7 @@ impl PyString {
|
||||
#[pymethod(name = "__eq__")]
|
||||
fn eq(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
|
||||
if objtype::isinstance(&rhs, &vm.ctx.types.str_type) {
|
||||
vm.new_bool(self.value == borrow_value(&rhs))
|
||||
vm.ctx.new_bool(self.value == borrow_value(&rhs))
|
||||
} else {
|
||||
vm.ctx.not_implemented()
|
||||
}
|
||||
@@ -233,7 +236,7 @@ impl PyString {
|
||||
#[pymethod(name = "__ne__")]
|
||||
fn ne(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
|
||||
if objtype::isinstance(&rhs, &vm.ctx.types.str_type) {
|
||||
vm.new_bool(self.value != borrow_value(&rhs))
|
||||
vm.ctx.new_bool(self.value != borrow_value(&rhs))
|
||||
} else {
|
||||
vm.ctx.not_implemented()
|
||||
}
|
||||
@@ -255,14 +258,14 @@ impl PyString {
|
||||
};
|
||||
|
||||
if let Some(character) = self.value.chars().nth(index) {
|
||||
Ok(vm.new_str(character.to_string()))
|
||||
Ok(vm.ctx.new_str(character.to_string()))
|
||||
} else {
|
||||
Err(vm.new_index_error("string index out of range".to_owned()))
|
||||
}
|
||||
}
|
||||
SequenceIndex::Slice(slice) => {
|
||||
let string = self.get_slice_items(vm, &slice)?;
|
||||
Ok(vm.new_str(string))
|
||||
Ok(vm.ctx.new_str(string))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -743,7 +746,7 @@ impl PyString {
|
||||
#[pymethod]
|
||||
fn splitlines(&self, args: pystr::SplitLinesArgs, vm: &VirtualMachine) -> PyObjectRef {
|
||||
vm.ctx
|
||||
.new_list(self.value.py_splitlines(args, |s| vm.new_str(s.to_owned())))
|
||||
.new_list(self.value.py_splitlines(args, |s| vm.ctx.new_str(s)))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -1001,11 +1004,15 @@ impl PyString {
|
||||
Ok(from_str) => {
|
||||
if to_str.len() == from_str.len() {
|
||||
for (c1, c2) in from_str.value.chars().zip(to_str.value.chars()) {
|
||||
new_dict.set_item(vm.new_int(c1 as u32), vm.new_int(c2 as u32), vm)?;
|
||||
new_dict.set_item(
|
||||
vm.ctx.new_int(c1 as u32),
|
||||
vm.ctx.new_int(c2 as u32),
|
||||
vm,
|
||||
)?;
|
||||
}
|
||||
if let OptionalArg::Present(none_str) = none_str {
|
||||
for c in none_str.value.chars() {
|
||||
new_dict.set_item(vm.new_int(c as u32), vm.get_none(), vm)?;
|
||||
new_dict.set_item(vm.ctx.new_int(c as u32), vm.get_none(), vm)?;
|
||||
}
|
||||
}
|
||||
Ok(new_dict.into_pyobject(vm))
|
||||
@@ -1115,7 +1122,7 @@ impl IntoPyObject for String {
|
||||
|
||||
impl IntoPyObject for &str {
|
||||
fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
|
||||
vm.ctx.new_str(self.to_owned())
|
||||
vm.ctx.new_str(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1299,13 +1306,9 @@ mod tests {
|
||||
let vm: VirtualMachine = Default::default();
|
||||
|
||||
let table = vm.context().new_dict();
|
||||
table
|
||||
.set_item("a", vm.new_str("🎅".to_owned()), &vm)
|
||||
.unwrap();
|
||||
table.set_item("a", vm.ctx.new_str("🎅"), &vm).unwrap();
|
||||
table.set_item("b", vm.get_none(), &vm).unwrap();
|
||||
table
|
||||
.set_item("c", vm.new_str("xda".to_owned()), &vm)
|
||||
.unwrap();
|
||||
table.set_item("c", vm.ctx.new_str("xda"), &vm).unwrap();
|
||||
let translated = PyString::maketrans(
|
||||
table.into_object(),
|
||||
OptionalArg::Missing,
|
||||
@@ -1316,7 +1319,7 @@ mod tests {
|
||||
let text = PyString::from("abc");
|
||||
let translated = text.translate(translated, &vm).unwrap();
|
||||
assert_eq!(translated, "🎅xda".to_owned());
|
||||
let translated = text.translate(vm.new_int(3), &vm);
|
||||
let translated = text.translate(vm.ctx.new_int(3), &vm);
|
||||
assert_eq!(
|
||||
translated.unwrap_err().lease_class().name,
|
||||
"TypeError".to_owned()
|
||||
|
||||
@@ -200,6 +200,6 @@ pub fn init(context: &PyContext) {
|
||||
super().cmeth(arg)\n";
|
||||
|
||||
extend_class!(context, super_type, {
|
||||
"__doc__" => context.new_str(super_doc.to_owned()),
|
||||
"__doc__" => context.new_str(super_doc),
|
||||
});
|
||||
}
|
||||
@@ -112,7 +112,7 @@ impl PyClassRef {
|
||||
.read()
|
||||
.get("__module__")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| vm.ctx.new_str("builtins".to_owned()))
|
||||
.unwrap_or_else(|| vm.ctx.new_str("builtins"))
|
||||
}
|
||||
|
||||
#[pyproperty(magic, setter)]
|
||||
@@ -325,7 +325,7 @@ impl PyClassRef {
|
||||
let set_name = meth?;
|
||||
vm.invoke(
|
||||
&set_name,
|
||||
vec![typ.clone().into_object(), vm.new_str(name.clone())],
|
||||
vec![typ.clone().into_object(), vm.ctx.new_str(name.clone())],
|
||||
)
|
||||
.map_err(|e| {
|
||||
let err = vm.new_runtime_error(format!(
|
||||
|
||||
@@ -80,7 +80,7 @@ impl PyWeak {
|
||||
self.upgrade()
|
||||
.and_then(|s| other.upgrade().map(|o| (s, o)))
|
||||
.map_or(Ok(false), |(a, b)| vm.bool_eq(a, b))
|
||||
.map(|b| vm.new_bool(b))
|
||||
.map(|b| vm.ctx.new_bool(b))
|
||||
} else {
|
||||
Ok(vm.ctx.not_implemented())
|
||||
}
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ impl Write for PyWriter<'_> {
|
||||
type Error = PyBaseExceptionRef;
|
||||
fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), Self::Error> {
|
||||
let PyWriter(obj, vm) = self;
|
||||
vm.call_method(obj, "write", vec![vm.new_str(args.to_string())])
|
||||
vm.call_method(obj, "write", vec![vm.ctx.new_str(args.to_string())])
|
||||
.map(drop)
|
||||
}
|
||||
}
|
||||
+11
-11
@@ -444,15 +444,15 @@ impl PyArray {
|
||||
let lhs = lhs.borrow_value();
|
||||
let rhs = rhs.borrow_value();
|
||||
if lhs.len() != rhs.len() {
|
||||
Ok(vm.new_bool(false))
|
||||
Ok(vm.ctx.new_bool(false))
|
||||
} else {
|
||||
for (a, b) in lhs.iter(vm).zip(rhs.iter(vm)) {
|
||||
let ne = objbool::boolval(vm, vm._ne(a, b)?)?;
|
||||
if ne {
|
||||
return Ok(vm.new_bool(false));
|
||||
return Ok(vm.ctx.new_bool(false));
|
||||
}
|
||||
}
|
||||
Ok(vm.new_bool(true))
|
||||
Ok(vm.ctx.new_bool(true))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -467,11 +467,11 @@ impl PyArray {
|
||||
let lt = objbool::boolval(vm, vm._lt(a, b)?)?;
|
||||
|
||||
if lt {
|
||||
return Ok(vm.new_bool(true));
|
||||
return Ok(vm.ctx.new_bool(true));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(vm.new_bool(lhs.len() < rhs.len()))
|
||||
Ok(vm.ctx.new_bool(lhs.len() < rhs.len()))
|
||||
}
|
||||
|
||||
#[pymethod(name = "__le__")]
|
||||
@@ -485,11 +485,11 @@ impl PyArray {
|
||||
let le = objbool::boolval(vm, vm._le(a, b)?)?;
|
||||
|
||||
if le {
|
||||
return Ok(vm.new_bool(true));
|
||||
return Ok(vm.ctx.new_bool(true));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(vm.new_bool(lhs.len() <= rhs.len()))
|
||||
Ok(vm.ctx.new_bool(lhs.len() <= rhs.len()))
|
||||
}
|
||||
|
||||
#[pymethod(name = "__gt__")]
|
||||
@@ -503,11 +503,11 @@ impl PyArray {
|
||||
let gt = objbool::boolval(vm, vm._gt(a, b)?)?;
|
||||
|
||||
if gt {
|
||||
return Ok(vm.new_bool(true));
|
||||
return Ok(vm.ctx.new_bool(true));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(vm.new_bool(lhs.len() > rhs.len()))
|
||||
Ok(vm.ctx.new_bool(lhs.len() > rhs.len()))
|
||||
}
|
||||
|
||||
#[pymethod(name = "__ge__")]
|
||||
@@ -521,11 +521,11 @@ impl PyArray {
|
||||
let ge = objbool::boolval(vm, vm._ge(a, b)?)?;
|
||||
|
||||
if ge {
|
||||
return Ok(vm.new_bool(true));
|
||||
return Ok(vm.ctx.new_bool(true));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(vm.new_bool(lhs.len() >= rhs.len()))
|
||||
Ok(vm.ctx.new_bool(lhs.len() >= rhs.len()))
|
||||
}
|
||||
|
||||
#[pymethod(name = "__len__")]
|
||||
|
||||
+17
-21
@@ -35,7 +35,7 @@ macro_rules! node {
|
||||
$(
|
||||
let field_name = stringify!($attr_name);
|
||||
$vm.set_attr(node.as_object(), field_name, $attr_value)?;
|
||||
field_names.push($vm.ctx.new_str(field_name.to_owned()));
|
||||
field_names.push($vm.ctx.new_str(field_name));
|
||||
)*
|
||||
$vm.set_attr(node.as_object(), "_fields", $vm.ctx.new_tuple(field_names))?;
|
||||
node
|
||||
@@ -81,7 +81,7 @@ fn statement_to_ast(vm: &VirtualMachine, statement: &ast::Statement) -> PyResult
|
||||
decorator_list,
|
||||
..
|
||||
} => node!(vm, ClassDef, {
|
||||
name => vm.ctx.new_str(name.to_owned()),
|
||||
name => vm.ctx.new_str(name),
|
||||
keywords => map_ast(keyword_to_ast, vm, keywords)?,
|
||||
body => statements_to_ast(vm, body)?,
|
||||
decorator_list => expressions_to_ast(vm, decorator_list)?,
|
||||
@@ -96,7 +96,7 @@ fn statement_to_ast(vm: &VirtualMachine, statement: &ast::Statement) -> PyResult
|
||||
} => {
|
||||
if *is_async {
|
||||
node!(vm, AsyncFunctionDef, {
|
||||
name => vm.ctx.new_str(name.to_owned()),
|
||||
name => vm.ctx.new_str(name),
|
||||
args => parameters_to_ast(vm, args)?,
|
||||
body => statements_to_ast(vm, body)?,
|
||||
decorator_list => expressions_to_ast(vm, decorator_list)?,
|
||||
@@ -104,7 +104,7 @@ fn statement_to_ast(vm: &VirtualMachine, statement: &ast::Statement) -> PyResult
|
||||
})
|
||||
} else {
|
||||
node!(vm, FunctionDef, {
|
||||
name => vm.ctx.new_str(name.to_owned()),
|
||||
name => vm.ctx.new_str(name),
|
||||
args => parameters_to_ast(vm, args)?,
|
||||
body => statements_to_ast(vm, body)?,
|
||||
decorator_list => expressions_to_ast(vm, decorator_list)?,
|
||||
@@ -245,7 +245,7 @@ fn statement_to_ast(vm: &VirtualMachine, statement: &ast::Statement) -> PyResult
|
||||
|
||||
fn alias_to_ast(vm: &VirtualMachine, alias: &ast::ImportSymbol) -> PyResult<AstNodeRef> {
|
||||
Ok(node!(vm, alias, {
|
||||
name => vm.ctx.new_str(alias.symbol.to_owned()),
|
||||
name => vm.ctx.new_str(&alias.symbol),
|
||||
asname => optional_string_to_py_obj(vm, &alias.alias)
|
||||
}))
|
||||
}
|
||||
@@ -281,7 +281,7 @@ fn handler_to_ast(vm: &VirtualMachine, handler: &ast::ExceptHandler) -> PyResult
|
||||
|
||||
fn make_string_list(vm: &VirtualMachine, names: &[String]) -> PyObjectRef {
|
||||
vm.ctx
|
||||
.new_list(names.iter().map(|x| vm.ctx.new_str(x.to_owned())).collect())
|
||||
.new_list(names.iter().map(|x| vm.ctx.new_str(x)).collect())
|
||||
}
|
||||
|
||||
fn optional_expressions_to_ast(
|
||||
@@ -340,7 +340,7 @@ fn expression_to_ast(vm: &VirtualMachine, expression: &ast::Expression) -> PyRes
|
||||
ast::UnaryOperator::Pos => "UAdd",
|
||||
};
|
||||
node!(vm, UnaryOp, {
|
||||
op => vm.ctx.new_str(op.to_owned()),
|
||||
op => vm.ctx.new_str(op),
|
||||
operand => expression_to_ast(vm, a)?,
|
||||
})
|
||||
}
|
||||
@@ -351,7 +351,7 @@ fn expression_to_ast(vm: &VirtualMachine, expression: &ast::Expression) -> PyRes
|
||||
ast::BooleanOperator::And => "And",
|
||||
ast::BooleanOperator::Or => "Or",
|
||||
};
|
||||
let py_op = vm.ctx.new_str(str_op.to_owned());
|
||||
let py_op = vm.ctx.new_str(str_op);
|
||||
|
||||
node!(vm, BoolOp, {
|
||||
op => py_op,
|
||||
@@ -374,11 +374,9 @@ fn expression_to_ast(vm: &VirtualMachine, expression: &ast::Expression) -> PyRes
|
||||
ast::Comparison::Is => "Is",
|
||||
ast::Comparison::IsNot => "IsNot",
|
||||
};
|
||||
let ops = vm.ctx.new_list(
|
||||
ops.iter()
|
||||
.map(|x| vm.ctx.new_str(to_operator(x).to_owned()))
|
||||
.collect(),
|
||||
);
|
||||
let ops = vm
|
||||
.ctx
|
||||
.new_list(ops.iter().map(|x| vm.ctx.new_str(to_operator(x))).collect());
|
||||
|
||||
let comparators: PyResult<_> = vals
|
||||
.iter()
|
||||
@@ -393,7 +391,7 @@ fn expression_to_ast(vm: &VirtualMachine, expression: &ast::Expression) -> PyRes
|
||||
})
|
||||
}
|
||||
Identifier { name } => node!(vm, Name, {
|
||||
id => vm.ctx.new_str(name.clone()),
|
||||
id => vm.ctx.new_str(name),
|
||||
ctx => vm.ctx.none() // TODO: add context.
|
||||
}),
|
||||
Lambda { args, body } => node!(vm, Lambda, {
|
||||
@@ -506,7 +504,7 @@ fn expression_to_ast(vm: &VirtualMachine, expression: &ast::Expression) -> PyRes
|
||||
}),
|
||||
Attribute { value, name } => node!(vm, Attribute, {
|
||||
value => expression_to_ast(vm, value)?,
|
||||
attr => vm.ctx.new_str(name.to_owned()),
|
||||
attr => vm.ctx.new_str(name),
|
||||
ctx => vm.ctx.none()
|
||||
}),
|
||||
Starred { value } => node!(vm, Starred, {
|
||||
@@ -575,7 +573,7 @@ fn parameter_to_ast(vm: &VirtualMachine, parameter: &ast::Parameter) -> PyResult
|
||||
};
|
||||
|
||||
let py_node = node!(vm, arg, {
|
||||
arg => vm.ctx.new_str(parameter.arg.to_owned()),
|
||||
arg => vm.ctx.new_str(¶meter.arg),
|
||||
annotation => py_annotation
|
||||
});
|
||||
|
||||
@@ -587,7 +585,7 @@ fn parameter_to_ast(vm: &VirtualMachine, parameter: &ast::Parameter) -> PyResult
|
||||
|
||||
fn optional_string_to_py_obj(vm: &VirtualMachine, name: &Option<String>) -> PyObjectRef {
|
||||
if let Some(name) = name {
|
||||
vm.ctx.new_str(name.to_owned())
|
||||
vm.ctx.new_str(name)
|
||||
} else {
|
||||
vm.ctx.none()
|
||||
}
|
||||
@@ -618,15 +616,13 @@ fn comprehension_to_ast(
|
||||
target => expression_to_ast(vm, &comprehension.target)?,
|
||||
iter => expression_to_ast(vm, &comprehension.iter)?,
|
||||
ifs => expressions_to_ast(vm, &comprehension.ifs)?,
|
||||
is_async => vm.new_bool(comprehension.is_async),
|
||||
is_async => vm.ctx.new_bool(comprehension.is_async),
|
||||
}))
|
||||
}
|
||||
|
||||
fn string_to_ast(vm: &VirtualMachine, string: &ast::StringGroup) -> PyResult<AstNodeRef> {
|
||||
let string = match string {
|
||||
ast::StringGroup::Constant { value } => {
|
||||
node!(vm, Str, { s => vm.ctx.new_str(value.clone()) })
|
||||
}
|
||||
ast::StringGroup::Constant { value } => node!(vm, Str, { s => vm.ctx.new_str(value) }),
|
||||
ast::StringGroup::FormattedValue { value, .. } => {
|
||||
node!(vm, FormattedValue, { value => expression_to_ast(vm, value)? })
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
|
||||
"errorcode" => errorcode.clone(),
|
||||
});
|
||||
for (name, code) in ERROR_CODES {
|
||||
let name = vm.new_str((*name).to_owned());
|
||||
let name = vm.ctx.new_str((*name).to_owned());
|
||||
let code = vm.ctx.new_int(*code);
|
||||
errorcode.set_item(code.clone(), name.clone(), vm).unwrap();
|
||||
vm.set_attr(&module, name, code).unwrap();
|
||||
|
||||
+19
-16
@@ -448,7 +448,8 @@ fn io_base_readline(
|
||||
let read = vm.get_attribute(instance, "read")?;
|
||||
let mut res = Vec::new();
|
||||
while size.map_or(true, |s| res.len() < s) {
|
||||
let read_res = PyBytesLike::try_from_object(vm, vm.invoke(&read, vec![vm.new_int(1)])?)?;
|
||||
let read_res =
|
||||
PyBytesLike::try_from_object(vm, vm.invoke(&read, vec![vm.ctx.new_int(1)])?)?;
|
||||
if read_res.with_ref(|b| b.is_empty()) {
|
||||
break;
|
||||
}
|
||||
@@ -468,7 +469,7 @@ fn io_base_checkclosed(
|
||||
if objbool::boolval(vm, vm.get_attribute(instance, "closed")?)? {
|
||||
let msg = msg
|
||||
.flatten()
|
||||
.unwrap_or_else(|| vm.new_str("I/O operation on closed file.".to_owned()));
|
||||
.unwrap_or_else(|| vm.ctx.new_str("I/O operation on closed file."));
|
||||
Err(vm.new_exception(vm.ctx.exceptions.value_error.clone(), vec![msg]))
|
||||
} else {
|
||||
Ok(())
|
||||
@@ -483,7 +484,7 @@ fn io_base_checkreadable(
|
||||
if !objbool::boolval(vm, vm.call_method(&instance, "readable", vec![])?)? {
|
||||
let msg = msg
|
||||
.flatten()
|
||||
.unwrap_or_else(|| vm.new_str("File or stream is not readable.".to_owned()));
|
||||
.unwrap_or_else(|| vm.ctx.new_str("File or stream is not readable."));
|
||||
Err(vm.new_exception(vm.ctx.exceptions.value_error.clone(), vec![msg]))
|
||||
} else {
|
||||
Ok(())
|
||||
@@ -498,7 +499,7 @@ fn io_base_checkwritable(
|
||||
if !objbool::boolval(vm, vm.call_method(&instance, "writable", vec![])?)? {
|
||||
let msg = msg
|
||||
.flatten()
|
||||
.unwrap_or_else(|| vm.new_str("File or stream is not writable.".to_owned()));
|
||||
.unwrap_or_else(|| vm.ctx.new_str("File or stream is not writable."));
|
||||
Err(vm.new_exception(vm.ctx.exceptions.value_error.clone(), vec![msg]))
|
||||
} else {
|
||||
Ok(())
|
||||
@@ -513,7 +514,7 @@ fn io_base_checkseekable(
|
||||
if !objbool::boolval(vm, vm.call_method(&instance, "seekable", vec![])?)? {
|
||||
let msg = msg
|
||||
.flatten()
|
||||
.unwrap_or_else(|| vm.new_str("File or stream is not seekable.".to_owned()));
|
||||
.unwrap_or_else(|| vm.ctx.new_str("File or stream is not seekable."));
|
||||
Err(vm.new_exception(vm.ctx.exceptions.value_error.clone(), vec![msg]))
|
||||
} else {
|
||||
Ok(())
|
||||
@@ -564,7 +565,7 @@ fn buffered_io_base_init(
|
||||
vm.set_attr(
|
||||
&instance,
|
||||
"buffer_size",
|
||||
vm.new_int(buffer_size.unwrap_or(DEFAULT_BUFFER_SIZE)),
|
||||
vm.ctx.new_int(buffer_size.unwrap_or(DEFAULT_BUFFER_SIZE)),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -667,8 +668,10 @@ mod fileio {
|
||||
}
|
||||
let mode = compute_c_flag(&mode);
|
||||
let fd = if let Some(opener) = args.opener {
|
||||
let fd =
|
||||
vm.invoke(&opener, vec![name.clone().into_object(), vm.new_int(mode)])?;
|
||||
let fd = vm.invoke(
|
||||
&opener,
|
||||
vec![name.clone().into_object(), vm.ctx.new_int(mode)],
|
||||
)?;
|
||||
if !vm.isinstance(&fd, &vm.ctx.types.int_type)? {
|
||||
return Err(vm.new_type_error("expected integer from opener".to_owned()));
|
||||
}
|
||||
@@ -688,14 +691,14 @@ mod fileio {
|
||||
};
|
||||
(name.into_object(), fd)
|
||||
}
|
||||
Either::B(fno) => (vm.new_int(fno), fno),
|
||||
Either::B(fno) => (vm.ctx.new_int(fno), fno),
|
||||
};
|
||||
|
||||
vm.set_attr(&file_io, "name", name)?;
|
||||
vm.set_attr(&file_io, "mode", vm.new_str(mode))?;
|
||||
vm.set_attr(&file_io, "__fileno", vm.new_int(file_no))?;
|
||||
vm.set_attr(&file_io, "closefd", vm.new_bool(args.closefd))?;
|
||||
vm.set_attr(&file_io, "__closed", vm.new_bool(false))?;
|
||||
vm.set_attr(&file_io, "mode", vm.ctx.new_str(mode))?;
|
||||
vm.set_attr(&file_io, "__fileno", vm.ctx.new_int(file_no))?;
|
||||
vm.set_attr(&file_io, "closefd", vm.ctx.new_bool(args.closefd))?;
|
||||
vm.set_attr(&file_io, "__closed", vm.ctx.new_bool(false))?;
|
||||
Ok(vm.get_none())
|
||||
}
|
||||
|
||||
@@ -793,7 +796,7 @@ mod fileio {
|
||||
i64::try_from_object(vm, vm.get_attribute(instance.clone(), "__fileno")?)?;
|
||||
drop(os::rust_file(raw_handle));
|
||||
}
|
||||
vm.set_attr(&instance, "__closed", vm.new_bool(true))?;
|
||||
vm.set_attr(&instance, "__closed", vm.ctx.new_bool(true))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1196,13 +1199,13 @@ pub fn io_open(
|
||||
PyFuncArgs::from((
|
||||
Args::new(vec![file.clone(), vm.ctx.new_str(mode.clone())]),
|
||||
KwArgs::new(maplit::hashmap! {
|
||||
"closefd".to_owned() => vm.new_bool(opts.closefd),
|
||||
"closefd".to_owned() => vm.ctx.new_bool(opts.closefd),
|
||||
"opener".to_owned() => opts.opener.unwrap_or_else(|| vm.get_none()),
|
||||
}),
|
||||
)),
|
||||
)?;
|
||||
|
||||
vm.set_attr(&file_io_obj, "mode", vm.new_str(mode_string.to_owned()))?;
|
||||
vm.set_attr(&file_io_obj, "mode", vm.ctx.new_str(mode_string))?;
|
||||
|
||||
// Create Buffered class to consume FileIO. The type of buffered class depends on
|
||||
// the operation in the mode.
|
||||
|
||||
@@ -326,8 +326,8 @@ mod decl {
|
||||
#[pymethod(name = "__length_hint__")]
|
||||
fn length_hint(&self, vm: &VirtualMachine) -> PyObjectRef {
|
||||
match self.times {
|
||||
Some(ref times) => vm.new_int(times.read().clone()),
|
||||
None => vm.new_int(0),
|
||||
Some(ref times) => vm.ctx.new_int(times.read().clone()),
|
||||
None => vm.ctx.new_int(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+18
-18
@@ -74,7 +74,7 @@ impl JsonScanner {
|
||||
let c = s
|
||||
.chars()
|
||||
.next()
|
||||
.ok_or_else(|| objiter::stop_iter_with_value(vm.new_int(idx), vm))?;
|
||||
.ok_or_else(|| objiter::stop_iter_with_value(vm.ctx.new_int(idx), vm))?;
|
||||
let next_idx = idx + c.len_utf8();
|
||||
match c {
|
||||
'"' => {
|
||||
@@ -84,8 +84,8 @@ impl JsonScanner {
|
||||
&parse_str,
|
||||
vec![
|
||||
pystr.into_object(),
|
||||
vm.new_int(next_idx),
|
||||
vm.new_bool(self.strict),
|
||||
vm.ctx.new_int(next_idx),
|
||||
vm.ctx.new_bool(self.strict),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -96,8 +96,8 @@ impl JsonScanner {
|
||||
&parse_obj,
|
||||
vec![
|
||||
vm.ctx
|
||||
.new_tuple(vec![pystr.into_object(), vm.new_int(next_idx)]),
|
||||
vm.new_bool(self.strict),
|
||||
.new_tuple(vec![pystr.into_object(), vm.ctx.new_int(next_idx)]),
|
||||
vm.ctx.new_bool(self.strict),
|
||||
scan_once,
|
||||
self.object_hook.clone().unwrap_or_else(|| vm.get_none()),
|
||||
self.object_pairs_hook
|
||||
@@ -113,7 +113,7 @@ impl JsonScanner {
|
||||
&parse_array,
|
||||
vec![
|
||||
vm.ctx
|
||||
.new_tuple(vec![pystr.into_object(), vm.new_int(next_idx)]),
|
||||
.new_tuple(vec![pystr.into_object(), vm.ctx.new_int(next_idx)]),
|
||||
scan_once,
|
||||
],
|
||||
);
|
||||
@@ -124,25 +124,25 @@ impl JsonScanner {
|
||||
macro_rules! parse_const {
|
||||
($s:literal, $val:expr) => {
|
||||
if s.starts_with($s) {
|
||||
return Ok(vm.ctx.new_tuple(vec![$val, vm.new_int(idx + $s.len())]));
|
||||
return Ok(vm.ctx.new_tuple(vec![$val, vm.ctx.new_int(idx + $s.len())]));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
parse_const!("null", vm.get_none());
|
||||
parse_const!("true", vm.new_bool(true));
|
||||
parse_const!("false", vm.new_bool(false));
|
||||
parse_const!("true", vm.ctx.new_bool(true));
|
||||
parse_const!("false", vm.ctx.new_bool(false));
|
||||
|
||||
if let Some((res, len)) = self.parse_number(s, vm) {
|
||||
return Ok(vm.ctx.new_tuple(vec![res?, vm.new_int(idx + len)]));
|
||||
return Ok(vm.ctx.new_tuple(vec![res?, vm.ctx.new_int(idx + len)]));
|
||||
}
|
||||
|
||||
macro_rules! parse_constant {
|
||||
($s:literal) => {
|
||||
if s.starts_with($s) {
|
||||
return Ok(vm.ctx.new_tuple(vec![
|
||||
vm.invoke(&self.parse_constant, vec![vm.new_str($s.to_owned())])?,
|
||||
vm.new_int(idx + $s.len()),
|
||||
vm.invoke(&self.parse_constant, vec![vm.ctx.new_str($s.to_owned())])?,
|
||||
vm.ctx.new_int(idx + $s.len()),
|
||||
]));
|
||||
}
|
||||
};
|
||||
@@ -152,7 +152,7 @@ impl JsonScanner {
|
||||
parse_constant!("Infinity");
|
||||
parse_constant!("-Infinity");
|
||||
|
||||
Err(objiter::stop_iter_with_value(vm.new_int(idx), vm))
|
||||
Err(objiter::stop_iter_with_value(vm.ctx.new_int(idx), vm))
|
||||
}
|
||||
|
||||
fn parse_number(&self, s: &str, vm: &VirtualMachine) -> Option<(PyResult, usize)> {
|
||||
@@ -179,14 +179,14 @@ impl JsonScanner {
|
||||
let ret = if has_decimal || has_exponent {
|
||||
// float
|
||||
if let Some(ref parse_float) = self.parse_float {
|
||||
vm.invoke(parse_float, vec![vm.new_str(buf.to_owned())])
|
||||
vm.invoke(parse_float, vec![vm.ctx.new_str(buf)])
|
||||
} else {
|
||||
Ok(vm.ctx.new_float(f64::from_str(buf).unwrap()))
|
||||
}
|
||||
} else if let Some(ref parse_int) = self.parse_int {
|
||||
vm.invoke(parse_int, vec![vm.new_str(buf.to_owned())])
|
||||
vm.invoke(parse_int, vec![vm.ctx.new_str(buf)])
|
||||
} else {
|
||||
Ok(vm.new_int(BigInt::from_str(buf).unwrap()))
|
||||
Ok(vm.ctx.new_int(BigInt::from_str(buf).unwrap()))
|
||||
};
|
||||
Some((ret, buf.len()))
|
||||
}
|
||||
@@ -201,7 +201,7 @@ impl JsonScanner {
|
||||
if idx > 0 {
|
||||
chars
|
||||
.nth(idx - 1)
|
||||
.ok_or_else(|| objiter::stop_iter_with_value(vm.new_int(idx), vm))?;
|
||||
.ok_or_else(|| objiter::stop_iter_with_value(vm.ctx.new_int(idx), vm))?;
|
||||
}
|
||||
zelf.parse(
|
||||
chars.as_str(),
|
||||
@@ -233,7 +233,7 @@ fn _json_encode_basestring_ascii(s: PyStringRef) -> String {
|
||||
pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
|
||||
let ctx = &vm.ctx;
|
||||
let scanner_cls = JsonScanner::make_class(ctx);
|
||||
scanner_cls.set_str_attr("__module__", vm.new_str("_json".to_owned()));
|
||||
scanner_cls.set_str_attr("__module__", vm.ctx.new_str("_json"));
|
||||
py_module!(vm, "_json", {
|
||||
"make_scanner" => scanner_cls,
|
||||
"encode_basestring" => named_function!(ctx, _json, encode_basestring),
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
|
||||
let keyword_kwlist = ctx.new_list(
|
||||
lexer::get_keywords()
|
||||
.keys()
|
||||
.map(|k| ctx.new_str(k.to_owned()))
|
||||
.map(|k| ctx.new_str(k))
|
||||
.collect(),
|
||||
);
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ use crate::VirtualMachine;
|
||||
use volatile::Volatile;
|
||||
|
||||
fn operator_length_hint(obj: PyObjectRef, default: OptionalArg, vm: &VirtualMachine) -> PyResult {
|
||||
let default = default.unwrap_or_else(|| vm.new_int(0));
|
||||
let default = default.unwrap_or_else(|| vm.ctx.new_int(0));
|
||||
if !objtype::isinstance(&default, &vm.ctx.types.int_type) {
|
||||
return Err(vm.new_type_error(format!(
|
||||
"'{}' type cannot be interpreted as an integer",
|
||||
@@ -15,7 +15,7 @@ fn operator_length_hint(obj: PyObjectRef, default: OptionalArg, vm: &VirtualMach
|
||||
)));
|
||||
}
|
||||
let hint = objiter::length_hint(vm, obj)?
|
||||
.map(|i| vm.new_int(i))
|
||||
.map(|i| vm.ctx.new_int(i))
|
||||
.unwrap_or(default);
|
||||
Ok(hint)
|
||||
}
|
||||
|
||||
+15
-15
@@ -45,7 +45,7 @@ impl OutputMode {
|
||||
})
|
||||
};
|
||||
match mode {
|
||||
OutputMode::String => path_as_string(path).map(|s| vm.new_str(s)),
|
||||
OutputMode::String => path_as_string(path).map(|s| vm.ctx.new_str(s)),
|
||||
OutputMode::Bytes => {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
@@ -152,7 +152,7 @@ impl IntoPyException for io::Error {
|
||||
};
|
||||
let os_error = vm.new_exception_msg(exc_type, self.to_string());
|
||||
let errno = match self.raw_os_error() {
|
||||
Some(errno) => vm.new_int(errno),
|
||||
Some(errno) => vm.ctx.new_int(errno),
|
||||
None => vm.get_none(),
|
||||
};
|
||||
vm.set_attr(os_error.as_object(), "errno", errno).unwrap();
|
||||
@@ -659,13 +659,13 @@ mod _os {
|
||||
#[pyfunction]
|
||||
fn getpid(vm: &VirtualMachine) -> PyObjectRef {
|
||||
let pid = std::process::id();
|
||||
vm.new_int(pid)
|
||||
vm.ctx.new_int(pid)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn cpu_count(vm: &VirtualMachine) -> PyObjectRef {
|
||||
let cpu_count = num_cpus::get();
|
||||
vm.new_int(cpu_count)
|
||||
vm.ctx.new_int(cpu_count)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -1442,39 +1442,39 @@ mod posix {
|
||||
#[pyfunction]
|
||||
fn getppid(vm: &VirtualMachine) -> PyObjectRef {
|
||||
let ppid = unistd::getppid().as_raw();
|
||||
vm.new_int(ppid)
|
||||
vm.ctx.new_int(ppid)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn getgid(vm: &VirtualMachine) -> PyObjectRef {
|
||||
let gid = unistd::getgid().as_raw();
|
||||
vm.new_int(gid)
|
||||
vm.ctx.new_int(gid)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn getegid(vm: &VirtualMachine) -> PyObjectRef {
|
||||
let egid = unistd::getegid().as_raw();
|
||||
vm.new_int(egid)
|
||||
vm.ctx.new_int(egid)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn getpgid(pid: u32, vm: &VirtualMachine) -> PyResult {
|
||||
match unistd::getpgid(Some(Pid::from_raw(pid as i32))) {
|
||||
Ok(pgid) => Ok(vm.new_int(pgid.as_raw())),
|
||||
Ok(pgid) => Ok(vm.ctx.new_int(pgid.as_raw())),
|
||||
Err(err) => Err(err.into_pyexception(vm)),
|
||||
}
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn getpgrp(vm: &VirtualMachine) -> PyResult {
|
||||
Ok(vm.new_int(unistd::getpgrp().as_raw()))
|
||||
Ok(vm.ctx.new_int(unistd::getpgrp().as_raw()))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "redox"))]
|
||||
#[pyfunction]
|
||||
fn getsid(pid: u32, vm: &VirtualMachine) -> PyResult {
|
||||
match unistd::getsid(Some(Pid::from_raw(pid as i32))) {
|
||||
Ok(sid) => Ok(vm.new_int(sid.as_raw())),
|
||||
Ok(sid) => Ok(vm.ctx.new_int(sid.as_raw())),
|
||||
Err(err) => Err(err.into_pyexception(vm)),
|
||||
}
|
||||
}
|
||||
@@ -1482,13 +1482,13 @@ mod posix {
|
||||
#[pyfunction]
|
||||
fn getuid(vm: &VirtualMachine) -> PyObjectRef {
|
||||
let uid = unistd::getuid().as_raw();
|
||||
vm.new_int(uid)
|
||||
vm.ctx.new_int(uid)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn geteuid(vm: &VirtualMachine) -> PyObjectRef {
|
||||
let euid = unistd::geteuid().as_raw();
|
||||
vm.new_int(euid)
|
||||
vm.ctx.new_int(euid)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -1557,7 +1557,7 @@ mod posix {
|
||||
let r = nix::pty::openpty(None, None).map_err(|err| err.into_pyexception(vm))?;
|
||||
Ok(vm
|
||||
.ctx
|
||||
.new_tuple(vec![vm.new_int(r.master), vm.new_int(r.slave)]))
|
||||
.new_tuple(vec![vm.ctx.new_int(r.master), vm.ctx.new_int(r.slave)]))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -1567,7 +1567,7 @@ mod posix {
|
||||
Err(errno_err(vm))
|
||||
} else {
|
||||
let name = unsafe { ffi::CStr::from_ptr(name) }.to_str().unwrap();
|
||||
Ok(vm.ctx.new_str(name.to_owned()))
|
||||
Ok(vm.ctx.new_str(name))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2239,7 +2239,7 @@ mod nt {
|
||||
|
||||
for (key, value) in env::vars() {
|
||||
environ
|
||||
.set_item(vm.new_str(key), vm.new_str(value), vm)
|
||||
.set_item(vm.ctx.new_str(key), vm.ctx.new_str(value), vm)
|
||||
.unwrap();
|
||||
}
|
||||
environ
|
||||
|
||||
@@ -50,7 +50,9 @@ fn pwd_getpwnam(name: PyStringRef, vm: &VirtualMachine) -> PyResult {
|
||||
.into_object()),
|
||||
None => {
|
||||
let name_repr = vm.to_repr(name.as_object())?;
|
||||
let message = vm.new_str(format!("getpwnam(): name not found: {}", name_repr));
|
||||
let message = vm
|
||||
.ctx
|
||||
.new_str(format!("getpwnam(): name not found: {}", name_repr));
|
||||
Err(vm.new_key_error(message))
|
||||
}
|
||||
}
|
||||
@@ -67,7 +69,9 @@ fn pwd_getpwuid(uid: PyIntRef, vm: &VirtualMachine) -> PyResult {
|
||||
.into_struct_sequence(vm, vm.try_class("pwd", "struct_passwd")?)?
|
||||
.into_object()),
|
||||
None => {
|
||||
let message = vm.new_str(format!("getpwuid(): uid not found: {}", uid.borrow_value()));
|
||||
let message = vm
|
||||
.ctx
|
||||
.new_str(format!("getpwuid(): uid not found: {}", uid.borrow_value()));
|
||||
Err(vm.new_key_error(message))
|
||||
}
|
||||
}
|
||||
|
||||
+11
-15
@@ -162,7 +162,7 @@ fn do_sub(
|
||||
repl.borrow_value().as_bytes(),
|
||||
);
|
||||
let out = String::from_utf8_lossy(&out).into_owned();
|
||||
Ok(vm.new_str(out))
|
||||
Ok(vm.ctx.new_str(out))
|
||||
}
|
||||
|
||||
fn do_match(vm: &VirtualMachine, pattern: &PyPattern, search_text: PyStringRef) -> PyResult {
|
||||
@@ -192,12 +192,12 @@ fn do_findall(vm: &VirtualMachine, pattern: &PyPattern, search_text: PyStringRef
|
||||
1 => {
|
||||
let full = captures.get(0).unwrap().as_bytes();
|
||||
let full = String::from_utf8_lossy(full).into_owned();
|
||||
vm.new_str(full)
|
||||
vm.ctx.new_str(full)
|
||||
}
|
||||
2 => {
|
||||
let capture = captures.get(1).unwrap().as_bytes();
|
||||
let capture = String::from_utf8_lossy(capture).into_owned();
|
||||
vm.new_str(capture)
|
||||
vm.ctx.new_str(capture)
|
||||
}
|
||||
_ => {
|
||||
let out = captures
|
||||
@@ -257,7 +257,7 @@ fn do_split(
|
||||
let split = output
|
||||
.into_iter()
|
||||
.map(|v| {
|
||||
v.map(|v| vm.new_str(String::from_utf8_lossy(v).into_owned()))
|
||||
v.map(|v| vm.ctx.new_str(String::from_utf8_lossy(v).into_owned()))
|
||||
.unwrap_or_else(|| vm.get_none())
|
||||
})
|
||||
.collect();
|
||||
@@ -370,31 +370,27 @@ impl PyPattern {
|
||||
impl PyMatch {
|
||||
#[pymethod]
|
||||
fn start(&self, group: OptionalArg, vm: &VirtualMachine) -> PyResult {
|
||||
let group = group.unwrap_or_else(|| vm.new_int(0));
|
||||
let group = group.unwrap_or_else(|| vm.ctx.new_int(0));
|
||||
let start = self
|
||||
.get_bounds(group, vm)?
|
||||
.map_or_else(|| vm.new_int(-1), |r| vm.new_int(r.start));
|
||||
.map_or_else(|| vm.ctx.new_int(-1), |r| vm.ctx.new_int(r.start));
|
||||
Ok(start)
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn end(&self, group: OptionalArg, vm: &VirtualMachine) -> PyResult {
|
||||
let group = group.unwrap_or_else(|| vm.new_int(0));
|
||||
let group = group.unwrap_or_else(|| vm.ctx.new_int(0));
|
||||
let end = self
|
||||
.get_bounds(group, vm)?
|
||||
.map_or_else(|| vm.new_int(-1), |r| vm.new_int(r.end));
|
||||
.map_or_else(|| vm.ctx.new_int(-1), |r| vm.ctx.new_int(r.end));
|
||||
Ok(end)
|
||||
}
|
||||
|
||||
fn subgroup(&self, bounds: std::ops::Range<usize>, vm: &VirtualMachine) -> PyObjectRef {
|
||||
vm.new_str(self.haystack.borrow_value()[bounds].to_owned())
|
||||
fn subgroup(&self, bounds: Range<usize>, vm: &VirtualMachine) -> PyObjectRef {
|
||||
vm.ctx.new_str(&self.haystack.borrow_value()[bounds])
|
||||
}
|
||||
|
||||
fn get_bounds(
|
||||
&self,
|
||||
id: PyObjectRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Option<std::ops::Range<usize>>> {
|
||||
fn get_bounds(&self, id: PyObjectRef, vm: &VirtualMachine) -> PyResult<Option<Range<usize>>> {
|
||||
match_class!(match id {
|
||||
i @ PyInt => {
|
||||
let i = usize::try_from_object(vm, i.into_object())?;
|
||||
|
||||
@@ -112,7 +112,7 @@ pub fn check_signals(vm: &VirtualMachine) -> PyResult<()> {
|
||||
if triggerd {
|
||||
let handler = &signal_handlers[signum];
|
||||
if vm.is_callable(handler) {
|
||||
vm.invoke(handler, vec![vm.new_int(signum), vm.get_none()])?;
|
||||
vm.invoke(handler, vec![vm.ctx.new_int(signum), vm.get_none()])?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,7 +324,7 @@ impl PySocket {
|
||||
if ret < 0 {
|
||||
Err(convert_sock_error(vm, io::Error::last_os_error()))
|
||||
} else {
|
||||
Ok(vm.new_int(flag))
|
||||
Ok(vm.ctx.new_int(flag))
|
||||
}
|
||||
} else {
|
||||
if buflen <= 0 || buflen > 1024 {
|
||||
@@ -473,7 +473,7 @@ fn get_addr_tuple<A: Into<socket2::SockAddr>>(addr: A) -> AddrTuple {
|
||||
fn socket_gethostname(vm: &VirtualMachine) -> PyResult {
|
||||
gethostname()
|
||||
.into_string()
|
||||
.map(|hostname| vm.new_str(hostname))
|
||||
.map(|hostname| vm.ctx.new_str(hostname))
|
||||
.map_err(|err| vm.new_os_error(err.into_string().unwrap()))
|
||||
}
|
||||
|
||||
@@ -495,7 +495,7 @@ fn socket_inet_ntoa(packed_ip: PyBytesRef, vm: &VirtualMachine) -> PyResult {
|
||||
return Err(vm.new_os_error("packed IP wrong length for inet_ntoa".to_owned()));
|
||||
}
|
||||
let ip_num = BigEndian::read_u32(&packed_ip);
|
||||
Ok(vm.new_str(Ipv4Addr::from(ip_num).to_string()))
|
||||
Ok(vm.ctx.new_str(Ipv4Addr::from(ip_num).to_string()))
|
||||
}
|
||||
|
||||
#[derive(FromArgs)]
|
||||
@@ -542,11 +542,11 @@ fn socket_getaddrinfo(opts: GAIOptions, vm: &VirtualMachine) -> PyResult {
|
||||
.map(|ai| {
|
||||
ai.map(|ai| {
|
||||
vm.ctx.new_tuple(vec![
|
||||
vm.new_int(ai.address),
|
||||
vm.new_int(ai.socktype),
|
||||
vm.new_int(ai.protocol),
|
||||
vm.ctx.new_int(ai.address),
|
||||
vm.ctx.new_int(ai.socktype),
|
||||
vm.ctx.new_int(ai.protocol),
|
||||
match ai.canonname {
|
||||
Some(s) => vm.new_str(s),
|
||||
Some(s) => vm.ctx.new_str(s),
|
||||
None => vm.get_none(),
|
||||
},
|
||||
get_addr_tuple(ai.sockaddr).into_pyobject(vm),
|
||||
@@ -575,7 +575,7 @@ fn socket_gethostbyaddr(
|
||||
hostname,
|
||||
vm.ctx.new_list(vec![]),
|
||||
vm.ctx
|
||||
.new_list(vec![vm.new_str(ai.sockaddr.ip().to_string())]),
|
||||
.new_list(vec![vm.ctx.new_str(ai.sockaddr.ip().to_string())]),
|
||||
))
|
||||
}
|
||||
|
||||
|
||||
+26
-22
@@ -130,14 +130,14 @@ fn ssl_enum_certificates(store_name: PyStringRef, vm: &VirtualMachine) -> PyResu
|
||||
(*ptr).dwCertEncodingType
|
||||
};
|
||||
let enc_type = match enc_type {
|
||||
wincrypt::X509_ASN_ENCODING => vm.new_str("x509_asn".to_owned()),
|
||||
wincrypt::PKCS_7_ASN_ENCODING => vm.new_str("pkcs_7_asn".to_owned()),
|
||||
other => vm.new_int(other),
|
||||
wincrypt::X509_ASN_ENCODING => vm.ctx.new_str("x509_asn"),
|
||||
wincrypt::PKCS_7_ASN_ENCODING => vm.ctx.new_str("pkcs_7_asn"),
|
||||
other => vm.ctx.new_int(other),
|
||||
};
|
||||
let usage = match c.valid_uses()? {
|
||||
ValidUses::All => vm.new_bool(true),
|
||||
ValidUses::All => vm.ctx.new_bool(true),
|
||||
ValidUses::Oids(oids) => {
|
||||
PyFrozenSet::from_iter(vm, oids.into_iter().map(|oid| vm.new_str(oid)))
|
||||
PyFrozenSet::from_iter(vm, oids.into_iter().map(|oid| vm.ctx.new_str(oid)))
|
||||
.unwrap()
|
||||
.into_ref(vm)
|
||||
.into_object()
|
||||
@@ -620,7 +620,7 @@ impl PySslSocket {
|
||||
stream.ssl_read(&mut buf.elements)
|
||||
})
|
||||
.map_err(|e| convert_ssl_error(vm, e))?;
|
||||
Ok(vm.new_int(n))
|
||||
Ok(vm.ctx.new_int(n))
|
||||
} else {
|
||||
let mut buf = vec![0u8; n];
|
||||
buf.truncate(n);
|
||||
@@ -669,10 +669,10 @@ fn cert_to_py(vm: &VirtualMachine, cert: &X509Ref, binary: bool) -> PyResult {
|
||||
name.entries()
|
||||
.map(|entry| {
|
||||
let txt = match obj2txt(entry.object(), false) {
|
||||
Some(s) => vm.new_str(s),
|
||||
Some(s) => vm.ctx.new_str(s),
|
||||
None => vm.get_none(),
|
||||
};
|
||||
let data = vm.new_str(entry.data().as_utf8()?.to_owned());
|
||||
let data = vm.ctx.new_str(entry.data().as_utf8()?.to_owned());
|
||||
Ok(vm.ctx.new_tuple(vec![vm.ctx.new_tuple(vec![txt, data])]))
|
||||
})
|
||||
.collect::<Result<_, _>>()
|
||||
@@ -684,36 +684,40 @@ fn cert_to_py(vm: &VirtualMachine, cert: &X509Ref, binary: bool) -> PyResult {
|
||||
dict.set_item("issuer", name_to_py(cert.issuer_name())?, vm)?;
|
||||
|
||||
let version = unsafe { sys::X509_get_version(cert.as_ptr()) };
|
||||
dict.set_item("version", vm.new_int(version), vm)?;
|
||||
dict.set_item("version", vm.ctx.new_int(version), vm)?;
|
||||
|
||||
let serial_num = cert
|
||||
.serial_number()
|
||||
.to_bn()
|
||||
.and_then(|bn| bn.to_hex_str())
|
||||
.map_err(|e| convert_openssl_error(vm, e))?;
|
||||
dict.set_item("serialNumber", vm.new_str(serial_num.to_owned()), vm)?;
|
||||
dict.set_item("serialNumber", vm.ctx.new_str(serial_num.to_owned()), vm)?;
|
||||
|
||||
dict.set_item("notBefore", vm.new_str(cert.not_before().to_string()), vm)?;
|
||||
dict.set_item("notAfter", vm.new_str(cert.not_after().to_string()), vm)?;
|
||||
dict.set_item(
|
||||
"notBefore",
|
||||
vm.ctx.new_str(cert.not_before().to_string()),
|
||||
vm,
|
||||
)?;
|
||||
dict.set_item("notAfter", vm.ctx.new_str(cert.not_after().to_string()), vm)?;
|
||||
|
||||
if let Some(names) = cert.subject_alt_names() {
|
||||
let san = names
|
||||
.iter()
|
||||
.filter_map(|gen_name| {
|
||||
if let Some(email) = gen_name.email() {
|
||||
Some(vm.ctx.new_tuple(vec![
|
||||
vm.new_str("email".to_owned()),
|
||||
vm.new_str(email.to_owned()),
|
||||
]))
|
||||
Some(
|
||||
vm.ctx
|
||||
.new_tuple(vec![vm.ctx.new_str("email"), vm.ctx.new_str(email)]),
|
||||
)
|
||||
} else if let Some(dnsname) = gen_name.dnsname() {
|
||||
Some(vm.ctx.new_tuple(vec![
|
||||
vm.new_str("DNS".to_owned()),
|
||||
vm.new_str(dnsname.to_owned()),
|
||||
]))
|
||||
Some(
|
||||
vm.ctx
|
||||
.new_tuple(vec![vm.ctx.new_str("DNS"), vm.ctx.new_str(dnsname)]),
|
||||
)
|
||||
} else if let Some(ip) = gen_name.ipaddress() {
|
||||
Some(vm.ctx.new_tuple(vec![
|
||||
vm.new_str("IP Address".to_owned()),
|
||||
vm.new_str(String::from_utf8_lossy(ip).into_owned()),
|
||||
vm.ctx.new_str("IP Address"),
|
||||
vm.ctx.new_str(String::from_utf8_lossy(ip).into_owned()),
|
||||
]))
|
||||
} else {
|
||||
// TODO: convert every type of general name:
|
||||
|
||||
@@ -78,7 +78,7 @@ mod _string {
|
||||
FieldName::parse(text.borrow_value()).map_err(|e| e.into_pyexception(vm))?;
|
||||
|
||||
let first = match field_name.field_type {
|
||||
FieldType::Auto => vm.new_str("".to_owned()),
|
||||
FieldType::Auto => vm.ctx.new_str("".to_owned()),
|
||||
FieldType::Index(index) => index.into_pyobject(vm),
|
||||
FieldType::Keyword(attribute) => attribute.into_pyobject(vm),
|
||||
};
|
||||
|
||||
@@ -119,7 +119,7 @@ impl PySymbolTable {
|
||||
}
|
||||
.into_ref(vm))
|
||||
} else {
|
||||
Err(vm.new_key_error(vm.new_str(format!("lookup {} failed", name))))
|
||||
Err(vm.new_key_error(vm.ctx.new_str(format!("lookup {} failed", name))))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ impl PySymbolTable {
|
||||
.symtable
|
||||
.symbols
|
||||
.keys()
|
||||
.map(|s| vm.ctx.new_str(s.to_owned()))
|
||||
.map(|s| vm.ctx.new_str(s))
|
||||
.collect();
|
||||
Ok(vm.ctx.new_list(symbols))
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
|
||||
let vars = vm.ctx.new_dict();
|
||||
macro_rules! hashmap {
|
||||
($($key:literal => $value:literal),*) => {{
|
||||
$(vars.set_item($key, vm.new_str($value.to_owned()), vm).unwrap();)*
|
||||
$(vars.set_item($key, vm.ctx.new_str($value.to_owned()), vm).unwrap();)*
|
||||
}};
|
||||
}
|
||||
include!(concat!(env!("OUT_DIR"), "/env_vars.rs"));
|
||||
|
||||
@@ -128,7 +128,7 @@ impl PyUCD {
|
||||
if let Some(c) = c {
|
||||
if self.check_age(c) {
|
||||
if let Some(name) = unicode_names2::name(c) {
|
||||
return Ok(vm.new_str(name.to_string()));
|
||||
return Ok(vm.ctx.new_str(name.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,7 +191,7 @@ fn reg_to_py(value: RegValue, vm: &VirtualMachine) -> PyResult {
|
||||
vm.new_value_error(format!("{} value is wrong length", stringify!(name)))
|
||||
})
|
||||
};
|
||||
i.map(|i| vm.new_int(i))
|
||||
i.map(|i| vm.ctx.new_int(i))
|
||||
}};
|
||||
};
|
||||
let bytes_to_wide = |b: &[u8]| -> Option<&[u16]> {
|
||||
@@ -215,7 +215,7 @@ fn reg_to_py(value: RegValue, vm: &VirtualMachine) -> PyResult {
|
||||
.position(|w| *w == 0)
|
||||
.unwrap_or_else(|| wide_slice.len());
|
||||
let s = String::from_utf16_lossy(&wide_slice[..nul_pos]);
|
||||
Ok(vm.new_str(s))
|
||||
Ok(vm.ctx.new_str(s))
|
||||
}
|
||||
RegType::REG_MULTI_SZ => {
|
||||
if value.bytes.is_empty() {
|
||||
@@ -233,7 +233,7 @@ fn reg_to_py(value: RegValue, vm: &VirtualMachine) -> PyResult {
|
||||
};
|
||||
let strings = wide_slice
|
||||
.split(|c| *c == 0)
|
||||
.map(|s| vm.new_str(String::from_utf16_lossy(s)))
|
||||
.map(|s| vm.ctx.new_str(String::from_utf16_lossy(s)))
|
||||
.collect();
|
||||
Ok(vm.ctx.new_list(strings))
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ fn zlib_adler32(data: PyBytesRef, begin_state: OptionalArg<i32>, vm: &VirtualMac
|
||||
|
||||
let checksum: u32 = hasher.hash();
|
||||
|
||||
Ok(vm.new_int(checksum))
|
||||
Ok(vm.ctx.new_int(checksum))
|
||||
}
|
||||
|
||||
/// Compute a CRC-32 checksum of data.
|
||||
@@ -76,7 +76,7 @@ fn zlib_crc32(data: PyBytesRef, begin_state: OptionalArg<i32>, vm: &VirtualMachi
|
||||
|
||||
let checksum: u32 = hasher.finalize();
|
||||
|
||||
Ok(vm.new_int(checksum))
|
||||
Ok(vm.ctx.new_int(checksum))
|
||||
}
|
||||
|
||||
/// Returns a bytes object containing compressed data.
|
||||
|
||||
+15
-15
@@ -21,7 +21,7 @@ fn argv(vm: &VirtualMachine) -> PyObjectRef {
|
||||
.settings
|
||||
.argv
|
||||
.iter()
|
||||
.map(|arg| vm.new_str(arg.to_owned()))
|
||||
.map(|arg| vm.ctx.new_str(arg))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
@@ -214,7 +214,7 @@ fn sys_exc_info(vm: &VirtualMachine) -> PyObjectRef {
|
||||
|
||||
fn sys_git_info(vm: &VirtualMachine) -> PyObjectRef {
|
||||
vm.ctx.new_tuple(vec![
|
||||
vm.ctx.new_str("RustPython".to_owned()),
|
||||
vm.ctx.new_str("RustPython"),
|
||||
vm.ctx.new_str(version::get_git_identifier()),
|
||||
vm.ctx.new_str(version::get_git_revision()),
|
||||
])
|
||||
@@ -472,8 +472,8 @@ pub fn make_module(vm: &VirtualMachine, module: PyObjectRef, builtins: PyObjectR
|
||||
|
||||
// TODO Add crate version to this namespace
|
||||
let implementation = py_namespace!(vm, {
|
||||
"name" => ctx.new_str("rustpython".to_owned()),
|
||||
"cache_tag" => ctx.new_str("rustpython-01".to_owned()),
|
||||
"name" => ctx.new_str("rustpython"),
|
||||
"cache_tag" => ctx.new_str("rustpython-01"),
|
||||
"_multiarch" => ctx.new_str(MULTIARCH.to_owned()),
|
||||
"version" => version_info.clone(),
|
||||
"hexversion" => ctx.new_int(version::VERSION_HEX),
|
||||
@@ -590,7 +590,7 @@ settrace() -- set the global debug tracing function
|
||||
"argv" => argv(vm),
|
||||
"builtin_module_names" => builtin_module_names,
|
||||
"byteorder" => ctx.new_str(bytorder),
|
||||
"copyright" => ctx.new_str(copyright.to_owned()),
|
||||
"copyright" => ctx.new_str(copyright),
|
||||
"_base_executable" => _base_executable(ctx),
|
||||
"executable" => executable(ctx),
|
||||
"flags" => flags,
|
||||
@@ -608,9 +608,9 @@ settrace() -- set the global debug tracing function
|
||||
"maxunicode" => ctx.new_int(std::char::MAX as u32),
|
||||
"maxsize" => ctx.new_int(std::isize::MAX),
|
||||
"path" => path,
|
||||
"ps1" => ctx.new_str(">>>>> ".to_owned()),
|
||||
"ps2" => ctx.new_str("..... ".to_owned()),
|
||||
"__doc__" => ctx.new_str(sys_doc.to_owned()),
|
||||
"ps1" => ctx.new_str(">>>>> "),
|
||||
"ps2" => ctx.new_str("..... "),
|
||||
"__doc__" => ctx.new_str(sys_doc),
|
||||
"_getframe" => ctx.new_function(getframe),
|
||||
"modules" => modules.clone(),
|
||||
"warnoptions" => ctx.new_list(vec![]),
|
||||
@@ -620,18 +620,18 @@ settrace() -- set the global debug tracing function
|
||||
"path_hooks" => ctx.new_list(vec![]),
|
||||
"path_importer_cache" => ctx.new_dict(),
|
||||
"pycache_prefix" => vm.get_none(),
|
||||
"dont_write_bytecode" => vm.new_bool(vm.state.settings.dont_write_bytecode),
|
||||
"dont_write_bytecode" => vm.ctx.new_bool(vm.state.settings.dont_write_bytecode),
|
||||
"setprofile" => ctx.new_function(sys_setprofile),
|
||||
"setrecursionlimit" => ctx.new_function(sys_setrecursionlimit),
|
||||
"settrace" => ctx.new_function(sys_settrace),
|
||||
"version" => vm.new_str(version::get_version()),
|
||||
"version" => vm.ctx.new_str(version::get_version()),
|
||||
"version_info" => version_info,
|
||||
"_git" => sys_git_info(vm),
|
||||
"exc_info" => ctx.new_function(sys_exc_info),
|
||||
"prefix" => ctx.new_str(prefix.to_owned()),
|
||||
"base_prefix" => ctx.new_str(base_prefix.to_owned()),
|
||||
"exec_prefix" => ctx.new_str(exec_prefix.to_owned()),
|
||||
"base_exec_prefix" => ctx.new_str(base_exec_prefix.to_owned()),
|
||||
"prefix" => ctx.new_str(prefix),
|
||||
"base_prefix" => ctx.new_str(base_prefix),
|
||||
"exec_prefix" => ctx.new_str(exec_prefix),
|
||||
"base_exec_prefix" => ctx.new_str(base_exec_prefix),
|
||||
"exit" => ctx.new_function(sys_exit),
|
||||
"abiflags" => ctx.new_str(ABIFLAGS.to_owned()),
|
||||
"audit" => ctx.new_function(sys_audit),
|
||||
@@ -643,7 +643,7 @@ settrace() -- set the global debug tracing function
|
||||
"api_version" => ctx.new_int(0x0), // what C api?
|
||||
"float_info" => float_info,
|
||||
"int_info" => int_info,
|
||||
"float_repr_style" => ctx.new_str("short".to_owned()),
|
||||
"float_repr_style" => ctx.new_str("short"),
|
||||
});
|
||||
|
||||
#[cfg(windows)]
|
||||
|
||||
+30
-47
@@ -11,8 +11,6 @@ use std::{env, fmt};
|
||||
|
||||
use arr_macro::arr;
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
use num_bigint::BigInt;
|
||||
use num_traits::ToPrimitive;
|
||||
use once_cell::sync::Lazy;
|
||||
use parking_lot::{Mutex, MutexGuard};
|
||||
#[cfg(feature = "rustpython-compiler")]
|
||||
@@ -40,8 +38,8 @@ use crate::obj::objstr::{PyString, PyStringRef};
|
||||
use crate::obj::objtuple::PyTuple;
|
||||
use crate::obj::objtype::{self, PyClassRef};
|
||||
use crate::pyobject::{
|
||||
BorrowValue, IdProtocol, ItemProtocol, PyContext, PyObject, PyObjectRef, PyRef, PyResult,
|
||||
PyValue, TryFromObject, TryIntoRef, TypeProtocol,
|
||||
BorrowValue, IdProtocol, IntoPyObject, ItemProtocol, PyContext, PyObject, PyObjectRef, PyRef,
|
||||
PyResult, PyValue, TryFromObject, TryIntoRef, TypeProtocol,
|
||||
};
|
||||
use crate::scope::Scope;
|
||||
use crate::stdlib;
|
||||
@@ -216,15 +214,10 @@ impl VirtualMachine {
|
||||
objmodule::init_module_dict(
|
||||
&vm,
|
||||
&builtins_dict,
|
||||
vm.new_str("builtins".to_owned()),
|
||||
vm.get_none(),
|
||||
);
|
||||
objmodule::init_module_dict(
|
||||
&vm,
|
||||
&sysmod_dict,
|
||||
vm.new_str("sys".to_owned()),
|
||||
vm.ctx.new_str("builtins"),
|
||||
vm.get_none(),
|
||||
);
|
||||
objmodule::init_module_dict(&vm, &sysmod_dict, vm.ctx.new_str("sys"), vm.get_none());
|
||||
vm.initialize(initialize_parameter);
|
||||
vm
|
||||
}
|
||||
@@ -258,7 +251,7 @@ impl VirtualMachine {
|
||||
let set_stdio = |name, fd, mode: &str| {
|
||||
let stdio = self.invoke(
|
||||
&io_open,
|
||||
vec![self.new_int(fd), self.new_str(mode.to_owned())],
|
||||
vec![self.ctx.new_int(fd), self.new_pyobj(mode)],
|
||||
)?;
|
||||
self.set_attr(
|
||||
&self.sys_module,
|
||||
@@ -379,25 +372,18 @@ impl VirtualMachine {
|
||||
class.downcast().expect("not a class")
|
||||
}
|
||||
|
||||
/// Create a new python string object.
|
||||
pub fn new_str(&self, s: String) -> PyObjectRef {
|
||||
self.ctx.new_str(s)
|
||||
}
|
||||
|
||||
/// Create a new python int object.
|
||||
#[inline]
|
||||
pub fn new_int<T: Into<BigInt> + ToPrimitive>(&self, i: T) -> PyObjectRef {
|
||||
self.ctx.new_int(i)
|
||||
}
|
||||
|
||||
/// Create a new python bool object.
|
||||
#[inline]
|
||||
pub fn new_bool(&self, b: bool) -> PyObjectRef {
|
||||
self.ctx.new_bool(b)
|
||||
/// Create a new python object
|
||||
pub fn new_pyobj<T: IntoPyObject>(&self, value: T) -> PyObjectRef {
|
||||
value.into_pyobject(self)
|
||||
}
|
||||
|
||||
pub fn new_module(&self, name: &str, dict: PyDictRef) -> PyObjectRef {
|
||||
objmodule::init_module_dict(self, &dict, self.new_str(name.to_owned()), self.get_none());
|
||||
objmodule::init_module_dict(
|
||||
self,
|
||||
&dict,
|
||||
self.new_pyobj(name.to_owned()),
|
||||
self.get_none(),
|
||||
);
|
||||
PyObject::new(PyModule {}, self.ctx.types.module_type.clone(), Some(dict))
|
||||
}
|
||||
|
||||
@@ -440,7 +426,7 @@ impl VirtualMachine {
|
||||
/// [invoke]: rustpython_vm::exceptions::invoke
|
||||
/// [ctor]: rustpython_vm::exceptions::ExceptionCtor
|
||||
pub fn new_exception_msg(&self, exc_type: PyClassRef, msg: String) -> PyBaseExceptionRef {
|
||||
self.new_exception(exc_type, vec![self.new_str(msg)])
|
||||
self.new_exception(exc_type, vec![self.ctx.new_str(msg)])
|
||||
}
|
||||
|
||||
pub fn new_lookup_error(&self, msg: String) -> PyBaseExceptionRef {
|
||||
@@ -539,20 +525,20 @@ impl VirtualMachine {
|
||||
self.ctx.exceptions.syntax_error.clone()
|
||||
};
|
||||
let syntax_error = self.new_exception_msg(syntax_error_type, error.to_string());
|
||||
let lineno = self.new_int(error.location.row());
|
||||
let offset = self.new_int(error.location.column());
|
||||
let lineno = self.ctx.new_int(error.location.row());
|
||||
let offset = self.ctx.new_int(error.location.column());
|
||||
self.set_attr(syntax_error.as_object(), "lineno", lineno)
|
||||
.unwrap();
|
||||
self.set_attr(syntax_error.as_object(), "offset", offset)
|
||||
.unwrap();
|
||||
if let Some(v) = error.statement.as_ref() {
|
||||
self.set_attr(syntax_error.as_object(), "text", self.new_str(v.to_owned()))
|
||||
self.set_attr(syntax_error.as_object(), "text", self.new_pyobj(v))
|
||||
.unwrap();
|
||||
}
|
||||
self.set_attr(
|
||||
syntax_error.as_object(),
|
||||
"filename",
|
||||
self.new_str(error.source_path.clone()),
|
||||
self.ctx.new_str(error.source_path.clone()),
|
||||
)
|
||||
.unwrap();
|
||||
syntax_error
|
||||
@@ -561,7 +547,7 @@ impl VirtualMachine {
|
||||
pub fn new_import_error(&self, msg: String, name: &str) -> PyBaseExceptionRef {
|
||||
let import_error = self.ctx.exceptions.import_error.clone();
|
||||
let exc = self.new_exception_msg(import_error, msg);
|
||||
self.set_attr(exc.as_object(), "name", self.new_str(name.to_owned()))
|
||||
self.set_attr(exc.as_object(), "name", self.new_pyobj(name))
|
||||
.unwrap();
|
||||
exc
|
||||
}
|
||||
@@ -667,7 +653,7 @@ impl VirtualMachine {
|
||||
let repr = self.call_method(obj, "__repr__", vec![])?;
|
||||
let repr: PyStringRef = TryFromObject::try_from_object(self, repr)?;
|
||||
let ascii = to_ascii(repr.borrow_value());
|
||||
Ok(self.new_str(ascii))
|
||||
Ok(self.ctx.new_str(ascii))
|
||||
}
|
||||
|
||||
pub fn to_index(&self, obj: &PyObjectRef) -> Option<PyResult<PyIntRef>> {
|
||||
@@ -729,16 +715,13 @@ impl VirtualMachine {
|
||||
} else {
|
||||
(self.get_none(), self.get_none())
|
||||
};
|
||||
let from_list = self.ctx.new_tuple(
|
||||
from_list
|
||||
.iter()
|
||||
.map(|name| self.new_str(name.to_owned()))
|
||||
.collect(),
|
||||
);
|
||||
let from_list = self
|
||||
.ctx
|
||||
.new_tuple(from_list.iter().map(|name| self.new_pyobj(name)).collect());
|
||||
self.invoke(
|
||||
&import_func,
|
||||
vec![
|
||||
self.new_str(module.to_owned()),
|
||||
self.new_pyobj(module),
|
||||
globals,
|
||||
locals,
|
||||
from_list,
|
||||
@@ -860,7 +843,7 @@ impl VirtualMachine {
|
||||
fn trace_event(&self, event: TraceEvent) -> PyResult<()> {
|
||||
if self.use_tracing.get() {
|
||||
let frame = self.get_none();
|
||||
let event = self.new_str(event.to_string());
|
||||
let event = self.ctx.new_str(event.to_string());
|
||||
let arg = self.get_none();
|
||||
let args = vec![frame, event, arg];
|
||||
|
||||
@@ -1374,13 +1357,13 @@ impl VirtualMachine {
|
||||
|
||||
pub fn _eq(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult {
|
||||
self._cmp(a, b, "__eq__", "__eq__", |vm, a, b| {
|
||||
Ok(vm.new_bool(a.is(&b)))
|
||||
Ok(vm.ctx.new_bool(a.is(&b)))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn _ne(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult {
|
||||
self._cmp(a, b, "__ne__", "__ne__", |vm, a, b| {
|
||||
Ok(vm.new_bool(!a.is(&b)))
|
||||
Ok(vm.ctx.new_bool(!a.is(&b)))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1423,12 +1406,12 @@ impl VirtualMachine {
|
||||
loop {
|
||||
if let Some(element) = objiter::get_next_object(self, &iter)? {
|
||||
if self.bool_eq(needle.clone(), element.clone())? {
|
||||
return Ok(self.new_bool(true));
|
||||
return Ok(self.ctx.new_bool(true));
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
return Ok(self.new_bool(false));
|
||||
return Ok(self.ctx.new_bool(false));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -298,7 +298,7 @@ impl Element {
|
||||
vm: &VirtualMachine,
|
||||
) -> PyObjectRef {
|
||||
match self.elem.get_attribute(attr.borrow_value()) {
|
||||
Some(s) => vm.new_str(s),
|
||||
Some(s) => vm.ctx.new_str(s),
|
||||
None => default.into_option().unwrap_or_else(|| vm.get_none()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,7 +259,7 @@ impl WASMVirtualMachine {
|
||||
.map_err(convert::syntax_err)?;
|
||||
let attrs = vm.ctx.new_dict();
|
||||
attrs
|
||||
.set_item("__name__", vm.new_str(name.clone()), vm)
|
||||
.set_item("__name__", vm.ctx.new_str(name.clone()), vm)
|
||||
.to_js(vm)?;
|
||||
|
||||
if let Some(imports) = imports {
|
||||
|
||||
Reference in new issue
Block a user