require "mlc"
require "std"

PRINT_AST  = true
LINE_WIDTH = 60

--------------------------------------------------------------------------------
-- Compile a line
--------------------------------------------------------------------------------
local function eval_line (x)
   if x:sub(1,1)=="=" then x="return "..x:sub(2,-1) end
   x = mlc.ast_of_string (x)
   if PRINT_AST then table.print(x, "nohash", LINE_WIDTH) end
   return mlc.function_of_ast (x)
end

--------------------------------------------------------------------------------
-- Attempt to load editline. If not found, replace it with a dumb substitute
-- base on io.read() and io.write().
--------------------------------------------------------------------------------
do
   local success, loader = 
      pcall (require, "editline")
   if success then 
      EDIT_LINE = editline.init ("metalua")
   else
      print "Warning: editlib not found, using dumb terminal instead"
      print (loader)
      EDIT_LINE = { prompt = "M> " }
      function EDIT_LINE:read()
         io.write (EDIT_LINE.prompt)
         return io.read()
      end
   end
end

printf ("Metalua %s, interactive REPLoop.\n"..
        "(c) 2006-2007 Fabien Fleutot ",
        METALUA_VERSION)

while true do
   local line  = EDIT_LINE:read()
   if #line==0 then break end
   local success, func = pcall (eval_line, line)
   if not success then 
      print("Parsing error: "..x)
   else
      local results = { pcall(func) }
      local success = table.remove (results, 1)
      if not success then 
         print("Execution error: "..results[1])
      end
      table.iforeach(table.print, results)
   end
end

printf ("\nBye.")