Program.cs 2.9 KB

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