loadBytecode method

dynamic loadBytecode({
  1. required Uint8List bytes,
  2. required String module,
  3. bool globallyImport = false,
  4. String? invoke,
  5. List positionalArgs = const [],
  6. Map<String, dynamic> namedArgs = const {},
})

Load a pre-compiled bytecode module. If invoke is true, run the bytecode immediately.

Implementation

dynamic loadBytecode({
  required Uint8List bytes,
  required String module,
  bool globallyImport = false,
  String? invoke,
  List<dynamic> positionalArgs = const [],
  Map<String, dynamic> namedArgs = const {},
  // List<HTType> typeArgs = const [],
}) {
  try {
    this.globallyImport = globallyImport;
    _extensionContextStack.clear();

    if (cachedModules.containsKey(module)) {
      _currentBytecodeModule = cachedModules[module]!;
    } else {
      _currentBytecodeModule = HTBytecodeModule(id: module, bytes: bytes);
      cachedModules[_currentBytecodeModule.id] = _currentBytecodeModule;
    }
    _currentBytecodeModule.init(
      invoke: invoke,
      positionalArgs: positionalArgs,
      namedArgs: namedArgs,
    );

    final signature = _currentBytecodeModule.readUint32();
    if (signature != HTCompiler.hetuSignature) {
      throw HTError.bytecode(
          filename: _currentFile, line: _currentLine, column: _currentColumn);
    }
    // compare the version of the compiler of the bytecode to my version.
    compilerVersion = _handleVersion();
    var incompatible = false;
    if (compilerVersion.major > 0) {
      if (compilerVersion.major > kHetuVersion.major) {
        incompatible = true;
      }
    } else {
      if (compilerVersion != kHetuVersion) {
        incompatible = true;
      }
    }
    if (incompatible) {
      throw HTError.version(
        _currentBytecodeModule.version.toString(),
        kHetuVersion.toString(),
        filename: _currentFile,
        line: _currentLine,
        column: _currentColumn,
      );
    }
    // read the version of the bytecode.
    final hasVersion = _currentBytecodeModule.readBool();
    if (hasVersion) {
      _currentBytecodeModule.version = _handleVersion();
    }
    _currentBytecodeModule.compiledAt =
        _currentBytecodeModule.readUtf8String();
    _currentFile = _currentBytecodeModule.readUtf8String();
    final sourceType =
        HTResourceType.values.elementAt(_currentBytecodeModule.read());
    scriptMode = (sourceType == HTResourceType.hetuScript) ||
        (sourceType == HTResourceType.hetuLiteralCode) ||
        (sourceType == HTResourceType.json);
    // TODO: import binary file
    dynamic result = execute();
    if (result is FutureExecution) {
      result = waitFutureExucution(result);
    }
    return result;
  } catch (error, stackTrace) {
    if (config.processError) {
      processError(error, stackTrace);
    } else {
      rethrow;
    }
  }
}