(&mut self, path: InternedString<'gc>)
| 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 | } |
no test coverage detected