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