@@ -4,6 +4,7 @@ use super::super::pyobject::{
4
4
} ;
5
5
use super :: super :: vm:: VirtualMachine ;
6
6
use super :: objfloat;
7
+ use super :: objstr;
7
8
use super :: objtype;
8
9
9
10
fn int_repr ( vm : & mut VirtualMachine , args : PyFuncArgs ) -> PyResult {
@@ -17,21 +18,40 @@ fn int_new(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
17
18
if !objtype:: issubclass ( cls, vm. ctx . int_type ( ) ) {
18
19
return Err ( vm. new_type_error ( format ! ( "{:?} is not a subtype of int" , cls) ) ) ;
19
20
}
20
- let val = to_int ( vm, & args. args [ 1 ] . clone ( ) ) ?;
21
+
22
+ // TODO: extract kwargs:
23
+ let base = 10 ;
24
+ let val = to_int ( vm, & args. args [ 1 ] . clone ( ) , base) ?;
21
25
Ok ( PyObject :: new (
22
26
PyObjectKind :: Integer { value : val } ,
23
27
cls. clone ( ) ,
24
28
) )
25
29
}
26
30
27
31
// Casting function:
28
- pub fn to_int ( vm : & mut VirtualMachine , obj : & PyObjectRef ) -> Result < i32 , PyObjectRef > {
32
+ pub fn to_int ( vm : & mut VirtualMachine , obj : & PyObjectRef , base : u32 ) -> Result < i32 , PyObjectRef > {
29
33
let val = if objtype:: isinstance ( obj, vm. ctx . int_type ( ) ) {
30
34
get_value ( obj)
31
35
} else if objtype:: isinstance ( obj, vm. ctx . float_type ( ) ) {
32
36
objfloat:: get_value ( obj) as i32
37
+ } else if objtype:: isinstance ( obj, vm. ctx . str_type ( ) ) {
38
+ let s = objstr:: get_value ( obj) ;
39
+ match i32:: from_str_radix ( & s, base) {
40
+ Ok ( v) => v,
41
+ Err ( err) => {
42
+ trace ! ( "Error occured during int conversion {:?}" , err) ;
43
+ return Err ( vm. new_value_error ( format ! (
44
+ "invalid literal for int() with base {}: '{}'" ,
45
+ base, s
46
+ ) ) ) ;
47
+ }
48
+ }
33
49
} else {
34
- return Err ( vm. new_type_error ( "Cannot construct int" . to_string ( ) ) ) ;
50
+ let type_name = objtype:: get_type_name ( & obj. typ ( ) ) ;
51
+ return Err ( vm. new_type_error ( format ! (
52
+ "int() argument must be a string or a number, not '{}'" ,
53
+ type_name
54
+ ) ) ) ;
35
55
} ;
36
56
Ok ( val)
37
57
}
0 commit comments