1 package org.simantics.db.layer0.scl;
3 import java.util.ArrayList;
4 import java.util.Collections;
7 import org.simantics.databoard.Bindings;
8 import org.simantics.db.ReadGraph;
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;
39 import gnu.trove.map.hash.THashMap;
42 * <p>This is a base implementation for compiling expressions stored into
43 * graph. It provides a skeleton and a set of methods that must be
44 * implemented to get a concrete compilation request.
46 * <p>The request returns an SCL function with type {@code EvaluationContext -> Result}
47 * where {@code EvaluationContext} is the type given by {@link #getContextVariableType()}
48 * and {@code Result} is the type of the expression that can be optionally restricted
49 * by {@link #getExpectedType(ReadGraph, AbstractExpressionCompilationContext)}.
51 * <p>Compilation calls {@link #getCompilationContext(ReadGraph)} to read all information
52 * that is needed about the context of the resource during compilation. The result must
53 * extend the type {@link AbstractExpressionCompilationContext} including at least information about
54 * {@link RuntimeEnvironment}.
56 * <p>Compilation calls {@link #getVariableAccessExpression(ReadGraph, AbstractExpressionCompilationContext, Variable, String)}
57 * to get access to local environment. The method may return null if the variable is not defined.
59 * @author Hannu Niemistö
63 public abstract class AbstractExpressionAnalysisRequest<CompilationContext extends AbstractExpressionCompilationContext,EvaluationContext>
64 implements Read<ExpressionAnalysis<EvaluationContext>> {
66 protected static final Type RESOURCE = Types.con("Simantics/DB", "Resource");
67 protected static final Type VARIABLE = Types.con("Simantics/Variables", "Variable");
68 protected static Name PROPERTY_VALUE = Name.create("Simantics/Variables", "propertyValue");
69 protected static Name VARIABLE_PARENT = Name.create("Simantics/Variables", "variableParent");
70 protected static Name FROM_DOUBLE = Name.create("Prelude", "fromDouble");
71 protected static Name TO_DOUBLE = Name.create("Prelude", "toDouble");
72 protected static Name FROM_DYNAMIC = Name.create("Prelude", "fromDynamic");
74 private static final Type DEFAULT_EXPECTED_EFFECT = Types.union(new Type[] {Types.PROC, Types.READ_GRAPH});
77 * Returns the expression that will be compiled in textual form.
79 protected abstract String getExpressionText(ReadGraph graph) throws DatabaseException;
81 * Returns the context that is used for the compilation of the expression. The context
82 * contains information about available constants and variables.
84 protected abstract CompilationContext getCompilationContext(ReadGraph graph) throws DatabaseException;
86 * This should return the SCL type corresponding to generic type parameter {@code EvaluationContext}.
88 protected abstract Type getContextVariableType();
90 * Returns <code>null</code>, if variable {@code name} is not defined.
92 protected abstract Expression getVariableAccessExpression(ReadGraph graph,
93 CompilationContext context, Variable contextVariable, String name) throws DatabaseException;
95 protected Type getExpectedType(ReadGraph graph, CompilationContext context) throws DatabaseException {
96 return Types.metaVar(Kinds.STAR);
99 protected Type getExpectedEffect(ReadGraph graph, CompilationContext context) throws DatabaseException {
100 return DEFAULT_EXPECTED_EFFECT;
103 private ExpressionEvaluator prepareEvaluator(final ReadGraph graph, final CompilationContext context, Type expectedType) throws DatabaseException {
104 final Variable contextVariable = new Variable("context", getContextVariableType());
105 LocalEnvironment localEnvironment = new AbstractLocalEnvironment() {
106 THashMap<String,Pair<Variable,Expression>> precalculatedVariables = new THashMap<String,Pair<Variable,Expression>>();
108 public Expression resolve(Environment environment, String localName) {
109 Pair<Variable,Expression> precalculatedVariable = precalculatedVariables.get(localName);
110 if(precalculatedVariable == null) {
112 Expression value = getVariableAccessExpression(graph, context, contextVariable, localName);
115 Variable variable = new Variable(localName);
116 precalculatedVariable = Pair.make(variable, value);
117 precalculatedVariables.put(localName, precalculatedVariable);
118 } catch (DatabaseException e) {
119 throw new RuntimeDatabaseException(e);
122 return new EVariable(precalculatedVariable.first);
125 public Expression preDecorateExpression(Expression expression) {
126 for(Pair<Variable,Expression> precalculatedVariable : precalculatedVariables.values())
127 expression = new ESimpleLet(precalculatedVariable.first, precalculatedVariable.second, expression);
131 protected Variable[] getContextVariables() {
132 return new Variable[] { contextVariable };
136 String expressionText = getExpressionText(graph);
137 return new ExpressionEvaluator(context.runtimeEnvironment, expressionText)
138 .localEnvironment(localEnvironment)
139 .expectedType(expectedType)
140 .parseAsBlock(parseAsBlock());
143 protected boolean parseAsBlock() {
147 private Function1<EvaluationContext, Object> eval(ExpressionEvaluator evaluator, ReadGraph graph) throws DatabaseException {
148 Object oldGraph = SCLContext.getCurrent().put("graph", graph);
150 return (Function1<EvaluationContext,Object>)evaluator.eval();
151 } catch(RuntimeDatabaseException e) {
153 if(e.getCause() instanceof DatabaseException)
154 throw (DatabaseException)e.getCause();
157 } catch (SCLExpressionCompilationException e) {
158 StringBuilder b = new StringBuilder();
159 b.append("Couldn't compile '");
160 b.append(evaluator.getExpressionText());
162 StringBuilder b2 = new StringBuilder();
163 for(CompilationError error : e.getErrors()) {
164 b2.append(error.description);
167 System.err.println(b.toString() + b2.toString());
168 throw new SCLDatabaseException(b.toString()+b2.toString(), b2.toString(), e.getErrors());
169 } catch(Throwable e) {
170 // Should not happen!
172 throw new RuntimeException(e);
174 SCLContext.getCurrent().put("graph", oldGraph);
178 public List<TCon> getExpressionEffects(final ReadGraph graph) throws DatabaseException {
179 CompilationContext context = getCompilationContext(graph);
180 Type type = Types.metaVar(Kinds.STAR);
181 eval(prepareEvaluator(graph, context, type), graph);
184 MultiFunction mfun = Types.matchFunction(type, 1);
185 ArrayList<TCon> concreteEffects = new ArrayList<TCon>();
186 mfun.effect.collectConcreteEffects(concreteEffects);
187 return concreteEffects;
188 } catch(MatchException e) {
189 // Should not happen!
191 throw new RuntimeException(e);
195 @SuppressWarnings("unchecked")
197 public ExpressionAnalysis<EvaluationContext> perform(final ReadGraph graph) throws DatabaseException {
198 CompilationContext context = getCompilationContext(graph);
199 Function1<EvaluationContext,Object> fn = eval(prepareEvaluator(graph, context, getExpectedType(graph, context)), graph);
200 return getAnalysis(context, fn);
203 protected ExpressionAnalysis<EvaluationContext> getAnalysis(CompilationContext context, Function1<EvaluationContext,Object> fn) {
204 return new ExpressionAnalysis(fn, Collections.emptySet());
207 protected static Expression getProperty(Environment environment, Expression variable, String propertyName, Type type) {
209 new EConstant(environment.getValue(FROM_DYNAMIC), type),
211 new EConstant(environment.getValue(PROPERTY_VALUE), Types.DYNAMIC),
213 new ELiteral(new StringConstant(propertyName))));
216 protected static Expression getPropertyFlexible(Environment environment, Expression variable, String propertyName, Type type) {
217 return makeTypeFlexible(environment, getProperty(environment, variable, propertyName, type), type);
220 protected static Expression makeTypeFlexible(Environment environment, Expression base, Type originalType) {
221 if(originalType.equals(Types.DOUBLE))
223 new EConstant(environment.getValue(FROM_DOUBLE)),
225 else if(originalType.equals(Types.FLOAT))
227 new EConstant(environment.getValue(FROM_DOUBLE)),
229 new EConstant(environment.getValue(TO_DOUBLE), Types.FLOAT),
235 protected static String resolveExpectedValueType(ReadGraph graph, org.simantics.db.layer0.variable.Variable context) throws DatabaseException {
236 Layer0 L0 = Layer0.getInstance(graph);
237 String valueType = graph.getPossibleRelatedValue(context.getPredicateResource(graph), L0.RequiresValueType, Bindings.STRING);