Repository navigation
Expand file tree
/
Copy pathmodule.rs
More file actions
588 lines (529 loc) · 20.4 KB
/
Copy pathmodule.rs
File metadata and controls
588 lines (529 loc) · 20.4 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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
use super::{PyDict, PyDictRef, PyNamespace, PyStr, PyStrRef, PyType, PyTypeRef, PyUtf8Str};
use crate::{
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
builtins::{PyStrInterned, pystr::AsPyStr},
class::PyClassImpl,
convert::ToPyObject,
function::{FuncArgs, PyMethodDef, PySetterValue},
import::{get_spec_file_origin, is_possibly_shadowing_path, is_stdlib_module_name},
types::{GetAttr, Initializer, Representable},
};
use alloc::borrow::Cow;
use core::ffi::{c_int, c_void};
use core::ptr::NonNull;
#[pyclass(module = false, name = "module")]
#[derive(Debug, Clone)]
pub struct PyModuleDef {
// pub index: usize,
pub name: &'static PyStrInterned,
pub doc: Option<&'static PyStrInterned>,
// pub size: isize,
pub methods: &'static [PyMethodDef],
pub slots: PyModuleSlots,
// traverse: traverse_proc
// clear: inquiry
// free: free_func
}
#[derive(Clone)]
pub enum ModuleCreate {
Rust(fn(&VirtualMachine, &PyObject, &PyModuleDef) -> PyResult<PyRef<PyModule>>),
C(unsafe extern "C" fn(spec: *mut PyObject, def: *mut c_void) -> *mut PyObject),
}
impl From<unsafe extern "C" fn(*mut PyObject, *mut c_void) -> *mut PyObject> for ModuleCreate {
fn from(func: unsafe extern "C" fn(*mut PyObject, *mut c_void) -> *mut PyObject) -> Self {
Self::C(func)
}
}
#[derive(Clone)]
pub enum ModuleExec {
Rust(fn(&VirtualMachine, &Py<PyModule>) -> PyResult<()>),
C(unsafe extern "C" fn(*mut PyObject) -> c_int),
}
impl From<unsafe extern "C" fn(*mut PyObject) -> c_int> for ModuleExec {
fn from(func: unsafe extern "C" fn(*mut PyObject) -> c_int) -> Self {
Self::C(func)
}
}
#[derive(Default, Clone)]
pub struct PyModuleSlots {
pub create: Option<ModuleCreate>,
pub exec: Option<ModuleExec>,
}
impl core::fmt::Debug for PyModuleSlots {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("PyModuleSlots")
.field("create", &self.create.is_some())
.field("exec", &self.exec.is_some())
.finish()
}
}
impl PyModuleDef {
/// Create a module from this definition (Phase 1 of multi-phase init).
///
/// This performs:
/// 1. Create module object (using create slot if provided)
/// 2. Initialize module dict from def
/// 3. Add methods to module
///
/// Does NOT add to sys.modules or call exec slot.
pub fn create_module(&'static self, vm: &VirtualMachine) -> PyResult<PyRef<PyModule>> {
use crate::PyPayload;
// Create module (use create slot if provided, else default creation)
let module = match self.slots.create {
Some(ModuleCreate::Rust(create)) => {
let spec = vm.ctx.new_str(self.name.as_str());
create(vm, spec.as_object(), self)?
}
Some(ModuleCreate::C(_)) => {
return Err(vm.new_system_error("C module create slot is not supported here"));
}
None => PyModule::from_def(self).into_ref(&vm.ctx),
};
// Initialize module dict and methods
PyModule::__init_dict_from_def(vm, &module);
module.__init_methods(vm)?;
Ok(module)
}
pub fn create_module_owned(self, vm: &VirtualMachine) -> PyResult<PyRef<PyModule>> {
use crate::PyPayload;
// Create module (use create slot if provided, else default creation)
let module = match self.slots.create {
Some(ModuleCreate::Rust(create)) => {
let spec = vm.ctx.new_str(self.name.as_str());
create(vm, spec.as_object(), &self)?
}
Some(ModuleCreate::C(create)) => {
let def = Box::leak(Box::new(self));
let spec = PyNamespace::default().into_ref(&vm.ctx);
spec.as_object()
.set_attr("name", vm.ctx.new_str(def.name.as_str()), vm)?;
let module_ptr =
unsafe { create(spec.as_object().as_raw().cast_mut(), core::ptr::null_mut()) };
let module_ptr = NonNull::new(module_ptr).ok_or_else(|| {
vm.take_raised_exception().unwrap_or_else(|| {
vm.new_system_error(
"module create slot failed without setting an exception",
)
})
})?;
let module_obj = unsafe { PyObjectRef::from_raw(module_ptr) };
module_obj.try_downcast::<PyModule>(vm)?
}
None => PyModule::from_def_owned(self).into_ref(&vm.ctx),
};
// Initialize module dict and methods
PyModule::__init_dict_from_def(vm, &module);
module.__init_methods(vm)?;
Ok(module)
}
/// Execute the module's exec slot (Phase 2 of multi-phase init).
///
/// Calls the exec slot if present. Returns Ok(()) if no exec slot.
pub fn exec_module(&self, vm: &VirtualMachine, module: &Py<PyModule>) -> PyResult<()> {
if let Some(exec) = self.slots.exec.as_ref() {
match exec {
ModuleExec::Rust(exec) => exec(vm, module)?,
ModuleExec::C(exec) => unsafe {
if exec(module.as_object().as_raw().cast_mut()) != 0 {
return Err(vm.take_raised_exception().unwrap_or_else(|| {
vm.new_system_error("Unknown error in module exec slot")
}));
}
},
};
}
Ok(())
}
pub fn from_slots<C: Into<ModuleCreate>, E: Into<ModuleExec>>(
name: &'static PyStrInterned,
doc: Option<&'static PyStrInterned>,
create: Option<C>,
exec: Option<E>,
) -> Self {
Self {
name,
doc,
methods: &[],
slots: PyModuleSlots {
create: create.map(Into::into),
exec: exec.map(Into::into),
},
}
}
}
#[pyclass(module = false, name = "module")]
// The dict lives in the object extension, not the payload. The offset is
// the dict cell at the front of that extension.
#[pymember(name = "__dict__", offset = ::rustpython_vm::object::dict_member_offset())]
#[derive(Debug)]
pub struct PyModule {
// PyObject *md_dict;
pub def: Option<Cow<'static, PyModuleDef>>,
// state: Any
// weaklist
// for logging purposes after md_dict is cleared
pub name: Option<&'static PyStrInterned>,
}
impl PyPayload for PyModule {
#[inline]
fn class(ctx: &Context) -> &'static Py<PyType> {
ctx.types.module_type
}
}
#[derive(FromArgs)]
pub struct ModuleInitArgs {
name: PyStrRef,
#[pyarg(any, default)]
doc: Option<PyStrRef>,
}
impl PyModule {
#[expect(
clippy::new_without_default,
reason = "avoid a misleading Default implementation"
)]
#[must_use]
pub const fn new() -> Self {
Self {
def: None,
name: None,
}
}
#[must_use]
pub const fn from_def(def: &'static PyModuleDef) -> Self {
Self {
def: Some(Cow::Borrowed(def)),
name: Some(def.name),
}
}
#[must_use]
pub const fn from_def_owned(def: PyModuleDef) -> Self {
let name = def.name;
Self {
def: Some(Cow::Owned(def)),
name: Some(name),
}
}
pub fn __init_dict_from_def(vm: &VirtualMachine, module: &Py<Self>) {
let doc = module.def.as_ref().unwrap().doc.map(|doc| doc.to_owned());
module.init_dict(module.name.unwrap(), doc, vm);
}
}
impl Py<PyModule> {
pub fn __init_methods(&self, vm: &VirtualMachine) -> PyResult<()> {
debug_assert!(self.def.is_some());
for method in self.def.as_ref().unwrap().methods {
let func = method
.to_function()
.with_module(self.name.unwrap())
.with_module_object(self.to_owned().into())
.into_ref(&vm.ctx);
vm.__module_set_attr(self, vm.ctx.intern_str(method.name), func)?;
}
Ok(())
}
fn getattr_inner(&self, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult {
if let Some(attr) = self.as_object().generic_getattr_opt(name, None, vm)? {
return Ok(attr);
}
if let Ok(getattr) = self.dict().get_item(identifier!(vm, __getattr__), vm) {
return getattr.call((name.to_owned(),), vm);
}
let dict = self.dict();
// Get the raw __name__ object (may be a str subclass)
let mod_name_obj = dict
.get_item_opt(identifier!(vm, __name__), vm)
.ok()
.flatten();
let mod_name = mod_name_obj
.as_ref()
.and_then(|n| n.downcast_ref::<PyUtf8Str>());
// If __name__ is not set or not a string, use a simpler error message
let Some(mod_display) = mod_name.map(|s| s.as_str()) else {
return Err(vm.new_attribute_error(format!("module has no attribute '{name}'")));
};
let spec = dict
.get_item_opt(vm.ctx.intern_str("__spec__"), vm)
.ok()
.flatten()
.filter(|s| !vm.is_none(s));
let origin = get_spec_file_origin(spec.as_deref(), vm);
let is_possibly_shadowing = origin
.as_ref()
.is_some_and(|o| is_possibly_shadowing_path(o, vm));
// Use the ORIGINAL __name__ object for stdlib check (may raise TypeError
// if __name__ is an unhashable str subclass)
let is_possibly_shadowing_stdlib = if is_possibly_shadowing {
if let Some(ref mod_name) = mod_name_obj {
is_stdlib_module_name(mod_name, vm)?
} else {
false
}
} else {
false
};
if is_possibly_shadowing_stdlib {
let origin = origin.as_ref().unwrap();
Err(vm.new_attribute_error(format!(
"module '{mod_display}' has no attribute '{name}' \
(consider renaming '{origin}' since it has the same \
name as the standard library module named '{mod_display}' \
and prevents importing that standard library module)"
)))
} else {
let is_initializing = PyModule::is_initializing(&dict, vm);
if is_initializing {
if is_possibly_shadowing {
let origin = origin.as_ref().unwrap();
Err(vm.new_attribute_error(format!(
"module '{mod_display}' has no attribute '{name}' \
(consider renaming '{origin}' if it has the same name \
as a library you intended to import)"
)))
} else if let Some(ref origin) = origin {
Err(vm.new_attribute_error(format!(
"partially initialized module '{mod_display}' from '{origin}' \
has no attribute '{name}' \
(most likely due to a circular import)"
)))
} else {
Err(vm.new_attribute_error(format!(
"partially initialized module '{mod_display}' \
has no attribute '{name}' \
(most likely due to a circular import)"
)))
}
} else {
// Check for uninitialized submodule
let submodule_initializing = is_uninitialized_submodule(mod_name, name, vm);
if submodule_initializing {
Err(vm.new_attribute_error(format!(
"cannot access submodule '{name}' of module '{mod_display}' \
(most likely due to a circular import)"
)))
} else {
Err(vm.new_attribute_error(format!(
"module '{mod_display}' has no attribute '{name}'"
)))
}
}
}
}
// TODO: to be replaced by the commented-out dict method above once dictoffset land
pub fn dict(&self) -> PyDictRef {
self.as_object().dict().unwrap()
}
// TODO: should be on PyModule, not Py<PyModule>
pub(crate) fn init_dict(
&self,
name: &'static PyStrInterned,
doc: Option<PyStrRef>,
vm: &VirtualMachine,
) {
let dict = self.dict();
dict.set_item(identifier!(vm, __name__), name.to_object(), vm)
.expect("Failed to set __name__ on module");
dict.set_item(identifier!(vm, __doc__), doc.to_pyobject(vm), vm)
.expect("Failed to set __doc__ on module");
dict.set_item("__package__", vm.ctx.none(), vm)
.expect("Failed to set __package__ on module");
dict.set_item("__loader__", vm.ctx.none(), vm)
.expect("Failed to set __loader__ on module");
dict.set_item("__spec__", vm.ctx.none(), vm)
.expect("Failed to set __spec__ on module");
}
pub fn get_attr<'a>(&self, attr_name: impl AsPyStr<'a>, vm: &VirtualMachine) -> PyResult {
let attr_name = attr_name.as_pystr(&vm.ctx);
self.getattr_inner(attr_name, vm)
}
pub fn set_attr<'a>(
&self,
attr_name: impl AsPyStr<'a>,
attr_value: impl Into<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
self.as_object().set_attr(attr_name, attr_value, vm)
}
}
#[pyclass(
with(GetAttr, Initializer, Representable),
flags(BASETYPE, HAS_DICT, HAS_WEAKREF)
)]
impl PyModule {
#[pyslot]
fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult {
Self::new().into_ref_with_type(vm, cls).map(Into::into)
}
#[pymethod]
fn __dir__(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<Vec<PyObjectRef>> {
// First check if __dict__ attribute exists and is actually a dictionary
let dict_attr = zelf.as_object().get_attr(identifier!(vm, __dict__), vm)?;
let dict = dict_attr
.downcast::<PyDict>()
.map_err(|_| vm.new_type_error("<module>.__dict__ is not a dictionary"))?;
// PEP 562: honor a module-level __dir__ if one is defined
if let Some(dir_func) = dict.get_item_opt(identifier!(vm, __dir__), vm)? {
return dir_func.call((), vm)?.try_to_value(vm);
}
let attrs = dict.into_iter().map(|(k, _v)| k).collect();
Ok(attrs)
}
#[pygetset]
fn __annotate__(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
let dict = zelf.dict();
// Get __annotate__ from dict; if not present, insert None and return it
// See: module_get_annotate()
if let Some(annotate) = dict.get_item_opt(identifier!(vm, __annotate__), vm)? {
Ok(annotate)
} else {
let none = vm.ctx.none();
dict.set_item(identifier!(vm, __annotate__), none.clone(), vm)?;
Ok(none)
}
}
#[pygetset(setter)]
fn set___annotate__(
zelf: &Py<Self>,
value: PySetterValue,
vm: &VirtualMachine,
) -> PyResult<()> {
match value {
PySetterValue::Assign(value) => {
if !vm.is_none(&value) && !value.is_callable() {
return Err(vm.new_type_error("__annotate__ must be callable or None"));
}
let dict = zelf.dict();
dict.set_item(identifier!(vm, __annotate__), value.clone(), vm)?;
// Clear __annotations__ if value is not None
if !vm.is_none(&value) {
dict.del_item(identifier!(vm, __annotations__), vm).ok();
}
Ok(())
}
PySetterValue::Delete => Err(vm.new_type_error("cannot delete __annotate__ attribute")),
}
}
#[pygetset]
fn __annotations__(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
let dict = zelf.dict();
// Check if __annotations__ is already in dict (explicitly set)
if let Some(annotations) = dict.get_item_opt(identifier!(vm, __annotations__), vm)? {
return Ok(annotations);
}
// Check if module is initializing
let is_initializing = Self::is_initializing(&dict, vm);
// PEP 649: Get __annotate__ and call it if callable
let annotations = if let Some(annotate) =
dict.get_item_opt(identifier!(vm, __annotate__), vm)?
&& annotate.is_callable()
{
// Call __annotate__(1) where 1 is FORMAT_VALUE
let result = annotate.call((1i32,), vm)?;
if !result.class().is(vm.ctx.types.dict_type) {
return Err(vm.new_type_error(format!(
"__annotate__ returned non-dict of type '{}'",
result.class().name()
)));
}
result
} else {
vm.ctx.new_dict().into()
};
// Cache result unless module is initializing
if !is_initializing {
dict.set_item(identifier!(vm, __annotations__), annotations.clone(), vm)?;
}
Ok(annotations)
}
/// Check if module is initializing via __spec__._initializing
fn is_initializing(dict: &Py<PyDict>, vm: &VirtualMachine) -> bool {
if let Ok(Some(spec)) = dict.get_item_opt(vm.ctx.intern_str("__spec__"), vm)
&& let Ok(initializing) = spec.get_attr(vm.ctx.intern_str("_initializing"), vm)
{
return initializing.try_to_bool(vm).unwrap_or(false);
}
false
}
#[pygetset(setter)]
fn set___annotations__(
zelf: &Py<Self>,
value: PySetterValue,
vm: &VirtualMachine,
) -> PyResult<()> {
let dict = zelf.dict();
match value {
PySetterValue::Assign(value) => {
dict.set_item(identifier!(vm, __annotations__), value, vm)?;
// Clear __annotate__ from dict
dict.del_item(identifier!(vm, __annotate__), vm).ok();
Ok(())
}
PySetterValue::Delete => {
if dict.del_item(identifier!(vm, __annotations__), vm).is_err() {
return Err(vm.new_attribute_error("__annotations__"));
}
// Also clear __annotate__
dict.del_item(identifier!(vm, __annotate__), vm).ok();
Ok(())
}
}
}
}
impl Initializer for PyModule {
type Args = ModuleInitArgs;
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
debug_assert!(
zelf.class()
.slots
.flags
.has_feature(crate::types::PyTypeFlags::HAS_DICT)
);
zelf.init_dict(vm.ctx.intern_str(args.name.as_wtf8()), args.doc, vm);
Ok(())
}
}
impl GetAttr for PyModule {
fn getattro(zelf: &Py<Self>, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult {
zelf.getattr_inner(name, vm)
}
}
impl Representable for PyModule {
#[inline]
fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
// Use cached importlib reference (like interp->importlib)
let module_repr = vm.importlib.get_attr("_module_repr", vm)?;
let repr = module_repr.call((zelf.to_owned(),), vm)?;
repr.downcast()
.map_err(|_| vm.new_type_error("_module_repr did not return a string"))
}
#[cold]
fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
unreachable!("use repr instead")
}
}
pub(crate) fn init(context: &'static Context) {
PyModule::extend_class(context, context.types.module_type);
}
/// Check if {module_name}.{name} is an uninitialized submodule in sys.modules.
fn is_uninitialized_submodule(
module_name: Option<&Py<PyUtf8Str>>,
name: &Py<PyStr>,
vm: &VirtualMachine,
) -> bool {
let Some(mod_name) = module_name else {
return false;
};
let Ok(sys_modules) = vm.sys_module.get_attr("modules", vm) else {
return false;
};
let full_name = vm.ctx.new_utf8_str(format!("{}.{name}", mod_name.as_str()));
let Ok(sub_mod) = sys_modules.get_item(&*full_name, vm) else {
return false;
};
let spec = match sub_mod.get_attr("__spec__", vm) {
Ok(s) if !vm.is_none(&s) => s,
_ => return false,
};
spec.get_attr("_initializing", vm)
.and_then(|v| v.try_to_bool(vm))
.unwrap_or(false)
}