1 package org.simantics.db.layer0.scl;
3 import gnu.trove.map.hash.THashMap;
5 import java.util.ArrayList;
8 import org.simantics.db.ReadGraph;
9 import org.simantics.db.exception.DatabaseException;
10 import org.simantics.db.exception.RuntimeDatabaseException;
11 import org.simantics.db.request.Read;
12 import org.simantics.scl.compiler.common.names.Name;
13 import org.simantics.scl.compiler.constants.StringConstant;
14 import org.simantics.scl.compiler.elaboration.expressions.EApply;
15 import org.simantics.scl.compiler.elaboration.expressions.EConstant;
16 import org.simantics.scl.compiler.elaboration.expressions.ELiteral;
17 import org.simantics.scl.compiler.elaboration.expressions.ESimpleLet;
18 import org.simantics.scl.compiler.elaboration.expressions.EVariable;
19 import org.simantics.scl.compiler.elaboration.expressions.Expression;
20 import org.simantics.scl.compiler.elaboration.expressions.Variable;
21 import org.simantics.scl.compiler.environment.AbstractLocalEnvironment;
22 import org.simantics.scl.compiler.environment.Environment;
23 import org.simantics.scl.compiler.environment.LocalEnvironment;
24 import org.simantics.scl.compiler.errors.CompilationError;
25 import org.simantics.scl.compiler.runtime.RuntimeEnvironment;
26 import org.simantics.scl.compiler.top.ExpressionEvaluator;
27 import org.simantics.scl.compiler.top.SCLExpressionCompilationException;
28 import org.simantics.scl.compiler.types.TCon;
29 import org.simantics.scl.compiler.types.Type;
30 import org.simantics.scl.compiler.types.Types;
31 import org.simantics.scl.compiler.types.exceptions.MatchException;
32 import org.simantics.scl.compiler.types.kinds.Kinds;
33 import org.simantics.scl.compiler.types.util.MultiFunction;
34 import org.simantics.scl.runtime.SCLContext;
35 import org.simantics.scl.runtime.function.Function1;
36 import org.simantics.utils.datastructures.Pair;
39 * <p>This is a base implementation for compiling expressions stored into
40 * graph. It provides a skeleton and a set of methods that must be
41 * implemented to get a concrete compilation request.
43 * <p>The request returns an SCL function with type {@code EvaluationContext -> Result}
44 * where {@code EvaluationContext} is the type given by {@link #getContextVariableType()}
45 * and {@code Result} is the type of the expression that can be optionally restricted
46 * by {@link #getExpectedType(ReadGraph, AbstractExpressionCompilationContext)}.
48 * <p>Compilation calls {@link #getCompilationContext(ReadGraph)} to read all information
49 * that is needed about the context of the resource during compilation. The result must
50 * extend the type {@link AbstractExpressionCompilationContext} including at least information about
51 * {@link RuntimeEnvironment}.
53 * <p>Compilation calls {@link #getVariableAccessExpression(ReadGraph, AbstractExpressionCompilationContext, Variable, String)}
54 * to get access to local environment. The method may return null if the variable is not defined.
56 * @author Hannu Niemistö
60 public abstract class AbstractExpressionCompilationRequest<CompilationContext extends AbstractExpressionCompilationContext,EvaluationContext>
61 implements Read<Function1<EvaluationContext,Object>> {
63 protected static final Type RESOURCE = Types.con("Simantics/DB", "Resource");
64 protected static final Type VARIABLE = Types.con("Simantics/Variables", "Variable");
65 protected static Name PROPERTY_VALUE = Name.create("Simantics/Variables", "propertyValue");
66 protected static Name VARIABLE_PARENT = Name.create("Simantics/Variables", "variableParent");
67 protected static Name FROM_DOUBLE = Name.create("Prelude", "fromDouble");
68 protected static Name TO_DOUBLE = Name.create("Prelude", "toDouble");
69 protected static Name FROM_DYNAMIC = Name.create("Prelude", "fromDynamic");
71 private static final Type DEFAULT_EXPECTED_EFFECT = Types.union(new Type[] {Types.PROC, Types.READ_GRAPH});
74 * Returns the expression that will be compiled in textual form.
76 protected abstract String getExpressionText(ReadGraph graph) throws DatabaseException;
78 * Returns the context that is used for the compilation of the expression. The context
79 * contains information about available constants and variables.
81 protected abstract CompilationContext getCompilationContext(ReadGraph graph) throws DatabaseException;
83 * This should return the SCL type corresponding to generic type parameter {@code EvaluationContext}.
85 protected abstract Type getContextVariableType();
87 * Returns <code>null</code>, if variable {@code name} is not defined.
89 protected abstract Expression getVariableAccessExpression(ReadGraph graph,
90 CompilationContext context, Variable contextVariable, String name) throws DatabaseException;
92 protected Type getExpectedType(ReadGraph graph, CompilationContext context) throws DatabaseException {
93 return Types.metaVar(Kinds.STAR);
96 protected Type getExpectedEffect(ReadGraph graph, CompilationContext context) throws DatabaseException {
97 return DEFAULT_EXPECTED_EFFECT;
100 private ExpressionEvaluator prepareEvaluator(final ReadGraph graph, final CompilationContext context, Type expectedType) throws DatabaseException {
101 final Variable contextVariable = new Variable("context", getContextVariableType());
102 LocalEnvironment localEnvironment = new AbstractLocalEnvironment() {
103 THashMap<String,Pair<Variable,Expression>> precalculatedVariables = new THashMap<String,Pair<Variable,Expression>>();
105 public Expression resolve(Environment environment, String localName) {
106 Pair<Variable,Expression> precalculatedVariable = precalculatedVariables.get(localName);
107 if(precalculatedVariable == null) {
109 Expression value = getVariableAccessExpression(graph, context, contextVariable, localName);
112 Variable variable = new Variable(localName);
113 precalculatedVariable = Pair.make(variable, value);
114 precalculatedVariables.put(localName, precalculatedVariable);
115 } catch (DatabaseException e) {
116 throw new RuntimeDatabaseException(e);
119 return new EVariable(precalculatedVariable.first);
122 public Expression preDecorateExpression(Expression expression) {
123 for(Pair<Variable,Expression> precalculatedVariable : precalculatedVariables.values())
124 expression = new ESimpleLet(precalculatedVariable.first, precalculatedVariable.second, expression);
128 protected Variable[] getContextVariables() {
129 return new Variable[] { contextVariable };
133 String expressionText = getExpressionText(graph);
134 return new ExpressionEvaluator(context.runtimeEnvironment, expressionText)
135 .localEnvironment(localEnvironment)
136 .expectedType(expectedType)
137 .parseAsBlock(parseAsBlock());
140 protected boolean parseAsBlock() {
144 private Function1<EvaluationContext, Object> eval(ExpressionEvaluator evaluator, ReadGraph graph) throws DatabaseException {
145 Object oldGraph = SCLContext.getCurrent().put("graph", graph);
147 return (Function1<EvaluationContext,Object>)evaluator.eval();
148 } catch(RuntimeDatabaseException e) {
150 if(e.getCause() instanceof DatabaseException)
151 throw (DatabaseException)e.getCause();
154 } catch (SCLExpressionCompilationException e) {
155 StringBuilder b = new StringBuilder();
156 b.append("Couldn't compile '");
157 b.append(evaluator.getExpressionText());
159 StringBuilder b2 = new StringBuilder();
160 for(CompilationError error : e.getErrors()) {
161 b2.append(error.description);
164 System.err.println(b.toString() + b2.toString());
165 throw new SCLDatabaseException(b.toString()+b2.toString(), b2.toString(), e.getErrors());
166 } catch(Throwable e) {
167 // Should not happen!
169 throw new RuntimeException(e);
171 SCLContext.getCurrent().put("graph", oldGraph);
175 public List<TCon> getExpressionEffects(final ReadGraph graph) throws DatabaseException {
176 CompilationContext context = getCompilationContext(graph);
177 Type type = Types.metaVar(Kinds.STAR);
178 eval(prepareEvaluator(graph, context, type), graph);
181 MultiFunction mfun = Types.matchFunction(type, 1);
182 ArrayList<TCon> concreteEffects = new ArrayList<TCon>();
183 mfun.effect.collectConcreteEffects(concreteEffects);
184 return concreteEffects;
185 } catch(MatchException e) {
186 // Should not happen!
188 throw new RuntimeException(e);
192 @SuppressWarnings("unchecked")
194 public Function1<EvaluationContext,Object> perform(final ReadGraph graph) throws DatabaseException {
195 CompilationContext context = getCompilationContext(graph);
196 return eval(prepareEvaluator(graph, context, getExpectedType(graph, context)), graph);
199 protected static Expression getProperty(Environment environment, Expression variable, String propertyName, Type type) {
201 new EConstant(environment.getValue(FROM_DYNAMIC), type),
203 new EConstant(environment.getValue(PROPERTY_VALUE), Types.DYNAMIC),
205 new ELiteral(new StringConstant(propertyName))));
208 protected static Expression getPropertyFlexible(Environment environment, Expression variable, String propertyName, Type type) {
209 return makeTypeFlexible(environment, getProperty(environment, variable, propertyName, type), type);
212 protected static Expression makeTypeFlexible(Environment environment, Expression base, Type originalType) {
213 if(originalType.equals(Types.DOUBLE))
215 new EConstant(environment.getValue(FROM_DOUBLE)),
217 else if(originalType.equals(Types.FLOAT))
219 new EConstant(environment.getValue(FROM_DOUBLE)),
221 new EConstant(environment.getValue(TO_DOUBLE), Types.FLOAT),