Skip to content

Fix int type casting error with negative base value #1406

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 25, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions tests/snippets/ints.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,15 @@
with assert_raises(ValueError):
int(' 1 ', base=37)

with assert_raises(ValueError):
int(' 1 ', base=-1)

with assert_raises(ValueError):
int(' 1 ', base=1000000000000000)

with assert_raises(ValueError):
int(' 1 ', base=-1000000000000000)

with assert_raises(TypeError):
int(base=2)

Expand Down
2 changes: 1 addition & 1 deletion vm/src/obj/objbyteinner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ impl ByteInnerNewOptions {

let mut data_bytes = vec![];
for elem in elements.unwrap() {
let v = objint::to_int(vm, &elem, 10)?;
let v = objint::to_int(vm, &elem, &BigInt::from(10))?;
if let Some(i) = v.to_u8() {
data_bytes.push(i);
} else {
Expand Down
37 changes: 24 additions & 13 deletions vm/src/obj/objint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -704,7 +704,7 @@ struct IntOptions {
#[pyarg(positional_only, optional = true)]
val_options: OptionalArg<PyObjectRef>,
#[pyarg(positional_or_keyword, optional = true)]
base: OptionalArg<u32>,
base: OptionalArg<PyIntRef>,
}

impl IntOptions {
Expand All @@ -720,9 +720,9 @@ impl IntOptions {
}
base
} else {
10
PyInt::new(10).into_ref(vm)
};
to_int(vm, &val, base)
to_int(vm, &val, base.as_bigint())
} else if let OptionalArg::Present(_) = self.base {
Err(vm.new_type_error("int() missing string argument".to_string()))
} else {
Expand All @@ -736,8 +736,14 @@ fn int_new(cls: PyClassRef, options: IntOptions, vm: &VirtualMachine) -> PyResul
}

// Casting function:
pub fn to_int(vm: &VirtualMachine, obj: &PyObjectRef, base: u32) -> PyResult<BigInt> {
if base != 0 && (base < 2 || base > 36) {
pub fn to_int(vm: &VirtualMachine, obj: &PyObjectRef, base: &BigInt) -> PyResult<BigInt> {
let base_u32 = match base.to_u32() {
Some(base_u32) => base_u32,
None => {
return Err(vm.new_value_error("int() base must be >= 2 and <= 36, or 0".to_string()))
}
};
if base_u32 != 0 && (base_u32 < 2 || base_u32 > 36) {
return Err(vm.new_value_error("int() base must be >= 2 and <= 36, or 0".to_string()));
}

Expand Down Expand Up @@ -772,38 +778,43 @@ pub fn to_int(vm: &VirtualMachine, obj: &PyObjectRef, base: u32) -> PyResult<Big
})
}

fn str_to_int(vm: &VirtualMachine, literal: &str, mut base: u32) -> PyResult<BigInt> {
fn str_to_int(vm: &VirtualMachine, literal: &str, base: &BigInt) -> PyResult<BigInt> {
let mut buf = validate_literal(vm, literal, base)?;
let is_signed = buf.starts_with('+') || buf.starts_with('-');
let radix_range = if is_signed { 1..3 } else { 0..2 };
let radix_candidate = buf.get(radix_range.clone());

let mut base_u32 = match base.to_u32() {
Some(base_u32) => base_u32,
None => return Err(invalid_literal(vm, literal, base)),
};

// try to find base
if let Some(radix_candidate) = radix_candidate {
if let Some(matched_radix) = detect_base(&radix_candidate) {
if base != 0 && base != matched_radix {
if base_u32 != 0 && base_u32 != matched_radix {
return Err(invalid_literal(vm, literal, base));
} else {
base = matched_radix;
base_u32 = matched_radix;
}

buf.drain(radix_range);
}
}

// base still not found, try to use default
if base == 0 {
if base_u32 == 0 {
if buf.starts_with('0') {
return Err(invalid_literal(vm, literal, base));
}

base = 10;
base_u32 = 10;
}

BigInt::from_str_radix(&buf, base).map_err(|_err| invalid_literal(vm, literal, base))
BigInt::from_str_radix(&buf, base_u32).map_err(|_err| invalid_literal(vm, literal, base))
}

fn validate_literal(vm: &VirtualMachine, literal: &str, base: u32) -> PyResult<String> {
fn validate_literal(vm: &VirtualMachine, literal: &str, base: &BigInt) -> PyResult<String> {
if literal.starts_with('_') || literal.ends_with('_') {
return Err(invalid_literal(vm, literal, base));
}
Expand Down Expand Up @@ -835,7 +846,7 @@ fn detect_base(literal: &str) -> Option<u32> {
}
}

fn invalid_literal(vm: &VirtualMachine, literal: &str, base: u32) -> PyObjectRef {
fn invalid_literal(vm: &VirtualMachine, literal: &str, base: &BigInt) -> PyObjectRef {
vm.new_value_error(format!(
"invalid literal for int() with base {}: '{}'",
base, literal
Expand Down
2 changes: 1 addition & 1 deletion vm/src/stdlib/pystruct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ where
}

fn get_int(vm: &VirtualMachine, arg: &PyObjectRef) -> PyResult<BigInt> {
objint::to_int(vm, arg, 10)
objint::to_int(vm, arg, &BigInt::from(10))
Copy link
Contributor

@windelbouwman windelbouwman Sep 25, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you want to prevent using BigInt here, you can change the signature of to_int to accept an Into<BigInt> instead of bigint itself. This will allow you to call the function with 10 and with a BigInt value as well.

Copy link
Contributor Author

@hqsz hqsz Sep 25, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@windelbouwman Thank you for reviewing. I agree that change signature of to_int will make to_int function more general.

But I have some questions. When we use base type to u32, we can easily pass the argument because u32 have copy trait. And when we use base type to pyIntRef, we can also pass reference of PyInt by as_bigint method.

But If i changed signature of to_int function. i cannot pass base to to_int function. Because PyInt does not have copy trait. Just simple modifying make this error.

error[E0507]: cannot move out of dereference of `pyobject::PyRef<obj::objint::PyInt>`
   --> vm/src/obj/objint.rs:721:34
    |
721 |                 to_int(vm, &val, base.value)
    |                                  ^^^^^^^^^^ move occurs because value has type `num_bigint::bigint::BigInt`, which does not implement the `Copy` trait

error: aborting due to previous error

And also change base type to BigInt occurs other error.

error[E0277]: the trait bound `num_bigint::bigint::BigInt: pyobject::TryFromObject` is not satisfied
   --> vm/src/obj/objint.rs:702:10
    |
702 | #[derive(FromArgs)]
    |          ^^^^^^^^ the trait `pyobject::TryFromObject` is not implemented for `num_bigint::bigint::BigInt`
    | 
   ::: vm/src/pyobject.rs:953:5
    |
953 |     fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self>;
    |     ---------------------------------------------------------------------------- required by `pyobject::TryFromObject::try_from_object`

Unfortunately, I'm not good at rust. so please give me an opinion. thx

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, okay, the copy trait is important here. I'm not a rust wizard either, so I think the current situation is probably ok. Maybe other people could have a look at this?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that the current solution is fine as well, passing an &BigInt rather than an Into<BigInt> removes the need for cloning as well.

}

fn pack_i8(vm: &VirtualMachine, arg: &PyObjectRef, data: &mut dyn Write) -> PyResult<()> {
Expand Down
1 change: 1 addition & 0 deletions wasm/lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ serde = "1.0"
js-sys = "0.3"
futures = "0.1"
num-traits = "0.2"
num-bigint = { version = "0.2.3", features = ["serde"] }

[dependencies.web-sys]
version = "0.3"
Expand Down
4 changes: 3 additions & 1 deletion wasm/lib/src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ use rustpython_vm::py_serde;
use rustpython_vm::pyobject::{ItemProtocol, PyObjectRef, PyResult, PyValue};
use rustpython_vm::VirtualMachine;

use num_bigint::BigInt;

use crate::browser_module;
use crate::vm_class::{stored_vm_from_wasm, WASMVirtualMachine};

Expand Down Expand Up @@ -43,7 +45,7 @@ pub fn py_err_to_js_err(vm: &VirtualMachine, py_err: &PyObjectRef) -> JsValue {
if objtype::isinstance(&top, &vm.ctx.tuple_type()) {
let element = objsequence::get_elements_tuple(&top);

if let Some(lineno) = objint::to_int(vm, &element[1], 10)
if let Some(lineno) = objint::to_int(vm, &element[1], &BigInt::from(10))
.ok()
.and_then(|lineno| lineno.to_u32())
{
Expand Down