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