repl.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/env node
  2. let KumaChan = require(`${__dirname}/build/dev/runtime.js`)
  3. let ChildProcess = require('child_process')
  4. let REPL = require('repl')
  5. let Compiler = mode => `${__dirname}/build/dev/compiler ${mode}`
  6. function load_modules () {
  7. let args = process.argv.map(a => a)
  8. args.shift()
  9. args.shift()
  10. if (args[0] == 'load') {
  11. for (let i=1; i<args.length; i++) {
  12. let module_path = args[i]
  13. console.log(`loading module ${module_path}`)
  14. let cmd = `${Compiler('module')} ${module_path}`
  15. let stdout = ChildProcess.execSync(cmd)
  16. eval(String(stdout))
  17. }
  18. }
  19. }
  20. function k_eval (command, context, filename, callback) {
  21. if (command.match(/^[ \t\n]*$/) != null) {
  22. callback(null)
  23. return
  24. }
  25. let p = ChildProcess.exec(Compiler('eval'), (error, stdout) => {
  26. if (error === null) {
  27. try {
  28. let value = eval(stdout)
  29. if (value !== KumaChan.Void) {
  30. callback(null, value)
  31. } else {
  32. callback(null)
  33. }
  34. } catch (error) {
  35. if (
  36. error instanceof KumaChan.CustomError
  37. || error instanceof KumaChan.RuntimeError
  38. ) {
  39. console.log(error.message)
  40. callback(null)
  41. } else {
  42. callback(null)
  43. throw error
  44. }
  45. }
  46. } else {
  47. console.log(error.message.replace(/^Command failed[^\n]*\n/, ''))
  48. callback(null)
  49. }
  50. })
  51. p.stdin.write(command)
  52. p.stdin.end()
  53. }
  54. load_modules()
  55. let instance = REPL.start({ prompt: '>> ', eval: k_eval })
  56. instance.context.KumaChan = KumaChan