Advertisement
osmarks

HasCCell

Dec 29th, 2018
2,143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.82 KB | None | 0 0
  1. local function URL_encode(str)
  2.    if str then
  3.       str = str:gsub("\n", "\r\n")
  4.       str = str:gsub("([^%w %-%_%.%~])", function(c)
  5.          return ("%%%02X"):format(string.byte(c))
  6.       end)
  7.       str = str:gsub(" ", "+")
  8.    end
  9.    return str  
  10. end
  11.  
  12. local API = "http://tryhaskell.org/eval"
  13.  
  14. local function evaluate(code, files, stdin)
  15.     local args = json.encode {
  16.         stdin or {},
  17.         files
  18.     }
  19.     local data = string.format("exp=%s&args=%s", URL_encode(code), URL_encode(args))
  20.     local h, err = http.post(API, data, {
  21.         ["User-Agent"] = "HasCCell"
  22.     })
  23.     if err then error(err) end
  24.     local c = h.readAll()
  25.     h.close()
  26.     return json.decode(c)
  27. end
  28.  
  29. local function save_files(files)
  30.     local f = fs.open(".tryhaskell-files", "w")
  31.     f.write(textutils.serialise(files))
  32.     f.close()
  33. end
  34.  
  35. local function load_files()
  36.     local f = fs.open(".tryhaskell-files", "r")
  37.     local files = textutils.unserialise(f.readAll())
  38.     f.close()
  39.     return files
  40. end
  41.  
  42. local function preprocess_output(o)
  43.     local o = o:gsub("‘", "'"):gsub("’", "'")
  44.     return o
  45. end
  46.  
  47. local history = {}
  48.  
  49. local files = {}
  50. local ok, result = pcall(load_files)
  51. if ok then files = result end
  52.  
  53. local last_expr
  54.  
  55. local function handle_result(result)
  56.     if result.success then
  57.         local s = result.success
  58.         for _, line in pairs(s.stdout) do write(preprocess_output(line)) end
  59.         print(preprocess_output(s.value))
  60.         print("::", preprocess_output(s.type))
  61.         files = s.files
  62.         save_files(files)
  63.     elseif result.error then
  64.         textutils.pagedPrint(preprocess_output(result.error))
  65.     else
  66.         write "-> "
  67.         local next_line = read()
  68.         handle_result(evaluate(last_expr, files, { next_line }))
  69.     end
  70. end
  71.  
  72. while true do
  73.     write "|> "
  74.     local input = read(nil, history)
  75.     last_expr = input
  76.     table.insert(history, input)
  77.     local result = evaluate(input, files)
  78.     handle_result(result)
  79. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement