]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/scl/AbstractExpressionCompilationRequest.java
Fixed all line endings of the repository
[simantics/platform.git] / bundles / org.simantics.db.layer0 / src / org / simantics / db / layer0 / scl / AbstractExpressionCompilationRequest.java
index e830b7b8c40782c9289731237e053155ad93b5d3..f7b78278c513ba3c7a0b20b018ec46e2ea161738 100644 (file)
-package org.simantics.db.layer0.scl;\r
-\r
-import gnu.trove.map.hash.THashMap;\r
-\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-\r
-import org.simantics.db.ReadGraph;\r
-import org.simantics.db.exception.DatabaseException;\r
-import org.simantics.db.exception.RuntimeDatabaseException;\r
-import org.simantics.db.request.Read;\r
-import org.simantics.scl.compiler.common.names.Name;\r
-import org.simantics.scl.compiler.constants.StringConstant;\r
-import org.simantics.scl.compiler.elaboration.expressions.EApply;\r
-import org.simantics.scl.compiler.elaboration.expressions.EConstant;\r
-import org.simantics.scl.compiler.elaboration.expressions.ELiteral;\r
-import org.simantics.scl.compiler.elaboration.expressions.ESimpleLet;\r
-import org.simantics.scl.compiler.elaboration.expressions.EVariable;\r
-import org.simantics.scl.compiler.elaboration.expressions.Expression;\r
-import org.simantics.scl.compiler.elaboration.expressions.Variable;\r
-import org.simantics.scl.compiler.environment.AbstractLocalEnvironment;\r
-import org.simantics.scl.compiler.environment.Environment;\r
-import org.simantics.scl.compiler.environment.LocalEnvironment;\r
-import org.simantics.scl.compiler.errors.CompilationError;\r
-import org.simantics.scl.compiler.runtime.RuntimeEnvironment;\r
-import org.simantics.scl.compiler.top.ExpressionEvaluator;\r
-import org.simantics.scl.compiler.top.SCLExpressionCompilationException;\r
-import org.simantics.scl.compiler.types.TCon;\r
-import org.simantics.scl.compiler.types.Type;\r
-import org.simantics.scl.compiler.types.Types;\r
-import org.simantics.scl.compiler.types.exceptions.MatchException;\r
-import org.simantics.scl.compiler.types.kinds.Kinds;\r
-import org.simantics.scl.compiler.types.util.MultiFunction;\r
-import org.simantics.scl.runtime.SCLContext;\r
-import org.simantics.scl.runtime.function.Function1;\r
-import org.simantics.utils.datastructures.Pair;\r
-\r
-/**\r
- * <p>This is a base implementation for compiling expressions stored into \r
- * graph. It provides a skeleton and a set of methods that must be\r
- * implemented to get a concrete compilation request.\r
- * \r
- * <p>The request returns an SCL function with type {@code EvaluationContext -> Result}\r
- * where {@code EvaluationContext} is the type given by {@link #getContextVariableType()}\r
- * and {@code Result} is the type of the expression that can be optionally restricted\r
- * by {@link #getExpectedType(ReadGraph, AbstractExpressionCompilationContext)}.\r
- * \r
- * <p>Compilation calls {@link #getCompilationContext(ReadGraph)} to read all information\r
- * that is needed about the context of the resource during compilation. The result must\r
- * extend the type {@link AbstractExpressionCompilationContext} including at least information about \r
- * {@link RuntimeEnvironment}.\r
- * \r
- * <p>Compilation calls {@link #getVariableAccessExpression(ReadGraph, AbstractExpressionCompilationContext, Variable, String)}\r
- * to get access to local environment. The method may return null if the variable is not defined.\r
- * \r
- * @author Hannu Niemist&ouml;\r
- *\r
- * @param <Context>\r
- */\r
-public abstract class AbstractExpressionCompilationRequest<CompilationContext extends AbstractExpressionCompilationContext,EvaluationContext>\r
-implements Read<Function1<EvaluationContext,Object>> {\r
-\r
-    protected static final Type RESOURCE = Types.con("Simantics/DB", "Resource");\r
-    protected static final Type VARIABLE = Types.con("Simantics/Variables", "Variable");\r
-    protected static Name PROPERTY_VALUE = Name.create("Simantics/Variables", "propertyValue");\r
-    protected static Name VARIABLE_PARENT = Name.create("Simantics/Variables", "variableParent");\r
-    protected static Name FROM_DOUBLE = Name.create("Prelude", "fromDouble");\r
-    protected static Name TO_DOUBLE = Name.create("Prelude", "toDouble");\r
-    protected static Name FROM_DYNAMIC = Name.create("Prelude", "fromDynamic");\r
-\r
-    private static final Type DEFAULT_EXPECTED_EFFECT = Types.union(new Type[] {Types.PROC, Types.READ_GRAPH});\r
-\r
-    /**\r
-     * Returns the expression that will be compiled in textual form.\r
-     */\r
-    protected abstract String getExpressionText(ReadGraph graph) throws DatabaseException;\r
-    /**\r
-     * Returns the context that is used for the compilation of the expression. The context\r
-     * contains information about available constants and variables.\r
-     */\r
-    protected abstract CompilationContext getCompilationContext(ReadGraph graph) throws DatabaseException;\r
-    /**\r
-     * This should return the SCL type corresponding to generic type parameter {@code EvaluationContext}.\r
-     */\r
-    protected abstract Type getContextVariableType();\r
-    /**\r
-     * Returns <code>null</code>, if variable {@code name} is not defined.\r
-     */\r
-    protected abstract Expression getVariableAccessExpression(ReadGraph graph,\r
-            CompilationContext context, Variable contextVariable, String name) throws DatabaseException;\r
-\r
-    protected Type getExpectedType(ReadGraph graph, CompilationContext context) throws DatabaseException {\r
-        return Types.metaVar(Kinds.STAR);\r
-    }\r
-\r
-    protected Type getExpectedEffect(ReadGraph graph, CompilationContext context) throws DatabaseException {\r
-        return DEFAULT_EXPECTED_EFFECT;\r
-    }\r
-    \r
-    private ExpressionEvaluator prepareEvaluator(final ReadGraph graph, final CompilationContext context, Type expectedType) throws DatabaseException {\r
-        final Variable contextVariable = new Variable("context", getContextVariableType());\r
-        LocalEnvironment localEnvironment = new AbstractLocalEnvironment() {\r
-            THashMap<String,Pair<Variable,Expression>> precalculatedVariables = new THashMap<String,Pair<Variable,Expression>>(); \r
-            @Override\r
-            public Expression resolve(Environment environment, String localName) {\r
-                Pair<Variable,Expression> precalculatedVariable = precalculatedVariables.get(localName);\r
-                if(precalculatedVariable == null) {\r
-                    try {\r
-                        Expression value = getVariableAccessExpression(graph, context, contextVariable, localName);\r
-                        if(value == null)\r
-                            return null;\r
-                        Variable variable = new Variable(localName);\r
-                        precalculatedVariable = Pair.make(variable, value);\r
-                        precalculatedVariables.put(localName, precalculatedVariable);\r
-                    } catch (DatabaseException e) {\r
-                        throw new RuntimeDatabaseException(e);\r
-                    }\r
-                }\r
-                return new EVariable(precalculatedVariable.first);\r
-            }\r
-            @Override\r
-            public Expression preDecorateExpression(Expression expression) {\r
-                for(Pair<Variable,Expression> precalculatedVariable : precalculatedVariables.values())\r
-                    expression = new ESimpleLet(precalculatedVariable.first, precalculatedVariable.second, expression);\r
-                return expression;\r
-            }\r
-            @Override\r
-            protected Variable[] getContextVariables() {\r
-                return new Variable[] { contextVariable };\r
-            }\r
-        };\r
-\r
-        String expressionText = getExpressionText(graph);\r
-        return new ExpressionEvaluator(context.runtimeEnvironment, expressionText)\r
-            .localEnvironment(localEnvironment)\r
-            .expectedType(expectedType)\r
-            .parseAsBlock(parseAsBlock());\r
-    }\r
-    \r
-    protected boolean parseAsBlock() {\r
-        return false;\r
-    }\r
-    \r
-    private Function1<EvaluationContext, Object> eval(ExpressionEvaluator evaluator, ReadGraph graph) throws DatabaseException {\r
-        Object oldGraph = SCLContext.getCurrent().put("graph", graph);\r
-        try {\r
-            return (Function1<EvaluationContext,Object>)evaluator.eval();\r
-        } catch(RuntimeDatabaseException e) {\r
-            e.printStackTrace();\r
-            if(e.getCause() instanceof DatabaseException)\r
-                throw (DatabaseException)e.getCause();\r
-            else\r
-                throw e;\r
-        } catch (SCLExpressionCompilationException e) {\r
-            StringBuilder b = new StringBuilder();\r
-            b.append("Couldn't compile '");\r
-            b.append(evaluator.getExpressionText());\r
-            b.append("':\n");\r
-            StringBuilder b2 = new StringBuilder();\r
-            for(CompilationError error : e.getErrors()) {\r
-                b2.append(error.description);\r
-                b2.append('\n');\r
-            }\r
-            System.err.println(b.toString() + b2.toString());\r
-            throw new SCLDatabaseException(b.toString()+b2.toString(), b2.toString(), e.getErrors());\r
-        } catch(Throwable e) {\r
-            // Should not happen!\r
-            e.printStackTrace();\r
-            throw new RuntimeException(e);\r
-        } finally {\r
-            SCLContext.getCurrent().put("graph", oldGraph);\r
-        }\r
-    }\r
-\r
-    public List<TCon> getExpressionEffects(final ReadGraph graph) throws DatabaseException {\r
-        CompilationContext context = getCompilationContext(graph);\r
-        Type type = Types.metaVar(Kinds.STAR);\r
-        eval(prepareEvaluator(graph, context, type), graph);\r
-\r
-        try {\r
-            MultiFunction mfun = Types.matchFunction(type, 1);\r
-            ArrayList<TCon> concreteEffects = new ArrayList<TCon>();\r
-            mfun.effect.collectConcreteEffects(concreteEffects);\r
-            return concreteEffects;\r
-        } catch(MatchException e) {\r
-            // Should not happen!\r
-            e.printStackTrace();\r
-            throw new RuntimeException(e);\r
-        }\r
-    }\r
-\r
-    @SuppressWarnings("unchecked")\r
-    @Override\r
-    public Function1<EvaluationContext,Object> perform(final ReadGraph graph) throws DatabaseException {\r
-        CompilationContext context = getCompilationContext(graph);\r
-        return eval(prepareEvaluator(graph, context, getExpectedType(graph, context)), graph);\r
-    }\r
-\r
-    protected static Expression getProperty(Environment environment, Expression variable, String propertyName, Type type) {\r
-        return new EApply(\r
-                new EConstant(environment.getValue(FROM_DYNAMIC), type),\r
-                new EApply(\r
-                        new EConstant(environment.getValue(PROPERTY_VALUE), Types.DYNAMIC),\r
-                        variable,\r
-                        new ELiteral(new StringConstant(propertyName))));\r
-    }\r
-\r
-    protected static Expression getPropertyFlexible(Environment environment, Expression variable, String propertyName, Type type) {\r
-        return makeTypeFlexible(environment, getProperty(environment, variable, propertyName, type), type);\r
-    }\r
-\r
-    protected static Expression makeTypeFlexible(Environment environment, Expression base, Type originalType) {\r
-        if(originalType.equals(Types.DOUBLE))\r
-            return new EApply(\r
-                    new EConstant(environment.getValue(FROM_DOUBLE)),\r
-                    base);\r
-        else if(originalType.equals(Types.FLOAT))\r
-            return new EApply(\r
-                    new EConstant(environment.getValue(FROM_DOUBLE)),\r
-                    new EApply(\r
-                            new EConstant(environment.getValue(TO_DOUBLE), Types.FLOAT),\r
-                            base));\r
-        else\r
-            return base;\r
-    }\r
-}\r
+package org.simantics.db.layer0.scl;
+
+import gnu.trove.map.hash.THashMap;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.simantics.db.ReadGraph;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.exception.RuntimeDatabaseException;
+import org.simantics.db.request.Read;
+import org.simantics.scl.compiler.common.names.Name;
+import org.simantics.scl.compiler.constants.StringConstant;
+import org.simantics.scl.compiler.elaboration.expressions.EApply;
+import org.simantics.scl.compiler.elaboration.expressions.EConstant;
+import org.simantics.scl.compiler.elaboration.expressions.ELiteral;
+import org.simantics.scl.compiler.elaboration.expressions.ESimpleLet;
+import org.simantics.scl.compiler.elaboration.expressions.EVariable;
+import org.simantics.scl.compiler.elaboration.expressions.Expression;
+import org.simantics.scl.compiler.elaboration.expressions.Variable;
+import org.simantics.scl.compiler.environment.AbstractLocalEnvironment;
+import org.simantics.scl.compiler.environment.Environment;
+import org.simantics.scl.compiler.environment.LocalEnvironment;
+import org.simantics.scl.compiler.errors.CompilationError;
+import org.simantics.scl.compiler.runtime.RuntimeEnvironment;
+import org.simantics.scl.compiler.top.ExpressionEvaluator;
+import org.simantics.scl.compiler.top.SCLExpressionCompilationException;
+import org.simantics.scl.compiler.types.TCon;
+import org.simantics.scl.compiler.types.Type;
+import org.simantics.scl.compiler.types.Types;
+import org.simantics.scl.compiler.types.exceptions.MatchException;
+import org.simantics.scl.compiler.types.kinds.Kinds;
+import org.simantics.scl.compiler.types.util.MultiFunction;
+import org.simantics.scl.runtime.SCLContext;
+import org.simantics.scl.runtime.function.Function1;
+import org.simantics.utils.datastructures.Pair;
+
+/**
+ * <p>This is a base implementation for compiling expressions stored into 
+ * graph. It provides a skeleton and a set of methods that must be
+ * implemented to get a concrete compilation request.
+ * 
+ * <p>The request returns an SCL function with type {@code EvaluationContext -> Result}
+ * where {@code EvaluationContext} is the type given by {@link #getContextVariableType()}
+ * and {@code Result} is the type of the expression that can be optionally restricted
+ * by {@link #getExpectedType(ReadGraph, AbstractExpressionCompilationContext)}.
+ * 
+ * <p>Compilation calls {@link #getCompilationContext(ReadGraph)} to read all information
+ * that is needed about the context of the resource during compilation. The result must
+ * extend the type {@link AbstractExpressionCompilationContext} including at least information about 
+ * {@link RuntimeEnvironment}.
+ * 
+ * <p>Compilation calls {@link #getVariableAccessExpression(ReadGraph, AbstractExpressionCompilationContext, Variable, String)}
+ * to get access to local environment. The method may return null if the variable is not defined.
+ * 
+ * @author Hannu Niemist&ouml;
+ *
+ * @param <Context>
+ */
+public abstract class AbstractExpressionCompilationRequest<CompilationContext extends AbstractExpressionCompilationContext,EvaluationContext>
+implements Read<Function1<EvaluationContext,Object>> {
+
+    protected static final Type RESOURCE = Types.con("Simantics/DB", "Resource");
+    protected static final Type VARIABLE = Types.con("Simantics/Variables", "Variable");
+    protected static Name PROPERTY_VALUE = Name.create("Simantics/Variables", "propertyValue");
+    protected static Name VARIABLE_PARENT = Name.create("Simantics/Variables", "variableParent");
+    protected static Name FROM_DOUBLE = Name.create("Prelude", "fromDouble");
+    protected static Name TO_DOUBLE = Name.create("Prelude", "toDouble");
+    protected static Name FROM_DYNAMIC = Name.create("Prelude", "fromDynamic");
+
+    private static final Type DEFAULT_EXPECTED_EFFECT = Types.union(new Type[] {Types.PROC, Types.READ_GRAPH});
+
+    /**
+     * Returns the expression that will be compiled in textual form.
+     */
+    protected abstract String getExpressionText(ReadGraph graph) throws DatabaseException;
+    /**
+     * Returns the context that is used for the compilation of the expression. The context
+     * contains information about available constants and variables.
+     */
+    protected abstract CompilationContext getCompilationContext(ReadGraph graph) throws DatabaseException;
+    /**
+     * This should return the SCL type corresponding to generic type parameter {@code EvaluationContext}.
+     */
+    protected abstract Type getContextVariableType();
+    /**
+     * Returns <code>null</code>, if variable {@code name} is not defined.
+     */
+    protected abstract Expression getVariableAccessExpression(ReadGraph graph,
+            CompilationContext context, Variable contextVariable, String name) throws DatabaseException;
+
+    protected Type getExpectedType(ReadGraph graph, CompilationContext context) throws DatabaseException {
+        return Types.metaVar(Kinds.STAR);
+    }
+
+    protected Type getExpectedEffect(ReadGraph graph, CompilationContext context) throws DatabaseException {
+        return DEFAULT_EXPECTED_EFFECT;
+    }
+    
+    private ExpressionEvaluator prepareEvaluator(final ReadGraph graph, final CompilationContext context, Type expectedType) throws DatabaseException {
+        final Variable contextVariable = new Variable("context", getContextVariableType());
+        LocalEnvironment localEnvironment = new AbstractLocalEnvironment() {
+            THashMap<String,Pair<Variable,Expression>> precalculatedVariables = new THashMap<String,Pair<Variable,Expression>>(); 
+            @Override
+            public Expression resolve(Environment environment, String localName) {
+                Pair<Variable,Expression> precalculatedVariable = precalculatedVariables.get(localName);
+                if(precalculatedVariable == null) {
+                    try {
+                        Expression value = getVariableAccessExpression(graph, context, contextVariable, localName);
+                        if(value == null)
+                            return null;
+                        Variable variable = new Variable(localName);
+                        precalculatedVariable = Pair.make(variable, value);
+                        precalculatedVariables.put(localName, precalculatedVariable);
+                    } catch (DatabaseException e) {
+                        throw new RuntimeDatabaseException(e);
+                    }
+                }
+                return new EVariable(precalculatedVariable.first);
+            }
+            @Override
+            public Expression preDecorateExpression(Expression expression) {
+                for(Pair<Variable,Expression> precalculatedVariable : precalculatedVariables.values())
+                    expression = new ESimpleLet(precalculatedVariable.first, precalculatedVariable.second, expression);
+                return expression;
+            }
+            @Override
+            protected Variable[] getContextVariables() {
+                return new Variable[] { contextVariable };
+            }
+        };
+
+        String expressionText = getExpressionText(graph);
+        return new ExpressionEvaluator(context.runtimeEnvironment, expressionText)
+            .localEnvironment(localEnvironment)
+            .expectedType(expectedType)
+            .parseAsBlock(parseAsBlock());
+    }
+    
+    protected boolean parseAsBlock() {
+        return false;
+    }
+    
+    private Function1<EvaluationContext, Object> eval(ExpressionEvaluator evaluator, ReadGraph graph) throws DatabaseException {
+        Object oldGraph = SCLContext.getCurrent().put("graph", graph);
+        try {
+            return (Function1<EvaluationContext,Object>)evaluator.eval();
+        } catch(RuntimeDatabaseException e) {
+            e.printStackTrace();
+            if(e.getCause() instanceof DatabaseException)
+                throw (DatabaseException)e.getCause();
+            else
+                throw e;
+        } catch (SCLExpressionCompilationException e) {
+            StringBuilder b = new StringBuilder();
+            b.append("Couldn't compile '");
+            b.append(evaluator.getExpressionText());
+            b.append("':\n");
+            StringBuilder b2 = new StringBuilder();
+            for(CompilationError error : e.getErrors()) {
+                b2.append(error.description);
+                b2.append('\n');
+            }
+            System.err.println(b.toString() + b2.toString());
+            throw new SCLDatabaseException(b.toString()+b2.toString(), b2.toString(), e.getErrors());
+        } catch(Throwable e) {
+            // Should not happen!
+            e.printStackTrace();
+            throw new RuntimeException(e);
+        } finally {
+            SCLContext.getCurrent().put("graph", oldGraph);
+        }
+    }
+
+    public List<TCon> getExpressionEffects(final ReadGraph graph) throws DatabaseException {
+        CompilationContext context = getCompilationContext(graph);
+        Type type = Types.metaVar(Kinds.STAR);
+        eval(prepareEvaluator(graph, context, type), graph);
+
+        try {
+            MultiFunction mfun = Types.matchFunction(type, 1);
+            ArrayList<TCon> concreteEffects = new ArrayList<TCon>();
+            mfun.effect.collectConcreteEffects(concreteEffects);
+            return concreteEffects;
+        } catch(MatchException e) {
+            // Should not happen!
+            e.printStackTrace();
+            throw new RuntimeException(e);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public Function1<EvaluationContext,Object> perform(final ReadGraph graph) throws DatabaseException {
+        CompilationContext context = getCompilationContext(graph);
+        return eval(prepareEvaluator(graph, context, getExpectedType(graph, context)), graph);
+    }
+
+    protected static Expression getProperty(Environment environment, Expression variable, String propertyName, Type type) {
+        return new EApply(
+                new EConstant(environment.getValue(FROM_DYNAMIC), type),
+                new EApply(
+                        new EConstant(environment.getValue(PROPERTY_VALUE), Types.DYNAMIC),
+                        variable,
+                        new ELiteral(new StringConstant(propertyName))));
+    }
+
+    protected static Expression getPropertyFlexible(Environment environment, Expression variable, String propertyName, Type type) {
+        return makeTypeFlexible(environment, getProperty(environment, variable, propertyName, type), type);
+    }
+
+    protected static Expression makeTypeFlexible(Environment environment, Expression base, Type originalType) {
+        if(originalType.equals(Types.DOUBLE))
+            return new EApply(
+                    new EConstant(environment.getValue(FROM_DOUBLE)),
+                    base);
+        else if(originalType.equals(Types.FLOAT))
+            return new EApply(
+                    new EConstant(environment.getValue(FROM_DOUBLE)),
+                    new EApply(
+                            new EConstant(environment.getValue(TO_DOUBLE), Types.FLOAT),
+                            base));
+        else
+            return base;
+    }
+}