Program.cs 2.2 KB

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