]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/scl/AbstractExpressionCompilationRequest.java
Multiple readers and variable optimization
[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.Resource;
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.layer0.Layer0;
13 import org.simantics.scl.compiler.common.names.Name;
14 import org.simantics.scl.compiler.constants.StringConstant;
15 import org.simantics.scl.compiler.elaboration.expressions.EApply;
16 import org.simantics.scl.compiler.elaboration.expressions.EConstant;
17 import org.simantics.scl.compiler.elaboration.expressions.ELiteral;
18 import org.simantics.scl.compiler.elaboration.expressions.ESimpleLet;
19 import org.simantics.scl.compiler.elaboration.expressions.EVariable;
20 import org.simantics.scl.compiler.elaboration.expressions.Expression;
21 import org.simantics.scl.compiler.elaboration.expressions.Variable;
22 import org.simantics.scl.compiler.environment.AbstractLocalEnvironment;
23 import org.simantics.scl.compiler.environment.Environment;
24 import org.simantics.scl.compiler.environment.LocalEnvironment;
25 import org.simantics.scl.compiler.errors.CompilationError;
26 import org.simantics.scl.compiler.runtime.RuntimeEnvironment;
27 import org.simantics.scl.compiler.top.ExpressionEvaluator;
28 import org.simantics.scl.compiler.top.SCLExpressionCompilationException;
29 import org.simantics.scl.compiler.types.TCon;
30 import org.simantics.scl.compiler.types.Type;
31 import org.simantics.scl.compiler.types.Types;
32 import org.simantics.scl.compiler.types.exceptions.MatchException;
33 import org.simantics.scl.compiler.types.kinds.Kinds;
34 import org.simantics.scl.compiler.types.util.MultiFunction;
35 import org.simantics.scl.runtime.SCLContext;
36 import org.simantics.scl.runtime.function.Function1;
37 import org.simantics.utils.datastructures.Pair;
38
39 import gnu.trove.map.hash.THashMap;
40
41 /**
42  * <p>This is a base implementation for compiling expressions stored into 
43  * graph. It provides a skeleton and a set of methods that must be
44  * implemented to get a concrete compilation request.
45  * 
46  * <p>The request returns an SCL function with type {@code EvaluationContext -> Result}
47  * where {@code EvaluationContext} is the type given by {@link #getContextVariableType()}
48  * and {@code Result} is the type of the expression that can be optionally restricted
49  * by {@link #getExpectedType(ReadGraph, AbstractExpressionCompilationContext)}.
50  * 
51  * <p>Compilation calls {@link #getCompilationContext(ReadGraph)} to read all information
52  * that is needed about the context of the resource during compilation. The result must
53  * extend the type {@link AbstractExpressionCompilationContext} including at least information about 
54  * {@link RuntimeEnvironment}.
55  * 
56  * <p>Compilation calls {@link #getVariableAccessExpression(ReadGraph, AbstractExpressionCompilationContext, Variable, String)}
57  * to get access to local environment. The method may return null if the variable is not defined.
58  * 
59  * @author Hannu Niemist&ouml;
60  *
61  * @param <Context>
62  */
63 public abstract class AbstractExpressionCompilationRequest<CompilationContext extends AbstractExpressionCompilationContext,EvaluationContext>
64 implements Read<Function1<EvaluationContext,Object>> {
65
66     protected static final Type RESOURCE = Types.con("Simantics/DB", "Resource");
67     protected static final Type VARIABLE = Types.con("Simantics/Variables", "Variable");
68     protected static Name PROPERTY_VALUE = Name.create("Simantics/Variables", "propertyValue");
69     protected static Name VARIABLE_PARENT = Name.create("Simantics/Variables", "variableParent");
70     protected static Name FROM_DOUBLE = Name.create("Prelude", "fromDouble");
71     protected static Name TO_DOUBLE = Name.create("Prelude", "toDouble");
72     protected static Name FROM_DYNAMIC = Name.create("Prelude", "fromDynamic");
73
74     private static final Type DEFAULT_EXPECTED_EFFECT = Types.union(new Type[] {Types.PROC, Types.READ_GRAPH});
75
76     /**
77      * Returns the expression that will be compiled in textual form.
78      */
79     protected abstract String getExpressionText(ReadGraph graph) throws DatabaseException;
80     /**
81      * Returns the context that is used for the compilation of the expression. The context
82      * contains information about available constants and variables.
83      */
84     protected abstract CompilationContext getCompilationContext(ReadGraph graph) throws DatabaseException;
85     /**
86      * This should return the SCL type corresponding to generic type parameter {@code EvaluationContext}.
87      */
88     protected abstract Type getContextVariableType();
89     /**
90      * Returns <code>null</code>, if variable {@code name} is not defined.
91      */
92     protected abstract Expression getVariableAccessExpression(ReadGraph graph,
93             CompilationContext context, Variable contextVariable, String name) throws DatabaseException;
94
95     protected Type getExpectedType(ReadGraph graph, CompilationContext context) throws DatabaseException {
96         return Types.metaVar(Kinds.STAR);
97     }
98
99     protected Type getExpectedEffect(ReadGraph graph, CompilationContext context) throws DatabaseException {
100         return DEFAULT_EXPECTED_EFFECT;
101     }
102     
103     private ExpressionEvaluator prepareEvaluator(final ReadGraph graph, final CompilationContext context, Type expectedType) throws DatabaseException {
104         final Variable contextVariable = new Variable("context", getContextVariableType());
105         LocalEnvironment localEnvironment = new AbstractLocalEnvironment() {
106             THashMap<String,Pair<Variable,Expression>> precalculatedVariables = new THashMap<String,Pair<Variable,Expression>>(); 
107             @Override
108             public Expression resolve(Environment environment, String localName) {
109                 Pair<Variable,Expression> precalculatedVariable = precalculatedVariables.get(localName);
110                 if(precalculatedVariable == null) {
111                     try {
112                         Expression value = getVariableAccessExpression(graph, context, contextVariable, localName);
113                         if(value == null)
114                             return null;
115                         Variable variable = new Variable(localName);
116                         precalculatedVariable = Pair.make(variable, value);
117                         precalculatedVariables.put(localName, precalculatedVariable);
118                     } catch (DatabaseException e) {
119                         throw new RuntimeDatabaseException(e);
120                     }
121                 }
122                 return new EVariable(precalculatedVariable.first);
123             }
124             @Override
125             public Expression preDecorateExpression(Expression expression) {
126                 for(Pair<Variable,Expression> precalculatedVariable : precalculatedVariables.values())
127                     expression = new ESimpleLet(precalculatedVariable.first, precalculatedVariable.second, expression);
128                 return expression;
129             }
130             @Override
131             protected Variable[] getContextVariables() {
132                 return new Variable[] { contextVariable };
133             }
134         };
135
136         String expressionText = getExpressionText(graph);
137         return new ExpressionEvaluator(context.runtimeEnvironment, expressionText)
138             .localEnvironment(localEnvironment)
139             .expectedType(expectedType)
140             .parseAsBlock(parseAsBlock());
141     }
142     
143     protected boolean parseAsBlock() {
144         return false;
145     }
146     
147     private Function1<EvaluationContext, Object> eval(ExpressionEvaluator evaluator, ReadGraph graph) throws DatabaseException {
148         Object oldGraph = SCLContext.getCurrent().put("graph", graph);
149         try {
150             return (Function1<EvaluationContext,Object>)evaluator.eval();
151         } catch(RuntimeDatabaseException e) {
152             e.printStackTrace();
153             if(e.getCause() instanceof DatabaseException)
154                 throw (DatabaseException)e.getCause();
155             else
156                 throw e;
157         } catch (SCLExpressionCompilationException e) {
158             StringBuilder b = new StringBuilder();
159             b.append("Couldn't compile '");
160             b.append(evaluator.getExpressionText());
161             b.append("':\n");
162             StringBuilder b2 = new StringBuilder();
163             for(CompilationError error : e.getErrors()) {
164                 b2.append(error.description);
165                 b2.append('\n');
166             }
167             System.err.println(b.toString() + b2.toString());
168             throw new SCLDatabaseException(b.toString()+b2.toString(), b2.toString(), e.getErrors());
169         } catch(Throwable e) {
170             // Should not happen!
171             e.printStackTrace();
172             throw new RuntimeException(e);
173         } finally {
174             SCLContext.getCurrent().put("graph", oldGraph);
175         }
176     }
177
178     public List<TCon> getExpressionEffects(final ReadGraph graph) throws DatabaseException {
179         CompilationContext context = getCompilationContext(graph);
180         Type type = Types.metaVar(Kinds.STAR);
181         eval(prepareEvaluator(graph, context, type), graph);
182
183         try {
184             MultiFunction mfun = Types.matchFunction(type, 1);
185             ArrayList<TCon> concreteEffects = new ArrayList<TCon>();
186             mfun.effect.collectConcreteEffects(concreteEffects);
187             return concreteEffects;
188         } catch(MatchException e) {
189             // Should not happen!
190             e.printStackTrace();
191             throw new RuntimeException(e);
192         }
193     }
194
195     @SuppressWarnings("unchecked")
196     @Override
197     public Function1<EvaluationContext,Object> perform(final ReadGraph graph) throws DatabaseException {
198         CompilationContext context = getCompilationContext(graph);
199         return eval(prepareEvaluator(graph, context, getExpectedType(graph, context)), graph);
200     }
201
202     protected static Expression getProperty(Environment environment, Expression variable, String propertyName, Type type) {
203         return new EApply(
204                 new EConstant(environment.getValue(FROM_DYNAMIC), type),
205                 new EApply(
206                         new EConstant(environment.getValue(PROPERTY_VALUE), Types.DYNAMIC),
207                         variable,
208                         new ELiteral(new StringConstant(propertyName))));
209     }
210
211     protected static Expression getPropertyFlexible(Environment environment, Expression variable, String propertyName, Type type) {
212         return makeTypeFlexible(environment, getProperty(environment, variable, propertyName, type), type);
213     }
214
215     protected static Expression makeTypeFlexible(Environment environment, Expression base, Type originalType) {
216         if(originalType.equals(Types.DOUBLE))
217             return new EApply(
218                     new EConstant(environment.getValue(FROM_DOUBLE)),
219                     base);
220         else if(originalType.equals(Types.FLOAT))
221             return new EApply(
222                     new EConstant(environment.getValue(FROM_DOUBLE)),
223                     new EApply(
224                             new EConstant(environment.getValue(TO_DOUBLE), Types.FLOAT),
225                             base));
226         else
227             return base;
228     }
229     
230     protected static String resolveExpectedValueType(ReadGraph graph, Resource predicate) throws DatabaseException {
231         Layer0 L0 = Layer0.getInstance(graph);
232         return graph.getPossibleRelatedValue(predicate, L0.RequiresValueType, Bindings.STRING);
233     }
234     
235 }