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