1 package org.simantics.scl.commands.internal;
3 import java.util.concurrent.ConcurrentHashMap;
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;
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;
23 private static final Type ALLOWED_EFFECT = Types.union(new Type[] {Types.READ_GRAPH, Types.PROC});
26 * Creates a string converter for given type.
27 * @throws ValueNotFound
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", "",
39 ), StringConverterFactory.class.getClassLoader()
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)))
45 CONVERTER_CACHE.put(type, converter);