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() {
152 * Override this to provide location information in compilation error situations.
154 protected String getContextDescription(ReadGraph graph) throws DatabaseException {
158 @SuppressWarnings("unchecked")
159 private Function1<EvaluationContext, Object> eval(ExpressionEvaluator evaluator, ReadGraph graph) throws DatabaseException {
160 Object oldGraph = SCLContext.getCurrent().put("graph", graph);
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();
169 } catch (SCLExpressionCompilationException e) {
170 StringBuilder b = new StringBuilder();
171 b.append("Couldn't compile '");
172 b.append(evaluator.getExpressionText());
174 b.append(getContextDescription(graph));
176 StringBuilder b2 = new StringBuilder();
177 for(CompilationError error : e.getErrors()) {
178 b2.append(error.description);
181 SCLDatabaseException exception = new SCLDatabaseException(b.toString()+b2.toString(), b2.toString(), e.getErrors());
182 LOGGER.info(exception.getMessage(), exception);
184 } catch(Throwable e) {
185 // Should not happen!
186 LOGGER.error("This error should never happen", e);
187 throw new RuntimeException(e);
189 SCLContext.getCurrent().put("graph", oldGraph);
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);
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);
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);
216 protected static Expression getProperty(Environment environment, Expression variable, String propertyName, Type type) {
218 new EConstant(environment.getValue(FROM_DYNAMIC), type),
220 new EConstant(environment.getValue(PROPERTY_VALUE), Types.DYNAMIC),
222 new ELiteral(new StringConstant(propertyName))));
225 protected static Expression getPropertyFlexible(Environment environment, Expression variable, String propertyName, Type type) {
226 return makeTypeFlexible(environment, getProperty(environment, variable, propertyName, type), type);
229 protected static Expression makeTypeFlexible(Environment environment, Expression base, Type originalType) {
230 if(originalType.equals(Types.DOUBLE))
232 new EConstant(environment.getValue(FROM_DOUBLE)),
234 else if(originalType.equals(Types.FLOAT))
236 new EConstant(environment.getValue(FROM_DOUBLE)),
238 new EConstant(environment.getValue(TO_DOUBLE), Types.FLOAT),
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);
250 public abstract int hashCode();
253 public abstract boolean equals(Object obj);