1 package org.simantics.scl.compiler.module.repository;
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.HashMap;
7 import java.util.WeakHashMap;
8 import java.util.concurrent.ConcurrentHashMap;
10 import org.simantics.scl.compiler.common.exceptions.InternalCompilerError;
11 import org.simantics.scl.compiler.elaboration.modules.SCLValue;
12 import org.simantics.scl.compiler.environment.ConcreteEnvironment;
13 import org.simantics.scl.compiler.environment.Environment;
14 import org.simantics.scl.compiler.environment.NamespaceImpl.ModuleImport;
15 import org.simantics.scl.compiler.environment.NamespaceSpec;
16 import org.simantics.scl.compiler.environment.filter.NamespaceFilter;
17 import org.simantics.scl.compiler.environment.filter.NamespaceFilters;
18 import org.simantics.scl.compiler.environment.specification.EnvironmentSpecification;
19 import org.simantics.scl.compiler.errors.CompilationError;
20 import org.simantics.scl.compiler.errors.DoesNotExist;
21 import org.simantics.scl.compiler.errors.Failable;
22 import org.simantics.scl.compiler.errors.Failure;
23 import org.simantics.scl.compiler.errors.Success;
24 import org.simantics.scl.compiler.module.ImportDeclaration;
25 import org.simantics.scl.compiler.module.Module;
26 import org.simantics.scl.compiler.module.options.ModuleCompilationOptionsAdvisor;
27 import org.simantics.scl.compiler.runtime.RuntimeEnvironment;
28 import org.simantics.scl.compiler.runtime.RuntimeEnvironmentImpl;
29 import org.simantics.scl.compiler.runtime.RuntimeModule;
30 import org.simantics.scl.compiler.runtime.RuntimeModuleMap;
31 import org.simantics.scl.compiler.source.ModuleSource;
32 import org.simantics.scl.compiler.source.repository.ModuleSourceRepository;
33 import org.simantics.scl.compiler.top.ModuleInitializer;
34 import org.simantics.scl.compiler.top.SCLCompilerConfiguration;
35 import org.simantics.scl.compiler.top.ValueNotFound;
36 import org.simantics.scl.compiler.types.Types;
38 import gnu.trove.map.hash.THashMap;
39 import gnu.trove.procedure.TObjectObjectProcedure;
40 import gnu.trove.set.hash.THashSet;
43 * Manages compilation and caching of SCL modules.
45 * @author Hannu Niemistö
47 public class ModuleRepository {
48 private final ModuleRepository parentRepository;
49 private final ModuleSourceRepository sourceRepository;
50 private ConcurrentHashMap<String, ModuleEntry> moduleCache = new ConcurrentHashMap<String, ModuleEntry>();
52 private static final ThreadLocal<THashSet<String>> PENDING_MODULES = new ThreadLocal<THashSet<String>>();
54 private ModuleCompilationOptionsAdvisor advisor = null;
56 private static void beginModuleCompilation(String moduleName) {
57 THashSet<String> set = PENDING_MODULES.get();
59 set = new THashSet<String>();
60 PENDING_MODULES.set(set);
62 if(!set.add(moduleName))
63 throw new IllegalArgumentException("Cyclic module dependency detected at " + moduleName + ".");
66 private static void finishModuleCompilation(String moduleName) {
67 PENDING_MODULES.get().remove(moduleName);
70 private class ModuleEntry implements UpdateListener {
71 final String moduleName;
72 WeakHashMap<UpdateListener,Object> listeners = new WeakHashMap<UpdateListener,Object>();
75 Failable<Module> compilationResult;
76 Failable<RuntimeModule> runtimeModule; // created lazily
78 public ModuleEntry(String moduleName) {
79 this.moduleName = moduleName;
82 synchronized void addListener(UpdateListener listener) {
84 listeners.put(listener, null);
88 public void notifyAboutUpdate() {
89 if (listeners == null)
91 ArrayList<UpdateListener> externalListeners = new ArrayList<UpdateListener>();
92 notifyAboutUpdate(externalListeners);
93 for(UpdateListener listener : externalListeners)
94 listener.notifyAboutUpdate();
97 synchronized void notifyAboutUpdate(ArrayList<UpdateListener> externalListeners) {
98 if(moduleCache.get(moduleName) == this) {
99 moduleCache.remove(moduleName);
100 if(SCLCompilerConfiguration.TRACE_MODULE_UPDATE) {
101 System.out.println("Invalidate " + moduleName);
102 for(UpdateListener l : listeners.keySet())
103 System.out.println(" " + l);
105 for(UpdateListener l : listeners.keySet())
106 if(l instanceof ModuleEntry)
107 ((ModuleEntry)l).notifyAboutUpdate(externalListeners);
109 externalListeners.add(l);
113 private ModuleEntry initModuleEntryAndAddListener(UpdateListener listener) {
114 source = sourceRepository.getModuleSource(moduleName, this);
117 compilationResult = DoesNotExist.getInstance();
119 if(SCLCompilerConfiguration.TRACE_MODULE_UPDATE)
120 System.out.println("Compile " + source);
121 beginModuleCompilation(moduleName);
122 compilationResult = source.compileModule(ModuleRepository.this, this, advisor == null ? null : advisor.getOptions(moduleName));
123 finishModuleCompilation(moduleName);
126 ModuleEntry oldEntry = moduleCache.putIfAbsent(moduleName, this);
127 if(oldEntry != null) {
128 oldEntry.addListener(listener);
132 addListener(listener);
136 @SuppressWarnings({ "rawtypes", "unchecked" })
137 public synchronized Failable<RuntimeModule> getRuntimeModule() {
138 if(runtimeModule == null) {
139 if(compilationResult.didSucceed()) {
140 Module module = compilationResult.getResult();
141 RuntimeModuleMap parentModules = new RuntimeModuleMap();
142 if(!moduleName.equals(Types.BUILTIN)) {
143 parentModules.add(ModuleRepository.this.getRuntimeModule(Types.BUILTIN)
145 Collection<ImportDeclaration> dependencies = module.getDependencies();
146 THashMap<String, ModuleEntry> moduleEntries;
148 moduleEntries = getModuleEntries(dependencies.toArray(new ImportDeclaration[dependencies.size()]), null);
149 } catch (ImportFailureException e) {
150 throw new InternalCompilerError(e);
152 for(RuntimeModule m : mapEntriesToRuntimeModules(moduleEntries).values())
153 parentModules.add(m);
155 /*for(ImportDeclaration importAst : module.getDependencies()) {
156 RuntimeModule parentModule =
157 ModuleRepository.this.getRuntimeModule(importAst.moduleName)
159 if(parentModule != null)
160 parentModules.add(parentModule);
162 RuntimeModule rm = new RuntimeModule(module, parentModules, source.getClassLoader());
163 ModuleInitializer initializer = module.getModuleInitializer();
164 if(initializer != null)
166 initializer.initializeModule(rm.getMutableClassLoader().getClassLoader());
167 } catch (Exception e) {
168 compilationResult = new Failure(new CompilationError[] {new CompilationError("Initialization of module " + moduleName + " failed: " + e.getMessage())});
171 runtimeModule = new Success<RuntimeModule>(rm);
174 runtimeModule = (Failable<RuntimeModule>)(Failable)compilationResult;
176 return runtimeModule;
179 public void dispose() {
183 compilationResult = null;
184 runtimeModule.getResult().dispose();
185 runtimeModule = null;
189 public String toString() {
190 return "ModuleEntry@" + moduleName + "@" + hashCode();
194 public ModuleRepository(ModuleRepository parentRepository, ModuleSourceRepository sourceRepository) {
195 this.parentRepository = parentRepository;
196 this.sourceRepository = sourceRepository;
199 public ModuleRepository(ModuleSourceRepository sourceRepository) {
200 this(null, sourceRepository);
203 public Failable<Module> getModule(String moduleName, UpdateListener listener) {
204 return getModuleEntry(moduleName, listener).compilationResult;
207 public Failable<Module> getModule(String moduleName) {
208 return getModule(moduleName, null);
211 public Failable<RuntimeModule> getRuntimeModule(String moduleName, UpdateListener listener) {
212 return getModuleEntry(moduleName, listener).getRuntimeModule();
215 public Failable<RuntimeModule> getRuntimeModule(String moduleName) {
216 return getRuntimeModule(moduleName, null);
219 private ModuleEntry getModuleEntry(String moduleName, UpdateListener listener) {
220 /* It is deliberate that the following code does not try to prevent
221 * simultaneous compilation of the same module. This is because in
222 * some situations only certain thread trying compilation can succeed
225 ModuleEntry entry = moduleCache.get(moduleName);
227 entry = new ModuleEntry(moduleName).initModuleEntryAndAddListener(listener);
229 entry.addListener(listener);
231 if(entry.compilationResult == DoesNotExist.INSTANCE && parentRepository != null)
232 return parentRepository.getModuleEntry(moduleName, listener);
237 private THashMap<String, ModuleEntry> getModuleEntries(
238 ImportDeclaration[] imports,
239 UpdateListener listener) throws ImportFailureException {
240 THashMap<String, ModuleEntry> result = new THashMap<String, ModuleEntry>();
241 Collection<ImportFailure> failures = null;
243 ArrayList<ImportDeclaration> stack = new ArrayList<ImportDeclaration>(imports.length);
244 for(ImportDeclaration import_ : imports)
246 while(!stack.isEmpty()) {
247 ImportDeclaration import_ = stack.remove(stack.size()-1);
248 if(!result.containsKey(import_.moduleName)) {
249 ModuleEntry entry = getModuleEntry(import_.moduleName, listener);
250 Failable<Module> compilationResult = entry.compilationResult;
251 if(compilationResult.didSucceed()) {
252 result.put(import_.moduleName, entry);
253 stack.addAll(compilationResult.getResult().getDependencies());
257 failures = new ArrayList<ImportFailure>(2);
258 failures.add(new ImportFailure(import_.location, import_.moduleName,
259 compilationResult == DoesNotExist.INSTANCE
260 ? ImportFailure.MODULE_DOES_NOT_EXIST_REASON
261 : ((Failure)compilationResult).errors));
267 throw new ImportFailureException(failures);
272 private static THashMap<String, Module> mapEntriesToModules(THashMap<String, ModuleEntry> entries) {
273 final THashMap<String, Module> result = new THashMap<String, Module>(entries.size());
274 entries.forEachEntry(new TObjectObjectProcedure<String, ModuleEntry>() {
276 public boolean execute(String a, ModuleEntry b) {
277 result.put(a, b.compilationResult.getResult());
284 private static THashMap<String, RuntimeModule> mapEntriesToRuntimeModules(THashMap<String, ModuleEntry> entries) {
285 final THashMap<String, RuntimeModule> result = new THashMap<String, RuntimeModule>(entries.size());
286 entries.forEachEntry(new TObjectObjectProcedure<String, ModuleEntry>() {
288 public boolean execute(String a, ModuleEntry b) {
289 result.put(a, b.getRuntimeModule().getResult());
296 public Environment createEnvironment(
297 ImportDeclaration[] imports,
298 UpdateListener listener) throws ImportFailureException {
299 THashMap<String, ModuleEntry> entries = getModuleEntries(imports, listener);
300 THashMap<String, Module> moduleMap = mapEntriesToModules(entries);
301 return createEnvironment(moduleMap, imports);
304 public Environment createEnvironment(
305 EnvironmentSpecification specification,
306 UpdateListener listener) throws ImportFailureException {
307 return createEnvironment(specification.imports.toArray(new ImportDeclaration[specification.imports.size()]), listener);
310 public RuntimeEnvironment createRuntimeEnvironment(
311 EnvironmentSpecification environmentSpecification, ClassLoader parentClassLoader) throws ImportFailureException {
312 return createRuntimeEnvironment(environmentSpecification, parentClassLoader, null);
315 public RuntimeEnvironment createRuntimeEnvironment(
316 EnvironmentSpecification environmentSpecification,
317 ClassLoader parentClassLoader,
318 UpdateListener listener) throws ImportFailureException {
319 return createRuntimeEnvironment(
320 environmentSpecification.imports.toArray(new ImportDeclaration[environmentSpecification.imports.size()]),
325 public RuntimeEnvironment createRuntimeEnvironment(
326 ImportDeclaration[] imports,
327 ClassLoader parentClassLoader,
328 UpdateListener listener) throws ImportFailureException {
329 THashMap<String, ModuleEntry> entries = getModuleEntries(imports, listener);
330 THashMap<String, Module> moduleMap = mapEntriesToModules(entries);
331 Environment environment = createEnvironment(moduleMap, imports);
332 THashMap<String, RuntimeModule> runtimeModuleMap = mapEntriesToRuntimeModules(entries);
333 return new RuntimeEnvironmentImpl(environment, parentClassLoader, runtimeModuleMap);
336 private static Environment createEnvironment(THashMap<String, Module> moduleMap,
337 ImportDeclaration[] imports) {
338 NamespaceSpec spec = new NamespaceSpec();
339 for(ImportDeclaration import_ : imports)
340 if(import_.localName != null)
341 addToNamespace(moduleMap, spec, import_.moduleName, import_.localName,
342 NamespaceFilters.createFromSpec(import_.spec));
344 return new ConcreteEnvironment(moduleMap, spec.toNamespace());
347 private static void addToNamespace(THashMap<String, Module> moduleMap,
348 NamespaceSpec namespace, String moduleName, String localName,
349 NamespaceFilter filter) {
350 if(localName.isEmpty())
351 addToNamespace(moduleMap, namespace, moduleName, filter);
353 addToNamespace(moduleMap, namespace.getNamespace(localName), moduleName, filter);
356 private static void addToNamespace(THashMap<String, Module> moduleMap,
357 NamespaceSpec namespace, String moduleName, NamespaceFilter filter) {
358 ModuleImport moduleImport = namespace.moduleMap.get(moduleName);
359 if(moduleImport == null) {
360 Module module = moduleMap.get(moduleName);
361 namespace.moduleMap.put(moduleName, new ModuleImport(module, filter));
362 for(ImportDeclaration import_ : module.getDependencies())
363 if(import_.localName != null) {
364 NamespaceFilter localFilter = NamespaceFilters.createFromSpec(import_.spec);
365 if(import_.localName.equals(""))
366 localFilter = NamespaceFilters.intersection(filter, localFilter);
367 addToNamespace(moduleMap, namespace, import_.moduleName, import_.localName, localFilter);
370 else if(!filter.isSubsetOf(moduleImport.filter)) {
371 moduleImport.filter = NamespaceFilters.union(moduleImport.filter, filter);
372 for(ImportDeclaration import_ : moduleImport.module.getDependencies())
373 // We have to recheck only modules imported to this namespace
374 if("".equals(import_.localName)) {
375 NamespaceFilter localFilter = NamespaceFilters.createFromSpec(import_.spec);
376 localFilter = NamespaceFilters.intersection(filter, localFilter);
377 addToNamespace(moduleMap, namespace, import_.moduleName, import_.localName, localFilter);
382 public Object getValue(String moduleName, String valueName) throws ValueNotFound {
383 Failable<RuntimeModule> module = getRuntimeModule(moduleName);
384 if(module.didSucceed())
385 return module.getResult().getValue(valueName);
386 else if(module == DoesNotExist.INSTANCE)
387 throw new ValueNotFound("Didn't find module " + moduleName);
389 throw new ValueNotFound(((Failure)module).toString());
392 public Object getValue(String fullValueName) throws ValueNotFound {
393 int p = fullValueName.lastIndexOf('/');
395 throw new ValueNotFound(fullValueName + " is not a valid full value name.");
396 return getValue(fullValueName.substring(0, p), fullValueName.substring(p+1));
399 public SCLValue getValueRef(String moduleName, String valueName) throws ValueNotFound {
400 Failable<Module> module = getModule(moduleName);
401 if(module.didSucceed()) {
402 SCLValue value = module.getResult().getValue(valueName);
404 throw new ValueNotFound("Module " + moduleName + " does not contain value " + valueName + ".");
407 else if(module == DoesNotExist.INSTANCE)
408 throw new ValueNotFound("Didn't find module " + moduleName);
410 throw new ValueNotFound(((Failure)module).toString());
413 public SCLValue getValueRef(String fullValueName) throws ValueNotFound {
414 int p = fullValueName.lastIndexOf('/');
416 throw new ValueNotFound(fullValueName + " is not a valid full value name.");
417 return getValueRef(fullValueName.substring(0, p), fullValueName.substring(p+1));
420 public ModuleSourceRepository getSourceRepository() {
421 return sourceRepository;
424 public String getDocumentation(String documentationName) {
425 String documentation = sourceRepository.getDocumentation(documentationName);
426 if(documentation == null && parentRepository != null)
427 return parentRepository.getDocumentation(documentationName);
428 return documentation;
431 public void flush() {
432 if (parentRepository != null)
433 parentRepository.flush();
434 if (moduleCache != null) {
435 for (ModuleEntry entry : moduleCache.values()) {
443 public Map<String, Module> getModules() {
444 Map<String, Module> result = new HashMap<>(moduleCache.size());
445 for (Map.Entry<String, ModuleEntry> entry : moduleCache.entrySet()) {
446 ModuleEntry moduleEntry = entry.getValue();
447 if (moduleEntry.compilationResult.didSucceed()) {
448 result.put(entry.getKey(), moduleEntry.compilationResult.getResult());
454 public ModuleCompilationOptionsAdvisor getAdvisor() {
458 public void setAdvisor(ModuleCompilationOptionsAdvisor advisor) {
459 this.advisor = advisor;