]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.commands/src/org/simantics/scl/commands/internal/StringConverterFactory.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.scl.commands / src / org / simantics / scl / commands / internal / StringConverterFactory.java
1 package org.simantics.scl.commands.internal;\r
2 \r
3 import java.util.concurrent.ConcurrentHashMap;\r
4 \r
5 import org.simantics.db.Resource;\r
6 import org.simantics.scl.compiler.environment.specification.EnvironmentSpecification;\r
7 import org.simantics.scl.compiler.module.repository.ImportFailureException;\r
8 import org.simantics.scl.compiler.runtime.RuntimeEnvironment;\r
9 import org.simantics.scl.compiler.top.ExpressionEvaluator;\r
10 import org.simantics.scl.compiler.top.SCLExpressionCompilationException;\r
11 import org.simantics.scl.compiler.top.ValueNotFound;\r
12 import org.simantics.scl.compiler.types.Type;\r
13 import org.simantics.scl.compiler.types.Types;\r
14 import org.simantics.scl.osgi.SCLOsgi;\r
15 import org.simantics.scl.runtime.function.Function2;\r
16 \r
17 @SuppressWarnings({"rawtypes", "unchecked"})\r
18 public class StringConverterFactory {\r
19     private static final ConcurrentHashMap<Type, Function2> CONVERTER_CACHE = \r
20             new ConcurrentHashMap<Type, Function2>();\r
21     private static RuntimeEnvironment environment;\r
22     \r
23     private static final Type ALLOWED_EFFECT = Types.union(new Type[] {Types.READ_GRAPH, Types.PROC});\r
24     \r
25     /**\r
26      * Creates a string converter for given type.\r
27      * @throws ValueNotFound \r
28      */\r
29     public static Function2<Resource,Object,String> stringConverterFor(Type type) throws SCLExpressionCompilationException, ImportFailureException {\r
30         Function2 converter = CONVERTER_CACHE.get(type);\r
31         if(converter == null) {\r
32             if(environment == null) {\r
33                 // no need to synchronize access to environment\r
34                 environment = SCLOsgi.MODULE_REPOSITORY.createRuntimeEnvironment(\r
35                         EnvironmentSpecification.of(\r
36                                 "Simantics/GShow", "",\r
37                                 "Simantics/RouteGraph", "",\r
38                                 "Prelude", ""\r
39                                 ), StringConverterFactory.class.getClassLoader()\r
40                         );\r
41             }\r
42             converter = (Function2)new ExpressionEvaluator(environment, "\\ctx r -> gshow ctx (Par 0 r)")\r
43             .expectedType(Types.function(Types.RESOURCE, Types.functionE(type, ALLOWED_EFFECT, Types.STRING)))\r
44             .eval();\r
45             CONVERTER_CACHE.put(type, converter);\r
46         }\r
47         return converter;\r
48     }\r
49 }\r