Merge pull request #1506 from youknowone/refactoring

Refactor function signatures
This commit is contained in:
Windel Bouwman
2019-10-11 17:35:24 +02:00
committed by GitHub
52 changed files with 444 additions and 528 deletions

View File

@@ -9,8 +9,12 @@ use std::str;
use num_bigint::Sign;
use num_traits::{Signed, ToPrimitive, Zero};
#[cfg(feature = "rustpython-compiler")]
use rustpython_compiler::compile;
use crate::function::{single_or_tuple_any, Args, KwArgs, OptionalArg, PyFuncArgs};
use crate::obj::objbool::{self, IntoPyBool};
use crate::obj::objbyteinner::PyByteInner;
use crate::obj::objbytes::PyBytesRef;
use crate::obj::objcode::PyCodeRef;
use crate::obj::objdict::PyDictRef;
@@ -19,10 +23,7 @@ use crate::obj::objint::{self, PyIntRef};
use crate::obj::objiter;
use crate::obj::objstr::{PyString, PyStringRef};
use crate::obj::objtype::{self, PyClassRef};
#[cfg(feature = "rustpython-compiler")]
use rustpython_compiler::compile;
use crate::function::{single_or_tuple_any, Args, KwArgs, OptionalArg, PyFuncArgs};
use crate::pyhash;
use crate::pyobject::{
Either, IdProtocol, IntoPyObject, ItemProtocol, PyIterable, PyObjectRef, PyResult, PyValue,
TryFromObject, TypeProtocol,
@@ -30,7 +31,6 @@ use crate::pyobject::{
use crate::scope::Scope;
use crate::vm::VirtualMachine;
use crate::obj::objbyteinner::PyByteInner;
#[cfg(not(target_arch = "wasm32"))]
use crate::stdlib::io::io_open;
@@ -299,8 +299,8 @@ fn builtin_hasattr(obj: PyObjectRef, attr: PyStringRef, vm: &VirtualMachine) ->
}
}
fn builtin_hash(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
vm._hash(&obj).and_then(|v| Ok(vm.new_int(v)))
fn builtin_hash(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<pyhash::PyHash> {
vm._hash(&obj)
}
// builtin_help
@@ -308,7 +308,7 @@ fn builtin_hash(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
fn builtin_hex(number: PyIntRef, vm: &VirtualMachine) -> PyResult {
let n = number.as_bigint();
let s = if n.is_negative() {
format!("-0x{:x}", n.abs())
format!("-0x{:x}", -n)
} else {
format!("0x{:x}", n)
};
@@ -316,8 +316,8 @@ fn builtin_hex(number: PyIntRef, vm: &VirtualMachine) -> PyResult {
Ok(vm.new_str(s))
}
fn builtin_id(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Ok(vm.context().new_int(obj.get_id()))
fn builtin_id(obj: PyObjectRef, _vm: &VirtualMachine) -> usize {
obj.get_id()
}
// builtin_input
@@ -492,7 +492,7 @@ fn builtin_oct(number: PyIntRef, vm: &VirtualMachine) -> PyResult {
Ok(vm.new_str(s))
}
fn builtin_ord(string: Either<PyByteInner, PyStringRef>, vm: &VirtualMachine) -> PyResult {
fn builtin_ord(string: Either<PyByteInner, PyStringRef>, vm: &VirtualMachine) -> PyResult<u32> {
match string {
Either::A(bytes) => {
let bytes_len = bytes.elements.len();
@@ -502,7 +502,7 @@ fn builtin_ord(string: Either<PyByteInner, PyStringRef>, vm: &VirtualMachine) ->
bytes_len
)));
}
Ok(vm.context().new_int(bytes.elements[0]))
Ok(u32::from(bytes.elements[0]))
}
Either::B(string) => {
let string = string.as_str();
@@ -514,7 +514,7 @@ fn builtin_ord(string: Either<PyByteInner, PyStringRef>, vm: &VirtualMachine) ->
)));
}
match string.chars().next() {
Some(character) => Ok(vm.context().new_int(character as i32)),
Some(character) => Ok(character as u32),
None => Err(vm.new_type_error(
"ord() could not guess the integer representing this character".to_string(),
)),

View File

@@ -1,4 +1,3 @@
use crate::format::get_num_digits;
/// Implementation of Printf-Style string formatting
/// [https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting]
use num_bigint::{BigInt, Sign};
@@ -7,6 +6,8 @@ use std::cmp;
use std::fmt;
use std::str::FromStr;
use crate::format::get_num_digits;
#[derive(Debug, PartialEq)]
pub enum CFormatErrorType {
UnmatchedKeyParentheses,

View File

@@ -1,6 +1,9 @@
use std::cell::RefCell;
use std::fmt;
use indexmap::IndexMap;
use itertools::Itertools;
use crate::bytecode;
use crate::function::PyFuncArgs;
use crate::obj::objbool;
@@ -19,8 +22,6 @@ use crate::pyobject::{
};
use crate::scope::{NameProtocol, Scope};
use crate::vm::VirtualMachine;
use indexmap::IndexMap;
use itertools::Itertools;
#[cfg(not(target_arch = "wasm32"))]
use crate::stdlib::signal::check_signals;
@@ -1162,14 +1163,24 @@ impl Frame {
a.get_id()
}
fn _in(&self, vm: &VirtualMachine, needle: PyObjectRef, haystack: PyObjectRef) -> PyResult {
fn _in(
&self,
vm: &VirtualMachine,
needle: PyObjectRef,
haystack: PyObjectRef,
) -> PyResult<bool> {
let found = vm._membership(haystack.clone(), needle)?;
Ok(vm.ctx.new_bool(objbool::boolval(vm, found)?))
Ok(objbool::boolval(vm, found)?)
}
fn _not_in(&self, vm: &VirtualMachine, needle: PyObjectRef, haystack: PyObjectRef) -> PyResult {
fn _not_in(
&self,
vm: &VirtualMachine,
needle: PyObjectRef,
haystack: PyObjectRef,
) -> PyResult<bool> {
let found = vm._membership(haystack.clone(), needle)?;
Ok(vm.ctx.new_bool(!objbool::boolval(vm, found)?))
Ok(!objbool::boolval(vm, found)?)
}
fn _is(&self, a: PyObjectRef, b: PyObjectRef) -> bool {
@@ -1177,10 +1188,8 @@ impl Frame {
a.is(&b)
}
fn _is_not(&self, vm: &VirtualMachine, a: PyObjectRef, b: PyObjectRef) -> PyResult {
let result_bool = !a.is(&b);
let result = vm.ctx.new_bool(result_bool);
Ok(result)
fn _is_not(&self, a: PyObjectRef, b: PyObjectRef) -> bool {
!a.is(&b)
}
#[cfg_attr(feature = "flame-it", flame("Frame"))]
@@ -1199,9 +1208,9 @@ impl Frame {
bytecode::ComparisonOperator::Greater => vm._gt(a, b)?,
bytecode::ComparisonOperator::GreaterOrEqual => vm._ge(a, b)?,
bytecode::ComparisonOperator::Is => vm.ctx.new_bool(self._is(a, b)),
bytecode::ComparisonOperator::IsNot => self._is_not(vm, a, b)?,
bytecode::ComparisonOperator::In => self._in(vm, a, b)?,
bytecode::ComparisonOperator::NotIn => self._not_in(vm, 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)?),
};
self.push_value(value);

View File

@@ -85,19 +85,19 @@ The class bool is a subclass of the class int, and cannot be subclassed.";
"__repr__" => context.new_rustfunc(bool_repr),
"__format__" => context.new_rustfunc(bool_format),
"__or__" => context.new_rustfunc(bool_or),
"__ror__" => context.new_rustfunc(bool_ror),
"__ror__" => context.new_rustfunc(bool_or),
"__and__" => context.new_rustfunc(bool_and),
"__rand__" => context.new_rustfunc(bool_rand),
"__rand__" => context.new_rustfunc(bool_and),
"__xor__" => context.new_rustfunc(bool_xor),
"__rxor__" => context.new_rustfunc(bool_rxor),
"__rxor__" => context.new_rustfunc(bool_xor),
"__doc__" => context.new_str(bool_doc.to_string()),
});
}
pub fn not(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult {
pub fn not(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<bool> {
if objtype::isinstance(obj, &vm.ctx.bool_type()) {
let value = get_value(obj);
Ok(vm.ctx.new_bool(!value))
Ok(!value)
} else {
Err(vm.new_type_error(format!("Can only invert a bool, on {:?}", obj)))
}
@@ -128,66 +128,42 @@ fn bool_format(
}
}
fn do_bool_or(vm: &VirtualMachine, lhs: &PyObjectRef, rhs: &PyObjectRef) -> PyResult {
if objtype::isinstance(lhs, &vm.ctx.bool_type())
&& objtype::isinstance(rhs, &vm.ctx.bool_type())
fn bool_or(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
if objtype::isinstance(&lhs, &vm.ctx.bool_type())
&& objtype::isinstance(&rhs, &vm.ctx.bool_type())
{
let lhs = get_value(lhs);
let rhs = get_value(rhs);
let lhs = get_value(&lhs);
let rhs = get_value(&rhs);
(lhs || rhs).into_pyobject(vm)
} else {
Ok(lhs.payload::<PyInt>().unwrap().or(rhs.clone(), vm))
}
}
fn bool_or(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
do_bool_or(vm, &lhs, &rhs)
}
fn bool_ror(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
do_bool_or(vm, &lhs, &rhs)
}
fn do_bool_and(vm: &VirtualMachine, lhs: &PyObjectRef, rhs: &PyObjectRef) -> PyResult {
if objtype::isinstance(lhs, &vm.ctx.bool_type())
&& objtype::isinstance(rhs, &vm.ctx.bool_type())
fn bool_and(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
if objtype::isinstance(&lhs, &vm.ctx.bool_type())
&& objtype::isinstance(&rhs, &vm.ctx.bool_type())
{
let lhs = get_value(lhs);
let rhs = get_value(rhs);
let lhs = get_value(&lhs);
let rhs = get_value(&rhs);
(lhs && rhs).into_pyobject(vm)
} else {
Ok(lhs.payload::<PyInt>().unwrap().and(rhs.clone(), vm))
}
}
fn bool_and(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
do_bool_and(vm, &lhs, &rhs)
}
fn bool_rand(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
do_bool_and(vm, &lhs, &rhs)
}
fn do_bool_xor(vm: &VirtualMachine, lhs: &PyObjectRef, rhs: &PyObjectRef) -> PyResult {
if objtype::isinstance(lhs, &vm.ctx.bool_type())
&& objtype::isinstance(rhs, &vm.ctx.bool_type())
fn bool_xor(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
if objtype::isinstance(&lhs, &vm.ctx.bool_type())
&& objtype::isinstance(&rhs, &vm.ctx.bool_type())
{
let lhs = get_value(lhs);
let rhs = get_value(rhs);
let lhs = get_value(&lhs);
let rhs = get_value(&rhs);
(lhs ^ rhs).into_pyobject(vm)
} else {
Ok(lhs.payload::<PyInt>().unwrap().xor(rhs.clone(), vm))
}
}
fn bool_xor(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
do_bool_xor(vm, &lhs, &rhs)
}
fn bool_rxor(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
do_bool_xor(vm, &lhs, &rhs)
}
fn bool_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
@@ -195,13 +171,11 @@ fn bool_new(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
required = [(_zelf, Some(vm.ctx.type_type()))],
optional = [(val, None)]
);
Ok(match val {
Some(val) => {
let bv = boolval(vm, val.clone())?;
vm.new_bool(bv)
}
None => vm.context().new_bool(false),
})
let value = match val {
Some(val) => boolval(vm, val.clone())?,
None => false,
};
Ok(vm.new_bool(value))
}
#[derive(Debug, Copy, Clone, PartialEq)]

View File

@@ -1,26 +1,26 @@
//! Implementation of the python bytearray object.
use std::cell::{Cell, RefCell};
use std::convert::TryFrom;
use crate::function::OptionalArg;
use crate::obj::objbyteinner::{
use num_traits::ToPrimitive;
use super::objbyteinner::{
ByteInnerExpandtabsOptions, ByteInnerFindOptions, ByteInnerNewOptions, ByteInnerPaddingOptions,
ByteInnerPosition, ByteInnerSplitOptions, ByteInnerSplitlinesOptions,
ByteInnerTranslateOptions, ByteOr, PyByteInner,
};
use crate::obj::objint::PyIntRef;
use crate::obj::objslice::PySliceRef;
use crate::obj::objstr::PyStringRef;
use crate::obj::objtuple::PyTupleRef;
use super::objint::PyIntRef;
use super::objiter;
use super::objslice::PySliceRef;
use super::objstr::PyStringRef;
use super::objtuple::PyTupleRef;
use super::objtype::PyClassRef;
use crate::function::OptionalArg;
use crate::pyobject::{
Either, PyClassImpl, PyContext, PyIterable, PyObjectRef, PyRef, PyResult, PyValue,
TryFromObject,
};
use crate::vm::VirtualMachine;
use num_traits::ToPrimitive;
use std::cell::{Cell, RefCell};
use std::convert::TryFrom;
use super::objiter;
use super::objtype::PyClassRef;
/// "bytearray(iterable_of_ints) -> bytearray\n\
/// bytearray(string, encoding[, errors]) -> bytearray\n\
@@ -100,8 +100,8 @@ impl PyByteArrayRef {
}
#[pymethod(name = "__repr__")]
fn repr(self, vm: &VirtualMachine) -> PyResult {
Ok(vm.new_str(format!("bytearray(b'{}')", self.inner.borrow().repr()?)))
fn repr(self, _vm: &VirtualMachine) -> PyResult<String> {
Ok(format!("bytearray(b'{}')", self.inner.borrow().repr()?))
}
#[pymethod(name = "__len__")]
@@ -157,7 +157,11 @@ impl PyByteArrayRef {
}
#[pymethod(name = "__contains__")]
fn contains(self, needle: Either<PyByteInner, PyIntRef>, vm: &VirtualMachine) -> PyResult {
fn contains(
self,
needle: Either<PyByteInner, PyIntRef>,
vm: &VirtualMachine,
) -> PyResult<bool> {
self.inner.borrow().contains(needle, vm)
}
@@ -177,42 +181,42 @@ impl PyByteArrayRef {
}
#[pymethod(name = "isalnum")]
fn isalnum(self, vm: &VirtualMachine) -> PyResult {
fn isalnum(self, vm: &VirtualMachine) -> bool {
self.inner.borrow().isalnum(vm)
}
#[pymethod(name = "isalpha")]
fn isalpha(self, vm: &VirtualMachine) -> PyResult {
fn isalpha(self, vm: &VirtualMachine) -> bool {
self.inner.borrow().isalpha(vm)
}
#[pymethod(name = "isascii")]
fn isascii(self, vm: &VirtualMachine) -> PyResult {
fn isascii(self, vm: &VirtualMachine) -> bool {
self.inner.borrow().isascii(vm)
}
#[pymethod(name = "isdigit")]
fn isdigit(self, vm: &VirtualMachine) -> PyResult {
fn isdigit(self, vm: &VirtualMachine) -> bool {
self.inner.borrow().isdigit(vm)
}
#[pymethod(name = "islower")]
fn islower(self, vm: &VirtualMachine) -> PyResult {
fn islower(self, vm: &VirtualMachine) -> bool {
self.inner.borrow().islower(vm)
}
#[pymethod(name = "isspace")]
fn isspace(self, vm: &VirtualMachine) -> PyResult {
fn isspace(self, vm: &VirtualMachine) -> bool {
self.inner.borrow().isspace(vm)
}
#[pymethod(name = "isupper")]
fn isupper(self, vm: &VirtualMachine) -> PyResult {
fn isupper(self, vm: &VirtualMachine) -> bool {
self.inner.borrow().isupper(vm)
}
#[pymethod(name = "istitle")]
fn istitle(self, vm: &VirtualMachine) -> PyResult {
fn istitle(self, vm: &VirtualMachine) -> bool {
self.inner.borrow().istitle(vm)
}
@@ -237,7 +241,7 @@ impl PyByteArrayRef {
}
#[pymethod(name = "hex")]
fn hex(self, vm: &VirtualMachine) -> PyResult {
fn hex(self, vm: &VirtualMachine) -> String {
self.inner.borrow().hex(vm)
}
@@ -285,7 +289,7 @@ impl PyByteArrayRef {
start: OptionalArg<PyObjectRef>,
end: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult {
) -> PyResult<bool> {
self.inner
.borrow()
.startsendswith(suffix, start, end, true, vm)
@@ -298,7 +302,7 @@ impl PyByteArrayRef {
start: OptionalArg<PyObjectRef>,
end: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult {
) -> PyResult<bool> {
self.inner
.borrow()
.startsendswith(prefix, start, end, false, vm)

View File

@@ -1,35 +1,26 @@
use crate::obj::objint::PyIntRef;
use crate::obj::objnone::PyNoneRef;
use crate::obj::objslice::PySliceRef;
use crate::obj::objtuple::PyTupleRef;
use crate::pyhash;
use crate::pyobject::Either;
use crate::pyobject::PyRef;
use crate::pyobject::PyValue;
use crate::pyobject::TryFromObject;
use crate::pyobject::{PyIterable, PyObjectRef};
use core::convert::TryFrom;
use core::ops::Range;
use std::convert::TryFrom;
use std::ops::Range;
use num_bigint::BigInt;
use crate::function::OptionalArg;
use crate::pyobject::{PyResult, TypeProtocol};
use crate::vm::VirtualMachine;
use super::objint;
use super::objsequence::{is_valid_slice_arg, PySliceableSequence};
use super::objstr::{PyString, PyStringRef};
use crate::obj::objint::PyInt;
use num_integer::Integer;
use num_traits::ToPrimitive;
use super::objbytearray::PyByteArray;
use super::objbytes::PyBytes;
use super::objint::{self, PyInt, PyIntRef};
use super::objlist::PyList;
use super::objmemory::PyMemoryView;
use super::objsequence;
use super::objnone::PyNoneRef;
use super::objsequence::{self, is_valid_slice_arg, PySliceableSequence};
use super::objslice::PySliceRef;
use super::objstr::{PyString, PyStringRef};
use super::objtuple::PyTupleRef;
use crate::function::OptionalArg;
use crate::pyhash;
use crate::pyobject::{
Either, PyIterable, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol,
};
use crate::vm::VirtualMachine;
#[derive(Debug, Default, Clone)]
pub struct PyByteInner {
@@ -429,7 +420,11 @@ impl PyByteInner {
.collect::<Vec<u8>>()
}
pub fn contains(&self, needle: Either<PyByteInner, PyIntRef>, vm: &VirtualMachine) -> PyResult {
pub fn contains(
&self,
needle: Either<PyByteInner, PyIntRef>,
vm: &VirtualMachine,
) -> PyResult<bool> {
match needle {
Either::A(byte) => {
let other = &byte.elements[..];
@@ -438,18 +433,12 @@ impl PyByteInner {
&& *i == other[0]
&& &self.elements[n..n + other.len()] == other
{
return Ok(vm.new_bool(true));
return Ok(true);
}
}
Ok(vm.new_bool(false))
}
Either::B(int) => {
if self.elements.contains(&int.as_bigint().byte_or(vm)?) {
Ok(vm.new_bool(true))
} else {
Ok(vm.new_bool(false))
}
Ok(false)
}
Either::B(int) => Ok(self.elements.contains(&int.as_bigint().byte_or(vm)?)),
}
}
@@ -532,67 +521,51 @@ impl PyByteInner {
}
}
pub fn isalnum(&self, vm: &VirtualMachine) -> PyResult {
Ok(vm.new_bool(
!self.elements.is_empty()
&& self
.elements
.iter()
.all(|x| char::from(*x).is_alphanumeric()),
))
pub fn isalnum(&self, _vm: &VirtualMachine) -> bool {
!self.elements.is_empty()
&& self
.elements
.iter()
.all(|x| char::from(*x).is_alphanumeric())
}
pub fn isalpha(&self, vm: &VirtualMachine) -> PyResult {
Ok(vm.new_bool(
!self.elements.is_empty()
&& self.elements.iter().all(|x| char::from(*x).is_alphabetic()),
))
pub fn isalpha(&self, _vm: &VirtualMachine) -> bool {
!self.elements.is_empty() && self.elements.iter().all(|x| char::from(*x).is_alphabetic())
}
pub fn isascii(&self, vm: &VirtualMachine) -> PyResult {
Ok(vm.new_bool(
!self.elements.is_empty() && self.elements.iter().all(|x| char::from(*x).is_ascii()),
))
pub fn isascii(&self, _vm: &VirtualMachine) -> bool {
!self.elements.is_empty() && self.elements.iter().all(|x| char::from(*x).is_ascii())
}
pub fn isdigit(&self, vm: &VirtualMachine) -> PyResult {
Ok(vm.new_bool(
!self.elements.is_empty() && self.elements.iter().all(|x| char::from(*x).is_digit(10)),
))
pub fn isdigit(&self, _vm: &VirtualMachine) -> bool {
!self.elements.is_empty() && self.elements.iter().all(|x| char::from(*x).is_digit(10))
}
pub fn islower(&self, vm: &VirtualMachine) -> PyResult {
Ok(vm.new_bool(
!self.elements.is_empty()
&& self
.elements
.iter()
.filter(|x| !char::from(**x).is_whitespace())
.all(|x| char::from(*x).is_lowercase()),
))
pub fn islower(&self, _vm: &VirtualMachine) -> bool {
!self.elements.is_empty()
&& self
.elements
.iter()
.filter(|x| !char::from(**x).is_whitespace())
.all(|x| char::from(*x).is_lowercase())
}
pub fn isspace(&self, vm: &VirtualMachine) -> PyResult {
Ok(vm.new_bool(
!self.elements.is_empty()
&& self.elements.iter().all(|x| char::from(*x).is_whitespace()),
))
pub fn isspace(&self, _vm: &VirtualMachine) -> bool {
!self.elements.is_empty() && self.elements.iter().all(|x| char::from(*x).is_whitespace())
}
pub fn isupper(&self, vm: &VirtualMachine) -> PyResult {
Ok(vm.new_bool(
!self.elements.is_empty()
&& self
.elements
.iter()
.filter(|x| !char::from(**x).is_whitespace())
.all(|x| char::from(*x).is_uppercase()),
))
pub fn isupper(&self, _vm: &VirtualMachine) -> bool {
!self.elements.is_empty()
&& self
.elements
.iter()
.filter(|x| !char::from(**x).is_whitespace())
.all(|x| char::from(*x).is_uppercase())
}
pub fn istitle(&self, vm: &VirtualMachine) -> PyResult {
pub fn istitle(&self, _vm: &VirtualMachine) -> bool {
if self.elements.is_empty() {
return Ok(vm.new_bool(false));
return false;
}
let mut iter = self.elements.iter().peekable();
@@ -603,9 +576,9 @@ impl PyByteInner {
let next = if let Some(k) = iter.peek() {
char::from(**k)
} else if current.is_uppercase() {
return Ok(vm.new_bool(!prev_cased));
return !prev_cased;
} else {
return Ok(vm.new_bool(prev_cased));
return prev_cased;
};
let is_cased = current.to_uppercase().next().unwrap() != current
@@ -613,13 +586,13 @@ impl PyByteInner {
if (is_cased && next.is_uppercase() && !prev_cased)
|| (!is_cased && next.is_lowercase())
{
return Ok(vm.new_bool(false));
return false;
}
prev_cased = is_cased;
}
Ok(vm.new_bool(true))
true
}
pub fn lower(&self, _vm: &VirtualMachine) -> Vec<u8> {
@@ -651,13 +624,11 @@ impl PyByteInner {
new
}
pub fn hex(&self, vm: &VirtualMachine) -> PyResult {
let bla = self
.elements
pub fn hex(&self, _vm: &VirtualMachine) -> String {
self.elements
.iter()
.map(|x| format!("{:02x}", x))
.collect::<String>();
Ok(vm.ctx.new_str(bla))
.collect::<String>()
}
pub fn fromhex(string: &str, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
@@ -780,6 +751,7 @@ impl PyByteInner {
Ok(vm.ctx.new_bytes(refs))
}
#[inline]
pub fn startsendswith(
&self,
arg: Either<PyByteInner, PyTupleRef>,
@@ -787,7 +759,7 @@ impl PyByteInner {
end: OptionalArg<PyObjectRef>,
endswith: bool, // true for endswith, false for startswith
vm: &VirtualMachine,
) -> PyResult {
) -> PyResult<bool> {
let suff = match arg {
Either::A(byte) => byte.elements,
Either::B(tuple) => {
@@ -800,7 +772,7 @@ impl PyByteInner {
};
if suff.is_empty() {
return Ok(vm.new_bool(true));
return Ok(true);
}
let range = self.elements.get_slice_range(
&is_valid_slice_arg(start, vm)?,
@@ -808,7 +780,7 @@ impl PyByteInner {
);
if range.end - range.start < suff.len() {
return Ok(vm.new_bool(false));
return Ok(false);
}
let offset = if endswith {
@@ -817,7 +789,7 @@ impl PyByteInner {
0..suff.len()
};
Ok(vm.new_bool(suff.as_slice() == &self.elements.do_slice(range)[offset]))
Ok(suff.as_slice() == &self.elements.do_slice(range)[offset])
}
pub fn find(

View File

@@ -1,30 +1,26 @@
use crate::obj::objint::PyIntRef;
use crate::obj::objslice::PySliceRef;
use crate::obj::objstr::PyStringRef;
use crate::obj::objtuple::PyTupleRef;
use crate::pyhash;
use crate::pyobject::Either;
use crate::vm::VirtualMachine;
use core::cell::Cell;
use std::cell::Cell;
use std::ops::Deref;
use crate::function::OptionalArg;
use crate::pyobject::{
IntoPyObject, PyClassImpl, PyContext, PyIterable, PyObjectRef, PyRef, PyResult, PyValue,
TryFromObject,
};
use wtf8;
use super::objbyteinner::{
ByteInnerExpandtabsOptions, ByteInnerFindOptions, ByteInnerNewOptions, ByteInnerPaddingOptions,
ByteInnerPosition, ByteInnerSplitOptions, ByteInnerSplitlinesOptions,
ByteInnerTranslateOptions, PyByteInner,
};
use super::objint::PyIntRef;
use super::objiter;
use super::objslice::PySliceRef;
use super::objstr::PyStringRef;
use super::objtuple::PyTupleRef;
use super::objtype::PyClassRef;
use wtf8;
use crate::function::OptionalArg;
use crate::pyhash;
use crate::pyobject::{
Either, IntoPyObject, PyClassImpl, PyContext, PyIterable, PyObjectRef, PyRef, PyResult,
PyValue, TryFromObject,
};
use crate::vm::VirtualMachine;
/// "bytes(iterable_of_ints) -> bytes\n\
/// bytes(string, encoding[, errors]) -> bytes\n\
@@ -163,7 +159,11 @@ impl PyBytesRef {
}
#[pymethod(name = "__contains__")]
fn contains(self, needle: Either<PyByteInner, PyIntRef>, vm: &VirtualMachine) -> PyResult {
fn contains(
self,
needle: Either<PyByteInner, PyIntRef>,
vm: &VirtualMachine,
) -> PyResult<bool> {
self.inner.contains(needle, vm)
}
@@ -173,42 +173,42 @@ impl PyBytesRef {
}
#[pymethod(name = "isalnum")]
fn isalnum(self, vm: &VirtualMachine) -> PyResult {
fn isalnum(self, vm: &VirtualMachine) -> bool {
self.inner.isalnum(vm)
}
#[pymethod(name = "isalpha")]
fn isalpha(self, vm: &VirtualMachine) -> PyResult {
fn isalpha(self, vm: &VirtualMachine) -> bool {
self.inner.isalpha(vm)
}
#[pymethod(name = "isascii")]
fn isascii(self, vm: &VirtualMachine) -> PyResult {
fn isascii(self, vm: &VirtualMachine) -> bool {
self.inner.isascii(vm)
}
#[pymethod(name = "isdigit")]
fn isdigit(self, vm: &VirtualMachine) -> PyResult {
fn isdigit(self, vm: &VirtualMachine) -> bool {
self.inner.isdigit(vm)
}
#[pymethod(name = "islower")]
fn islower(self, vm: &VirtualMachine) -> PyResult {
fn islower(self, vm: &VirtualMachine) -> bool {
self.inner.islower(vm)
}
#[pymethod(name = "isspace")]
fn isspace(self, vm: &VirtualMachine) -> PyResult {
fn isspace(self, vm: &VirtualMachine) -> bool {
self.inner.isspace(vm)
}
#[pymethod(name = "isupper")]
fn isupper(self, vm: &VirtualMachine) -> PyResult {
fn isupper(self, vm: &VirtualMachine) -> bool {
self.inner.isupper(vm)
}
#[pymethod(name = "istitle")]
fn istitle(self, vm: &VirtualMachine) -> PyResult {
fn istitle(self, vm: &VirtualMachine) -> bool {
self.inner.istitle(vm)
}
@@ -233,7 +233,7 @@ impl PyBytesRef {
}
#[pymethod(name = "hex")]
fn hex(self, vm: &VirtualMachine) -> PyResult {
fn hex(self, vm: &VirtualMachine) -> String {
self.inner.hex(vm)
}
@@ -273,7 +273,7 @@ impl PyBytesRef {
start: OptionalArg<PyObjectRef>,
end: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult {
) -> PyResult<bool> {
self.inner.startsendswith(suffix, start, end, true, vm)
}
@@ -284,7 +284,7 @@ impl PyBytesRef {
start: OptionalArg<PyObjectRef>,
end: OptionalArg<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult {
) -> PyResult<bool> {
self.inner.startsendswith(prefix, start, end, false, vm)
}

View File

@@ -52,10 +52,9 @@ impl PyClassMethod {
}
#[pymethod(name = "__get__")]
fn get(&self, _inst: PyObjectRef, owner: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Ok(vm
.ctx
.new_bound_method(self.callable.clone(), owner.clone()))
fn get(&self, _inst: PyObjectRef, owner: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx
.new_bound_method(self.callable.clone(), owner.clone())
}
#[pyproperty(name = "__func__")]

View File

@@ -4,8 +4,8 @@
use std::fmt;
use super::objtype::PyClassRef;
use crate::bytecode;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{IdProtocol, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;

View File

@@ -2,6 +2,8 @@ use num_complex::Complex64;
use num_traits::Zero;
use std::num::Wrapping;
use super::objfloat::{self, IntoPyFloat};
use super::objtype::{self, PyClassRef};
use crate::function::OptionalArg;
use crate::pyhash;
use crate::pyobject::{
@@ -9,9 +11,6 @@ use crate::pyobject::{
};
use crate::vm::VirtualMachine;
use super::objfloat::{self, IntoPyFloat, PyFloat};
use super::objtype::{self, PyClassRef};
/// Create a complex number from a real part and an optional imaginary part.
///
/// This is equivalent to (real + imag*1j) where imag defaults to 0.
@@ -61,19 +60,19 @@ fn try_complex(value: &PyObjectRef, vm: &VirtualMachine) -> PyResult<Option<Comp
#[pyimpl]
impl PyComplex {
#[pyproperty(name = "real")]
fn real(&self, _vm: &VirtualMachine) -> PyFloat {
self.value.re.into()
fn real(&self, _vm: &VirtualMachine) -> f64 {
self.value.re
}
#[pyproperty(name = "imag")]
fn imag(&self, _vm: &VirtualMachine) -> PyFloat {
self.value.im.into()
fn imag(&self, _vm: &VirtualMachine) -> f64 {
self.value.im
}
#[pymethod(name = "__abs__")]
fn abs(&self, _vm: &VirtualMachine) -> PyFloat {
fn abs(&self, _vm: &VirtualMachine) -> f64 {
let Complex64 { im, re } = self.value;
re.hypot(im).into()
re.hypot(im)
}
#[pymethod(name = "__add__")]
@@ -126,12 +125,12 @@ impl PyComplex {
}
#[pymethod(name = "__float__")]
fn float(&self, vm: &VirtualMachine) -> PyResult {
fn float(&self, vm: &VirtualMachine) -> PyResult<()> {
Err(vm.new_type_error(String::from("Can't convert complex to float")))
}
#[pymethod(name = "__int__")]
fn int(&self, vm: &VirtualMachine) -> PyResult {
fn int(&self, vm: &VirtualMachine) -> PyResult<()> {
Err(vm.new_type_error(String::from("Can't convert complex to int")))
}
@@ -260,10 +259,9 @@ impl PyComplex {
}
#[pymethod(name = "__getnewargs__")]
fn complex_getnewargs(&self, vm: &VirtualMachine) -> PyResult {
fn complex_getnewargs(&self, vm: &VirtualMachine) -> PyObjectRef {
let Complex64 { re, im } = self.value;
Ok(vm
.ctx
.new_tuple(vec![vm.ctx.new_float(re), vm.ctx.new_float(im)]))
vm.ctx
.new_tuple(vec![vm.ctx.new_float(re), vm.ctx.new_float(im)])
}
}

View File

@@ -1,20 +1,17 @@
use std::cell::{Cell, RefCell};
use std::fmt;
use crate::function::{KwArgs, OptionalArg};
use crate::pyobject::{
IdProtocol, IntoPyObject, ItemProtocol, PyAttributes, PyContext, PyIterable, PyObjectRef,
PyRef, PyResult, PyValue,
};
use crate::vm::{ReprGuard, VirtualMachine};
use super::objbool;
use super::objiter;
use super::objstr;
use super::objtype;
use super::objtype::{self, PyClassRef};
use crate::dictdatatype::{self, DictKey};
use crate::obj::objtype::PyClassRef;
use crate::pyobject::PyClassImpl;
use crate::function::{KwArgs, OptionalArg};
use crate::pyobject::{
IdProtocol, IntoPyObject, ItemProtocol, PyAttributes, PyClassImpl, PyContext, PyIterable,
PyObjectRef, PyRef, PyResult, PyValue,
};
use crate::vm::{ReprGuard, VirtualMachine};
pub type DictContentType = dictdatatype::Dict;

View File

@@ -1,4 +1,4 @@
use crate::obj::objtype::{issubclass, PyClassRef};
use super::objtype::{issubclass, PyClassRef};
use crate::pyobject::{PyContext, PyEllipsisRef, PyResult};
use crate::vm::VirtualMachine;

View File

@@ -4,13 +4,12 @@ use std::ops::AddAssign;
use num_bigint::BigInt;
use num_traits::Zero;
use crate::function::OptionalArg;
use crate::pyobject::{PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;
use super::objint::PyIntRef;
use super::objiter;
use super::objtype::PyClassRef;
use crate::function::OptionalArg;
use crate::pyobject::{PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;
#[pyclass]
#[derive(Debug)]

View File

@@ -1,9 +1,8 @@
use crate::pyobject::{IdProtocol, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;
use super::objbool;
use super::objiter;
use crate::obj::objtype::PyClassRef;
use super::objtype::PyClassRef;
use crate::pyobject::{IdProtocol, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;
pub type PyFilterRef = PyRef<PyFilter>;

View File

@@ -1,20 +1,19 @@
use hexf_parse;
use num_bigint::{BigInt, ToBigInt};
use num_rational::Ratio;
use num_traits::{float::Float, sign::Signed, ToPrimitive, Zero};
use super::objbytes;
use super::objint;
use super::objstr;
use super::objtype;
use super::objstr::{self, PyStringRef};
use super::objtype::{self, PyClassRef};
use crate::function::OptionalArg;
use crate::obj::objstr::PyStringRef;
use crate::obj::objtype::PyClassRef;
use crate::pyhash;
use crate::pyobject::{
IdProtocol, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue,
TryFromObject, TypeProtocol,
};
use crate::vm::VirtualMachine;
use hexf_parse;
use num_bigint::{BigInt, ToBigInt};
use num_rational::Ratio;
use num_traits::{float::Float, sign::Signed, ToPrimitive, Zero};
/// Convert a string or number to a floating point number, if possible.
#[pyclass(name = "float")]

View File

@@ -1,8 +1,8 @@
use super::objcode::PyCodeRef;
use super::objdict::PyDictRef;
use super::objtuple::PyTupleRef;
use super::objtype::PyClassRef;
use crate::function::PyFuncArgs;
use crate::obj::objcode::PyCodeRef;
use crate::obj::objdict::PyDictRef;
use crate::obj::objtuple::PyTupleRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{IdProtocol, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol};
use crate::scope::Scope;
use crate::vm::VirtualMachine;

View File

@@ -2,8 +2,8 @@
* The mythical generator.
*/
use super::objtype::{isinstance, PyClassRef};
use crate::frame::{ExecutionResult, FrameRef};
use crate::obj::objtype::{isinstance, PyClassRef};
use crate::pyobject::{PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;

View File

@@ -5,23 +5,21 @@ use num_bigint::{BigInt, Sign};
use num_integer::Integer;
use num_traits::{Num, One, Pow, Signed, ToPrimitive, Zero};
use crate::format::FormatSpec;
use crate::function::{OptionalArg, PyFuncArgs};
use crate::obj::objtype::PyClassRef;
use crate::pyhash;
use crate::pyobject::{
IdProtocol, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue,
TryFromObject, TypeProtocol,
};
use crate::vm::VirtualMachine;
use super::objbool::IntoPyBool;
use super::objbyteinner::PyByteInner;
use super::objbytes::PyBytes;
use super::objfloat;
use super::objint;
use super::objstr::{PyString, PyStringRef};
use super::objtype;
use super::objtype::{self, PyClassRef};
use crate::format::FormatSpec;
use crate::function::{OptionalArg, PyFuncArgs};
use crate::pyhash;
use crate::pyobject::{
IdProtocol, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue,
TryFromObject, TypeProtocol,
};
use crate::vm::VirtualMachine;
/// int(x=0) -> integer
/// int(x, base=10) -> integer

View File

@@ -4,14 +4,12 @@
use std::cell::Cell;
use super::objtype::{self, PyClassRef};
use crate::pyobject::{
PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol,
};
use crate::vm::VirtualMachine;
use super::objtype;
use super::objtype::PyClassRef;
/*
* This helper function is called at multiple places. First, it is called
* in the vm when a for loop is entered. Next, it is used when the builtin

View File

@@ -1,18 +1,10 @@
use std::cell::{Cell, RefCell};
use std::fmt;
use std::ops::Range;
use num_bigint::{BigInt, ToBigInt};
use num_traits::{One, Signed, ToPrimitive, Zero};
use crate::function::OptionalArg;
use crate::pyobject::{
IdProtocol, PyClassImpl, PyContext, PyIterable, PyObjectRef, PyRef, PyResult, PyValue,
TryFromObject, TypeProtocol,
};
use crate::vm::{ReprGuard, VirtualMachine};
use super::objbool;
use super::objbyteinner;
use super::objint::PyIntRef;
@@ -21,8 +13,13 @@ use super::objsequence::{
get_elements_list, get_item, seq_equal, seq_ge, seq_gt, seq_le, seq_lt, seq_mul, SequenceIndex,
};
use super::objslice::PySliceRef;
use super::objtype;
use crate::obj::objtype::PyClassRef;
use super::objtype::{self, PyClassRef};
use crate::function::OptionalArg;
use crate::pyobject::{
IdProtocol, PyClassImpl, PyContext, PyIterable, PyObjectRef, PyRef, PyResult, PyValue,
TryFromObject, TypeProtocol,
};
use crate::vm::{ReprGuard, VirtualMachine};
#[derive(Default)]
pub struct PyList {
@@ -529,25 +526,25 @@ impl PyListRef {
}
fn eq(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
if self.as_object().is(&other) {
return Ok(vm.new_bool(true));
}
if objtype::isinstance(&other, &vm.ctx.list_type()) {
Ok(vm.new_bool(self.inner_eq(&other, vm)?))
let value = if self.as_object().is(&other) {
vm.new_bool(true)
} else if objtype::isinstance(&other, &vm.ctx.list_type()) {
vm.new_bool(self.inner_eq(&other, vm)?)
} else {
Ok(vm.ctx.not_implemented())
}
vm.ctx.not_implemented()
};
Ok(value)
}
fn ne(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
if self.as_object().is(&other) {
return Ok(vm.new_bool(false));
}
if objtype::isinstance(&other, &vm.ctx.list_type()) {
Ok(vm.new_bool(!self.inner_eq(&other, vm)?))
let value = if self.as_object().is(&other) {
vm.new_bool(false)
} else if objtype::isinstance(&other, &vm.ctx.list_type()) {
vm.new_bool(!self.inner_eq(&other, vm)?)
} else {
Ok(vm.ctx.not_implemented())
}
vm.ctx.not_implemented()
};
Ok(value)
}
fn inner_eq(self, other: &PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {

View File

@@ -1,10 +1,9 @@
use super::objiter;
use super::objtype::PyClassRef;
use crate::function::Args;
use crate::pyobject::{PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;
use super::objiter;
use super::objtype::PyClassRef;
/// map(func, *iterables) --> map object
///
/// Make an iterator that computes the function using arguments from

View File

@@ -1,7 +1,7 @@
use std::borrow::Borrow;
use crate::obj::objbyteinner::try_as_byte;
use crate::obj::objtype::{issubclass, PyClassRef};
use super::objbyteinner::try_as_byte;
use super::objtype::{issubclass, PyClassRef};
use crate::pyobject::{PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
use crate::stdlib::array::PyArray;
use crate::vm::VirtualMachine;

View File

@@ -1,7 +1,7 @@
use super::objdict::PyDictRef;
use super::objstr::PyStringRef;
use super::objtype::PyClassRef;
use crate::function::OptionalOption;
use crate::obj::objdict::PyDictRef;
use crate::obj::objstr::PyStringRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{ItemProtocol, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;

View File

@@ -1,5 +1,5 @@
use super::objtype::PyClassRef;
use crate::function::KwArgs;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{PyClassImpl, PyContext, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;

View File

@@ -1,6 +1,6 @@
use crate::obj::objproperty::PyPropertyRef;
use crate::obj::objstr::PyStringRef;
use crate::obj::objtype::{class_get_attr, class_has_attr, PyClassRef};
use super::objproperty::PyPropertyRef;
use super::objstr::PyStringRef;
use super::objtype::{class_get_attr, class_has_attr, PyClassRef};
use crate::pyobject::{
IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject,
TypeProtocol,

View File

@@ -1,10 +1,9 @@
use super::objdict::PyDictRef;
use super::objlist::PyList;
use super::objproperty::PropertyBuilder;
use super::objstr::PyStringRef;
use super::objtype;
use super::objtype::{self, PyClassRef};
use crate::function::PyFuncArgs;
use crate::obj::objproperty::PropertyBuilder;
use crate::obj::objtype::PyClassRef;
use crate::pyhash;
use crate::pyobject::{
IdProtocol, ItemProtocol, PyAttributes, PyContext, PyObject, PyObjectRef, PyResult, PyValue,

View File

@@ -1,14 +1,15 @@
/*! Python `property` descriptor class.
*/
use std::cell::RefCell;
use super::objtype::PyClassRef;
use crate::function::{IntoPyNativeFunc, OptionalArg};
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{
IdProtocol, PyClassImpl, PyContext, PyObject, PyObjectRef, PyRef, PyResult, PyValue,
TypeProtocol,
};
use crate::vm::VirtualMachine;
use std::cell::RefCell;
// Read-only property, doesn't have __set__ or __delete__
#[pyclass]

View File

@@ -4,6 +4,10 @@ use num_bigint::{BigInt, Sign};
use num_integer::Integer;
use num_traits::{One, Signed, Zero};
use super::objint::{PyInt, PyIntRef};
use super::objiter;
use super::objslice::{PySlice, PySliceRef};
use super::objtype::PyClassRef;
use crate::function::{OptionalArg, PyFuncArgs};
use crate::pyhash;
use crate::pyobject::{
@@ -11,11 +15,6 @@ use crate::pyobject::{
};
use crate::vm::VirtualMachine;
use super::objint::{PyInt, PyIntRef};
use super::objiter;
use super::objslice::{PySlice, PySliceRef};
use super::objtype::PyClassRef;
/// range(stop) -> range object
/// range(start, stop[, step]) -> range object
///
@@ -260,50 +259,50 @@ impl PyRange {
}
#[pymethod(name = "__eq__")]
fn eq(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
fn eq(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if let Some(rhs) = rhs.payload::<PyRange>() {
let eq = self.inner_eq(rhs);
Ok(vm.ctx.new_bool(eq))
vm.ctx.new_bool(eq)
} else {
Ok(vm.ctx.not_implemented())
vm.ctx.not_implemented()
}
}
#[pymethod(name = "__ne__")]
fn ne(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
fn ne(&self, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if let Some(rhs) = rhs.payload::<PyRange>() {
let eq = self.inner_eq(rhs);
Ok(vm.ctx.new_bool(!eq))
vm.ctx.new_bool(!eq)
} else {
Ok(vm.ctx.not_implemented())
vm.ctx.not_implemented()
}
}
#[pymethod(name = "__lt__")]
fn lt(&self, _rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.not_implemented())
fn lt(&self, _rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.not_implemented()
}
#[pymethod(name = "__gt__")]
fn gt(&self, _rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.not_implemented())
fn gt(&self, _rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.not_implemented()
}
#[pymethod(name = "__ge__")]
fn ge(&self, _rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.not_implemented())
fn ge(&self, _rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.not_implemented()
}
#[pymethod(name = "__le__")]
fn le(&self, _rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.not_implemented())
fn le(&self, _rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.not_implemented()
}
#[pymethod(name = "index")]
fn index(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyInt> {
fn index(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<BigInt> {
if let Ok(int) = needle.downcast::<PyInt>() {
match self.index_of(int.as_bigint()) {
Some(idx) => Ok(PyInt::new(idx)),
Some(idx) => Ok(idx),
None => Err(vm.new_value_error(format!("{} is not in range", int))),
}
} else {
@@ -312,15 +311,15 @@ impl PyRange {
}
#[pymethod(name = "count")]
fn count(&self, item: PyObjectRef, _vm: &VirtualMachine) -> PyInt {
fn count(&self, item: PyObjectRef, _vm: &VirtualMachine) -> usize {
if let Ok(int) = item.downcast::<PyInt>() {
if self.index_of(int.as_bigint()).is_some() {
PyInt::new(1)
1
} else {
PyInt::new(0)
0
}
} else {
PyInt::new(0)
0
}
}

View File

@@ -1,19 +1,18 @@
use crate::function::OptionalArg;
use crate::obj::objnone::PyNone;
use std::cell::RefCell;
use std::marker::Sized;
use std::ops::{Deref, DerefMut, Range};
use crate::pyobject::{IdProtocol, PyObject, PyObjectRef, PyResult, TryFromObject, TypeProtocol};
use crate::vm::VirtualMachine;
use num_bigint::{BigInt, ToBigInt};
use num_traits::{One, Signed, ToPrimitive, Zero};
use super::objint::{PyInt, PyIntRef};
use super::objlist::PyList;
use super::objnone::PyNone;
use super::objslice::{PySlice, PySliceRef};
use super::objtuple::PyTuple;
use crate::function::OptionalArg;
use crate::pyobject::{IdProtocol, PyObject, PyObjectRef, PyResult, TryFromObject, TypeProtocol};
use crate::vm::VirtualMachine;
pub trait PySliceableSequence {
type Sliced;

View File

@@ -2,10 +2,11 @@
* Builtin set type with a sequence of unique items.
*/
use std::borrow::Borrow;
use std::cell::{Cell, RefCell};
use std::fmt;
use super::objlist::PyListIterator;
use super::objtype::{self, PyClassRef};
use crate::dictdatatype;
use crate::function::OptionalArg;
use crate::pyobject::{
@@ -14,11 +15,6 @@ use crate::pyobject::{
};
use crate::vm::{ReprGuard, VirtualMachine};
use super::objbool;
use super::objlist::PyListIterator;
use super::objtype;
use super::objtype::PyClassRef;
pub type SetContentType = dictdatatype::Dict<()>;
/// set() -> new empty set object
@@ -112,21 +108,21 @@ impl PySetInner {
size_func: fn(usize, usize) -> bool,
swap: bool,
vm: &VirtualMachine,
) -> PyResult {
) -> PyResult<bool> {
let (zelf, other) = if swap { (other, self) } else { (self, other) };
if size_func(zelf.len(), other.len()) {
return Ok(vm.new_bool(false));
return Ok(false);
}
for key in other.content.keys() {
if !zelf.contains(&key, vm)? {
return Ok(vm.new_bool(false));
return Ok(false);
}
}
Ok(vm.new_bool(true))
Ok(true)
}
fn eq(&self, other: &PySetInner, vm: &VirtualMachine) -> PyResult {
fn eq(&self, other: &PySetInner, vm: &VirtualMachine) -> PyResult<bool> {
self._compare_inner(
other,
|zelf: usize, other: usize| -> bool { zelf != other },
@@ -135,12 +131,11 @@ impl PySetInner {
)
}
fn ne(&self, other: &PySetInner, vm: &VirtualMachine) -> PyResult {
let eq = objbool::get_value(self.eq(other, vm)?.borrow());
Ok(vm.new_bool(!eq))
fn ne(&self, other: &PySetInner, vm: &VirtualMachine) -> PyResult<bool> {
Ok(!self.eq(other, vm)?)
}
fn ge(&self, other: &PySetInner, vm: &VirtualMachine) -> PyResult {
fn ge(&self, other: &PySetInner, vm: &VirtualMachine) -> PyResult<bool> {
self._compare_inner(
other,
|zelf: usize, other: usize| -> bool { zelf < other },
@@ -149,7 +144,7 @@ impl PySetInner {
)
}
fn gt(&self, other: &PySetInner, vm: &VirtualMachine) -> PyResult {
fn gt(&self, other: &PySetInner, vm: &VirtualMachine) -> PyResult<bool> {
self._compare_inner(
other,
|zelf: usize, other: usize| -> bool { zelf <= other },
@@ -158,7 +153,7 @@ impl PySetInner {
)
}
fn le(&self, other: &PySetInner, vm: &VirtualMachine) -> PyResult {
fn le(&self, other: &PySetInner, vm: &VirtualMachine) -> PyResult<bool> {
self._compare_inner(
other,
|zelf: usize, other: usize| -> bool { zelf < other },
@@ -167,7 +162,7 @@ impl PySetInner {
)
}
fn lt(&self, other: &PySetInner, vm: &VirtualMachine) -> PyResult {
fn lt(&self, other: &PySetInner, vm: &VirtualMachine) -> PyResult<bool> {
self._compare_inner(
other,
|zelf: usize, other: usize| -> bool { zelf <= other },
@@ -223,7 +218,7 @@ impl PySetInner {
Ok(true)
}
fn issubset(&self, other: PyIterable, vm: &VirtualMachine) -> PyResult {
fn issubset(&self, other: PyIterable, vm: &VirtualMachine) -> PyResult<bool> {
let other_set = PySetInner::new(other, vm)?;
self.le(&other_set, vm)
}
@@ -319,13 +314,13 @@ impl PySetInner {
}
}
macro_rules! try_set_inner {
macro_rules! try_set_cmp {
($vm:expr, $other:expr, $op:expr) => {
match_class!(match ($other) {
set @ PySet => ($op(&*set.inner.borrow())),
frozen @ PyFrozenSet => ($op(&frozen.inner)),
_ => Ok($vm.ctx.not_implemented()),
});
Ok(match_class!(match ($other) {
set @ PySet => ($vm.new_bool($op(&*set.inner.borrow())?)),
frozen @ PyFrozenSet => ($vm.new_bool($op(&frozen.inner)?)),
_ => $vm.ctx.not_implemented(),
}));
};
}
@@ -362,32 +357,32 @@ impl PySet {
#[pymethod(name = "__eq__")]
fn eq(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
try_set_inner!(vm, other, |other| self.inner.borrow().eq(other, vm))
try_set_cmp!(vm, other, |other| self.inner.borrow().eq(other, vm))
}
#[pymethod(name = "__ne__")]
fn ne(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
try_set_inner!(vm, other, |other| self.inner.borrow().ne(other, vm))
try_set_cmp!(vm, other, |other| self.inner.borrow().ne(other, vm))
}
#[pymethod(name = "__ge__")]
fn ge(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
try_set_inner!(vm, other, |other| self.inner.borrow().ge(other, vm))
try_set_cmp!(vm, other, |other| self.inner.borrow().ge(other, vm))
}
#[pymethod(name = "__gt__")]
fn gt(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
try_set_inner!(vm, other, |other| self.inner.borrow().gt(other, vm))
try_set_cmp!(vm, other, |other| self.inner.borrow().gt(other, vm))
}
#[pymethod(name = "__le__")]
fn le(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
try_set_inner!(vm, other, |other| self.inner.borrow().le(other, vm))
try_set_cmp!(vm, other, |other| self.inner.borrow().le(other, vm))
}
#[pymethod(name = "__lt__")]
fn lt(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
try_set_inner!(vm, other, |other| self.inner.borrow().lt(other, vm))
try_set_cmp!(vm, other, |other| self.inner.borrow().lt(other, vm))
}
#[pymethod]
@@ -419,7 +414,7 @@ impl PySet {
}
#[pymethod]
fn issubset(&self, other: PyIterable, vm: &VirtualMachine) -> PyResult {
fn issubset(&self, other: PyIterable, vm: &VirtualMachine) -> PyResult<bool> {
self.inner.borrow().issubset(other, vm)
}
@@ -613,32 +608,32 @@ impl PyFrozenSet {
#[pymethod(name = "__eq__")]
fn eq(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
try_set_inner!(vm, other, |other| self.inner.eq(other, vm))
try_set_cmp!(vm, other, |other| self.inner.eq(other, vm))
}
#[pymethod(name = "__ne__")]
fn ne(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
try_set_inner!(vm, other, |other| self.inner.ne(other, vm))
try_set_cmp!(vm, other, |other| self.inner.ne(other, vm))
}
#[pymethod(name = "__ge__")]
fn ge(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
try_set_inner!(vm, other, |other| self.inner.ge(other, vm))
try_set_cmp!(vm, other, |other| self.inner.ge(other, vm))
}
#[pymethod(name = "__gt__")]
fn gt(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
try_set_inner!(vm, other, |other| self.inner.gt(other, vm))
try_set_cmp!(vm, other, |other| self.inner.gt(other, vm))
}
#[pymethod(name = "__le__")]
fn le(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
try_set_inner!(vm, other, |other| self.inner.le(other, vm))
try_set_cmp!(vm, other, |other| self.inner.le(other, vm))
}
#[pymethod(name = "__lt__")]
fn lt(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
try_set_inner!(vm, other, |other| self.inner.lt(other, vm))
try_set_cmp!(vm, other, |other| self.inner.lt(other, vm))
}
#[pymethod]
@@ -670,7 +665,7 @@ impl PyFrozenSet {
}
#[pymethod]
fn issubset(&self, other: PyIterable, vm: &VirtualMachine) -> PyResult {
fn issubset(&self, other: PyIterable, vm: &VirtualMachine) -> PyResult<bool> {
self.inner.issubset(other, vm)
}

View File

@@ -1,12 +1,12 @@
use num_bigint::BigInt;
use super::objint::PyInt;
use super::objtype::{class_has_attr, PyClassRef};
use crate::function::{OptionalArg, PyFuncArgs};
use crate::pyobject::{
IdProtocol, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol,
};
use crate::obj::objint::PyInt;
use crate::obj::objtype::{class_has_attr, PyClassRef};
use crate::vm::VirtualMachine;
use num_bigint::BigInt;
#[pyclass]
#[derive(Debug)]

View File

@@ -10,8 +10,19 @@ use std::string::ToString;
use num_traits::ToPrimitive;
use unicode_casing::CharExt;
use unicode_categories::UnicodeCategories;
use unicode_xid::UnicodeXID;
use super::objbytes::PyBytes;
use super::objdict::PyDict;
use super::objfloat;
use super::objint::{self, PyInt};
use super::objiter;
use super::objnone::PyNone;
use super::objsequence::PySliceableSequence;
use super::objslice::PySlice;
use super::objtuple;
use super::objtype::{self, PyClassRef};
use crate::cformat::{
CFormatPart, CFormatPreconversor, CFormatQuantity, CFormatSpec, CFormatString, CFormatType,
CNumberType,
@@ -25,19 +36,6 @@ use crate::pyobject::{
};
use crate::vm::VirtualMachine;
use super::objbytes::PyBytes;
use super::objdict::PyDict;
use super::objfloat;
use super::objint::{self, PyInt};
use super::objiter;
use super::objnone::PyNone;
use super::objsequence::PySliceableSequence;
use super::objslice::PySlice;
use super::objtuple;
use super::objtype::{self, PyClassRef};
use unicode_categories::UnicodeCategories;
/// str(object='') -> str
/// str(bytes_or_buffer[, encoding[, errors]]) -> str
///

View File

@@ -6,18 +6,16 @@ https://github.com/python/cpython/blob/50b48572d9a90c5bb36e2bef6179548ea927a35a/
*/
use super::objfunction::PyMethod;
use super::objstr::PyStringRef;
use super::objtype::{self, PyClass, PyClassRef};
use crate::function::OptionalArg;
use crate::obj::objfunction::PyMethod;
use crate::obj::objstr::PyStringRef;
use crate::obj::objtype::{PyClass, PyClassRef};
use crate::pyobject::{
PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol,
};
use crate::scope::NameProtocol;
use crate::vm::VirtualMachine;
use super::objtype;
pub type PySuperRef = PyRef<PySuper>;
#[pyclass]

View File

@@ -1,19 +1,18 @@
use std::cell::Cell;
use std::fmt;
use crate::function::OptionalArg;
use crate::pyhash;
use crate::pyobject::{
IdProtocol, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue,
};
use crate::vm::{ReprGuard, VirtualMachine};
use super::objbool;
use super::objiter;
use super::objsequence::{
get_elements_tuple, get_item, seq_equal, seq_ge, seq_gt, seq_le, seq_lt, seq_mul,
};
use super::objtype::{self, PyClassRef};
use crate::function::OptionalArg;
use crate::pyhash;
use crate::pyobject::{
IdProtocol, IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue,
};
use crate::vm::{ReprGuard, VirtualMachine};
/// tuple() -> empty tuple
/// tuple(iterable) -> tuple initialized from iterable's items

View File

@@ -2,13 +2,6 @@ use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use crate::function::{PyFuncArgs, PyNativeFunc};
use crate::pyobject::{
IdProtocol, PyAttributes, PyContext, PyIterable, PyObject, PyObjectRef, PyRef, PyResult,
PyValue, TypeProtocol,
};
use crate::vm::VirtualMachine;
use super::objdict::PyDictRef;
use super::objlist::PyList;
use super::objmappingproxy::PyMappingProxy;
@@ -16,6 +9,12 @@ use super::objproperty::PropertyBuilder;
use super::objstr::PyStringRef;
use super::objtuple::PyTuple;
use super::objweakref::PyWeak;
use crate::function::{PyFuncArgs, PyNativeFunc};
use crate::pyobject::{
IdProtocol, PyAttributes, PyContext, PyIterable, PyObject, PyObjectRef, PyRef, PyResult,
PyValue, TypeProtocol,
};
use crate::vm::VirtualMachine;
#[derive(Debug)]
pub struct PyClass {

View File

@@ -1,6 +1,6 @@
use super::objtype::PyClassRef;
use super::objweakref::PyWeak;
use crate::function::OptionalArg;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;

View File

@@ -1,7 +1,8 @@
use super::objtype::PyClassRef;
use crate::function::OptionalArg;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::PyValue;
use crate::pyobject::{PyContext, PyObject, PyObjectPayload, PyObjectRef, PyRef, PyResult};
use crate::pyobject::{
PyContext, PyObject, PyObjectPayload, PyObjectRef, PyRef, PyResult, PyValue,
};
use crate::vm::VirtualMachine;
use std::rc::{Rc, Weak};

View File

@@ -1,10 +1,9 @@
use super::objiter;
use super::objtype::PyClassRef;
use crate::function::Args;
use crate::pyobject::{PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;
use super::objiter;
use crate::obj::objtype::PyClassRef;
pub type PyZipRef = PyRef<PyZip>;
#[pyclass]

View File

@@ -6,6 +6,7 @@ use std::marker::PhantomData;
use std::ops::Deref;
use std::rc::Rc;
use indexmap::IndexMap;
use num_bigint::BigInt;
use num_complex::Complex64;
use num_traits::{One, ToPrimitive, Zero};
@@ -39,7 +40,6 @@ use crate::obj::objtype::{self, PyClass, PyClassRef};
use crate::scope::Scope;
use crate::types::{create_type, initialize_types, TypeZoo};
use crate::vm::VirtualMachine;
use indexmap::IndexMap;
/* Python objects and references.
@@ -409,11 +409,12 @@ impl PyContext {
}
pub fn new_bool(&self, b: bool) -> PyObjectRef {
if b {
self.true_value.clone().into_object()
let value = if b {
&self.true_value
} else {
self.false_value.clone().into_object()
}
&self.false_value
};
value.clone().into_object()
}
pub fn new_tuple(&self, elements: Vec<PyObjectRef>) -> PyObjectRef {

View File

@@ -600,7 +600,7 @@ fn map_ast<T>(
f: fn(vm: &VirtualMachine, &T) -> PyResult<AstNodeRef>,
vm: &VirtualMachine,
items: &[T],
) -> PyResult<PyObjectRef> {
) -> PyResult {
let list: PyResult<Vec<PyObjectRef>> =
items.iter().map(|x| Ok(f(vm, x)?.into_object())).collect();
Ok(vm.ctx.new_list(list?))

View File

@@ -8,12 +8,10 @@ use num_traits::ToPrimitive;
use crate::function::{OptionalArg, PyFuncArgs};
use crate::obj::objbool;
use crate::obj::objint;
use crate::obj::objint::{PyInt, PyIntRef};
use crate::obj::objint::{self, PyInt, PyIntRef};
use crate::obj::objiter::{call_next, get_iter, new_stop_iteration};
use crate::obj::objtuple::PyTuple;
use crate::obj::objtype;
use crate::obj::objtype::PyClassRef;
use crate::obj::objtype::{self, PyClassRef};
use crate::pyobject::{
IdProtocol, PyCallable, PyClassImpl, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol,
};
@@ -671,7 +669,7 @@ impl PyValue for PyItertoolsTee {
#[pyimpl]
impl PyItertoolsTee {
fn from_iter(iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
fn from_iter(iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let it = get_iter(vm, &iterable)?;
if it.class().is(&PyItertoolsTee::class(vm)) {
return vm.call_method(&it, "__copy__", PyFuncArgs::from(vec![]));

View File

@@ -11,9 +11,9 @@ use num_traits::cast::ToPrimitive;
use num_traits::{One, Zero};
use crate::function::OptionalArg;
use crate::obj::objfloat::{IntoPyFloat, PyFloatRef};
use crate::obj::objfloat::{self, IntoPyFloat, PyFloatRef};
use crate::obj::objint::PyIntRef;
use crate::obj::{objfloat, objtype};
use crate::obj::objtype;
use crate::pyobject::{PyObjectRef, PyResult, TypeProtocol};
use crate::vm::VirtualMachine;

View File

@@ -11,6 +11,7 @@ use std::os::windows::fs::OpenOptionsExt;
use std::time::{Duration, SystemTime};
use std::{env, fs};
use bitflags::bitflags;
#[cfg(unix)]
use exitcode;
#[cfg(unix)]
@@ -35,8 +36,6 @@ use crate::pyobject::{
};
use crate::vm::VirtualMachine;
use bitflags::bitflags;
#[cfg(unix)]
pub fn raw_file_number(handle: File) -> i64 {
use std::os::unix::io::IntoRawFd;

View File

@@ -4,17 +4,17 @@
* This module fits the python re interface onto the rust regular expression
* system.
*/
use regex::bytes::{Captures, Regex, RegexBuilder};
use std::fmt;
use num_traits::{Signed, ToPrimitive};
use regex::bytes::{Captures, Regex, RegexBuilder};
use crate::function::{Args, OptionalArg};
use crate::obj::objint::{PyInt, PyIntRef};
use crate::obj::objstr::{PyString, PyStringRef};
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{PyClassImpl, PyObjectRef, PyResult, PyValue, TryFromObject};
use crate::vm::VirtualMachine;
use num_traits::{Signed, ToPrimitive};
#[pyclass(name = "Pattern")]
#[derive(Debug)]

View File

@@ -9,7 +9,6 @@ use arr_macro::arr;
use nix::unistd::alarm as sig_alarm;
use libc;
#[cfg(not(windows))]
use libc::{SIG_DFL, SIG_ERR, SIG_IGN};
@@ -38,7 +37,7 @@ fn assert_in_range(signum: i32, vm: &VirtualMachine) -> PyResult<()> {
}
}
fn signal(signalnum: i32, handler: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
fn signal(signalnum: i32, handler: PyObjectRef, vm: &VirtualMachine) -> PyResult {
assert_in_range(signalnum, vm)?;
let sig_handler = match usize::try_from_object(vm, handler.clone()).ok() {
@@ -76,7 +75,7 @@ fn signal(signalnum: i32, handler: PyObjectRef, vm: &VirtualMachine) -> PyResult
Ok(old_handler)
}
fn getsignal(signalnum: i32, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
fn getsignal(signalnum: i32, vm: &VirtualMachine) -> PyResult {
assert_in_range(signalnum, vm)?;
Ok(vm.signal_handlers.borrow()[signalnum as usize].clone())
}

View File

@@ -5,26 +5,23 @@ use std::io::Write;
use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream, ToSocketAddrs, UdpSocket};
use std::time::Duration;
use byteorder::{BigEndian, ByteOrder};
use gethostname::gethostname;
#[cfg(all(unix, not(target_os = "redox")))]
use nix::unistd::sethostname;
use gethostname::gethostname;
use byteorder::{BigEndian, ByteOrder};
use num_bigint::Sign;
use num_traits::ToPrimitive;
use crate::function::PyFuncArgs;
use crate::obj::objbytes::PyBytesRef;
use crate::obj::objint::PyIntRef;
use crate::obj::objstr::PyStringRef;
use crate::obj::objtuple::PyTupleRef;
use crate::pyobject::{PyObjectRef, PyRef, PyResult, PyValue, TryFromObject};
use crate::vm::VirtualMachine;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{PyObjectRef, PyRef, PyResult, PyValue, TryFromObject};
#[cfg(unix)]
use crate::stdlib::os::convert_nix_error;
use num_bigint::Sign;
use num_traits::ToPrimitive;
use crate::vm::VirtualMachine;
#[derive(Debug, Copy, Clone)]
enum AddressFamily {

View File

@@ -1,6 +1,4 @@
/* String builtin module
*
*
*/
use crate::pyobject::PyObjectRef;

View File

@@ -1,10 +1,12 @@
use std::fmt;
use rustpython_compiler::{compile, error::CompileError, symboltable};
use rustpython_parser::parser;
use crate::obj::objstr::PyStringRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{PyClassImpl, PyObjectRef, PyRef, PyResult, PyValue};
use crate::vm::VirtualMachine;
use rustpython_compiler::{compile, error::CompileError, symboltable};
use rustpython_parser::parser;
use std::fmt;
pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
let ctx = &vm.ctx;
@@ -169,43 +171,43 @@ impl PyValue for PySymbol {
#[pyimpl]
impl PySymbol {
#[pymethod(name = "get_name")]
fn get_name(&self, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.new_str(self.symbol.name.clone()))
fn get_name(&self, _vm: &VirtualMachine) -> String {
self.symbol.name.clone()
}
#[pymethod(name = "is_global")]
fn is_global(&self, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.new_bool(self.symbol.is_global()))
fn is_global(&self, _vm: &VirtualMachine) -> bool {
self.symbol.is_global()
}
#[pymethod(name = "is_local")]
fn is_local(&self, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.new_bool(self.symbol.is_local()))
fn is_local(&self, _vm: &VirtualMachine) -> bool {
self.symbol.is_local()
}
#[pymethod(name = "is_referenced")]
fn is_referenced(&self, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.new_bool(self.symbol.is_referenced))
fn is_referenced(&self, _vm: &VirtualMachine) -> bool {
self.symbol.is_referenced
}
#[pymethod(name = "is_assigned")]
fn is_assigned(&self, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.new_bool(self.symbol.is_assigned))
fn is_assigned(&self, _vm: &VirtualMachine) -> bool {
self.symbol.is_assigned
}
#[pymethod(name = "is_parameter")]
fn is_parameter(&self, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.new_bool(self.symbol.is_parameter))
fn is_parameter(&self, _vm: &VirtualMachine) -> bool {
self.symbol.is_parameter
}
#[pymethod(name = "is_free")]
fn is_free(&self, vm: &VirtualMachine) -> PyResult {
Ok(vm.ctx.new_bool(self.symbol.is_free))
fn is_free(&self, _vm: &VirtualMachine) -> bool {
self.symbol.is_free
}
#[pymethod(name = "is_namespace")]
fn is_namespace(&self, vm: &VirtualMachine) -> PyResult {
fn is_namespace(&self, _vm: &VirtualMachine) -> bool {
// TODO
Ok(vm.ctx.new_bool(false))
false
}
}

View File

@@ -1,8 +1,7 @@
/// Implementation of the _thread module, currently noop implementation as RustPython doesn't yet
/// support threading
use super::super::pyobject::PyObjectRef;
use crate::function::PyFuncArgs;
use crate::pyobject::PyResult;
use crate::pyobject::{PyObjectRef, PyResult};
use crate::vm::VirtualMachine;
#[cfg(not(target_os = "windows"))]

View File

@@ -5,22 +5,19 @@ use std::fmt;
use std::ops::Range;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::function::OptionalArg;
use crate::obj::objfloat::PyFloatRef;
use crate::obj::objint::PyInt;
use crate::obj::objsequence::get_sequence_index;
use crate::obj::objsequence::PySliceableSequence;
use crate::obj::objslice::PySlice;
use crate::obj::objstr::PyStringRef;
use crate::obj::objtype::PyClassRef;
use crate::obj::{objfloat, objint, objtype};
use crate::pyobject::{PyClassImpl, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol};
use crate::vm::VirtualMachine;
use num_traits::cast::ToPrimitive;
use chrono::naive::NaiveDateTime;
use chrono::{Datelike, Timelike};
use num_traits::cast::ToPrimitive;
use crate::function::OptionalArg;
use crate::obj::objfloat::{self, PyFloatRef};
use crate::obj::objint::{self, PyInt};
use crate::obj::objsequence::{get_sequence_index, PySliceableSequence};
use crate::obj::objslice::PySlice;
use crate::obj::objstr::PyStringRef;
use crate::obj::objtype::{self, PyClassRef};
use crate::pyobject::{PyClassImpl, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol};
use crate::vm::VirtualMachine;
#[cfg(unix)]
fn time_sleep(seconds: PyFloatRef, vm: &VirtualMachine) -> PyResult<()> {

View File

@@ -45,7 +45,7 @@ fn zlib_adler32(
data: PyBytesRef,
begin_state: OptionalArg<PyIntRef>,
vm: &VirtualMachine,
) -> PyResult<PyObjectRef> {
) -> PyResult {
let data = data.get_value();
let begin_state = begin_state
@@ -67,7 +67,7 @@ fn zlib_crc32(
data: PyBytesRef,
begin_state: OptionalArg<PyIntRef>,
vm: &VirtualMachine,
) -> PyResult<PyObjectRef> {
) -> PyResult {
let data = data.get_value();
let begin_state = begin_state
@@ -85,11 +85,7 @@ fn zlib_crc32(
}
/// Returns a bytes object containing compressed data.
fn zlib_compress(
data: PyBytesRef,
level: OptionalArg<PyIntRef>,
vm: &VirtualMachine,
) -> PyResult<PyObjectRef> {
fn zlib_compress(data: PyBytesRef, level: OptionalArg<PyIntRef>, vm: &VirtualMachine) -> PyResult {
let input_bytes = data.get_value();
let level = level
@@ -119,7 +115,7 @@ fn zlib_decompress(
wbits: OptionalArg<PyIntRef>,
bufsize: OptionalArg<PyIntRef>,
vm: &VirtualMachine,
) -> PyResult<PyObjectRef> {
) -> PyResult {
let encoded_bytes = data.get_value();
let wbits = wbits

View File

@@ -11,6 +11,12 @@ use std::fmt;
use std::rc::Rc;
use std::sync::{Mutex, MutexGuard};
use arr_macro::arr;
use num_bigint::BigInt;
use num_traits::ToPrimitive;
#[cfg(feature = "rustpython-compiler")]
use rustpython_compiler::{compile, error::CompileError};
use crate::builtins::{self, to_ascii};
use crate::bytecode;
use crate::frame::{ExecutionResult, Frame, FrameRef};
@@ -29,8 +35,7 @@ use crate::obj::objmodule::{self, PyModule};
use crate::obj::objsequence;
use crate::obj::objstr::{PyString, PyStringRef};
use crate::obj::objtuple::PyTupleRef;
use crate::obj::objtype;
use crate::obj::objtype::PyClassRef;
use crate::obj::objtype::{self, PyClassRef};
use crate::pyhash;
use crate::pyobject::{
IdProtocol, ItemProtocol, PyContext, PyObject, PyObjectRef, PyResult, PyValue, TryFromObject,
@@ -39,11 +44,6 @@ use crate::pyobject::{
use crate::scope::Scope;
use crate::stdlib;
use crate::sysmodule;
use arr_macro::arr;
use num_bigint::BigInt;
use num_traits::ToPrimitive;
#[cfg(feature = "rustpython-compiler")]
use rustpython_compiler::{compile, error::CompileError};
// use objects::objects;
@@ -1194,7 +1194,7 @@ impl VirtualMachine {
pub fn _ne(&self, a: PyObjectRef, b: PyObjectRef) -> PyResult {
self.call_or_reflection(a, b, "__ne__", "__ne__", |vm, a, b| {
let eq = vm._eq(a, b)?;
objbool::not(vm, &eq)
Ok(vm.new_bool(objbool::not(vm, &eq)?))
})
}