2
0

Program.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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.Runtime;
  8. namespace Jint.Repl
  9. {
  10. internal static class Program
  11. {
  12. private static void Main(string[] args)
  13. {
  14. var engine = new Engine(cfg => cfg
  15. .AllowClr()
  16. );
  17. engine
  18. .SetValue("print", new Action<object>(Console.WriteLine))
  19. .SetValue("load", new Func<string, object>(
  20. path => engine.Evaluate(File.ReadAllText(path)))
  21. );
  22. var filename = args.Length > 0 ? args[0] : "";
  23. if (!string.IsNullOrEmpty(filename))
  24. {
  25. if (!File.Exists(filename))
  26. {
  27. Console.WriteLine("Could not find file: {0}", filename);
  28. }
  29. var script = File.ReadAllText(filename);
  30. engine.Evaluate(script);
  31. return;
  32. }
  33. var assembly = Assembly.GetExecutingAssembly();
  34. var fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
  35. var version = fvi.FileVersion;
  36. Console.WriteLine("Welcome to Jint ({0})", version);
  37. Console.WriteLine("Type 'exit' to leave, " +
  38. "'print()' to write on the console, " +
  39. "'load()' to load scripts.");
  40. Console.WriteLine();
  41. var defaultColor = Console.ForegroundColor;
  42. var parserOptions = new ParserOptions("repl")
  43. {
  44. Tolerant = true,
  45. AdaptRegexp = true
  46. };
  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.IsNull() && !result.IsUndefined())
  60. {
  61. var str = TypeConverter.ToString(engine.Json.Stringify(engine.Json, Arguments.From(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. }