Program.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System.Diagnostics;
  2. using System.Reflection;
  3. using Esprima;
  4. using Jint;
  5. using Jint.Native;
  6. using Jint.Native.Json;
  7. using Jint.Runtime;
  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 fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
  29. var version = fvi.FileVersion;
  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. }