Merge pull request #440 from aasimk2000/add-nil-if-test
[jackhill/mal.git] / crystal / step9_try.cr
index 3d2c964..d56f149 100755 (executable)
@@ -1,6 +1,6 @@
 #! /usr/bin/env crystal run
 
-require "./readline"
+require "readline"
 require "./reader"
 require "./printer"
 require "./types"
@@ -11,143 +11,149 @@ require "./error"
 # Note:
 # Employed downcase names because Crystal prohibits uppercase names for methods
 
-def func_of(env, binds, body)
-  -> (args : Array(Mal::Type)) {
-    new_env = Mal::Env.new(env, binds, args)
-    eval(body, new_env)
-  } as Mal::Func
-end
+module Mal
+  extend self
+
+  def func_of(env, binds, body)
+    ->(args : Array(Mal::Type)) {
+      new_env = Mal::Env.new(env, binds, args)
+      eval(body, new_env)
+    }.as(Mal::Func)
+  end
 
-def eval_ast(ast, env)
-  return ast.map{|n| eval(n, env) as Mal::Type} if ast.is_a? Mal::List
+  def eval_ast(ast, env)
+    return ast.map { |n| eval(n, env).as(Mal::Type) } if ast.is_a? Mal::List
 
-  val = ast.unwrap
+    val = ast.unwrap
 
-  Mal::Type.new case val
-  when Mal::Symbol
-    if e = env.get(val.str)
-      e
+    Mal::Type.new case val
+    when Mal::Symbol
+      if e = env.get(val.str)
+        e
+      else
+        eval_error "'#{val.str}' not found"
+      end
+    when Mal::List
+      val.each_with_object(Mal::List.new) { |n, l| l << eval(n, env) }
+    when Mal::Vector
+      val.each_with_object(Mal::Vector.new) { |n, l| l << eval(n, env) }
+    when Array(Mal::Type)
+      val.map { |n| eval(n, env).as(Mal::Type) }
+    when Mal::HashMap
+      val.each { |k, v| val[k] = eval(v, env) }
+      val
     else
-      eval_error "'#{val.str}' not found"
+      val
     end
-  when Mal::List
-    val.each_with_object(Mal::List.new){|n, l| l << eval(n, env)}
-  when Mal::Vector
-    val.each_with_object(Mal::Vector.new){|n, l| l << eval(n, env)}
-  when Array(Mal::Type)
-    val.map{|n| eval(n, env)}
-  when Mal::HashMap
-    val.each{|k, v| val[k] = eval(v, env)}
-    val
-  else
-    val
   end
-end
 
-def read(str)
-  read_str str
-end
+  def read(str)
+    read_str str
+  end
 
-macro pair?(list)
-  {{list}}.is_a?(Array) && !{{list}}.empty?
-end
+  macro pair?(list)
+    {{list}}.is_a?(Array) && !{{list}}.empty?
+  end
 
-def quasiquote(ast)
-  list = ast.unwrap
+  def quasiquote(ast)
+    list = ast.unwrap
 
-  unless pair?(list)
-    return Mal::Type.new(
-      Mal::List.new << gen_type(Mal::Symbol, "quote") << ast
-    )
-  end
+    unless pair?(list)
+      return Mal::Type.new(
+        Mal::List.new << gen_type(Mal::Symbol, "quote") << ast
+      )
+    end
+
+    head = list.first.unwrap
 
