MCPcopy Index your code
hub / github.com/aiscriptdev/aiscript / import_module

Method import_module

aiscript-vm/src/vm/state.rs:165–224  ·  view source on GitHub ↗
(&mut self, path: InternedString<'gc>)

Source from the content-addressed store, hash-verified

163 }
164
165 pub fn import_module(&mut self, path: InternedString<'gc>) -> Result<(), VmError> {
166 // Get the simple name (last component) from the path
167 let simple_name = path.to_str().unwrap().split('.').last().unwrap();
168 let simple_name = self.intern(simple_name.as_bytes());
169
170 // Check if simple name is already used
171 if self.globals.contains_key(&simple_name) {
172 return Err(VmError::RuntimeError(format!(
173 "Name '{}' is already in use",
174 simple_name
175 )));
176 }
177
178 // Get module source
179 let module_source = self.module_manager.get_or_load_module(path)?;
180
181 match module_source {
182 ModuleSource::Cached => {
183 // For any module (std or script), just bind it to its simple name
184 self.globals.insert(simple_name, Value::Module(path));
185 Ok(())
186 }
187 ModuleSource::New {
188 source,
189 path: module_path,
190 } => {
191 let prev_module = self.current_module.replace(path);
192 let prev_globals = mem::take(&mut self.globals);
193
194 let module = ModuleKind::Script {
195 name: path,
196 exports: HashMap::default(),
197 globals: HashMap::default(),
198 path: module_path,
199 };
200
201 self.module_manager.register_script_module(path, module);
202
203 let source: &'static str = Box::leak(source.into_boxed_str());
204 let chunks = crate::compiler::compile(self.get_context(), source)?;
205
206 let imported_script_chunk_id = chunks.keys().last().copied().unwrap();
207 self.chunks.extend(chunks);
208 let function = self.get_chunk(imported_script_chunk_id)?;
209 self.eval_function(function, &[])?;
210
211 if let Some(ModuleKind::Script { globals, .. }) =
212 self.module_manager.modules.get_mut(&path)
213 {
214 *globals = mem::replace(&mut self.globals, prev_globals);
215 }
216
217 // Add the module to globals with its simple name
218 self.globals.insert(simple_name, Value::Module(path));
219
220 self.current_module = prev_module;
221 Ok(())
222 }

Callers 1

dispatch_nextMethod · 0.80

Calls 12

RuntimeErrorClass · 0.85
compileFunction · 0.85
replaceFunction · 0.85
lastMethod · 0.80
to_strMethod · 0.80
as_bytesMethod · 0.80
get_or_load_moduleMethod · 0.80
get_contextMethod · 0.80
get_chunkMethod · 0.80
internMethod · 0.45
eval_functionMethod · 0.45

Tested by

no test coverage detected