require method
Load a source into current bytecode dynamically.
Implementation
HTNamespace require(String path) {
final key = config.normalizeImportPath
? sourceContext.getAbsolutePath(key: path)
: path;
// Search in current module first
if (interpreter.currentBytecodeModule.namespaces.containsKey(key)) {
return interpreter.currentBytecodeModule.namespaces[key]!;
}
// Then try to search it in any loaded modules.
else {
for (final module in interpreter.cachedModules.values) {
for (final nsp in module.namespaces.values) {
if (nsp.fullName == key) {
return nsp;
}
}
}
}
// Then we have to load the source dynamically
final source = sourceContext.getResource(key);
// Because we are loading it dynamically, it has to be a script rather than a module.
source.type = HTResourceType.hetuScript;
final bytes = _compileSource(source);
final HTContext storedContext = interpreter.getContext();
interpreter.loadBytecode(bytes: bytes, moduleName: key);
final nsp = interpreter.currentBytecodeModule.namespaces.values.last;
interpreter.setContext(context: storedContext);
return nsp;
}