changeset 703:6e6e9e73abaa

cache classes in compiler
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 13 May 2016 14:51:05 -0600
parents 87970832a3c3
children 90c89138c234
files core/src/luan/impl/LuanCompiler.java
diffstat 1 files changed, 32 insertions(+), 13 deletions(-) [+]
line wrap: on
line diff
--- a/core/src/luan/impl/LuanCompiler.java	Wed May 04 20:45:40 2016 -0600
+++ b/core/src/luan/impl/LuanCompiler.java	Fri May 13 14:51:05 2016 -0600
@@ -1,7 +1,9 @@
 package luan.impl;
 
+import java.lang.ref.WeakReference;
+import java.lang.reflect.InvocationTargetException;
 import java.util.Map;
-import java.lang.reflect.InvocationTargetException;
+import java.util.HashMap;
 import luan.LuanFunction;
 import luan.LuanState;
 import luan.LuanException;
@@ -12,20 +14,10 @@
 
 
 public final class LuanCompiler {
-	private LuanCompiler() {}  // never
+	private static final Map<String,WeakReference<Class>> map = new HashMap<String,WeakReference<Class>>();
 
 	public static LuanFunction compile(String sourceText,String sourceName,LuanTable env) throws LuanException {
-		LuanParser parser = new LuanParser(sourceText,sourceName);
-		parser.addVar( "java" );
-		parser.addVar( "require" );
-		if( env != null )  parser.addVar( "_ENV" );
-		Class fnClass;
-		try {
-			fnClass = parser.RequiredModule();
-		} catch(ParseException e) {
-//e.printStackTrace();
-			throw new LuanException( e.getFancyMessage() );
-		}
+		Class fnClass = env==null ? getClass(sourceText,sourceName) : getClass(sourceText,sourceName,env);
 		LuanJava java;
 		if( env == null ) {
 			java = new LuanJava();
@@ -54,6 +46,32 @@
 		return closure;
 	}
 
+	private static synchronized Class getClass(String sourceText,String sourceName) throws LuanException {
+		String key = sourceName + "~~~" + sourceText;
+		WeakReference<Class> ref = map.get(key);
+		if( ref != null ) {
+			Class cls = ref.get();
+			if( cls != null )
+				return cls;
+		}
+		Class cls = getClass(sourceText,sourceName,null);
+		map.put(key,new WeakReference<Class>(cls));
+		return cls;
+	}
+
+	private static Class getClass(String sourceText,String sourceName,LuanTable env) throws LuanException {
+		LuanParser parser = new LuanParser(sourceText,sourceName);
+		parser.addVar( "java" );
+		parser.addVar( "require" );
+		if( env != null )  parser.addVar( "_ENV" );
+		try {
+			return parser.RequiredModule();
+		} catch(ParseException e) {
+//e.printStackTrace();
+			throw new LuanException( e.getFancyMessage() );
+		}
+	}
+
 	public static String toJava(String sourceName,String sourceText) throws LuanException {
 		LuanParser parser = new LuanParser(sourceName,sourceText);
 		parser.addVar( "java" );
@@ -65,4 +83,5 @@
 		}
 	}
 
+	private LuanCompiler() {}  // never
 }