Program.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System.Reflection;
  2. using Jint;
  3. using Jint.Native;
  4. using Jint.Native.Json;
  5. using Jint.Runtime;
  6. // ReSharper disable LocalizableElement
  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("console", new JsConsole())
  15. .SetValue("load", new Func<string, object>(
  16. path => engine.Evaluate(File.ReadAllText(path)))
  17. );
  18. var filename = args.Length > 0 ? args[0] : "";
  19. if (!string.IsNullOrEmpty(filename))
  20. {
  21. if (!File.Exists(filename))
  22. {
  23. Console.WriteLine($"Could not find file: {filename}");
  24. }
  25. var script = File.ReadAllText(filename);
  26. engine.Evaluate(script, "repl");
  27. return;
  28. }
  29. var assembly = Assembly.GetExecutingAssembly();
  30. var version = assembly.GetName().Version?.ToString();
  31. Console.WriteLine($"Welcome to Jint ({version})");
  32. Console.WriteLine("Type 'exit' to leave, 'print()' to write on the console, '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. }
  78. file sealed class JsConsole
  79. {
  80. public void Log(object value)
  81. {
  82. Console.WriteLine(value?.ToString() ?? "null");
  83. }
  84. public void Error(object value)
  85. {
  86. Console.ForegroundColor = ConsoleColor.Red;
  87. Console.WriteLine(value?.ToString() ?? "null");
  88. Console.ResetColor();
  89. }
  90. }