1 package org.simantics.db.layer0.scl;
3 import java.util.ArrayList;
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;
41 import gnu.trove.map.hash.THashMap;
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.
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)}.
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}.
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.
61 * @author Hannu Niemistö
65 public abstract class AbstractExpressionCompilationRequest<CompilationContext extends AbstractExpressionCompilationContext,EvaluationContext>
66 implements Read<Function1<EvaluationContext,Object>> {
68 private static final Logger LOGGER = LoggerFactory.getLogger(AbstractExpressionCompilationRequest.class);
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");
78 private static final Type DEFAULT_EXPECTED_EFFECT = Types.union(new Type[] {Types.PROC, Types.READ_GRAPH});
81 * Returns the expression that will be compiled in textual form.
83 protected abstract String getExpressionText(ReadGraph graph) throws DatabaseException;
85 * Returns the context that is used for the compilation of the expression. The context
86 * contains information about available constants and variables.
88 protected abstract CompilationContext getCompilationContext(ReadGraph graph) throws DatabaseException;
90 * This should return the SCL type corresponding to generic type parameter {@code EvaluationContext}.
92 protected abstract Type getContextVariableType();
94 * Returns <code>null</code>, if variable {@code name} is not defined.
96 protected abstract Expression getVariableAccessExpression(ReadGraph graph,
97 CompilationContext context, Variable contextVariable, String name) throws DatabaseException;
99 protected Type getExpectedType(ReadGraph graph, CompilationContext context) throws DatabaseException {
100 return Types.metaVar(Kinds.STAR);
103 protected Type getExpectedEffect(ReadGraph graph, CompilationContext context) throws DatabaseException {
104 return DEFAULT_EXPECTED_EFFECT;
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>>();
112 public Expression resolve(Environment environment, String localName) {
113 Pair<Variable,Expression> precalculatedVariable = precalculatedVariables.get(localName);
114 if(precalculatedVariable == null) {
116 Expression value = getVariableAccessExpression(graph, context, contextVariable, localName);
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);
126 return new EVariable(precalculatedVariable.first);
129 public Expression preDecorateExpression(Expression expression) {
130 for(Pair<Variable,Expression> precalculatedVariable : precalculatedVariables.values())
131 expression = new ESimpleLet(precalculatedVariable.first, precalculatedVariable.second, expression);
135 protected Variable[] getContextVariables() {
136 return new Variable[] { contextVariable };
140 String expressionText = getExpressionText(graph);
141 return new ExpressionEvaluator(context.runtimeEnvironment, expressionText)
142 .localEnvironment(localEnvironment)
143 .expectedType(expectedType)
144 .parseAsBlock(parseAsBlock());
147 protected boolean parseAsBlock() {
151 @SuppressWarnings("unchecked")
152 private Function1<EvaluationContext, Object> eval(ExpressionEvaluator evaluator, ReadGraph graph) throws DatabaseException {
153 Object oldGraph = SCLContext.getCurrent().put("graph", graph);
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();
162 } catch (SCLExpressionCompilationException e) {
163 StringBuilder b = new StringBuilder();
164 b.append("Couldn't compile '");
165 b.append(evaluator.getExpressionText());
167 StringBuilder b2 = new StringBuilder();
168 for(CompilationError error : e.getErrors()) {
169 b2.append(error.description);
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);
179 SCLContext.getCurrent().put("graph", oldGraph);
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);
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);
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);
206 protected static Expression getProperty(Environment environment, Expression variable, String propertyName, Type type) {
208 new EConstant(environment.getValue(FROM_DYNAMIC), type),
210 new EConstant(environment.getValue(PROPERTY_VALUE), Types.DYNAMIC),
212 new ELiteral(new StringConstant(propertyName))));
215 protected static Expression getPropertyFlexible(Environment environment, Expression variable, String propertyName, Type type) {
216 return makeTypeFlexible(environment, getProperty(environment, variable, propertyName, type), type);
219 protected static Expression makeTypeFlexible(Environment environment, Expression base, Type originalType) {
220 if(originalType.equals(Types.DOUBLE))
222 new EConstant(environment.getValue(FROM_DOUBLE)),
224 else if(originalType.equals(Types.FLOAT))
226 new EConstant(environment.getValue(FROM_DOUBLE)),
228 new EConstant(environment.getValue(TO_DOUBLE), Types.FLOAT),
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);
240 public abstract int hashCode();
243 public abstract boolean equals(Object obj);