]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.document.server/src/org/simantics/document/server/request/ServerSCLValueRequest.java
Improved environment resolution for document SCL expressions
[simantics/platform.git] / bundles / org.simantics.document.server / src / org / simantics / document / server / request / ServerSCLValueRequest.java
1 package org.simantics.document.server.request;
2
3 import java.util.Collections;
4 import java.util.Map;
5
6 import org.simantics.databoard.Bindings;
7 import org.simantics.db.ReadGraph;
8 import org.simantics.db.Resource;
9 import org.simantics.db.Statement;
10 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
11 import org.simantics.db.common.request.IndexRoot;
12 import org.simantics.db.common.request.UnaryRead;
13 import org.simantics.db.common.utils.NameUtils;
14 import org.simantics.db.exception.DatabaseException;
15 import org.simantics.db.layer0.scl.AbstractExpressionCompilationContext;
16 import org.simantics.db.layer0.util.RuntimeEnvironmentRequest2;
17 import org.simantics.db.layer0.variable.Variable;
18 import org.simantics.layer0.Layer0;
19 import org.simantics.scl.compiler.common.names.Name;
20 import org.simantics.scl.compiler.constants.StringConstant;
21 import org.simantics.scl.compiler.elaboration.expressions.EApply;
22 import org.simantics.scl.compiler.elaboration.expressions.EConstant;
23 import org.simantics.scl.compiler.elaboration.expressions.ELiteral;
24 import org.simantics.scl.compiler.elaboration.expressions.EVariable;
25 import org.simantics.scl.compiler.elaboration.expressions.Expression;
26 import org.simantics.scl.compiler.elaboration.modules.SCLValue;
27 import org.simantics.scl.compiler.environment.Environment;
28 import org.simantics.scl.compiler.environment.Environments;
29 import org.simantics.scl.compiler.environment.specification.EnvironmentSpecification;
30 import org.simantics.scl.compiler.runtime.RuntimeEnvironment;
31 import org.simantics.scl.compiler.top.SCLExpressionCompilationException;
32 import org.simantics.scl.compiler.types.Type;
33 import org.simantics.scl.compiler.types.Types;
34 import org.simantics.scl.compiler.types.kinds.Kinds;
35 import org.simantics.scl.runtime.SCLContext;
36 import org.simantics.scl.runtime.function.Function1;
37 import org.simantics.structural2.scl.ComponentTypeProperty;
38 import org.simantics.structural2.scl.FindPossibleComponentTypeRequest;
39 import org.simantics.structural2.scl.ReadComponentTypeInterfaceRequest;
40 import org.simantics.utils.datastructures.Pair;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 public class ServerSCLValueRequest extends ServerSCLValueRequestBase<org.simantics.document.server.request.ServerSCLValueRequest.CompilationContext> {
45
46         private final Pair<Resource,Resource> componentTypeAndRoot;
47         private final Resource literal;
48     protected String possibleExpectedValueType;
49
50         public static class CompilationContext extends AbstractExpressionCompilationContext {
51                 public final Map<String, ComponentTypeProperty> propertyMap;
52
53                 public CompilationContext(RuntimeEnvironment runtimeEnvironment,
54                                 Map<String, ComponentTypeProperty> propertyMap) {
55                         super(runtimeEnvironment);
56                         this.propertyMap = propertyMap;
57                 }
58         }
59
60         private ServerSCLValueRequest(Pair<Resource,Resource> componentTypeAndRoot, Resource literal, String possibleExpectedValueType) {
61                 assert(literal != null);
62                 this.literal = literal;
63                 this.componentTypeAndRoot = componentTypeAndRoot;
64                 this.possibleExpectedValueType = possibleExpectedValueType;
65         }
66
67         public ServerSCLValueRequest(ReadGraph graph, Variable context) throws DatabaseException {
68                 this(getComponentTypeAndRoot(graph, context), context.getRepresents(graph), resolveExpectedValueType(graph, context.getPredicateResource(graph)));
69         }
70
71         public ServerSCLValueRequest(ReadGraph graph, Resource s, Resource o, Resource p) throws DatabaseException {
72             this(getComponentTypeAndRoot(graph, s, o), o, resolveExpectedValueType(graph, p));
73         }
74
75         private static Pair<Resource,Resource> getComponentTypeAndRoot(ReadGraph graph, Variable property)  throws DatabaseException {
76                 Variable parent = property.getParent(graph);
77                 Resource represents = parent.getRepresents(graph);
78                 if(represents != null) {
79                         Resource type = graph.syncRequest(new FindPossibleComponentTypeRequest(represents));
80                         if(type != null) {
81                                 Resource root = graph.syncRequest(new IndexRoot(type));
82                                 return Pair.make(type, root);
83                         }
84                 }
85                 parent = parent.getParent(graph);
86                 Resource root = graph.syncRequest(new IndexRoot(property.getRepresents(graph)));
87                 return Pair.make(parent.getType(graph), root);
88         }
89
90         public static Object compileAndEvaluate(ReadGraph graph, Variable context) throws DatabaseException {
91                 SCLContext sclContext = SCLContext.getCurrent();
92                 Object oldGraph = sclContext.get("graph");
93                 try {
94                         Function1<Object,Object> exp = compile(graph, context);
95                         sclContext.put("graph", graph);
96                         return exp.apply(context);
97                 } catch (DatabaseException e) {
98                         throw (DatabaseException)e;
99                 } catch (Throwable t) {
100                         throw new DatabaseException(t);
101                 } finally {
102                         sclContext.put("graph", oldGraph);
103                 }
104         }
105
106         public static Function1<Object, Object> compile(ReadGraph graph, Variable context) throws DatabaseException {
107                 return graph.syncRequest(new ServerSCLValueRequest(graph, context), TransientCacheListener.instance());
108         }
109
110         public static Function1<Object, Object> compile(ReadGraph graph, Resource s, Resource o, Resource p) throws DatabaseException {
111                 return graph.syncRequest(new ServerSCLValueRequest(graph, s, o, p), TransientCacheListener.instance());
112         }
113
114         @Override
115         protected String getExpressionText(ReadGraph graph)
116                         throws DatabaseException {
117                 Layer0 L0 = Layer0.getInstance(graph);
118                 return graph.getRelatedValue(literal, L0.SCLValue_expression, Bindings.STRING);
119         }
120
121         protected RuntimeEnvironmentRequest2 getRuntimeEnvironmentRequest(Resource componentType, Resource indexRoot) {
122                 return new RuntimeEnvironmentRequest2(componentType, indexRoot) {
123                         @Override
124                         protected void fillEnvironmentSpecification(
125                                         EnvironmentSpecification environmentSpecification) {
126                         }
127                 };
128         }
129
130         @Override
131         protected CompilationContext getCompilationContext(ReadGraph graph)
132                         throws DatabaseException {
133                 return graph.syncRequest(new UnaryRead<Pair<Resource,Resource>,CompilationContext>(componentTypeAndRoot) {
134                         @Override
135                         public CompilationContext perform(ReadGraph graph)
136                                         throws DatabaseException {
137                                 RuntimeEnvironment runtimeEnvironment = graph.syncRequest(getRuntimeEnvironmentRequest(parameter.first, parameter.second));
138                                 Map<String, ComponentTypeProperty> propertyMap;
139                                 if (parameter.first != null) {
140                                     propertyMap =
141                                                 graph.syncRequest(new ReadComponentTypeInterfaceRequest(parameter.first, runtimeEnvironment.getEnvironment()),
142                                                                 TransientCacheListener.<Map<String, ComponentTypeProperty>>instance());
143                                 } else {
144                                     // TODO: Antti to consider
145                                     // To handle procedural user components
146                                     propertyMap = Collections.emptyMap();
147                                 }
148                                 return new CompilationContext(runtimeEnvironment, propertyMap);
149                         }
150                 });
151         }
152
153         @Override
154         protected Type getContextVariableType() {
155                 return VARIABLE; 
156         }
157
158         private static Expression accessInputVariable(Environment environment,
159                         org.simantics.scl.compiler.elaboration.expressions.Variable contextVariable) {
160                 SCLValue variableParentFunction = environment.getValue(VARIABLE_PARENT);
161                 return new EApply(new EConstant(variableParentFunction),
162                                 new EApply(new EConstant(variableParentFunction),
163                                                 new EVariable(contextVariable)));
164         }
165
166     protected static Name PROPERTY_VALUE_CACHED = Name.create("Document/All", "propertyValueCached");
167
168     protected static Expression getProperty(Environment environment, Expression variable, String propertyName, Type type) {
169         return new EApply(
170                 new EConstant(environment.getValue(FROM_DYNAMIC), type),
171                 new EApply(
172                         new EConstant(environment.getValue(PROPERTY_VALUE_CACHED), Types.DYNAMIC),
173                         variable,
174                         new ELiteral(new StringConstant(propertyName))));
175     }
176     
177     protected static Expression getPropertyFlexible(Environment environment, Expression variable, String propertyName, Type type) {
178         return makeTypeFlexible(environment, getProperty(environment, variable, propertyName, type), type);
179     }
180         
181         protected static Expression standardGetProperty(
182                         Environment environment,
183                         org.simantics.scl.compiler.elaboration.expressions.Variable contextVariable,
184                         String name,
185                         Type type) {
186                 return getPropertyFlexible(environment, accessInputVariable(environment, contextVariable), name, type);
187         }
188
189
190         @Override
191         protected Expression getVariableAccessExpression(
192                         ReadGraph graph,
193                         CompilationContext context,
194                         org.simantics.scl.compiler.elaboration.expressions.Variable contextVariable,
195                         String name) throws DatabaseException {
196                 ComponentTypeProperty property = context.propertyMap.get(name);
197                 if(property != null)
198                         return standardGetProperty(
199                                         context.runtimeEnvironment.getEnvironment(),
200                                         contextVariable,
201                                         name,
202                                         property.type == null ? Types.metaVar(Kinds.STAR) : property.type);
203                 else
204                         return getSpecialVariableAccessExpression(graph, context, contextVariable, name);
205         }
206
207         protected Expression getSpecialVariableAccessExpression(ReadGraph graph,
208                         CompilationContext context,
209                         org.simantics.scl.compiler.elaboration.expressions.Variable contextVariable,
210                         String name) throws DatabaseException {
211                 if(name.equals("input")) {
212                         Environment environment = context.runtimeEnvironment.getEnvironment();
213                         return accessInputVariable(environment, contextVariable);
214                 }
215                 else if(name.equals("self"))
216                         return new EVariable(contextVariable);
217                 else
218                         return null;
219         }
220         
221     @Override
222     protected Type getExpectedType(ReadGraph graph, CompilationContext context) throws DatabaseException {
223         return super.getExpectedType(graph, context);
224     }
225
226
227         @Override
228         public int hashCode() {
229                 return 31*(31*getClass().hashCode() + literal.hashCode()) + componentTypeAndRoot.hashCode();
230         }
231
232         @Override
233         public boolean equals(Object obj) {
234                 if(this == obj)
235                         return true;
236                 if(obj == null || obj.getClass() != getClass())
237                         return false;
238                 ServerSCLValueRequest other = (ServerSCLValueRequest)obj;
239                 return literal.equals(other.literal) && componentTypeAndRoot.equals(other.componentTypeAndRoot);
240         }
241
242     public static Function1<Object, Object> validate(ReadGraph graph, Variable context) throws DatabaseException {
243         return graph.syncRequest(new ServerSCLValueValidationRequest(graph, context), TransientCacheListener.instance());
244     }
245
246     @Override
247     protected String getContextDescription(ReadGraph graph) throws DatabaseException {
248         Layer0 L0 = Layer0.getInstance(graph);
249         Statement possibleOwner = graph.getPossibleStatement(literal, L0.IsOwnedBy);
250         if(possibleOwner != null) {
251             String uri = graph.getPossibleURI(possibleOwner.getObject());
252             if(uri != null) {
253                 String propertyName = NameUtils.getSafeName(graph, graph.getInverse(possibleOwner.getPredicate()));
254                 return uri + "#" + propertyName;
255             }
256         }
257         return super.getContextDescription(graph);
258     }
259     
260     public static class ServerSCLValueValidationRequest extends ServerSCLValueRequest {
261
262         private static final Logger LOGGER = LoggerFactory.getLogger(ServerSCLHandlerValueRequest.class);
263
264         public ServerSCLValueValidationRequest(ReadGraph graph, Variable context) throws DatabaseException {
265             super(graph, context);
266         }
267
268         @Override
269         protected Type getExpectedType(ReadGraph graph, CompilationContext context) throws DatabaseException {
270             if(possibleExpectedValueType != null) {
271                 try {
272                     return Environments.getType(context.runtimeEnvironment.getEnvironment(), possibleExpectedValueType);
273                 } catch (SCLExpressionCompilationException e) {
274                     LOGGER.error("Could not get type for " + String.valueOf(possibleExpectedValueType), e);
275                 }
276             }
277             return super.getExpectedType(graph, context);
278         }
279     }
280 }