Test262ModuleLoader.cs 1.9 KB

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