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