AcornimaExtensions.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using Jint.Runtime;
  2. namespace Jint;
  3. internal static class AcornimaExtensions
  4. {
  5. public static Script ParseScriptGuarded(this Parser parser, Realm realm, string code, string? source = null, bool strict = false)
  6. {
  7. try
  8. {
  9. return parser.ParseScript(code, source, strict);
  10. }
  11. catch (ParseErrorException e)
  12. {
  13. Throw.SyntaxError(realm, e.Message, ToLocation(e, source));
  14. return default;
  15. }
  16. }
  17. public static Module ParseModuleGuarded(this Parser parser, Engine engine, string code, string? source = null)
  18. {
  19. try
  20. {
  21. return parser.ParseModule(code, source);
  22. }
  23. catch (ParseErrorException ex)
  24. {
  25. Throw.SyntaxError(engine.Realm, $"Error while loading module: error in module '{source}': {ex.Error}", ToLocation(ex, source));
  26. return default;
  27. }
  28. catch (Exception)
  29. {
  30. Throw.JavaScriptException(engine, $"Could not load module {source}", AstExtensions.DefaultLocation);
  31. return default;
  32. }
  33. }
  34. private static SourceLocation ToLocation(ParseErrorException ex, string? source)
  35. {
  36. return SourceLocation.From(Position.From(ex.LineNumber, ex.Column), Position.From(ex.LineNumber, ex.Column), source);
  37. }
  38. }