executeFileContinued function

ScriptExecutionResult executeFileContinued(
  1. D4rt d4rt,
  2. String filePath, {
  3. void log(
    1. String
    )?,
})

Execute a Dart script file in the current interpreter environment.

This method:

  1. Reads the script from the file
  2. Recursively resolves all relative imports
  3. Evaluates each imported file using D4rt.eval
  4. Evaluates the main script using D4rt.eval

Note: Unlike executeFile, this uses eval() for each file, which means each file's declarations are added to the global environment. The imports are processed in dependency order (deepest first).

d4rt The D4rt interpreter instance. filePath Path to the Dart script file. log Optional logging function for debugging import resolution.

Returns a ScriptExecutionResult with the execution outcome.

Implementation

ScriptExecutionResult executeFileContinued(
  D4rt d4rt,
  String filePath, {
  void Function(String)? log,
}) {
  final file = File(filePath);

  if (!file.existsSync()) {
    return ScriptExecutionResult.failure('File not found: $filePath');
  }

  // Use resolveSymbolicLinksSync to normalize path (removes ./ and ..)
  final fullPath = file.resolveSymbolicLinksSync();

  try {
    final source = file.readAsStringSync();
    final libraryUri = 'file://$fullPath';

    // Pre-resolve all imports into sources map
    final sources = <String, String>{};
    resolveImportsRecursively(source, libraryUri, sources, log);

    // Eval each imported file in reverse order (dependencies first, main last)
    // Skip the main file itself - we'll eval it at the end
    final orderedUris = sources.keys.toList();

    for (final uri in orderedUris) {
      if (uri == libraryUri) continue; // Skip main file

      final importSource = sources[uri]!;
      log?.call('Evaluating import: $uri');

      // Wrap in a try-catch to get better error messages
      try {
        d4rt.eval(importSource);
      } catch (e) {
        log?.call('Error evaluating $uri: $e');
        rethrow;
      }
    }

    // Finally eval the main file
    log?.call('Evaluating main: $libraryUri');
    final result = d4rt.eval(source);

    return ScriptExecutionResult.success(result, sources.length);
  } catch (e, stackTrace) {
    return ScriptExecutionResult.failure(e.toString(), stackTrace: stackTrace);
  }
}