-  head = list.first.unwrap
-
-  case
-  # ("unquote" ...)
-  when head.is_a?(Mal::Symbol) && head.str == "unquote"
-    list[1]
-  # (("splice-unquote" ...) ...)
-  when pair?(head) && (arg0 = head.first.unwrap).is_a?(Mal::Symbol) && arg0.str == "splice-unquote"
-    tail = Mal::Type.new list[1..-1].to_mal
-    Mal::Type.new(
-      Mal::List.new << gen_type(Mal::Symbol, "concat") << head[1] << quasiquote(tail)
-    )
-  else
-    tail = Mal::Type.new list[1..-1].to_mal
-    Mal::Type.new(
-      Mal::List.new << gen_type(Mal::Symbol, "cons") << quasiquote(list.first) << quasiquote(tail)
-    )
+    case
+    # ("unquote" ...)
+    when head.is_a?(Mal::Symbol) && head.str == "unquote"
+      list[1]
+      # (("splice-unquote" ...) ...)
+    when pair?(head) && (arg0 = head.first.unwrap).is_a?(Mal::Symbol) && arg0.str == "splice-unquote"
+      tail = Mal::Type.new list[1..-1].to_mal
+      Mal::Type.new(
+        Mal::List.new << gen_type(Mal::Symbol, "concat") << head[1] << quasiquote(tail)
+      )
+    else
+      tail = Mal::Type.new list[1..-1].to_mal
+      Mal::Type.new(
+        Mal::List.new << gen_type(Mal::Symbol, "cons") << quasiquote(list.first) << quasiquote(tail)
+      )
+    end
   end
-end
 
-def macro_call?(ast, env)
-  list = ast.unwrap
-  return false unless list.is_a? Mal::List
+  def macro_call?(ast, env)
+    list = ast.unwrap
+    return false unless list.is_a? Mal::List
+    return false if list.empty?
 
-  sym = list.first.unwrap
-  return false unless sym.is_a? Mal::Symbol
+    sym = list.first.unwrap
+    return false unless sym.is_a? Mal::Symbol
 
-  func = env.find(sym.str).try(&.data[sym.str])
-  return false unless func && func.macro?
+    func = env.find(sym.str).try(&.data[sym.str])
+    return false unless func && func.macro?
 
-  true
-end
+    true
+  end
 
-def macroexpand(ast, env)
-  while macro_call?(ast, env)
+  def macroexpand(ast, env)
+    while macro_call?(ast, env)
+      # Already checked in macro_call?
+      list = ast.unwrap.as(Mal::List)
+      func_sym = list[0].unwrap.as(Mal::Symbol)
+      func = env.get(func_sym.str).unwrap
+
+      case func
+      when Mal::Func
+        ast = func.call(list[1..-1])
+      when Mal::Closure
+        ast = func.fn.call(list[1..-1])
+      else
+        eval_error "macro '#{func_sym.str}' must be function: #{ast}"
+      end
+    end
 
-    # Already checked in macro_call?
-    list = ast.unwrap as Mal::List
-    func_sym = list[0].unwrap as Mal::Symbol
-    func = env.get(func_sym.str).unwrap
+    ast
+  end
 
-    case func
-    when Mal::Func
-      ast = func.call(list[1..-1])
+  macro invoke_list(l, env)
+    f = eval({{l}}.first, {{env}}).unwrap
+    args = eval_ast({{l}}[1..-1].to_mal, {{env}})
+    case f
     when Mal::Closure
-      ast = func.fn.call(list[1..-1])
+      ast = f.ast
+      {{env}} = Mal::Env.new(f.env, f.params, args)
+      next # TCO
+    when Mal::Func
+      return f.call args
     else
-      eval_error "macro '#{func_sym.str}' must be function: #{ast}"
+      eval_error "expected function as the first argument: #{f}"
     end
   end
 
-  ast
-end
+  def eval(ast, env)
+    # 'next' in 'do...end' has a bug in crystal 0.7.1
+    # https://github.com/manastech/crystal/issues/659
+    while true
+      list = ast.unwrap
 
-macro invoke_list(l, env)
-  f = eval({{l}}.first, {{env}}).unwrap
-  args = eval_ast({{l}}[1..-1].to_mal, {{env}})
-  case f
-  when Mal::Closure
-    ast = f.ast
-    {{env}} = Mal::Env.new(f.env, f.params, args)
-    next # TCO
-  when Mal::Func
-    return f.call args
-  else
-    eval_error "expected function as the first argument: #{f}"
-  end
-end
+      return eval_ast(ast, env) unless list.is_a? Mal::List
+      return ast if list.empty?
 
