Program.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. Loc = true,
  45. Range = true,
  46. Tolerant = true,
  47. AdaptRegexp = true
  48. };
  49. while (true)
  50. {
  51. Console.ForegroundColor = defaultColor;
  52. Console.Write("jint> ");
  53. var input = Console.ReadLine();
  54. if (input == "exit")
  55. {
  56. return;
  57. }
  58. try
  59. {
  60. var result = engine.GetValue(engine.Execute(input, parserOptions).GetCompletionValue());
  61. if (result.Type != Types.None && result.Type != Types.Null && result.Type != Types.Undefined)
  62. {
  63. var str = TypeConverter.ToString(engine.Json.Stringify(engine.Json, Arguments.From(result, Undefined.Instance, " ")));
  64. Console.WriteLine("=> {0}", str);
  65. }
  66. }
  67. catch (JavaScriptException je)
  68. {
  69. Console.ForegroundColor = ConsoleColor.Red;
  70. Console.WriteLine(je.ToString());
  71. }
  72. catch (Exception e)
  73. {
  74. Console.ForegroundColor = ConsoleColor.Red;
  75. Console.WriteLine(e.Message);
  76. }
  77. }
  78. }
  79. }
  80. }