forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_opcode.rs
More file actions
341 lines (303 loc) · 10.3 KB
/
_opcode.rs
File metadata and controls
341 lines (303 loc) · 10.3 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
pub(crate) use _opcode::module_def;
#[pymodule]
mod _opcode {
use crate::vm::{
AsObject, PyObjectRef, PyResult, VirtualMachine,
builtins::{PyInt, PyIntRef},
bytecode::{AnyInstruction, Instruction, InstructionMetadata, PseudoInstruction},
};
use core::ops::Deref;
#[derive(Clone, Copy)]
struct Opcode(AnyInstruction);
impl Deref for Opcode {
type Target = AnyInstruction;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl TryFrom<i32> for Opcode {
type Error = ();
fn try_from(value: i32) -> Result<Self, Self::Error> {
Ok(Self(
u16::try_from(value)
.map_err(|_| ())?
.try_into()
.map_err(|_| ())?,
))
}
}
impl Opcode {
// https://github.com/python/cpython/blob/v3.14.2/Include/opcode_ids.h#L252
const HAVE_ARGUMENT: i32 = 43;
pub fn try_from_pyint(raw: PyIntRef, vm: &VirtualMachine) -> PyResult<Self> {
let instruction = raw
.try_to_primitive::<u16>(vm)
.and_then(|v| {
AnyInstruction::try_from(v).map_err(|_| {
vm.new_exception_empty(vm.ctx.exceptions.value_error.to_owned())
})
})
.map_err(|_| vm.new_value_error("invalid opcode or oparg"))?;
Ok(Self(instruction))
}
const fn inner(self) -> AnyInstruction {
self.0
}
/// Check if opcode is valid (can be converted to an AnyInstruction)
#[must_use]
pub fn is_valid(opcode: i32) -> bool {
Self::try_from(opcode).is_ok()
}
/// Check if instruction has an argument
#[must_use]
pub fn has_arg(opcode: i32) -> bool {
Self::is_valid(opcode) && opcode > Self::HAVE_ARGUMENT
}
/// Check if instruction uses co_consts
#[must_use]
pub fn has_const(opcode: i32) -> bool {
matches!(
Self::try_from(opcode).map(|op| op.inner()),
Ok(AnyInstruction::Real(Instruction::LoadConst { .. }))
)
}
/// Check if instruction uses co_names
#[must_use]
pub fn has_name(opcode: i32) -> bool {
matches!(
Self::try_from(opcode).map(|op| op.inner()),
Ok(AnyInstruction::Real(
Instruction::DeleteAttr { .. }
| Instruction::DeleteGlobal { .. }
| Instruction::DeleteName { .. }
| Instruction::ImportFrom { .. }
| Instruction::ImportName { .. }
| Instruction::LoadAttr { .. }
| Instruction::LoadGlobal { .. }
| Instruction::LoadName { .. }
| Instruction::StoreAttr { .. }
| Instruction::StoreGlobal { .. }
| Instruction::StoreName { .. }
))
)
}
/// Check if instruction is a jump
#[must_use]
pub fn has_jump(opcode: i32) -> bool {
matches!(
Self::try_from(opcode).map(|op| op.inner()),
Ok(AnyInstruction::Real(
Instruction::ForIter { .. }
| Instruction::PopJumpIfFalse { .. }
| Instruction::PopJumpIfTrue { .. }
| Instruction::Send { .. }
) | AnyInstruction::Pseudo(PseudoInstruction::Jump { .. }))
)
}
/// Check if instruction uses co_freevars/co_cellvars
#[must_use]
pub fn has_free(opcode: i32) -> bool {
matches!(
Self::try_from(opcode).map(|op| op.inner()),
Ok(AnyInstruction::Real(
Instruction::DeleteDeref { .. }
| Instruction::LoadFromDictOrDeref { .. }
| Instruction::LoadDeref { .. }
| Instruction::StoreDeref { .. }
))
)
}
/// Check if instruction uses co_varnames (local variables)
#[must_use]
pub fn has_local(opcode: i32) -> bool {
matches!(
Self::try_from(opcode).map(|op| op.inner()),
Ok(AnyInstruction::Real(
Instruction::DeleteFast { .. }
| Instruction::LoadFast { .. }
| Instruction::LoadFastAndClear { .. }
| Instruction::StoreFast { .. }
| Instruction::StoreFastLoadFast { .. }
))
)
}
/// Check if instruction has exception info
#[must_use]
pub fn has_exc(_opcode: i32) -> bool {
// No instructions have exception info in RustPython
// (exception handling is done via exception table)
false
}
}
// prepare specialization
#[pyattr]
const ENABLE_SPECIALIZATION: i8 = 1;
#[pyattr]
const ENABLE_SPECIALIZATION_FT: i8 = 1;
#[derive(FromArgs)]
struct StackEffectArgs {
#[pyarg(positional)]
opcode: PyIntRef,
#[pyarg(positional, optional)]
oparg: Option<PyObjectRef>,
#[pyarg(named, optional)]
jump: Option<PyObjectRef>,
}
#[pyfunction]
fn stack_effect(args: StackEffectArgs, vm: &VirtualMachine) -> PyResult<i32> {
let oparg = args
.oparg
.map(|v| {
if !v.fast_isinstance(vm.ctx.types.int_type) {
return Err(vm.new_type_error(format!(
"'{}' object cannot be interpreted as an integer",
v.class().name()
)));
}
v.downcast_ref::<PyInt>()
.ok_or_else(|| {
vm.new_type_error(format!(
"'{}' object cannot be interpreted as an integer",
v.class().name()
))
})?
.try_to_primitive::<u32>(vm)
})
.unwrap_or(Ok(0))?;
let jump = args
.jump
.map(|v| {
v.try_to_bool(vm).map_err(|_| {
vm.new_value_error("stack_effect: jump must be False, True or None")
})
})
.unwrap_or(Ok(false))?;
let opcode = Opcode::try_from_pyint(args.opcode, vm)?;
let _ = jump; // Python API accepts jump but it's not used
Ok(opcode.stack_effect(oparg))
}
#[pyfunction]
fn is_valid(opcode: i32) -> bool {
Opcode::is_valid(opcode)
}
#[pyfunction]
fn has_arg(opcode: i32) -> bool {
Opcode::has_arg(opcode)
}
#[pyfunction]
fn has_const(opcode: i32) -> bool {
Opcode::has_const(opcode)
}
#[pyfunction]
fn has_name(opcode: i32) -> bool {
Opcode::has_name(opcode)
}
#[pyfunction]
fn has_jump(opcode: i32) -> bool {
Opcode::has_jump(opcode)
}
#[pyfunction]
fn has_free(opcode: i32) -> bool {
Opcode::has_free(opcode)
}
#[pyfunction]
fn has_local(opcode: i32) -> bool {
Opcode::has_local(opcode)
}
#[pyfunction]
fn has_exc(opcode: i32) -> bool {
Opcode::has_exc(opcode)
}
#[pyfunction]
fn get_intrinsic1_descs(vm: &VirtualMachine) -> Vec<PyObjectRef> {
[
"INTRINSIC_1_INVALID",
"INTRINSIC_PRINT",
"INTRINSIC_IMPORT_STAR",
"INTRINSIC_STOPITERATION_ERROR",
"INTRINSIC_ASYNC_GEN_WRAP",
"INTRINSIC_UNARY_POSITIVE",
"INTRINSIC_LIST_TO_TUPLE",
"INTRINSIC_TYPEVAR",
"INTRINSIC_PARAMSPEC",
"INTRINSIC_TYPEVARTUPLE",
"INTRINSIC_SUBSCRIPT_GENERIC",
"INTRINSIC_TYPEALIAS",
]
.into_iter()
.map(|x| vm.ctx.new_str(x).into())
.collect()
}
#[pyfunction]
fn get_intrinsic2_descs(vm: &VirtualMachine) -> Vec<PyObjectRef> {
[
"INTRINSIC_2_INVALID",
"INTRINSIC_PREP_RERAISE_STAR",
"INTRINSIC_TYPEVAR_WITH_BOUND",
"INTRINSIC_TYPEVAR_WITH_CONSTRAINTS",
"INTRINSIC_SET_FUNCTION_TYPE_PARAMS",
"INTRINSIC_SET_TYPEPARAM_DEFAULT",
]
.into_iter()
.map(|x| vm.ctx.new_str(x).into())
.collect()
}
#[pyfunction]
fn get_nb_ops(vm: &VirtualMachine) -> Vec<PyObjectRef> {
[
("NB_ADD", "+"),
("NB_AND", "&"),
("NB_FLOOR_DIVIDE", "//"),
("NB_LSHIFT", "<<"),
("NB_MATRIX_MULTIPLY", "@"),
("NB_MULTIPLY", "*"),
("NB_REMAINDER", "%"),
("NB_OR", "|"),
("NB_POWER", "**"),
("NB_RSHIFT", ">>"),
("NB_SUBTRACT", "-"),
("NB_TRUE_DIVIDE", "/"),
("NB_XOR", "^"),
("NB_INPLACE_ADD", "+="),
("NB_INPLACE_AND", "&="),
("NB_INPLACE_FLOOR_DIVIDE", "//="),
("NB_INPLACE_LSHIFT", "<<="),
("NB_INPLACE_MATRIX_MULTIPLY", "@="),
("NB_INPLACE_MULTIPLY", "*="),
("NB_INPLACE_REMAINDER", "%="),
("NB_INPLACE_OR", "|="),
("NB_INPLACE_POWER", "**="),
("NB_INPLACE_RSHIFT", ">>="),
("NB_INPLACE_SUBTRACT", "-="),
("NB_INPLACE_TRUE_DIVIDE", "/="),
("NB_INPLACE_XOR", "^="),
("NB_SUBSCR", "[]"),
]
.into_iter()
.map(|(a, b)| {
vm.ctx
.new_tuple(vec![vm.ctx.new_str(a).into(), vm.ctx.new_str(b).into()])
.into()
})
.collect()
}
#[pyfunction]
fn get_special_method_names(vm: &VirtualMachine) -> Vec<PyObjectRef> {
["__enter__", "__exit__", "__aenter__", "__aexit__"]
.into_iter()
.map(|x| vm.ctx.new_str(x).into())
.collect()
}
#[pyfunction]
fn get_executor(
_code: PyObjectRef,
_offset: i32,
vm: &VirtualMachine,
) -> PyResult<PyObjectRef> {
Ok(vm.ctx.none())
}
#[pyfunction]
fn get_specialization_stats(vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.none()
}
}