Test262ModuleLoader.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #nullable enable
  2. using Esprima;
  3. using Esprima.Ast;
  4. using Jint.Runtime;
  5. using Jint.Runtime.Modules;
  6. using Zio;
  7. namespace Jint.Tests.Test262;
  8. internal sealed class Test262ModuleLoader : IModuleLoader
  9. {
  10. private readonly IFileSystem _fileSystem;
  11. private readonly string _basePath;
  12. public Test262ModuleLoader(IFileSystem fileSystem, string basePath)
  13. {
  14. _fileSystem = fileSystem;
  15. _basePath = "/test/" + basePath.TrimStart('\\').TrimStart('/');
  16. }
  17. public ResolvedSpecifier Resolve(string? referencingModuleLocation, string specifier)
  18. {
  19. return new ResolvedSpecifier(referencingModuleLocation ?? "", specifier ?? "", null, SpecifierType.Bare);
  20. }
  21. public Module LoadModule(Engine engine, ResolvedSpecifier resolved)
  22. {
  23. Module module;
  24. try
  25. {
  26. string code;
  27. lock (_fileSystem)
  28. {
  29. var fileName = Path.Combine(_basePath, resolved.Key).Replace('\\', '/');
  30. using var stream = new StreamReader(_fileSystem.OpenFile(fileName, FileMode.Open, FileAccess.Read));
  31. code = stream.ReadToEnd();
  32. }
  33. var parserOptions = new ParserOptions
  34. {
  35. AdaptRegexp = true,
  36. Tolerant = true
  37. };
  38. module = new JavaScriptParser(parserOptions).ParseModule(code, source: resolved.Uri?.LocalPath!);
  39. }
  40. catch (ParserException ex)
  41. {
  42. ExceptionHelper.ThrowSyntaxError(engine.Realm, $"Error while loading module: error in module '{resolved.Uri?.LocalPath}': {ex.Error}");
  43. module = null;
  44. }
  45. catch (Exception ex)
  46. {
  47. var message = $"Could not load module {resolved.Uri?.LocalPath}: {ex.Message}";
  48. ExceptionHelper.ThrowJavaScriptException(engine, message, (Location) default);
  49. module = null;
  50. }
  51. return module;
  52. }
  53. }