forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport.rs
More file actions
116 lines (101 loc) · 3.54 KB
/
import.rs
File metadata and controls
116 lines (101 loc) · 3.54 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
/*
* Import mechanics
*/
extern crate rustpython_parser;
use std::io;
use std::io::ErrorKind::NotFound;
use std::path::PathBuf;
use self::rustpython_parser::parser;
use super::compile;
use super::pyobject::{DictProtocol, PyObjectKind, PyResult};
use super::vm::VirtualMachine;
fn import_module(vm: &mut VirtualMachine, module: &String) -> PyResult {
// First, see if we already loaded the module:
let sys_modules = vm.sys_module.get_item("modules").unwrap();
if let Some(module) = sys_modules.get_item(module) {
return Ok(module);
}
// Check for Rust-native modules
if let Some(module) = vm.stdlib_inits.get(module) {
return Ok(module(&vm.ctx).clone());
}
// TODO: introduce import error:
let import_error = vm.context().exceptions.exception_type.clone();
// Time to search for module in any place:
let filepath = find_source(vm, module)
.map_err(|e| vm.new_exception(import_error.clone(), format!("Error: {:?}", e)))?;
let source = parser::read_file(filepath.as_path())
.map_err(|e| vm.new_exception(import_error.clone(), format!("Error: {:?}", e)))?;
let code_obj = match compile::compile(
vm,
&source,
compile::Mode::Exec,
Some(filepath.to_str().unwrap().to_string()),
) {
Ok(bytecode) => {
debug!("Code object: {:?}", bytecode);
bytecode
}
Err(value) => {
panic!("Error: {}", value);
}
};
let builtins = vm.get_builtin_scope();
let scope = vm.ctx.new_scope(Some(builtins));
match vm.run_code_obj(code_obj, scope.clone()) {
Ok(_) => {}
Err(value) => return Err(value),
}
let py_module = vm.ctx.new_module(module, scope);
Ok(py_module)
}
pub fn import(vm: &mut VirtualMachine, module_name: &String, symbol: &Option<String>) -> PyResult {
let module = import_module(vm, module_name)?;
// If we're importing a symbol, look it up and use it, otherwise construct a module and return
// that
let obj = match symbol {
Some(symbol) => module.get_item(symbol).unwrap(),
None => module,
};
Ok(obj)
}
fn find_source(vm: &VirtualMachine, name: &String) -> io::Result<PathBuf> {
let sys_path = vm.sys_module.get_item("path").unwrap();
let mut paths: Vec<PathBuf> = match sys_path.borrow().kind {
PyObjectKind::List { ref elements } => elements
.iter()
.filter_map(|item| match item.borrow().kind {
PyObjectKind::String { ref value } => Some(PathBuf::from(value)),
_ => None,
}).collect(),
_ => panic!("sys.path unexpectedly not a list"),
};
let source_path = &vm.current_frame().code.source_path;
paths.insert(
0,
match source_path {
Some(source_path) => {
let mut source_pathbuf = PathBuf::from(source_path);
source_pathbuf.pop();
source_pathbuf
}
None => PathBuf::from("."),
},
);
let suffixes = [".py", "/__init__.py"];
let mut filepaths = vec![];
for path in paths {
for suffix in suffixes.iter() {
let mut filepath = path.clone();
filepath.push(format!("{}{}", name, suffix));
filepaths.push(filepath);
}
}
match filepaths.iter().filter(|p| p.exists()).next() {
Some(path) => Ok(path.to_path_buf()),
None => Err(io::Error::new(
NotFound,
format!("Module ({}) could not be found.", name),
)),
}
}