view core/src/luan/impl/LuanCompiler.java @ 670:58ebfec6178b

all luan now compiles
author Franklin Schmidt <fschmidt@gmail.com>
date Tue, 12 Apr 2016 01:05:57 -0600
parents 08966099aa6d
children d3e5414bdf4c
line wrap: on
line source

package luan.impl;

import java.util.Map;
import java.lang.reflect.InvocationTargetException;
import luan.LuanFunction;
import luan.LuanState;
import luan.LuanException;
import luan.LuanTable;
import luan.modules.JavaLuan;
import luan.modules.PackageLuan;


public final class LuanCompiler {
	private LuanCompiler() {}  // never

	public static LuanFunction compile(LuanState luan,String sourceName,String sourceText,LuanTable env,boolean allowExpr) throws LuanException {
		LuanParser parser = new LuanParser(sourceName,sourceText);
		parser.addVar( env!=null ? "_ENV" : null );
		parser.addVar( "java" );
		parser.addVar( "require" );
		Class fnClass = parse(parser,allowExpr);
		final LuanStateImpl luanImpl = (LuanStateImpl)luan;
		Closure closure;
		try {
			closure = (Closure)fnClass.getConstructor(LuanState.class).newInstance(luanImpl);
		} catch(NoSuchMethodException e) {
			throw new RuntimeException(e);
		} catch(InstantiationException e) {
			throw new RuntimeException(e);
		} catch(IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch(InvocationTargetException e) {
			throw new RuntimeException(e);
		}
		closure.upValues[0].o = env!=null ? env : new LuanTable();
		closure.upValues[1].o = JavaLuan.javaFn;
		closure.upValues[2].o = PackageLuan.requireFn;
		return closure;
	}

	private static Class parse(LuanParser parser,boolean allowExpr) throws LuanException {
		try {
			if( allowExpr ) {
				Class fnClass = parser.Expression();
				if( fnClass != null )
					return fnClass;
			}
			return parser.RequiredModule();
		} catch(ParseException e) {
e.printStackTrace();
			throw new LuanException( e.getFancyMessage() );
		}
	}

	public static LuanState newLuanState() {
		return new LuanStateImpl();
	}
}