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.concurrent.ConcurrentHashMap;
9 import org.simantics.scl.compiler.common.exceptions.InternalCompilerError;
10 import org.simantics.scl.compiler.compilation.CompilationContext;
11 import org.simantics.scl.compiler.elaboration.modules.SCLValue;
12 import org.simantics.scl.compiler.environment.ConcreteEnvironment;
13 import org.simantics.scl.compiler.environment.EmptyEnvironment;
14 import org.simantics.scl.compiler.environment.Environment;
15 import org.simantics.scl.compiler.environment.NamespaceImpl.ModuleImport;
16 import org.simantics.scl.compiler.environment.NamespaceSpec;
17 import org.simantics.scl.compiler.environment.filter.NamespaceFilter;
18 import org.simantics.scl.compiler.environment.filter.NamespaceFilters;
19 import org.simantics.scl.compiler.environment.specification.EnvironmentSpecification;
20 import org.simantics.scl.compiler.errors.CompilationError;
21 import org.simantics.scl.compiler.errors.DoesNotExist;
22 import org.simantics.scl.compiler.errors.Failable;
23 import org.simantics.scl.compiler.errors.Failure;
24 import org.simantics.scl.compiler.errors.Locations;
25 import org.simantics.scl.compiler.errors.Success;
26 import org.simantics.scl.compiler.module.ImportDeclaration;
27 import org.simantics.scl.compiler.module.Module;
28 import org.simantics.scl.compiler.module.options.ModuleCompilationOptionsAdvisor;
29 import org.simantics.scl.compiler.module.repository.UpdateListener.Observable;
30 import org.simantics.scl.compiler.runtime.RuntimeEnvironment;
31 import org.simantics.scl.compiler.runtime.RuntimeEnvironmentImpl;
32 import org.simantics.scl.compiler.runtime.RuntimeModule;
33 import org.simantics.scl.compiler.runtime.RuntimeModuleMap;
34 import org.simantics.scl.compiler.source.ModuleSource;
35 import org.simantics.scl.compiler.source.repository.ModuleSourceRepository;
36 import org.simantics.scl.compiler.top.ModuleInitializer;
37 import org.simantics.scl.compiler.top.SCLCompilerConfiguration;
38 import org.simantics.scl.compiler.top.ValueNotFound;
39 import org.simantics.scl.compiler.types.Types;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
43 import gnu.trove.map.hash.THashMap;
44 import gnu.trove.map.hash.TObjectLongHashMap;
45 import gnu.trove.procedure.TObjectObjectProcedure;
46 import gnu.trove.set.hash.THashSet;
49 * Manages compilation and caching of SCL modules.
51 * @author Hannu Niemistö
53 public class ModuleRepository {
55 private static final Logger LOGGER = LoggerFactory.getLogger(ModuleRepository.class);
57 private final ModuleRepository parentRepository;
58 private final ModuleSourceRepository sourceRepository;
59 private ConcurrentHashMap<String, ModuleEntry> moduleCache = new ConcurrentHashMap<String, ModuleEntry>();
61 private static final ThreadLocal<THashSet<String>> PENDING_MODULES = new ThreadLocal<THashSet<String>>();
63 private ModuleCompilationOptionsAdvisor advisor = null;
65 private static void beginModuleCompilation(String moduleName) {
66 THashSet<String> set = PENDING_MODULES.get();
68 set = new THashSet<String>();
69 PENDING_MODULES.set(set);
71 if(!set.add(moduleName))
72 throw new IllegalArgumentException("Cyclic module dependency detected at " + moduleName + ".");
75 private static void finishModuleCompilation(String moduleName) {
76 PENDING_MODULES.get().remove(moduleName);
79 private class ModuleEntry extends UpdateListener implements Observable {
80 final String moduleName;
81 THashSet<UpdateListener> listeners = new THashSet<UpdateListener>(); // listeners == null is used as a marker that this entry is disposed
82 // should be handled only inside synchronized code
85 Failable<Module> compilationResult;
86 Failable<RuntimeModule> runtimeModule; // created lazily
88 public ModuleEntry(String moduleName) {
89 this.moduleName = moduleName;
92 synchronized void addListener(UpdateListener listener) {
93 if(listener == null || listeners == null)
95 listeners.add(listener);
96 listener.addObservable(this);
99 public synchronized void removeListener(UpdateListener listener) {
100 if (listeners == null)
102 listeners.remove(listener);
106 public void notifyAboutUpdate() {
107 // There is a chance that another observable calls notifyAboutUpdate() before stopListening has been completed,
108 // but notifyAboutUpdate(ArrayList<UpdateListener>) lets only one thread to do the notification of dependencies
109 // by clearing listeners field.
111 ArrayList<UpdateListener> externalListeners = new ArrayList<UpdateListener>();
112 notifyAboutUpdate(externalListeners);
113 for(UpdateListener listener : externalListeners)
114 listener.notifyAboutUpdate();
117 void notifyAboutUpdate(ArrayList<UpdateListener> externalListeners) {
118 THashSet<UpdateListener> listenersCopy;
120 listenersCopy = listeners;
121 if (listenersCopy == null)
125 if(moduleCache.get(moduleName) == this) {
126 moduleCache.remove(moduleName);
127 if(SCLCompilerConfiguration.TRACE_MODULE_UPDATE) {
128 LOGGER.info("Invalidate " + moduleName);
129 for(UpdateListener l : listenersCopy)
130 LOGGER.info(" " + l);
132 for(UpdateListener l : listenersCopy)
133 if(!l.stopListening())
135 else if(l instanceof ModuleEntry)
136 ((ModuleEntry)l).notifyAboutUpdate(externalListeners);
138 externalListeners.add(l);
142 private ModuleEntry initModuleEntryAndAddListener(UpdateListener listener) {
143 source = sourceRepository.getModuleSource(moduleName, this);
146 compilationResult = DoesNotExist.getInstance();
148 if(SCLCompilerConfiguration.TRACE_MODULE_UPDATE)
149 LOGGER.info("Compile " + source);
150 beginModuleCompilation(moduleName);
151 compilationResult = source.compileModule(ModuleRepository.this, this, advisor == null ? null : advisor.getOptions(moduleName));
152 finishModuleCompilation(moduleName);
155 ModuleEntry oldEntry = moduleCache.putIfAbsent(moduleName, this);
156 if(oldEntry != null) {
157 oldEntry.addListener(listener);
161 addListener(listener);
165 @SuppressWarnings({ "rawtypes", "unchecked" })
166 public synchronized Failable<RuntimeModule> getRuntimeModule() {
167 if(runtimeModule == null) {
168 if(compilationResult.didSucceed()) {
169 Module module = compilationResult.getResult();
170 RuntimeModuleMap parentModules = new RuntimeModuleMap();
171 if(!moduleName.equals(Types.BUILTIN)) {
172 parentModules.add(ModuleRepository.this.getRuntimeModule(Types.BUILTIN)
174 Collection<ImportDeclaration> dependencies = module.getDependencies();
175 THashMap<String, ModuleEntry> moduleEntries;
177 moduleEntries = getModuleEntries(null, dependencies.toArray(new ImportDeclaration[dependencies.size()]), null, false);
178 } catch (ImportFailureException e) {
179 throw new InternalCompilerError(e);
181 for(RuntimeModule m : mapEntriesToRuntimeModules(moduleEntries).values())
182 parentModules.add(m);
184 /*for(ImportDeclaration importAst : module.getDependencies()) {
185 RuntimeModule parentModule =
186 ModuleRepository.this.getRuntimeModule(importAst.moduleName)
188 if(parentModule != null)
189 parentModules.add(parentModule);
191 RuntimeModule rm = new RuntimeModule(module, parentModules, module.getParentClassLoader());
192 ModuleInitializer initializer = module.getModuleInitializer();
193 if(initializer != null)
195 initializer.initializeModule(rm.getMutableClassLoader().getClassLoader());
196 } catch (Exception e) {
197 compilationResult = new Failure(new CompilationError[] {new CompilationError("Initialization of module " + moduleName + " failed: " + e.getMessage())});
200 runtimeModule = new Success<RuntimeModule>(rm);
203 runtimeModule = (Failable<RuntimeModule>)(Failable)compilationResult;
205 return runtimeModule;
208 public synchronized void dispose() {
212 compilationResult = null;
213 if (runtimeModule != null) {
214 if (runtimeModule.didSucceed())
215 runtimeModule.getResult().dispose();
217 runtimeModule = null;
221 public String toString() {
222 return "ModuleEntry@" + moduleName + "@" + hashCode();
226 public ModuleRepository(ModuleRepository parentRepository, ModuleSourceRepository sourceRepository) {
227 this.parentRepository = parentRepository;
228 this.sourceRepository = sourceRepository;
231 public ModuleRepository(ModuleSourceRepository sourceRepository) {
232 this(null, sourceRepository);
235 public Failable<Module> getModule(String moduleName, UpdateListener listener) {
236 return getModuleEntry(moduleName, listener).compilationResult;
239 public Failable<Module> getModule(String moduleName) {
240 return getModule(moduleName, null);
243 public Failable<RuntimeModule> getRuntimeModule(String moduleName, UpdateListener listener) {
244 return getModuleEntry(moduleName, listener).getRuntimeModule();
247 public Failable<RuntimeModule> getRuntimeModule(String moduleName) {
248 return getRuntimeModule(moduleName, null);
251 private ModuleEntry getModuleEntry(String moduleName, UpdateListener listener) {
252 /* It is deliberate that the following code does not try to prevent
253 * simultaneous compilation of the same module. This is because in
254 * some situations only certain thread trying compilation can succeed
257 ModuleEntry entry = moduleCache.get(moduleName);
259 entry = new ModuleEntry(moduleName).initModuleEntryAndAddListener(listener);
261 entry.addListener(listener);
263 if(entry.compilationResult == DoesNotExist.INSTANCE && parentRepository != null)
264 return parentRepository.getModuleEntry(moduleName, listener);
269 private THashMap<String, ModuleEntry> getModuleEntries(
270 CompilationContext compilationContext,
271 ImportDeclaration[] imports,
272 UpdateListener listener,
273 boolean robustly) throws ImportFailureException {
274 THashMap<String, ModuleEntry> result = new THashMap<String, ModuleEntry>();
275 Collection<ImportFailure> failures = null;
277 TObjectLongHashMap<String> originalImports = new TObjectLongHashMap<String>();
278 ArrayList<ImportDeclaration> stack = new ArrayList<ImportDeclaration>(imports.length);
279 for(ImportDeclaration import_ : imports) {
281 originalImports.put(import_.moduleName, import_.location);
283 while(!stack.isEmpty()) {
284 ImportDeclaration import_ = stack.remove(stack.size()-1);
285 if(!result.containsKey(import_.moduleName)) {
286 boolean originalImport = originalImports.contains(import_.moduleName);
287 ModuleEntry entry = getModuleEntry(import_.moduleName, originalImport ? listener : null);
288 Failable<Module> compilationResult = entry.compilationResult;
289 if(compilationResult.didSucceed()) {
290 result.put(import_.moduleName, entry);
291 stack.addAll(compilationResult.getResult().getDependencies());
293 String deprecation = compilationResult.getResult().getDeprecation();
294 if(deprecation != null && compilationContext != null) {
295 long location = originalImport ? originalImports.get(import_.moduleName) : Locations.NO_LOCATION;
296 compilationContext.errorLog.logWarning(location, "Deprecated module " + import_.moduleName + (deprecation.isEmpty() ? "." : ": " + deprecation));
302 failures = new ArrayList<ImportFailure>(2);
303 failures.add(new ImportFailure(import_.location, import_.moduleName,
304 compilationResult == DoesNotExist.INSTANCE
305 ? ImportFailure.MODULE_DOES_NOT_EXIST_REASON
306 : ((Failure)compilationResult).errors));
311 if(failures != null && !robustly)
312 throw new ImportFailureException(failures);
317 private static THashMap<String, Module> mapEntriesToModules(THashMap<String, ModuleEntry> entries) {
318 final THashMap<String, Module> result = new THashMap<String, Module>(entries.size());
319 entries.forEachEntry(new TObjectObjectProcedure<String, ModuleEntry>() {
321 public boolean execute(String a, ModuleEntry b) {
322 result.put(a, b.compilationResult.getResult());
329 private static THashMap<String, RuntimeModule> mapEntriesToRuntimeModules(THashMap<String, ModuleEntry> entries) {
330 final THashMap<String, RuntimeModule> result = new THashMap<String, RuntimeModule>(entries.size());
331 entries.forEachEntry(new TObjectObjectProcedure<String, ModuleEntry>() {
333 public boolean execute(String a, ModuleEntry b) {
334 result.put(a, b.getRuntimeModule().getResult());
341 public Environment createEnvironment(
342 ImportDeclaration[] imports,
343 UpdateListener listener) throws ImportFailureException {
344 return createEnvironment(null, imports, listener);
347 public Environment createEnvironment(
348 CompilationContext compilationContext,
349 ImportDeclaration[] imports,
350 UpdateListener listener) throws ImportFailureException {
351 THashMap<String, ModuleEntry> entries = getModuleEntries(compilationContext, imports, listener, false);
352 THashMap<String, Module> moduleMap = mapEntriesToModules(entries);
353 return createEnvironment(moduleMap, imports);
356 public Environment createEnvironmentRobustly(
357 CompilationContext compilationContext,
358 ImportDeclaration[] imports,
359 UpdateListener listener) {
361 THashMap<String, ModuleEntry> entries = getModuleEntries(compilationContext, imports, listener, true);
362 THashMap<String, Module> moduleMap = mapEntriesToModules(entries);
363 return createEnvironment(moduleMap, imports);
364 } catch(ImportFailureException e) {
365 // Should not happen because of robust flag
366 return EmptyEnvironment.INSTANCE;
370 public Environment createEnvironment(
371 EnvironmentSpecification specification,
372 UpdateListener listener) throws ImportFailureException {
373 return createEnvironment(specification.imports.toArray(new ImportDeclaration[specification.imports.size()]), listener);
376 public RuntimeEnvironment createRuntimeEnvironment(
377 EnvironmentSpecification environmentSpecification, ClassLoader parentClassLoader) throws ImportFailureException {
378 return createRuntimeEnvironment(environmentSpecification, parentClassLoader, null);
381 public RuntimeEnvironment createRuntimeEnvironment(EnvironmentSpecification environmentSpecification) throws ImportFailureException {
382 return createRuntimeEnvironment(environmentSpecification, getClass().getClassLoader());
385 public RuntimeEnvironment createRuntimeEnvironment(
386 EnvironmentSpecification environmentSpecification,
387 ClassLoader parentClassLoader,
388 UpdateListener listener) throws ImportFailureException {
389 return createRuntimeEnvironment(
390 environmentSpecification.imports.toArray(new ImportDeclaration[environmentSpecification.imports.size()]),
395 public RuntimeEnvironment createRuntimeEnvironment(
396 ImportDeclaration[] imports,
397 ClassLoader parentClassLoader,
398 UpdateListener listener) throws ImportFailureException {
399 THashMap<String, ModuleEntry> entries = getModuleEntries(null, imports, listener, false);
400 THashMap<String, Module> moduleMap = mapEntriesToModules(entries);
401 Environment environment = createEnvironment(moduleMap, imports);
402 THashMap<String, RuntimeModule> runtimeModuleMap = mapEntriesToRuntimeModules(entries);
403 return new RuntimeEnvironmentImpl(environment, parentClassLoader, runtimeModuleMap);
406 private static Environment createEnvironment(
407 THashMap<String, Module> moduleMap,
408 ImportDeclaration[] imports) {
409 NamespaceSpec spec = new NamespaceSpec();
410 for(ImportDeclaration import_ : imports)
411 if(import_.localName != null)
412 addToNamespace(moduleMap, spec, import_.moduleName, import_.localName,
413 NamespaceFilters.createFromSpec(import_.spec));
415 return new ConcreteEnvironment(moduleMap, spec.toNamespace());
418 private static void addToNamespace(THashMap<String, Module> moduleMap,
419 NamespaceSpec namespace, String moduleName, String localName,
420 NamespaceFilter filter) {
421 if(localName.isEmpty())
422 addToNamespace(moduleMap, namespace, moduleName, filter);
424 addToNamespace(moduleMap, namespace.getNamespace(localName), moduleName, filter);
427 private static void addToNamespace(THashMap<String, Module> moduleMap,
428 NamespaceSpec namespace, String moduleName, NamespaceFilter filter) {
429 ModuleImport moduleImport = namespace.moduleMap.get(moduleName);
430 if(moduleImport == null) {
431 Module module = moduleMap.get(moduleName);
432 namespace.moduleMap.put(moduleName, new ModuleImport(module, filter));
433 for(ImportDeclaration import_ : module.getDependencies())
434 if(import_.localName != null) {
435 NamespaceFilter localFilter = NamespaceFilters.createFromSpec(import_.spec);
436 if(import_.localName.equals(""))
437 localFilter = NamespaceFilters.intersection(filter, localFilter);
438 addToNamespace(moduleMap, namespace, import_.moduleName, import_.localName, localFilter);
441 else if(!filter.isSubsetOf(moduleImport.filter)) {
442 moduleImport.filter = NamespaceFilters.union(moduleImport.filter, filter);
443 for(ImportDeclaration import_ : moduleImport.module.getDependencies())
444 // We have to recheck only modules imported to this namespace
445 if("".equals(import_.localName)) {
446 NamespaceFilter localFilter = NamespaceFilters.createFromSpec(import_.spec);
447 localFilter = NamespaceFilters.intersection(filter, localFilter);
448 addToNamespace(moduleMap, namespace, import_.moduleName, import_.localName, localFilter);
453 public Object getValue(String moduleName, String valueName) throws ValueNotFound {
454 Failable<RuntimeModule> module = getRuntimeModule(moduleName);
455 if(module.didSucceed())
456 return module.getResult().getValue(valueName);
457 else if(module == DoesNotExist.INSTANCE)
458 throw new ValueNotFound("Didn't find module " + moduleName);
460 throw new ValueNotFound(((Failure)module).toString());
463 public Object getValue(String fullValueName) throws ValueNotFound {
464 int p = fullValueName.lastIndexOf('/');
466 throw new ValueNotFound(fullValueName + " is not a valid full value name.");
467 return getValue(fullValueName.substring(0, p), fullValueName.substring(p+1));
470 public SCLValue getValueRef(String moduleName, String valueName) throws ValueNotFound {
471 Failable<Module> module = getModule(moduleName);
472 if(module.didSucceed()) {
473 SCLValue value = module.getResult().getValue(valueName);
475 throw new ValueNotFound("Module " + moduleName + " does not contain value " + valueName + ".");
478 else if(module == DoesNotExist.INSTANCE)
479 throw new ValueNotFound("Didn't find module " + moduleName);
481 throw new ValueNotFound(((Failure)module).toString());
484 public SCLValue getValueRef(String fullValueName) throws ValueNotFound {
485 int p = fullValueName.lastIndexOf('/');
487 throw new ValueNotFound(fullValueName + " is not a valid full value name.");
488 return getValueRef(fullValueName.substring(0, p), fullValueName.substring(p+1));
491 public ModuleSourceRepository getSourceRepository() {
492 return sourceRepository;
495 public String getDocumentation(String documentationName) {
496 String documentation = sourceRepository.getDocumentation(documentationName);
497 if(documentation == null && parentRepository != null)
498 return parentRepository.getDocumentation(documentationName);
499 return documentation;
503 * Flush clears module repository cache completely. It should not be called in
504 * normal operation, but may be useful during testing for clearing repositories
505 * that are statically defined.
507 public void flush() {
508 if (parentRepository != null)
509 parentRepository.flush();
510 if (moduleCache != null)
511 for (ModuleEntry entry : moduleCache.values())
513 moduleCache = new ConcurrentHashMap<String, ModuleEntry>();
517 * Gets the map of all modules that have been currently compiled successfully.
518 * Not that the method does not return all possible modules in the source repository.
520 public Map<String, Module> getModules() {
521 Map<String, Module> result = new HashMap<>(moduleCache.size());
522 for (Map.Entry<String, ModuleEntry> entry : moduleCache.entrySet()) {
523 ModuleEntry moduleEntry = entry.getValue();
524 if (moduleEntry.compilationResult.didSucceed()) {
525 result.put(entry.getKey(), moduleEntry.compilationResult.getResult());
531 public ModuleCompilationOptionsAdvisor getAdvisor() {
535 public void setAdvisor(ModuleCompilationOptionsAdvisor advisor) {
536 this.advisor = advisor;