Program.cs 3.2 KB

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