Program.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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);
  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("repl")
  42. {
  43. Tolerant = true,
  44. AdaptRegexp = true
  45. };
  46. while (true)
  47. {
  48. Console.ForegroundColor = defaultColor;
  49. Console.Write("jint> ");
  50. var input = Console.ReadLine();
  51. if (input is "exit" or ".exit")
  52. {
  53. return;
  54. }
  55. try
  56. {
  57. var result = engine.Evaluate(input, parserOptions);
  58. if (!result.IsPrimitive() && result is not IPrimitiveInstance)
  59. {
  60. var serializer = new JsonSerializer(engine);
  61. var str = serializer.Serialize(result, Undefined.Instance, " ");
  62. Console.WriteLine(str);
  63. }
  64. else
  65. {
  66. Console.WriteLine(result);
  67. }
  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. }
  80. }
  81. }
  82. }