--- /dev/null
+package org.simantics.db.layer0.scl;\r
+\r
+import gnu.trove.map.hash.THashMap;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.exception.RuntimeDatabaseException;\r
+import org.simantics.db.request.Read;\r
+import org.simantics.scl.compiler.common.names.Name;\r
+import org.simantics.scl.compiler.constants.StringConstant;\r
+import org.simantics.scl.compiler.elaboration.expressions.EApply;\r
+import org.simantics.scl.compiler.elaboration.expressions.EConstant;\r
+import org.simantics.scl.compiler.elaboration.expressions.ELiteral;\r
+import org.simantics.scl.compiler.elaboration.expressions.ESimpleLet;\r
+import org.simantics.scl.compiler.elaboration.expressions.EVariable;\r
+import org.simantics.scl.compiler.elaboration.expressions.Expression;\r
+import org.simantics.scl.compiler.elaboration.expressions.Variable;\r
+import org.simantics.scl.compiler.environment.AbstractLocalEnvironment;\r
+import org.simantics.scl.compiler.environment.Environment;\r
+import org.simantics.scl.compiler.environment.LocalEnvironment;\r
+import org.simantics.scl.compiler.errors.CompilationError;\r
+import org.simantics.scl.compiler.runtime.RuntimeEnvironment;\r
+import org.simantics.scl.compiler.top.ExpressionEvaluator;\r
+import org.simantics.scl.compiler.top.SCLExpressionCompilationException;\r
+import org.simantics.scl.compiler.types.TCon;\r
+import org.simantics.scl.compiler.types.Type;\r
+import org.simantics.scl.compiler.types.Types;\r
+import org.simantics.scl.compiler.types.exceptions.MatchException;\r
+import org.simantics.scl.compiler.types.kinds.Kinds;\r
+import org.simantics.scl.compiler.types.util.MultiFunction;\r
+import org.simantics.scl.runtime.SCLContext;\r
+import org.simantics.scl.runtime.function.Function1;\r
+import org.simantics.utils.datastructures.Pair;\r
+\r
+/**\r
+ * <p>This is a base implementation for compiling expressions stored into \r
+ * graph. It provides a skeleton and a set of methods that must be\r
+ * implemented to get a concrete compilation request.\r
+ * \r
+ * <p>The request returns an SCL function with type {@code EvaluationContext -> Result}\r
+ * where {@code EvaluationContext} is the type given by {@link #getContextVariableType()}\r
+ * and {@code Result} is the type of the expression that can be optionally restricted\r
+ * by {@link #getExpectedType(ReadGraph, AbstractExpressionCompilationContext)}.\r
+ * \r
+ * <p>Compilation calls {@link #getCompilationContext(ReadGraph)} to read all information\r
+ * that is needed about the context of the resource during compilation. The result must\r
+ * extend the type {@link AbstractExpressionCompilationContext} including at least information about \r
+ * {@link RuntimeEnvironment}.\r
+ * \r
+ * <p>Compilation calls {@link #getVariableAccessExpression(ReadGraph, AbstractExpressionCompilationContext, Variable, String)}\r
+ * to get access to local environment. The method may return null if the variable is not defined.\r
+ * \r
+ * @author Hannu Niemistö\r
+ *\r
+ * @param <Context>\r
+ */\r
+public abstract class AbstractExpressionCompilationRequest<CompilationContext extends AbstractExpressionCompilationContext,EvaluationContext>\r
+implements Read<Function1<EvaluationContext,Object>> {\r
+\r
+ protected static final Type RESOURCE = Types.con("Simantics/DB", "Resource");\r
+ protected static final Type VARIABLE = Types.con("Simantics/Variables", "Variable");\r
+ protected static Name PROPERTY_VALUE = Name.create("Simantics/Variables", "propertyValue");\r
+ protected static Name VARIABLE_PARENT = Name.create("Simantics/Variables", "variableParent");\r
+ protected static Name FROM_DOUBLE = Name.create("Prelude", "fromDouble");\r
+ protected static Name TO_DOUBLE = Name.create("Prelude", "toDouble");\r
+ protected static Name FROM_DYNAMIC = Name.create("Prelude", "fromDynamic");\r
+\r
+ private static final Type DEFAULT_EXPECTED_EFFECT = Types.union(new Type[] {Types.PROC, Types.READ_GRAPH});\r
+\r
+ /**\r
+ * Returns the expression that will be compiled in textual form.\r
+ */\r
+ protected abstract String getExpressionText(ReadGraph graph) throws DatabaseException;\r
+ /**\r
+ * Returns the context that is used for the compilation of the expression. The context\r
+ * contains information about available constants and variables.\r
+ */\r
+ protected abstract CompilationContext getCompilationContext(ReadGraph graph) throws DatabaseException;\r
+ /**\r
+ * This should return the SCL type corresponding to generic type parameter {@code EvaluationContext}.\r
+ */\r
+ protected abstract Type getContextVariableType();\r
+ /**\r
+ * Returns <code>null</code>, if variable {@code name} is not defined.\r
+ */\r
+ protected abstract Expression getVariableAccessExpression(ReadGraph graph,\r
+ CompilationContext context, Variable contextVariable, String name) throws DatabaseException;\r
+\r
+ protected Type getExpectedType(ReadGraph graph, CompilationContext context) throws DatabaseException {\r
+ return Types.metaVar(Kinds.STAR);\r
+ }\r
+\r
+ protected Type getExpectedEffect(ReadGraph graph, CompilationContext context) throws DatabaseException {\r
+ return DEFAULT_EXPECTED_EFFECT;\r
+ }\r
+ \r
+ private ExpressionEvaluator prepareEvaluator(final ReadGraph graph, final CompilationContext context, Type expectedType) throws DatabaseException {\r
+ final Variable contextVariable = new Variable("context", getContextVariableType());\r
+ LocalEnvironment localEnvironment = new AbstractLocalEnvironment() {\r
+ THashMap<String,Pair<Variable,Expression>> precalculatedVariables = new THashMap<String,Pair<Variable,Expression>>(); \r
+ @Override\r
+ public Expression resolve(Environment environment, String localName) {\r
+ Pair<Variable,Expression> precalculatedVariable = precalculatedVariables.get(localName);\r
+ if(precalculatedVariable == null) {\r
+ try {\r
+ Expression value = getVariableAccessExpression(graph, context, contextVariable, localName);\r
+ if(value == null)\r
+ return null;\r
+ Variable variable = new Variable(localName);\r
+ precalculatedVariable = Pair.make(variable, value);\r
+ precalculatedVariables.put(localName, precalculatedVariable);\r
+ } catch (DatabaseException e) {\r
+ throw new RuntimeDatabaseException(e);\r
+ }\r
+ }\r
+ return new EVariable(precalculatedVariable.first);\r
+ }\r
+ @Override\r
+ public Expression preDecorateExpression(Expression expression) {\r
+ for(Pair<Variable,Expression> precalculatedVariable : precalculatedVariables.values())\r
+ expression = new ESimpleLet(precalculatedVariable.first, precalculatedVariable.second, expression);\r
+ return expression;\r
+ }\r
+ @Override\r
+ protected Variable[] getContextVariables() {\r
+ return new Variable[] { contextVariable };\r
+ }\r
+ };\r
+\r
+ String expressionText = getExpressionText(graph);\r
+ return new ExpressionEvaluator(context.runtimeEnvironment, expressionText)\r
+ .localEnvironment(localEnvironment)\r
+ .expectedType(expectedType)\r
+ .parseAsBlock(parseAsBlock());\r
+ }\r
+ \r
+ protected boolean parseAsBlock() {\r
+ return false;\r
+ }\r
+ \r
+ private Function1<EvaluationContext, Object> eval(ExpressionEvaluator evaluator, ReadGraph graph) throws DatabaseException {\r
+ Object oldGraph = SCLContext.getCurrent().put("graph", graph);\r
+ try {\r
+ return (Function1<EvaluationContext,Object>)evaluator.eval();\r
+ } catch(RuntimeDatabaseException e) {\r
+ e.printStackTrace();\r
+ if(e.getCause() instanceof DatabaseException)\r
+ throw (DatabaseException)e.getCause();\r
+ else\r
+ throw e;\r
+ } catch (SCLExpressionCompilationException e) {\r
+ StringBuilder b = new StringBuilder();\r
+ b.append("Couldn't compile '");\r
+ b.append(evaluator.getExpressionText());\r
+ b.append("':\n");\r
+ StringBuilder b2 = new StringBuilder();\r
+ for(CompilationError error : e.getErrors()) {\r
+ b2.append(error.description);\r
+ b2.append('\n');\r
+ }\r
+ System.err.println(b.toString() + b2.toString());\r
+ throw new SCLDatabaseException(b.toString()+b2.toString(), b2.toString(), e.getErrors());\r
+ } catch(Throwable e) {\r
+ // Should not happen!\r
+ e.printStackTrace();\r
+ throw new RuntimeException(e);\r
+ } finally {\r
+ SCLContext.getCurrent().put("graph", oldGraph);\r
+ }\r
+ }\r
+\r
+ public List<TCon> getExpressionEffects(final ReadGraph graph) throws DatabaseException {\r
+ CompilationContext context = getCompilationContext(graph);\r
+ Type type = Types.metaVar(Kinds.STAR);\r
+ eval(prepareEvaluator(graph, context, type), graph);\r
+\r
+ try {\r
+ MultiFunction mfun = Types.matchFunction(type, 1);\r
+ ArrayList<TCon> concreteEffects = new ArrayList<TCon>();\r
+ mfun.effect.collectConcreteEffects(concreteEffects);\r
+ return concreteEffects;\r
+ } catch(MatchException e) {\r
+ // Should not happen!\r
+ e.printStackTrace();\r
+ throw new RuntimeException(e);\r
+ }\r
+ }\r
+\r
+ @SuppressWarnings("unchecked")\r
+ @Override\r
+ public Function1<EvaluationContext,Object> perform(final ReadGraph graph) throws DatabaseException {\r
+ CompilationContext context = getCompilationContext(graph);\r
+ return eval(prepareEvaluator(graph, context, getExpectedType(graph, context)), graph);\r
+ }\r
+\r
+ protected static Expression getProperty(Environment environment, Expression variable, String propertyName, Type type) {\r
+ return new EApply(\r
+ new EConstant(environment.getValue(FROM_DYNAMIC), type),\r
+ new EApply(\r
+ new EConstant(environment.getValue(PROPERTY_VALUE), Types.DYNAMIC),\r
+ variable,\r
+ new ELiteral(new StringConstant(propertyName))));\r
+ }\r
+\r
+ protected static Expression getPropertyFlexible(Environment environment, Expression variable, String propertyName, Type type) {\r
+ return makeTypeFlexible(environment, getProperty(environment, variable, propertyName, type), type);\r
+ }\r
+\r
+ protected static Expression makeTypeFlexible(Environment environment, Expression base, Type originalType) {\r
+ if(originalType.equals(Types.DOUBLE))\r
+ return new EApply(\r
+ new EConstant(environment.getValue(FROM_DOUBLE)),\r
+ base);\r
+ else if(originalType.equals(Types.FLOAT))\r
+ return new EApply(\r
+ new EConstant(environment.getValue(FROM_DOUBLE)),\r
+ new EApply(\r
+ new EConstant(environment.getValue(TO_DOUBLE), Types.FLOAT),\r
+ base));\r
+ else\r
+ return base;\r
+ }\r
+}\r