Guest User

Untitled

a guest
Nov 15th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. #!/usr/bin/env swift
  2. // REPL for JavaScriptCore (for arrow keys, use rlwrap command)
  3. import JavaScriptCore
  4.  
  5. guard let ctx = JSContext() else {exit(1)}
  6. guard let syntaxError = ctx.globalObject?.forProperty("SyntaxError") else {exit(1)}
  7. let ueEoS = "Unexpected end of script"
  8.  
  9. // override console.log()
  10. guard let console = ctx.evaluateScript("console") else {exit(1)}
  11. let log: @convention(block) (JSValue) -> Void = {arg in
  12. if arg.isUndefined {print()} else {print(arg)}
  13. }
  14. console.setValue(log, forProperty: "log")
  15.  
  16. var repl = (lines: "", prompt: "> ")
  17. print(repl.prompt, terminator: "")
  18. while let line = readLine(strippingNewline: false) {
  19. let code = repl.lines + line
  20. repl = (lines: "", prompt: "> ")
  21. let value = ctx.evaluateScript(code)
  22. if let exp = ctx.exception {
  23. ctx.exception = nil
  24. let se = exp.isObject && exp.forProperty("constructor").isEqual(to: syntaxError)
  25. if se && exp.forProperty("message").isEqual(to: ueEoS) {
  26. repl = (lines: code, prompt: "+ ")
  27. } else {
  28. print(exp)
  29. }
  30. } else if let val = value {
  31. print(val)
  32. }
  33. print(repl.prompt, terminator: "")
  34. }
  35. print()
Add Comment
Please, Sign In to add comment