view core/src/luan/impl/Closure.java @ 668:7780cafca27f

minor
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 11 Apr 2016 14:13:52 -0600
parents 08966099aa6d
children 58ebfec6178b
line wrap: on
line source

package luan.impl;

import luan.Luan;
import luan.LuanFunction;
import luan.LuanState;
import luan.LuanException;
import luan.DeepCloner;
import luan.DeepCloneable;


public abstract class Closure extends LuanFunction implements DeepCloneable, Cloneable {
	private final int stackSize;
	private final int numArgs;
	private final boolean isVarArg;
	private UpValue[] upValues;

	public Closure(LuanStateImpl luan,int stackSize,int numArgs,boolean isVarArg,UpValue.Getter[] upValueGetters) throws LuanException {
		this.stackSize = stackSize;
		this.numArgs = numArgs;
		this.isVarArg = isVarArg;
		this.upValues = new UpValue[upValueGetters.length];
		for( int i=0; i<upValues.length; i++ ) {
			upValues[i] = upValueGetters[i].get(luan);
		}
	}

	@Override public Closure shallowClone() {
		try {
			return (Closure)clone();
		} catch(CloneNotSupportedException e) {
			throw new RuntimeException(e);
		}
	}

	@Override public void deepenClone(DeepCloneable clone,DeepCloner cloner) {
		((Closure)clone).upValues = (UpValue[])cloner.deepClone(upValues);
	}

	UpValue[] upValues() {
		return upValues;
	}

	@Override public Object call(LuanState ls,Object[] args) throws LuanException {
		LuanStateImpl luan = (LuanStateImpl)ls;
		Object[] varArgs = null;
		if( isVarArg ) {
			if( args.length > numArgs ) {
				varArgs = new Object[ args.length - numArgs ];
				for( int i=0; i<varArgs.length; i++ ) {
					varArgs[i] = args[numArgs+i];
				}
			} else {
				varArgs = LuanFunction.NOTHING;
			}
		}
		Object[] stack = luan.newFrame(this,stackSize,varArgs);
		final int n = Math.min(args.length,numArgs);
		for( int i=0; i<n; i++ ) {
			stack[i] = args[i];
		}
		try {
			return run(luan);
		} catch(StackOverflowError e) {
			throw new LuanException( "stack overflow", e );
		} finally {
			luan.popFrame();
		}
	}

	public abstract Object run(LuanStateImpl luan) throws LuanException;
}