Skip to content

Commit 4c3642d

Browse files
committed
Use enum for initialize parameters
1 parent edf7092 commit 4c3642d

File tree

5 files changed

+59
-57
lines changed

5 files changed

+59
-57
lines changed

src/main.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use rustpython_vm::{
1212
print_exception,
1313
pyobject::{ItemProtocol, PyResult},
1414
scope::Scope,
15-
util, PySettings, VirtualMachine,
15+
util, InitParameter, PySettings, VirtualMachine,
1616
};
1717

1818
use std::convert::TryInto;
@@ -32,7 +32,9 @@ fn main() {
3232
let mut settings = create_settings(&matches);
3333

3434
// We only include the standard library bytecode in WASI when initializing
35-
settings.initialize_with_external_importer = Some(cfg!(not(target_os = "wasi")));
35+
if cfg!(target_os = "wasi") {
36+
settings.initialization_parameter = InitParameter::InitializeInternal;
37+
}
3638

3739
let vm = VirtualMachine::new(settings);
3840

vm/src/import.rs

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,31 +9,38 @@ use crate::obj::{objcode, objtype};
99
use crate::pyobject::{ItemProtocol, PyObjectRef, PyResult, PyValue};
1010
use crate::scope::Scope;
1111
use crate::version::get_git_revision;
12-
use crate::vm::VirtualMachine;
12+
use crate::vm::{InitParameter, VirtualMachine};
1313
#[cfg(feature = "rustpython-compiler")]
1414
use rustpython_compiler::compile;
1515

16-
pub fn init_importlib(vm: &VirtualMachine, external: bool) -> PyResult {
16+
pub fn init_importlib(vm: &VirtualMachine, initialize_parameter: InitParameter) -> PyResult {
1717
flame_guard!("init importlib");
1818
let importlib = import_frozen(vm, "_frozen_importlib")?;
1919
let impmod = import_builtin(vm, "_imp")?;
2020
let install = vm.get_attribute(importlib.clone(), "_install")?;
2121
vm.invoke(&install, vec![vm.sys_module.clone(), impmod])?;
2222
vm.import_func
2323
.replace(vm.get_attribute(importlib.clone(), "__import__")?);
24-
if external && cfg!(feature = "rustpython-compiler") {
25-
flame_guard!("install_external");
26-
let install_external =
27-
vm.get_attribute(importlib.clone(), "_install_external_importers")?;
28-
vm.invoke(&install_external, vec![])?;
29-
// Set pyc magic number to commit hash. Should be changed when bytecode will be more stable.
30-
let importlib_external = vm.import("_frozen_importlib_external", &[], 0)?;
31-
let mut magic = get_git_revision().into_bytes();
32-
magic.truncate(4);
33-
if magic.len() != 4 {
34-
magic = rand::thread_rng().gen::<[u8; 4]>().to_vec();
24+
25+
match initialize_parameter {
26+
InitParameter::InitializeExternal if cfg!(feature = "rustpython-compiler") => {
27+
flame_guard!("install_external");
28+
let install_external =
29+
vm.get_attribute(importlib.clone(), "_install_external_importers")?;
30+
vm.invoke(&install_external, vec![])?;
31+
// Set pyc magic number to commit hash. Should be changed when bytecode will be more stable.
32+
let importlib_external = vm.import("_frozen_importlib_external", &[], 0)?;
33+
let mut magic = get_git_revision().into_bytes();
34+
magic.truncate(4);
35+
if magic.len() != 4 {
36+
magic = rand::thread_rng().gen::<[u8; 4]>().to_vec();
37+
}
38+
vm.set_attr(&importlib_external, "MAGIC_NUMBER", vm.ctx.new_bytes(magic))?;
39+
}
40+
InitParameter::NoInitialize => {
41+
panic!("Import library initialize should be InitializeInternal or InitializeExternal");
3542
}
36-
vm.set_attr(&importlib_external, "MAGIC_NUMBER", vm.ctx.new_bytes(magic))?;
43+
_ => {}
3744
}
3845
Ok(vm.get_none())
3946
}

vm/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ mod vm;
7373

7474
// pub use self::pyobject::Executor;
7575
pub use self::exceptions::{print_exception, write_exception};
76-
pub use self::vm::{PySettings, VirtualMachine};
76+
pub use self::vm::{InitParameter, PySettings, VirtualMachine};
7777
pub use rustpython_bytecode::*;
7878

7979
#[doc(hidden)]

vm/src/vm.rs

Lines changed: 29 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,13 @@ pub struct VirtualMachine {
7474

7575
pub const NSIG: usize = 64;
7676

77+
#[derive(Copy, Clone)]
78+
pub enum InitParameter {
79+
NoInitialize,
80+
InitializeInternal,
81+
InitializeExternal,
82+
}
83+
7784
/// Struct containing all kind of settings for the python vm.
7885
pub struct PySettings {
7986
/// -d command line switch
@@ -109,17 +116,9 @@ pub struct PySettings {
109116
/// sys.argv
110117
pub argv: Vec<String>,
111118

112-
/// Initialize VM after VM created
113-
/// - Some(true):
114-
/// VM will be created and initialized with the importers, which require external
115-
/// filesystem access
116-
/// - Some(false):
117-
/// VM will be created and initialized with the importers wihout external filesystem access
118-
/// - None:
119-
/// VM will be created but not initialized, so it is ready to be injected with modules.
120-
/// After injection, the `initialize_as_external` or `initialize_without_external`
121-
/// should be called, such that the VM will be ready to use.
122-
pub initialize_with_external_importer: Option<bool>,
119+
/// Initialization parameter to decide to initialize or not,
120+
/// and to decide the importer required external filesystem access or not
121+
pub initialization_parameter: InitParameter,
123122
}
124123

125124
/// Trace events for sys.settrace and sys.setprofile.
@@ -153,7 +152,7 @@ impl Default for PySettings {
153152
dont_write_bytecode: false,
154153
path_list: vec![],
155154
argv: vec![],
156-
initialize_with_external_importer: Some(true),
155+
initialization_parameter: InitParameter::InitializeExternal,
157156
}
158157
}
159158
}
@@ -181,7 +180,7 @@ impl VirtualMachine {
181180
let profile_func = RefCell::new(ctx.none());
182181
let trace_func = RefCell::new(ctx.none());
183182
let signal_handlers = RefCell::new(arr![ctx.none(); 64]);
184-
let initialize_parameter = settings.initialize_with_external_importer;
183+
let initialize_parameter = settings.initialization_parameter;
185184

186185
let mut vm = VirtualMachine {
187186
builtins: builtins.clone(),
@@ -215,37 +214,32 @@ impl VirtualMachine {
215214
vm.new_str("sys".to_owned()),
216215
vm.get_none(),
217216
);
218-
if let Some(with_external_importer) = initialize_parameter {
219-
vm._initialize(with_external_importer);
220-
vm.initialized = true;
221-
}
217+
vm.initialize(initialize_parameter);
222218
vm
223219
}
224220

225-
fn _initialize(&mut self, with_external_importer: bool) {
221+
pub fn initialize(&mut self, initialize_parameter: InitParameter) {
226222
flame_guard!("init VirtualMachine");
227223

228-
if self.initialized {
229-
panic!("Double Initialize Error");
230-
}
231-
232-
builtins::make_module(self, self.builtins.clone());
233-
sysmodule::make_module(self, self.sys_module.clone(), self.builtins.clone());
234-
235-
#[cfg(not(target_arch = "wasm32"))]
236-
import::import_builtin(self, "signal").expect("Couldn't initialize signal module");
224+
match initialize_parameter {
225+
InitParameter::NoInitialize => {}
226+
_ => {
227+
if self.initialized {
228+
panic!("Double Initialize Error");
229+
}
237230

238-
import::init_importlib(self, with_external_importer).expect("Initialize importlib fail");
231+
builtins::make_module(self, self.builtins.clone());
232+
sysmodule::make_module(self, self.sys_module.clone(), self.builtins.clone());
239233

240-
self.initialized = true;
241-
}
234+
#[cfg(not(target_arch = "wasm32"))]
235+
import::import_builtin(self, "signal").expect("Couldn't initialize signal module");
242236

243-
pub fn initialize_with_external_importer(&mut self) {
244-
self._initialize(true);
245-
}
237+
import::init_importlib(self, initialize_parameter)
238+
.expect("Initialize importlib fail");
246239

247-
pub fn initialize_without_external_importer(&mut self) {
248-
self._initialize(false);
240+
self.initialized = true;
241+
}
242+
}
249243
}
250244

251245
pub fn run_code_obj(&self, code: PyCodeRef, scope: Scope) -> PyResult {

wasm/lib/src/vm_class.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use rustpython_compiler::compile;
99
use rustpython_vm::function::PyFuncArgs;
1010
use rustpython_vm::pyobject::{PyObject, PyObjectPayload, PyObjectRef, PyResult, PyValue};
1111
use rustpython_vm::scope::{NameProtocol, Scope};
12-
use rustpython_vm::{PySettings, VirtualMachine};
12+
use rustpython_vm::{InitParameter, PySettings, VirtualMachine};
1313

1414
use crate::browser_module::setup_browser_module;
1515
use crate::convert;
@@ -28,9 +28,8 @@ impl StoredVirtualMachine {
2828
fn new(id: String, inject_browser_module: bool) -> StoredVirtualMachine {
2929
let mut settings = PySettings::default();
3030

31-
// The VM will not be initialized.
32-
// It will be initialized after js module injected.
33-
settings.initialize_with_external_importer = None;
31+
// After js, browser modules injected, the VM will not be initialized.
32+
settings.initialization_parameter = InitParameter::NoInitialize;
3433

3534
let mut vm: VirtualMachine = VirtualMachine::new(settings);
3635

@@ -50,7 +49,7 @@ impl StoredVirtualMachine {
5049
setup_browser_module(&vm);
5150
}
5251

53-
vm.initialize_without_external_importer();
52+
vm.initialize(InitParameter::InitializeInternal);
5453

5554
StoredVirtualMachine {
5655
vm,

0 commit comments

Comments
 (0)