Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env swift
- // REPL for JavaScriptCore (for arrow keys, use rlwrap command)
- import JavaScriptCore
- guard let ctx = JSContext() else {exit(1)}
- guard let syntaxError = ctx.globalObject?.forProperty("SyntaxError") else {exit(1)}
- let ueEoS = "Unexpected end of script"
- // override console.log()
- guard let console = ctx.evaluateScript("console") else {exit(1)}
- let log: @convention(block) (JSValue) -> Void = {arg in
- if arg.isUndefined {print()} else {print(arg)}
- }
- console.setValue(log, forProperty: "log")
- var repl = (lines: "", prompt: "> ")
- print(repl.prompt, terminator: "")
- while let line = readLine(strippingNewline: false) {
- let code = repl.lines + line
- repl = (lines: "", prompt: "> ")
- let value = ctx.evaluateScript(code)
- if let exp = ctx.exception {
- ctx.exception = nil
- let se = exp.isObject && exp.forProperty("constructor").isEqual(to: syntaxError)
- if se && exp.forProperty("message").isEqual(to: ueEoS) {
- repl = (lines: code, prompt: "+ ")
- } else {
- print(exp)
- }
- } else if let val = value {
- print(val)
- }
- print(repl.prompt, terminator: "")
- }
- print()
Add Comment
Please, Sign In to add comment