Skip to content
This repository was archived by the owner on May 5, 2023. It is now read-only.

Commit a899a25

Browse files
committed
Merge branch 'master' of github.com:shinglyu/RustPython
2 parents f4888e5 + 88927a3 commit a899a25

File tree

7 files changed

+66
-13
lines changed

7 files changed

+66
-13
lines changed

README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@ pip install bytecode
1313

1414
# Run
1515

16+
```
17+
./test.sh <path/to/file.py> # compile and run
18+
./test.sh --bytecode <path/to/file.py> # print the bytecode
19+
./test.sh --dis <path/to/file.py> # Run python -m dis
20+
```
21+
22+
## Manual
1623
Given a python file `test.py`
1724

1825
```
@@ -22,6 +29,18 @@ cd RustPython
2229
cargo run ../test.bytecode
2330
```
2431

32+
# Testing & debugging
33+
34+
```
35+
./test_all.sh
36+
```
37+
38+
## Logging
39+
40+
```
41+
RUST_LOG=debug ./tests_all.sh
42+
```
43+
2544
# TODOs
2645
* Native types => Partial
2746
* Control flow => if(v)
@@ -37,6 +56,7 @@ cargo run ../test.bytecode
3756
* Support all builtin functions
3857
* Runs the [pybenchmark](https://pybenchmarks.org/) benchmark test
3958
* Run famous/popular python modules (which?)
59+
4060
* Compatible with CPython 2.7
4161

4262
# Rust version

RustPython/src/builtins.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,15 @@ pub fn print(args: Vec<NativeType>) -> NativeType {
77
}
88
NativeType::NoneType
99
}
10+
11+
pub fn len(args: Vec<NativeType>) -> NativeType {
12+
if args.len() != 1 {
13+
panic!("len(s) expects exactly one parameter");
14+
}
15+
let len = match &args[0] {
16+
&NativeType::List(ref l) => l.len(),
17+
&NativeType::Tuple(ref t) => t.len(),
18+
_ => panic!("TypeError: object of this type has no len()")
19+
};
20+
NativeType::Int(len as i32)
21+
}

RustPython/src/main.rs

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ impl VirtualMachine {
142142
//TODO: move this into the __builtin__ module when we have a module type
143143
let mut locals = callargs;
144144
locals.insert("print".to_string(), NativeType::NativeFunction(builtins::print));
145+
locals.insert("len".to_string(), NativeType::NativeFunction(builtins::len));
145146
Frame {
146147
code: code,
147148
stack: vec![],
@@ -233,7 +234,12 @@ impl VirtualMachine {
233234
("LOAD_NAME", Some(namei)) => {
234235
// println!("Loading const at index: {}", consti);
235236
let curr_frame = self.curr_frame();
236-
curr_frame.stack.push(curr_frame.locals.get::<str>(&curr_frame.code.co_names[namei]).unwrap().clone());
237+
if let Some(code) = curr_frame.locals.get::<str>(&curr_frame.code.co_names[namei]) {
238+
curr_frame.stack.push(code.clone());
239+
}
240+
else {
241+
panic!("Can't find symbol {:?} in the current frame", &curr_frame.code.co_names[namei]);
242+
}
237243
None
238244
},
239245
("LOAD_GLOBAL", Some(namei)) => {
@@ -503,14 +509,10 @@ impl VirtualMachine {
503509
let curr_frame = self.curr_frame();
504510
let tos = curr_frame.stack.pop().unwrap();
505511
let tos1 = curr_frame.stack.pop().unwrap();
506-
if let (NativeType::List(v), NativeType::Int(idx)) = (tos1, tos) {
507-
if idx as usize >= v.len() {
508-
// TODO: change this to a exception
509-
panic!("IndexError: list index out of range");
510-
}
511-
curr_frame.stack.push(v[idx as usize].clone());
512-
} else {
513-
panic!("TypeError in BINARY_SUBSTRACT");
512+
match (&tos1, &tos) {
513+
(&NativeType::List(ref l), &NativeType::Int(ref index)) => curr_frame.stack.push(l[*index as usize].clone()),
514+
(&NativeType::Tuple(ref t), &NativeType::Int(ref index)) => curr_frame.stack.push(t[*index as usize].clone()),
515+
_ => panic!("TypeError: indexing type {:?} with index {:?} is not supported", tos1, tos)
514516
};
515517
None
516518
},
@@ -608,7 +610,8 @@ impl VirtualMachine {
608610
},
609611
NativeType::NativeFunction(func) => {
610612
pos_args.reverse();
611-
func(pos_args);
613+
let return_value = func(pos_args);
614+
self.curr_frame().stack.push(return_value);
612615
},
613616
_ => panic!("The item on the stack should be a code object")
614617
}
@@ -743,13 +746,17 @@ fn main() {
743746
let mut s = String::new();
744747
f.read_to_string(&mut s).unwrap();
745748
// println!("Read string");
746-
let code: PyCodeObject = serde_json::from_str(&s).unwrap();
749+
let code: PyCodeObject = match serde_json::from_str(&s) {
750+
Ok(c) => c,
751+
Err(_) => panic!("Fail to parse the bytecode")
752+
};
747753

748754
let mut vm = VirtualMachine::new();
749755
vm.run_code(code);
750756
// println!("Done");
751757
}
752758

759+
/*
753760
#[test]
754761
fn test_parse_native_type() {
755762
@@ -853,3 +860,10 @@ let input = "{\"co_consts\":[{\"Int\":1},\"NoneType\",{\"Int\":2}],\"co_names\":
853860
let deserialized: PyCodeObject = serde_json::from_str(&input).unwrap();
854861
assert_eq!(expected, deserialized)
855862
}
863+
*/
864+
865+
#[test]
866+
fn test_tuple_serialization(){
867+
let tuple = NativeType::Tuple(vec![NativeType::Int(1),NativeType::Int(2)]);
868+
println!("{}", serde_json::to_string(&tuple).unwrap());
869+
}

compile_code.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,10 @@ def capitalize_first(s):
2828
return s[0].upper() + s[1:]
2929

3030
def const_to_rust_enum(const):
31-
return {capitalize_first(str(type(const).__name__)): const}
31+
if type(const).__name__ == "tuple":
32+
return {capitalize_first(str(type(const).__name__)): list(map(const_to_rust_enum, const))}
33+
else:
34+
return {capitalize_first(str(type(const).__name__)): const}
3235
return list(map(const_to_rust_enum, consts))
3336

3437

test.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ echo "${MODE}"
2828
case "${MODE}" in
2929
"run" )
3030
cd RustPython
31-
cargo run "../${TMP_FILE}"
31+
RUST_BACKTRACE=1 cargo run "../${TMP_FILE}"
3232
;;
3333
"view_bytecode" )
3434
cat "${TMP_FILE}" | python -m json.tool

tests/builtin_len.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
assert 3 == len([1,2,3])
2+
assert 2 == len((1,2))

tests/tuple.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
x = (1,2)
2+
assert x[0] == 1

0 commit comments

Comments
 (0)