// Copyright 2008 Peter William Birch <birchb@genyis.org>
//
// This software may be used and distributed according to the terms
// of the Genyris License, in the file "LICENSE", incorporated herein by reference.
//
package org.genyris.interp;

import org.genyris.core.Exp;
import org.genyris.core.Lsymbol;
import org.genyris.exception.AccessException;
import org.genyris.exception.GenyrisException;

public class Evaluator {

    // TODO - refactor this to use visitor in Exp and gt rid of if()s

    public static Exp eval(Environment env, Exp expression) throws UnboundException, AccessException, GenyrisException {
        if( expression.isSelfEvaluating()) {
            return expression; }
        else if( expression.getClass() == Lsymbol.class) {
            return env.lookupVariableValue(expression);
        }
        else if( expression.listp() ) {
            try {
                Closure proc = (Closure) eval(env, expression.car());
                Exp[] arguments = proc.computeArguments(env, expression.cdr());
                return proc.applyFunction(env, arguments );
            }
            catch (ClassCastException e) {
                throw new GenyrisException("Attempt to call something which is not callable." + expression.toString());
            }
        }
        else {
            throw new GenyrisException("Evaluator does not know how to eval: " + expression.toString());
        }
    }

    public static Exp evalSequence(Environment env, Exp body) throws GenyrisException {
        Lsymbol NIL = env.getNil();
        if(body == NIL) {
            return NIL;
        }
        if( body.cdr() == NIL) {
            return eval(env, body.car());
        }
        else {
            eval(env, body.car());
            return evalSequence(env, body.cdr());
        }
    }


}
@@ -575,16 +575,28 @@
 ception,
+%0A           
  AccessE
@@ -634,18 +634,18 @@
       if
-(
  
+(
 expressi
@@ -699,16 +699,24 @@
 ression;
+%0A       
  %7D%0A     
@@ -717,34 +717,34 @@
 %0A        else if
-(
  
+(
 expression.getCl
@@ -850,18 +850,18 @@
  else if
-(
  
+(
 expressi
@@ -870,17 +870,16 @@
 .listp()
- 
 ) %7B%0A    
@@ -1098,17 +1098,16 @@
 rguments
- 
 );%0A     
@@ -1251,16 +1251,40 @@
 llable.%22
+%0A                       
  + expre
@@ -1419,16 +1419,36 @@
  eval: %22
+%0A                   
  + expre
@@ -1617,16 +1617,17 @@
       if
+ 
 (body ==
@@ -1682,10 +1682,10 @@
   if
-(
  
+(
 body
@@ -1870,10 +1870,9 @@
 %0A    %7D%0A%0A
-%0A
 %7D

Throw exception in eval, dicts are self-evaluating.