]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/scl/AbstractExpressionCompilationRequest.java
Documented difference of RuntimeEnvironmentRequest and Runti...quest2
[simantics/platform.git] / bundles / org.simantics.db.layer0 / src / org / simantics / db / layer0 / scl / AbstractExpressionCompilationRequest.java
1 package org.simantics.db.layer0.scl;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import org.simantics.databoard.Bindings;
7 import org.simantics.db.ReadGraph;
8 import org.simantics.db.exception.DatabaseException;
9 import org.simantics.db.exception.RuntimeDatabaseException;
10 import org.simantics.db.request.Read;
11 import org.simantics.layer0.Layer0;
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;
37
38 import gnu.trove.map.hash.THashMap;
39
40 /**
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.
44  * 
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)}.
49  * 
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}.
54  * 
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.
57  * 
58  * @author Hannu Niemist&ouml;
59  *
60  * @param <Context>
61  */
62 public abstract class AbstractExpressionCompilationRequest<CompilationContext extends AbstractExpressionCompilationContext,EvaluationContext>
63 implements Read<Function1<EvaluationContext,Object>> {
64
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");
72
73     private static final Type DEFAULT_EXPECTED_EFFECT = Types.union(new Type[] {Types.PROC, Types.READ_GRAPH});
74
75     /**
76      * Returns the expression that will be compiled in textual form.
77      */
78     protected abstract String getExpressionText(ReadGraph graph) throws DatabaseException;
79     /**
80      * Returns the context that is used for the compilation of the expression. The context
81      * contains information about available constants and variables.
82      */
83     protected abstract CompilationContext getCompilationContext(ReadGraph graph) throws DatabaseException;
84     /**
85      * This should return the SCL type corresponding to generic type parameter {@code EvaluationContext}.
86      */
87     protected abstract Type getContextVariableType();
88     /**
89      * Returns <code>null</code>, if variable {@code name} is not defined.
90      */
91     protected abstract Expression getVariableAccessExpression(ReadGraph graph,
92             CompilationContext context, Variable contextVariable, String name) throws DatabaseException;
93
94     protected Type getExpectedType(ReadGraph graph, CompilationContext context) throws DatabaseException {
95         return Types.metaVar(Kinds.STAR);
96     }
97
98     protected Type getExpectedEffect(ReadGraph graph, CompilationContext context) throws DatabaseException {
99         return DEFAULT_EXPECTED_EFFECT;
100     }
101     
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>>(); 
106             @Override
107             public Expression resolve(Environment environment, String localName) {
108                 Pair<Variable,Expression> precalculatedVariable = precalculatedVariables.get(localName);
109                 if(precalculatedVariable == null) {
110                     try {
111                         Expression value = getVariableAccessExpression(graph, context, contextVariable, localName);
112                         if(value == null)
113                             return null;
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);
119                     }
120                 }
121                 return new EVariable(precalculatedVariable.first);
122             }
123             @Override
124             public Expression preDecorateExpression(Expression expression) {
125                 for(Pair<Variable,Expression> precalculatedVariable : precalculatedVariables.values())
126                     expression = new ESimpleLet(precalculatedVariable.first, precalculatedVariable.second, expression);
127                 return expression;
128             }
129             @Override
130             protected Variable[] getContextVariables() {
131                 return new Variable[] { contextVariable };
132             }
133         };
134
135         String expressionText = getExpressionText(graph);
136         return new ExpressionEvaluator(context.runtimeEnvironment, expressionText)
137             .localEnvironment(localEnvironment)
138             .expectedType(expectedType)
139             .parseAsBlock(parseAsBlock());
140     }
141     
142     protected boolean parseAsBlock() {
143         return false;
144     }
145     
146     private Function1<EvaluationContext, Object> eval(ExpressionEvaluator evaluator, ReadGraph graph) throws DatabaseException {
147         Object oldGraph = SCLContext.getCurrent().put("graph", graph);
148         try {
149             return (Function1<EvaluationContext,Object>)evaluator.eval();
150         } catch(RuntimeDatabaseException e) {
151             e.printStackTrace();
152             if(e.getCause() instanceof DatabaseException)
153                 throw (DatabaseException)e.getCause();
154             else
155                 throw e;
156         } catch (SCLExpressionCompilationException e) {
157             StringBuilder b = new StringBuilder();
158             b.append("Couldn't compile '");
159             b.append(evaluator.getExpressionText());
160             b.append("':\n");
161             StringBuilder b2 = new StringBuilder();
162             for(CompilationError error : e.getErrors()) {
163                 b2.append(error.description);
164                 b2.append('\n');
165             }
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!
170             e.printStackTrace();
171             throw new RuntimeException(e);
172         } finally {
173             SCLContext.getCurrent().put("graph", oldGraph);
174         }
175     }
176
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);
181
182         try {
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!
189             e.printStackTrace();
190             throw new RuntimeException(e);
191         }
192     }
193
194     @SuppressWarnings("unchecked")
195     @Override
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);
199     }
200
201     protected static Expression getProperty(Environment environment, Expression variable, String propertyName, Type type) {
202         return new EApply(
203                 new EConstant(environment.getValue(FROM_DYNAMIC), type),
204                 new EApply(
205                         new EConstant(environment.getValue(PROPERTY_VALUE), Types.DYNAMIC),
206                         variable,
207                         new ELiteral(new StringConstant(propertyName))));
208     }
209
210     protected static Expression getPropertyFlexible(Environment environment, Expression variable, String propertyName, Type type) {
211         return makeTypeFlexible(environment, getProperty(environment, variable, propertyName, type), type);
212     }
213
214     protected static Expression makeTypeFlexible(Environment environment, Expression base, Type originalType) {
215         if(originalType.equals(Types.DOUBLE))
216             return new EApply(
217                     new EConstant(environment.getValue(FROM_DOUBLE)),
218                     base);
219         else if(originalType.equals(Types.FLOAT))
220             return new EApply(
221                     new EConstant(environment.getValue(FROM_DOUBLE)),
222                     new EApply(
223                             new EConstant(environment.getValue(TO_DOUBLE), Types.FLOAT),
224                             base));
225         else
226             return base;
227     }
228     
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);
232         return valueType;
233     }
234 }