-def eval(ast, env)
-  # 'next' in 'do...end' has a bug in crystal 0.7.1
-  # https://github.com/manastech/crystal/issues/659
-  while true
-    return eval_ast(ast, env) unless ast.unwrap.is_a? Mal::List
+      ast = macroexpand(ast, env)
 
-    ast = macroexpand(ast, env)
+      list = ast.unwrap
 
-    list = ast.unwrap
-
-    return ast unless list.is_a? Mal::List
-    return ast if list.empty?
+      return eval_ast(ast, env) unless list.is_a? Mal::List
+      return ast if list.empty?
 
-    head = list.first.unwrap
+      head = list.first.unwrap
 
-    return invoke_list(list, env) unless head.is_a? Mal::Symbol
+      return invoke_list(list, env) unless head.is_a? Mal::Symbol
 
-    return Mal::Type.new case head.str
+      return Mal::Type.new case head.str
       when "def!"
         eval_error "wrong number of argument for 'def!'" unless list.size == 3
         a1 = list[1].unwrap
@@ -201,11 +207,11 @@ def eval(ast, env)
         eval_error "wrong number of argument for 'defmacro!'" unless list.size == 3
         a1 = list[1].unwrap
         eval_error "1st argument of 'defmacro!' must be symbol: #{a1}" unless a1.is_a? Mal::Symbol
-        env.set(a1.str, eval(list[2], env).tap{|n| n.is_macro = true})
+        env.set(a1.str, eval(list[2], env).tap { |n| n.is_macro = true })
       when "macroexpand"
         macroexpand(list[1], env)
       when "try*"
-        catch_list = list[2].unwrap
+        catch_list = list.size >= 3 ? list[2].unwrap : Mal::Type.new(nil)
         return eval(list[1], env) unless catch_list.is_a? Mal::List
 
         catch_head = catch_list.first.unwrap
@@ -224,47 +230,49 @@ def eval(ast, env)
       else
         invoke_list(list, env)
       end
+    end
   end
-end
 
-def print(result)
-  pr_str(result, true)
-end
+  def print(result)
+    pr_str(result, true)
+  end
 
-def rep(str)
-  print(eval(read(str), $repl_env))
+  def rep(str)
+    print(eval(read(str), REPL_ENV))
+  end
 end
 
-$repl_env = Mal::Env.new nil
-Mal::NS.each{|k,v| $repl_env.set(k, Mal::Type.new(v))}
-$repl_env.set("eval", Mal::Type.new -> (args: Array(Mal::Type)){ eval(args[0], $repl_env) })
-rep "(def! not (fn* (a) (if a false true)))"
-rep "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))"
-rep "(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))"
-rep "(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) `(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))"
+REPL_ENV = Mal::Env.new nil
+Mal::NS.each { |k, v| REPL_ENV.set(k, Mal::Type.new(v)) }
+REPL_ENV.set("eval", Mal::Type.new ->(args : Array(Mal::Type)) { Mal.eval(args[0], REPL_ENV) })
+Mal.rep "(def! not (fn* (a) (if a false true)))"
+Mal.rep "(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \"\nnil)\")))))"
+Mal.rep "(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))"
 
-$argv = Mal::List.new
-$repl_env.set("*ARGV*", Mal::Type.new $argv)
+argv = Mal::List.new
+REPL_ENV.set("*ARGV*", Mal::Type.new argv)
 
 unless ARGV.empty?
   if ARGV.size > 1
     ARGV[1..-1].each do |a|
-      $argv << Mal::Type.new(a)
+      argv << Mal::Type.new(a)
     end
   end
 
   begin
-    rep "(load-file \"#{ARGV[0]}\")"
+    Mal.rep "(load-file \"#{ARGV[0]}\")"
   rescue e
     STDERR.puts e
   end
   exit
 end
 
-while line = my_readline("user> ")
+while line = Readline.readline("user> ", true)
   begin
-    puts rep(line)
+    puts Mal.rep(line)
+  rescue e : Mal::RuntimeException
+    STDERR.puts "Error: #{pr_str(e.thrown, true)}"
   rescue e
-    STDERR.puts e
+    STDERR.puts "Error: #{e}"
   end
 end