Program.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System.Reflection;
  2. using Esprima;
  3. using Jint;
  4. using Jint.Native;
  5. using Jint.Native.Json;
  6. using Jint.Runtime;
  7. #pragma warning disable IL2026
  8. #pragma warning disable IL2111
  9. var engine = new Engine(cfg => cfg
  10. .AllowClr()
  11. );
  12. engine
  13. .SetValue("print", new Action<object>(Console.WriteLine))
  14. .SetValue("load", new Func<string, object>(
  15. path => engine.Evaluate(File.ReadAllText(path)))
  16. );
  17. var filename = args.Length > 0 ? args[0] : "";
  18. if (!string.IsNullOrEmpty(filename))
  19. {
  20. if (!File.Exists(filename))
  21. {
  22. Console.WriteLine("Could not find file: {0}", filename);
  23. }
  24. var script = File.ReadAllText(filename);
  25. engine.Evaluate(script, "repl");
  26. return;
  27. }
  28. var assembly = Assembly.GetExecutingAssembly();
  29. var version = assembly.GetName().Version?.ToString();
  30. Console.WriteLine("Welcome to Jint ({0})", version);
  31. Console.WriteLine("Type 'exit' to leave, " +
  32. "'print()' to write on the console, " +
  33. "'load()' to load scripts.");
  34. Console.WriteLine();
  35. var defaultColor = Console.ForegroundColor;
  36. var parserOptions = new ParserOptions
  37. {
  38. Tolerant = true,
  39. RegExpParseMode = RegExpParseMode.AdaptToInterpreted
  40. };
  41. var serializer = new JsonSerializer(engine);
  42. while (true)
  43. {
  44. Console.ForegroundColor = defaultColor;
  45. Console.Write("jint> ");
  46. var input = Console.ReadLine();
  47. if (input is "exit" or ".exit")
  48. {
  49. return;
  50. }
  51. try
  52. {
  53. var result = engine.Evaluate(input, parserOptions);
  54. JsValue str = result;
  55. if (!result.IsPrimitive() && result is not IJsPrimitive)
  56. {
  57. str = serializer.Serialize(result, JsValue.Undefined, " ");
  58. if (str == JsValue.Undefined)
  59. {
  60. str = result;
  61. }
  62. }
  63. else if (result.IsString())
  64. {
  65. str = serializer.Serialize(result, JsValue.Undefined, JsValue.Undefined);
  66. }
  67. Console.WriteLine(str);
  68. }
  69. catch (JavaScriptException je)
  70. {
  71. Console.ForegroundColor = ConsoleColor.Red;
  72. Console.WriteLine(je.ToString());
  73. }
  74. catch (Exception e)
  75. {
  76. Console.ForegroundColor = ConsoleColor.Red;
  77. Console.WriteLine(e.Message);
  78. }
  79. }