feat(cli): add repl and file runner entry point
This commit is contained in:
1 parent
c925f014b4
commit
fdca256d6d
1 file changed
+67
@@ -0,0 +1,67 @@
|
||||
import Foundation
|
||||
import KiteCore
|
||||
|
||||
func runFile(_ path: String) -> Int32 {
|
||||
guard let source = try? String(contentsOfFile: path, encoding: .utf8) else {
|
||||
FileHandle.standardError.write(Data("kite: cannot read file: \(path)\n".utf8))
|
||||
return 1
|
||||
}
|
||||
let interp = Interpreter()
|
||||
do {
|
||||
try interp.evalString(source)
|
||||
return 0
|
||||
} catch let error as SchemeError {
|
||||
FileHandle.standardError.write(Data("error: \(error.description)\n".utf8))
|
||||
return 1
|
||||
} catch {
|
||||
FileHandle.standardError.write(Data("error: \(error)\n".utf8))
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
func runRepl() {
|
||||
let interp = Interpreter()
|
||||
print("kite - a Scheme interpreter. Ctrl-D to exit.")
|
||||
var buffer = ""
|
||||
while true {
|
||||
if buffer.isEmpty {
|
||||
print("kite> ", terminator: "")
|
||||
} else {
|
||||
print("... ", terminator: "")
|
||||
}
|
||||
guard let line = readLine(strippingNewline: false) else {
|
||||
print("")
|
||||
break
|
||||
}
|
||||
buffer += line
|
||||
let forms: [Value]
|
||||
do {
|
||||
forms = try Reader(buffer).readProgram()
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
buffer = ""
|
||||
for form in forms {
|
||||
do {
|
||||
let result = try interp.evalTop(form)
|
||||
switch result {
|
||||
case .unspecified:
|
||||
break
|
||||
default:
|
||||
print(writeString(result))
|
||||
}
|
||||
} catch let error as SchemeError {
|
||||
print("error: \(error.description)")
|
||||
} catch {
|
||||
print("error: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let arguments = CommandLine.arguments
|
||||
if arguments.count > 1 {
|
||||
exit(runFile(arguments[1]))
|
||||
} else {
|
||||
runRepl()
|
||||
}
|
||||
Reference in new issue
Block a user