Program.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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.Execute(File.ReadAllText(path)).GetCompletionValue())
  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. var result = engine.GetValue(engine.Execute(script).GetCompletionValue());
  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 == "exit")
  53. {
  54. return;
  55. }
  56. try
  57. {
  58. var result = engine.GetValue(engine.Execute(input, parserOptions).GetCompletionValue());
  59. if (result.Type != Types.None && result.Type != Types.Null && result.Type != Types.Undefined)
  60. {
  61. var str = TypeConverter.ToString(engine.Json.Stringify(engine.Json, Arguments.From(result, Undefined.Instance, " ")));
  62. Console.WriteLine("=> {0}", str);
  63. }
  64. }
  65. catch (JavaScriptException je)
  66. {
  67. Console.ForegroundColor = ConsoleColor.Red;
  68. Console.WriteLine(je.ToString());
  69. }
  70. catch (Exception e)
  71. {
  72. Console.ForegroundColor = ConsoleColor.Red;
  73. Console.WriteLine(e.Message);
  74. }
  75. }
  76. }
  77. }
  78. }