-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmod.rs
More file actions
218 lines (201 loc) · 8.79 KB
/
Copy pathmod.rs
File metadata and controls
218 lines (201 loc) · 8.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::collections::linked_list::LinkedList;
use std::rc::Rc;
use std::cell::RefCell;
use std::iter::IntoIterator;
use super::sandbox::EnvProxy;
use super::state::{State, PyFunction, raise, return_value};
use super::objects::{ObjectRef, ObjectContent, Object, ObjectStore};
use super::processor::frame::Frame;
use super::processor::instructions::{Instruction, InstructionDecoder};
use super::varstack::VectorVarStack;
macro_rules! parse_first_arguments {
( $funcname:expr, $store:expr, $args:ident, $args_iter:ident, $( $argname:tt $argexpected:tt : { $($argpattern:pat => $argcode:block,)* } ),* ) => {{
$(
match $args_iter.next() {
None => panic!(format!("Not enough arguments for function {}: no argument for positional parameter {}.", $funcname, $argname)),
Some(obj_ref) => {
match $store.deref(&obj_ref).content {
$( $argpattern => $argcode, )*
ref obj => panic!(format!("Bad argument for function {}: {} should be {}, not {:?}.", $funcname, $argname, $argexpected, obj)),
}
}
}
)*
}};
}
macro_rules! parse_arguments {
( $funcname:expr, $store:expr, $args:ident, $( $argname:tt $argexpected:tt : { $($argpattern:pat => $argcode:block,)* } ),* ) => {{
let mut args_iter = $args.iter();
parse_first_arguments!($funcname, $store, $args, args_iter, $( $argname $argexpected : { $($argpattern => $argcode,)* } ),*);
if let Some(_) = args_iter.next() {
panic!(format!("Too many positional arguments for function {}.", $funcname))
}
}};
}
fn write_stdout<EP: EnvProxy>(processor: &mut State<EP>, call_stack: &mut Vec<Frame>, args: Vec<ObjectRef>) {
parse_arguments!("__primitives__.write_stdout", processor.store, args,
"value" "a string, boolean, or integer": {
ObjectContent::String(ref s) => {
processor.envproxy.stdout().write(s.clone().into_bytes().as_slice()).unwrap(); // TODO: check
},
ObjectContent::Int(ref i) => {
processor.envproxy.stdout().write(i.to_string().into_bytes().as_slice()).unwrap(); // TODO: check
},
ObjectContent::True => {
processor.envproxy.stdout().write(b"True").unwrap(); // TODO: check
},
ObjectContent::False => {
processor.envproxy.stdout().write(b"False").unwrap(); // TODO: check
},
}
);
return_value(call_stack, processor.primitive_objects.none.clone())
}
fn build_class<EP: EnvProxy>(state: &mut State<EP>, call_stack: &mut Vec<Frame>, args: Vec<ObjectRef>) {
let name;
let code;
let mut args_iter = args.into_iter();
parse_first_arguments!("__primitives__.build_class", state.store, args, args_iter,
"func" "a function": {
ObjectContent::Function(_, ref code_arg, _) => {
match state.store.deref(code_arg).content {
ObjectContent::Code(ref code_) => code = code_.clone(),
_ => panic!("__build_class__'s function argument has a code that is not code.")
}
},
},
"name" "a string": {
ObjectContent::String(ref name_arg) => { name = name_arg.clone() },
}
);
let bases: Vec<ObjectRef> = args_iter.collect();
let bases = if bases.len() == 0 {
vec![state.primitive_objects.object.clone()]
}
else {
bases
};
let attributes = Rc::new(RefCell::new(HashMap::new()));
let cls_ref = state.store.allocate(Object::new_class(name, Some(attributes.clone()), state.primitive_objects.type_.clone(), bases));
let mut instructions: Vec<Instruction> = InstructionDecoder::new(code.code.iter()).collect();
// Hack to made the class' code return the class instead of None
let mut last_instruction;
while {last_instruction = instructions.pop(); last_instruction == Some(Instruction::Nop)} {};
assert_eq!(last_instruction, Some(Instruction::ReturnValue));
instructions.pop(); // LoadConst None
instructions.push(Instruction::PushImmediate(cls_ref.clone()));
instructions.push(Instruction::ReturnValue);
let frame = Frame {
object: cls_ref,
var_stack: VectorVarStack::new(),
block_stack: vec![],
locals: attributes,
instructions: instructions,
code: (*code).clone(),
program_counter: 0,
};
call_stack.push(frame);
}
pub fn native_issubclass(store: &ObjectStore, first: &ObjectRef, second: &ObjectRef) -> bool {
let mut visited = HashSet::new();
let mut to_visit = LinkedList::new();
to_visit.push_back(first.clone());
while let Some(candidate) = to_visit.pop_front() {
if !visited.insert(candidate.clone()) {
// Already visited
continue
};
if candidate.is(second) {
return true
};
match store.deref(&candidate).bases {
None => (),
Some(ref bases) => {
for base in bases.iter() {
to_visit.push_back(base.clone())
}
}
};
}
false
}
fn issubclass<EP: EnvProxy>(state: &mut State<EP>, call_stack: &mut Vec<Frame>, args: Vec<ObjectRef>) {
if args.len() != 2 {
panic!(format!("__primitives__.issubclass takes 2 arguments, not {}", args.len()))
}
let first = args.get(0).unwrap();
let second = args.get(1).unwrap();
let res = native_issubclass(&state.store, first, second);
if res {
return_value(call_stack, state.primitive_objects.true_obj.clone())
}
else {
return_value(call_stack, state.primitive_objects.false_obj.clone())
}
}
pub fn native_isinstance(store: &ObjectStore, first: &ObjectRef, second: &ObjectRef) -> bool {
native_issubclass(store, &store.deref(&first).class, second)
}
fn isinstance<EP: EnvProxy>(state: &mut State<EP>, call_stack: &mut Vec<Frame>, mut args: Vec<ObjectRef>) {
if args.len() != 2 {
panic!(format!("__primitives__.isinstance takes 2 arguments, not {}", args.len()))
}
let second = args.pop().unwrap();
let first = args.pop().unwrap();
let res = native_isinstance(&state.store, &first, &second);
if res {
return_value(call_stack, state.primitive_objects.true_obj.clone())
}
else {
return_value(call_stack, state.primitive_objects.false_obj.clone())
}
}
fn iter<EP: EnvProxy>(state: &mut State<EP>, call_stack: &mut Vec<Frame>, args: Vec<ObjectRef>) {
if args.len() != 1 {
panic!(format!("__primitives__.iter takes 1 arguments, not {}", args.len()))
}
let iterator_ref = args.last().unwrap();
let iterator = state.store.deref(iterator_ref).clone();
match iterator.content {
ObjectContent::RandomAccessIterator(container_ref, index, container_version) => {
let value = {
let container = state.store.deref(&container_ref);
if container.version != container_version {
panic!("Container changed while iterating.")
};
match container.content {
ObjectContent::List(ref v) | ObjectContent::Tuple(ref v) => v.get(index).map(|r| r.clone()),
_ => panic!(format!("RandomAccessIterator does not support {}", container_ref.repr(&state.store)))
}
};
match value {
Some(value) => {
let mut iterator = state.store.deref_mut(iterator_ref);
iterator.content = ObjectContent::RandomAccessIterator(container_ref, index+1, container_version);
return_value(call_stack, value.clone())
}
None => {
let stopiteration = state.primitive_objects.stopiteration.clone();
return raise(state, call_stack, stopiteration, "StopIteration instance".to_string())
}
}
}
_ => {
let repr = iterator_ref.repr(&state.store);
let exc = Object::new_instance(None, state.primitive_objects.typeerror.clone(), ObjectContent::OtherObject);
let exc = state.store.allocate(exc);
raise(state, call_stack, exc, format!("{} is not an iterator", repr));
}
}
}
pub fn get_default_primitives<EP: EnvProxy>() -> HashMap<String, PyFunction<EP>> {
let mut builtins: HashMap<String, PyFunction<EP>> = HashMap::new();
builtins.insert("write_stdout".to_string(), write_stdout);
builtins.insert("build_class".to_string(), build_class);
builtins.insert("issubclass".to_string(), issubclass);
builtins.insert("isinstance".to_string(), isinstance);
builtins.insert("iter".to_string(), iter);
builtins
}