view core/src/luan/impl/ReturnStmt.java @ 615:abc3198c86dd

fix tail recursion bug; add Hosting.exists();
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 17 Dec 2015 01:53:48 -0700
parents 4723d22062ce
children 859c0dedc8b6
line wrap: on
line source

package luan.impl;

import luan.Luan;
import luan.LuanException;
import luan.LuanFunction;
import luan.LuanElement;


final class ReturnStmt extends CodeImpl implements Stmt {
	private final Expressions expressions;
	boolean throwReturnException = true;

	ReturnStmt(LuanElement el,Expressions expressions) {
		super(el);
		this.expressions = expressions;
	}

	@Override public void eval(LuanStateImpl luan) throws LuanException {
		if( !(expressions instanceof FnCall) ) {
			luan.returnValues = expressions.eval(luan);
		} else {  // tail call
			FnCall tailFnCall = (FnCall)expressions;
			LuanFunction tailFn = luan.checkFunction( tailFnCall.fnExpr.eval(luan) );
			luan.returnValues = tailFnCall.args.eval(luan);
			if( tailFn instanceof Closure ) {
				luan.tailFn = (Closure)tailFn;
			} else {
				luan.push(el,tailFnCall.fnName);
				try {
					luan.returnValues =  tailFn.call(luan,Luan.array(luan.returnValues));
				} finally {
					luan.pop();
				}
			}
		}
		if( throwReturnException )
			throw new ReturnException();
	}
}