Program.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 parsingOptions = new ScriptParsingOptions
  36. {
  37. Tolerant = true,
  38. };
  39. var serializer = new JsonSerializer(engine);
  40. while (true)
  41. {
  42. Console.ForegroundColor = defaultColor;
  43. Console.Write("jint> ");
  44. var input = Console.ReadLine();
  45. if (input is "exit" or ".exit")
  46. {
  47. return;
  48. }
  49. try
  50. {
  51. var result = engine.Evaluate(input, parsingOptions);
  52. JsValue str = result;
  53. if (!result.IsPrimitive() && result is not IJsPrimitive)
  54. {
  55. str = serializer.Serialize(result, JsValue.Undefined, " ");
  56. if (str == JsValue.Undefined)
  57. {
  58. str = result;
  59. }
  60. }
  61. else if (result.IsString())
  62. {
  63. str = serializer.Serialize(result, JsValue.Undefined, JsValue.Undefined);
  64. }
  65. Console.WriteLine(str);
  66. }
  67. catch (JavaScriptException je)
  68. {
  69. Console.ForegroundColor = ConsoleColor.Red;
  70. Console.WriteLine(je.ToString());
  71. }
  72. catch (Exception e)
  73. {
  74. Console.ForegroundColor = ConsoleColor.Red;
  75. Console.WriteLine(e.Message);
  76. }
  77. }