view src/luan/interp/LuanCompiler.java @ 48:64ecb7a3aad7

rename Lua to Luan git-svn-id: https://luan-java.googlecode.com/svn/trunk@49 21e917c8-12df-6dd8-5cb6-c86387c605b9
author fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9>
date Fri, 28 Dec 2012 03:29:12 +0000
parents
children 8ede219cd111
line wrap: on
line source

package luan.interp;

import org.parboiled.Parboiled;
import org.parboiled.errors.ErrorUtils;
import org.parboiled.parserunners.ReportingParseRunner;
import org.parboiled.parserunners.TracingParseRunner;
import org.parboiled.support.ParsingResult;
import luan.LuanFunction;
import luan.LuanState;
import luan.LuanException;
import luan.LuanSource;
import luan.LuanElement;


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

	public static LuanFunction compile(LuanState lua,LuanSource src) throws LuanException {
		LuanParser parser = Parboiled.createParser(LuanParser.class);
		parser.source = src;
		ParsingResult<?> result = new ReportingParseRunner(parser.Target()).run(src.text);
//		ParsingResult<?> result = new TracingParseRunner(parser.Target()).run(src);
		if( result.hasErrors() )
			throw new LuanException( lua, null, ErrorUtils.printParseErrors(result) );
		Object resultValue = result.resultValue;
		if( resultValue instanceof Expressions ) {
			final Expressions expressions = (Expressions)resultValue;
			return new LuanFunction() {
				public Object[] call(LuanState lua,Object[] args) throws LuanException {
					return expressions.eval((LuanStateImpl)lua);
				}
			};
		}
		Chunk chunk = (Chunk)resultValue;
		return chunk.newClosure((LuanStateImpl)lua);
	}

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