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