]> gerrit.simantics Code Review - simantics/platform.git/blob
3a95f25304f78248cde70c51fdd4eb127ff39d9c
[simantics/platform.git] /
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     private 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     @SuppressWarnings("unchecked")
152     private Function1<EvaluationContext, Object> eval(ExpressionEvaluator evaluator, ReadGraph graph) throws DatabaseException {
153         Object oldGraph = SCLContext.getCurrent().put("graph", graph);
154         try {
155             return (Function1<EvaluationContext,Object>)evaluator.eval();
156         } catch(RuntimeDatabaseException e) {
157             LOGGER.error("Failed to evaluate SCL expression", e);
158             if(e.getCause() instanceof DatabaseException)
159                 throw (DatabaseException)e.getCause();
160             else
161                 throw e;
162         } catch (SCLExpressionCompilationException e) {
163             StringBuilder b = new StringBuilder();
164             b.append("Couldn't compile '");
165             b.append(evaluator.getExpressionText());
166             b.append("':\n");
167             StringBuilder b2 = new StringBuilder();
168             for(CompilationError error : e.getErrors()) {
169                 b2.append(error.description);
170                 b2.append('\n');
171             }
172             System.err.println(b.toString() + b2.toString());
173             throw new SCLDatabaseException(b.toString()+b2.toString(), b2.toString(), e.getErrors());
174         } catch(Throwable e) {
175             // Should not happen!
176             LOGGER.error("This error should never happen", e);
177             throw new RuntimeException(e);
178         } finally {
179             SCLContext.getCurrent().put("graph", oldGraph);
180         }
181     }
182
183     public List<TCon> getExpressionEffects(final ReadGraph graph) throws DatabaseException {
184         CompilationContext context = getCompilationContext(graph);
185         Type type = Types.metaVar(Kinds.STAR);
186         eval(prepareEvaluator(graph, context, type), graph);
187
188         try {
189             MultiFunction mfun = Types.matchFunction(type, 1);
190             ArrayList<TCon> concreteEffects = new ArrayList<TCon>();
191             mfun.effect.collectConcreteEffects(concreteEffects);
192             return concreteEffects;
193         } catch(MatchException e) {
194             // Should not happen!
195             LOGGER.error("Failed to get expression effects", e);
196             throw new RuntimeException(e);
197         }
198     }
199
200     @Override
201     public Function1<EvaluationContext,Object> perform(final ReadGraph graph) throws DatabaseException {
202         CompilationContext context = getCompilationContext(graph);
203         return eval(prepareEvaluator(graph, context, getExpectedType(graph, context)), graph);
204     }
205
206     protected static Expression getProperty(Environment environment, Expression variable, String propertyName, Type type) {
207         return new EApply(
208                 new EConstant(environment.getValue(FROM_DYNAMIC), type),
209                 new EApply(
210                         new EConstant(environment.getValue(PROPERTY_VALUE), Types.DYNAMIC),
211                         variable,
212                         new ELiteral(new StringConstant(propertyName))));
213     }
214
215     protected static Expression getPropertyFlexible(Environment environment, Expression variable, String propertyName, Type type) {
216         return makeTypeFlexible(environment, getProperty(environment, variable, propertyName, type), type);
217     }
218
219     protected static Expression makeTypeFlexible(Environment environment, Expression base, Type originalType) {
220         if(originalType.equals(Types.DOUBLE))
221             return new EApply(
222                     new EConstant(environment.getValue(FROM_DOUBLE)),
223                     base);
224         else if(originalType.equals(Types.FLOAT))
225             return new EApply(
226                     new EConstant(environment.getValue(FROM_DOUBLE)),
227                     new EApply(
228                             new EConstant(environment.getValue(TO_DOUBLE), Types.FLOAT),
229                             base));
230         else
231             return base;
232     }
233
234     protected static String resolveExpectedValueType(ReadGraph graph, Resource predicate) throws DatabaseException {
235         Layer0 L0 = Layer0.getInstance(graph);
236         return graph.getPossibleRelatedValue(predicate, L0.RequiresValueType, Bindings.STRING);
237     }
238
239 }