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