forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjitfunc.rs
More file actions
199 lines (179 loc) · 6.78 KB
/
jitfunc.rs
File metadata and controls
199 lines (179 loc) · 6.78 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
use crate::{
builtins::{bool_, float, int, PyBaseExceptionRef, PyDictRef, PyFunction, PyStrInterned},
bytecode::CodeFlags,
convert::ToPyObject,
function::FuncArgs,
AsObject, Py, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine,
};
use num_traits::ToPrimitive;
use rustpython_jit::{AbiValue, Args, CompiledCode, JitArgumentError, JitType};
#[derive(Debug, thiserror::Error)]
pub enum ArgsError {
#[error("wrong number of arguments passed")]
WrongNumberOfArgs,
#[error("argument passed multiple times")]
ArgPassedMultipleTimes,
#[error("not a keyword argument")]
NotAKeywordArg,
#[error("not all arguments passed")]
NotAllArgsPassed,
#[error("integer can't fit into a machine integer")]
IntOverflow,
#[error("type can't be used in a jit function")]
NonJitType,
#[error("{0}")]
JitError(#[from] JitArgumentError),
}
impl ToPyObject for AbiValue {
fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
match self {
AbiValue::Int(i) => i.to_pyobject(vm),
AbiValue::Float(f) => f.to_pyobject(vm),
AbiValue::Bool(b) => b.to_pyobject(vm),
_ => unimplemented!(),
}
}
}
pub fn new_jit_error(msg: String, vm: &VirtualMachine) -> PyBaseExceptionRef {
let jit_error = vm.ctx.exceptions.jit_error.to_owned();
vm.new_exception_msg(jit_error, msg)
}
fn get_jit_arg_type(dict: &PyDictRef, name: &str, vm: &VirtualMachine) -> PyResult<JitType> {
if let Some(value) = dict.get_item_opt(name, vm)? {
if value.is(vm.ctx.types.int_type) {
Ok(JitType::Int)
} else if value.is(vm.ctx.types.float_type) {
Ok(JitType::Float)
} else if value.is(vm.ctx.types.bool_type) {
Ok(JitType::Bool)
} else {
Err(new_jit_error(
"Jit requires argument to be either int or float".to_owned(),
vm,
))
}
} else {
Err(new_jit_error(
format!("argument {name} needs annotation"),
vm,
))
}
}
pub fn get_jit_arg_types(func: &Py<PyFunction>, vm: &VirtualMachine) -> PyResult<Vec<JitType>> {
let arg_names = func.code.arg_names();
if func
.code
.flags
.intersects(CodeFlags::HAS_VARARGS | CodeFlags::HAS_VARKEYWORDS)
{
return Err(new_jit_error(
"Can't jit functions with variable number of arguments".to_owned(),
vm,
));
}
if arg_names.args.is_empty() && arg_names.kwonlyargs.is_empty() {
return Ok(Vec::new());
}
let func_obj: PyObjectRef = func.as_ref().to_owned();
let annotations = func_obj.get_attr("__annotations__", vm)?;
if vm.is_none(&annotations) {
Err(new_jit_error(
"Jitting function requires arguments to have annotations".to_owned(),
vm,
))
} else if let Ok(dict) = PyDictRef::try_from_object(vm, annotations) {
let mut arg_types = Vec::new();
for arg in arg_names.args {
arg_types.push(get_jit_arg_type(&dict, arg.as_str(), vm)?);
}
for arg in arg_names.kwonlyargs {
arg_types.push(get_jit_arg_type(&dict, arg.as_str(), vm)?);
}
Ok(arg_types)
} else {
Err(vm.new_type_error("Function annotations aren't a dict".to_owned()))
}
}
fn get_jit_value(vm: &VirtualMachine, obj: &PyObject) -> Result<AbiValue, ArgsError> {
// This does exact type checks as subclasses of int/float can't be passed to jitted functions
let cls = obj.class();
if cls.is(vm.ctx.types.int_type) {
int::get_value(obj)
.to_i64()
.map(AbiValue::Int)
.ok_or(ArgsError::IntOverflow)
} else if cls.is(vm.ctx.types.float_type) {
Ok(AbiValue::Float(
obj.downcast_ref::<float::PyFloat>().unwrap().to_f64(),
))
} else if cls.is(vm.ctx.types.bool_type) {
Ok(AbiValue::Bool(bool_::get_value(obj)))
} else {
Err(ArgsError::NonJitType)
}
}
/// Like `fill_locals_from_args` but to populate arguments for calling a jit function.
/// This also doesn't do full error handling but instead return None if anything is wrong. In
/// that case it falls back to the executing the bytecode version which will call
/// `fill_locals_from_args` which will raise the actual exception if needed.
#[cfg(feature = "jit")]
pub(crate) fn get_jit_args<'a>(
func: &PyFunction,
func_args: &FuncArgs,
jitted_code: &'a CompiledCode,
vm: &VirtualMachine,
) -> Result<Args<'a>, ArgsError> {
let mut jit_args = jitted_code.args_builder();
let nargs = func_args.args.len();
let arg_names = func.code.arg_names();
if nargs > func.code.arg_count as usize || nargs < func.code.posonlyarg_count as usize {
return Err(ArgsError::WrongNumberOfArgs);
}
// Add positional arguments
for i in 0..nargs {
jit_args.set(i, get_jit_value(vm, &func_args.args[i])?)?;
}
// Handle keyword arguments
for (name, value) in &func_args.kwargs {
let arg_pos =
|args: &[&PyStrInterned], name: &str| args.iter().position(|arg| arg.as_str() == name);
if let Some(arg_idx) = arg_pos(arg_names.args, name) {
if jit_args.is_set(arg_idx) {
return Err(ArgsError::ArgPassedMultipleTimes);
}
jit_args.set(arg_idx, get_jit_value(vm, value)?)?;
} else if let Some(kwarg_idx) = arg_pos(arg_names.kwonlyargs, name) {
let arg_idx = kwarg_idx + func.code.arg_count as usize;
if jit_args.is_set(arg_idx) {
return Err(ArgsError::ArgPassedMultipleTimes);
}
jit_args.set(arg_idx, get_jit_value(vm, value)?)?;
} else {
return Err(ArgsError::NotAKeywordArg);
}
}
let (defaults, kwdefaults) = func.defaults_and_kwdefaults.lock().clone();
// fill in positional defaults
if let Some(defaults) = defaults {
for (i, default) in defaults.iter().enumerate() {
let arg_idx = i + func.code.arg_count as usize - defaults.len();
if !jit_args.is_set(arg_idx) {
jit_args.set(arg_idx, get_jit_value(vm, default)?)?;
}
}
}
// fill in keyword only defaults
if let Some(kw_only_defaults) = kwdefaults {
for (i, name) in arg_names.kwonlyargs.iter().enumerate() {
let arg_idx = i + func.code.arg_count as usize;
if !jit_args.is_set(arg_idx) {
let default = kw_only_defaults
.get_item(&**name, vm)
.map_err(|_| ArgsError::NotAllArgsPassed)
.and_then(|obj| get_jit_value(vm, &obj))?;
jit_args.set(arg_idx, default)?;
}
}
}
jit_args.into_args().ok_or(ArgsError::NotAllArgsPassed)
}