1 package org.simantics.db.layer0.scl;
3 import gnu.trove.map.hash.THashMap;
5 import java.util.ArrayList;
8 import org.simantics.databoard.Bindings;
9 import org.simantics.db.ReadGraph;
10 import org.simantics.db.exception.DatabaseException;
11 import org.simantics.db.exception.RuntimeDatabaseException;
12 import org.simantics.db.request.Read;
13 import org.simantics.layer0.Layer0;
14 import org.simantics.scl.compiler.common.names.Name;
15 import org.simantics.scl.compiler.constants.StringConstant;
16 import org.simantics.scl.compiler.elaboration.expressions.EApply;
17 import org.simantics.scl.compiler.elaboration.expressions.EConstant;
18 import org.simantics.scl.compiler.elaboration.expressions.ELiteral;
19 import org.simantics.scl.compiler.elaboration.expressions.ESimpleLet;
20 import org.simantics.scl.compiler.elaboration.expressions.EVariable;
21 import org.simantics.scl.compiler.elaboration.expressions.Expression;
22 import org.simantics.scl.compiler.elaboration.expressions.Variable;
23 import org.simantics.scl.compiler.environment.AbstractLocalEnvironment;
24 import org.simantics.scl.compiler.environment.Environment;
25 import org.simantics.scl.compiler.environment.LocalEnvironment;
26 import org.simantics.scl.compiler.errors.CompilationError;
27 import org.simantics.scl.compiler.runtime.RuntimeEnvironment;
28 import org.simantics.scl.compiler.top.ExpressionEvaluator;
29 import org.simantics.scl.compiler.top.SCLExpressionCompilationException;
30 import org.simantics.scl.compiler.types.TCon;
31 import org.simantics.scl.compiler.types.Type;
32 import org.simantics.scl.compiler.types.Types;
33 import org.simantics.scl.compiler.types.exceptions.MatchException;
34 import org.simantics.scl.compiler.types.kinds.Kinds;
35 import org.simantics.scl.compiler.types.util.MultiFunction;
36 import org.simantics.scl.runtime.SCLContext;
37 import org.simantics.scl.runtime.function.Function1;
38 import org.simantics.utils.datastructures.Pair;
41 * <p>This is a base implementation for compiling expressions stored into
42 * graph. It provides a skeleton and a set of methods that must be
43 * implemented to get a concrete compilation request.
45 * <p>The request returns an SCL function with type {@code EvaluationContext -> Result}
46 * where {@code EvaluationContext} is the type given by {@link #getContextVariableType()}
47 * and {@code Result} is the type of the expression that can be optionally restricted
48 * by {@link #getExpectedType(ReadGraph, AbstractExpressionCompilationContext)}.
50 * <p>Compilation calls {@link #getCompilationContext(ReadGraph)} to read all information
51 * that is needed about the context of the resource during compilation. The result must
52 * extend the type {@link AbstractExpressionCompilationContext} including at least information about
53 * {@link RuntimeEnvironment}.
55 * <p>Compilation calls {@link #getVariableAccessExpression(ReadGraph, AbstractExpressionCompilationContext, Variable, String)}
56 * to get access to local environment. The method may return null if the variable is not defined.
58 * @author Hannu Niemistö
62 public abstract class AbstractExpressionCompilationRequest<CompilationContext extends AbstractExpressionCompilationContext,EvaluationContext>
63 implements Read<Function1<EvaluationContext,Object>> {
65 protected static final Type RESOURCE = Types.con("Simantics/DB", "Resource");
66 protected static final Type VARIABLE = Types.con("Simantics/Variables", "Variable");
67 protected static Name PROPERTY_VALUE = Name.create("Simantics/Variables", "propertyValue");
68 protected static Name VARIABLE_PARENT = Name.create("Simantics/Variables", "variableParent");
69 protected static Name FROM_DOUBLE = Name.create("Prelude", "fromDouble");
70 protected static Name TO_DOUBLE = Name.create("Prelude", "toDouble");
71 protected static Name FROM_DYNAMIC = Name.create("Prelude", "fromDynamic");
73 private static final Type DEFAULT_EXPECTED_EFFECT = Types.union(new Type[] {Types.PROC, Types.READ_GRAPH});
76 * Returns the expression that will be compiled in textual form.
78 protected abstract String getExpressionText(ReadGraph graph) throws DatabaseException;
80 * Returns the context that is used for the compilation of the expression. The context
81 * contains information about available constants and variables.
83 protected abstract CompilationContext getCompilationContext(ReadGraph graph) throws DatabaseException;
85 * This should return the SCL type corresponding to generic type parameter {@code EvaluationContext}.
87 protected abstract Type getContextVariableType();
89 * Returns <code>null</code>, if variable {@code name} is not defined.
91 protected abstract Expression getVariableAccessExpression(ReadGraph graph,
92 CompilationContext context, Variable contextVariable, String name) throws DatabaseException;
94 protected Type getExpectedType(ReadGraph graph, CompilationContext context) throws DatabaseException {
95 return Types.metaVar(Kinds.STAR);
98 protected Type getExpectedEffect(ReadGraph graph, CompilationContext context) throws DatabaseException {
99 return DEFAULT_EXPECTED_EFFECT;
102 private ExpressionEvaluator prepareEvaluator(final ReadGraph graph, final CompilationContext context, Type expectedType) throws DatabaseException {
103 final Variable contextVariable = new Variable("context", getContextVariableType());
104 LocalEnvironment localEnvironment = new AbstractLocalEnvironment() {
105 THashMap<String,Pair<Variable,Expression>> precalculatedVariables = new THashMap<String,Pair<Variable,Expression>>();
107 public Expression resolve(Environment environment, String localName) {
108 Pair<Variable,Expression> precalculatedVariable = precalculatedVariables.get(localName);
109 if(precalculatedVariable == null) {
111 Expression value = getVariableAccessExpression(graph, context, contextVariable, localName);
114 Variable variable = new Variable(localName);
115 precalculatedVariable = Pair.make(variable, value);
116 precalculatedVariables.put(localName, precalculatedVariable);
117 } catch (DatabaseException e) {
118 throw new RuntimeDatabaseException(e);
121 return new EVariable(precalculatedVariable.first);
124 public Expression preDecorateExpression(Expression expression) {
125 for(Pair<Variable,Expression> precalculatedVariable : precalculatedVariables.values())
126 expression = new ESimpleLet(precalculatedVariable.first, precalculatedVariable.second, expression);
130 protected Variable[] getContextVariables() {
131 return new Variable[] { contextVariable };
135 String expressionText = getExpressionText(graph);
136 return new ExpressionEvaluator(context.runtimeEnvironment, expressionText)
137 .localEnvironment(localEnvironment)
138 .expectedType(expectedType)
139 .parseAsBlock(parseAsBlock());
142 protected boolean parseAsBlock() {
146 private Function1<EvaluationContext, Object> eval(ExpressionEvaluator evaluator, ReadGraph graph) throws DatabaseException {
147 Object oldGraph = SCLContext.getCurrent().put("graph", graph);
149 return (Function1<EvaluationContext,Object>)evaluator.eval();
150 } catch(RuntimeDatabaseException e) {
152 if(e.getCause() instanceof DatabaseException)
153 throw (DatabaseException)e.getCause();
156 } catch (SCLExpressionCompilationException e) {
157 StringBuilder b = new StringBuilder();
158 b.append("Couldn't compile '");
159 b.append(evaluator.getExpressionText());
161 StringBuilder b2 = new StringBuilder();
162 for(CompilationError error : e.getErrors()) {
163 b2.append(error.description);
166 System.err.println(b.toString() + b2.toString());
167 throw new SCLDatabaseException(b.toString()+b2.toString(), b2.toString(), e.getErrors());
168 } catch(Throwable e) {
169 // Should not happen!
171 throw new RuntimeException(e);
173 SCLContext.getCurrent().put("graph", oldGraph);
177 public List<TCon> getExpressionEffects(final ReadGraph graph) throws DatabaseException {
178 CompilationContext context = getCompilationContext(graph);
179 Type type = Types.metaVar(Kinds.STAR);
180 eval(prepareEvaluator(graph, context, type), graph);
183 MultiFunction mfun = Types.matchFunction(type, 1);
184 ArrayList<TCon> concreteEffects = new ArrayList<TCon>();
185 mfun.effect.collectConcreteEffects(concreteEffects);
186 return concreteEffects;
187 } catch(MatchException e) {
188 // Should not happen!
190 throw new RuntimeException(e);
194 @SuppressWarnings("unchecked")
196 public Function1<EvaluationContext,Object> perform(final ReadGraph graph) throws DatabaseException {
197 CompilationContext context = getCompilationContext(graph);
198 return eval(prepareEvaluator(graph, context, getExpectedType(graph, context)), graph);
201 protected static Expression getProperty(Environment environment, Expression variable, String propertyName, Type type) {
203 new EConstant(environment.getValue(FROM_DYNAMIC), type),
205 new EConstant(environment.getValue(PROPERTY_VALUE), Types.DYNAMIC),
207 new ELiteral(new StringConstant(propertyName))));
210 protected static Expression getPropertyFlexible(Environment environment, Expression variable, String propertyName, Type type) {
211 return makeTypeFlexible(environment, getProperty(environment, variable, propertyName, type), type);
214 protected static Expression makeTypeFlexible(Environment environment, Expression base, Type originalType) {
215 if(originalType.equals(Types.DOUBLE))
217 new EConstant(environment.getValue(FROM_DOUBLE)),
219 else if(originalType.equals(Types.FLOAT))
221 new EConstant(environment.getValue(FROM_DOUBLE)),
223 new EConstant(environment.getValue(TO_DOUBLE), Types.FLOAT),
229 protected static String resolveExpectedValueType(ReadGraph graph, org.simantics.db.layer0.variable.Variable context) throws DatabaseException {
230 Layer0 L0 = Layer0.getInstance(graph);
231 String valueType = graph.getPossibleRelatedValue(context.getPredicateResource(graph), L0.RequiresValueType, Bindings.STRING);