]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/module/repository/ModuleRepository.java
79b596908962b2f4d8fbc4b8c09e74c9266bd213
[simantics/platform.git] / bundles / org.simantics.scl.compiler / src / org / simantics / scl / compiler / module / repository / ModuleRepository.java
1 package org.simantics.scl.compiler.module.repository;
2
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.HashMap;
6 import java.util.Map;
7 import java.util.concurrent.ConcurrentHashMap;
8
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;
42
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;
47
48 /**
49  * Manages compilation and caching of SCL modules.
50  * 
51  * @author Hannu Niemistö
52  */
53 public class ModuleRepository {
54     
55     private static final Logger LOGGER = LoggerFactory.getLogger(ModuleRepository.class);
56
57     private final ModuleRepository parentRepository;
58     private final ModuleSourceRepository sourceRepository;
59     private ConcurrentHashMap<String, ModuleEntry> moduleCache = new ConcurrentHashMap<String, ModuleEntry>();
60     
61     private static final ThreadLocal<THashSet<String>> PENDING_MODULES = new ThreadLocal<THashSet<String>>();
62     
63     private ModuleCompilationOptionsAdvisor advisor = null;
64     
65     private static void beginModuleCompilation(String moduleName) {
66         THashSet<String> set = PENDING_MODULES.get();
67         if(set == null) {
68             set = new THashSet<String>();
69             PENDING_MODULES.set(set);
70         }
71         if(!set.add(moduleName))
72             throw new IllegalArgumentException("Cyclic module dependency detected at " + moduleName + ".");
73     }
74     
75     private static void finishModuleCompilation(String moduleName) {
76         PENDING_MODULES.get().remove(moduleName);
77     }
78             
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
83         
84         ModuleSource source;
85         Failable<Module> compilationResult;
86         Failable<RuntimeModule> runtimeModule; // created lazily
87
88         public ModuleEntry(String moduleName) {
89             this.moduleName = moduleName;
90         }
91         
92         synchronized void addListener(UpdateListener listener) {
93             if(listener == null || listeners == null)
94                 return;
95             listeners.add(listener);
96             listener.addObservable(this);
97         }
98
99         public synchronized void removeListener(UpdateListener listener) {
100             if (listeners == null)
101                 return;
102             listeners.remove(listener);
103         }
104         
105         @Override
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.
110             stopListening();
111             ArrayList<UpdateListener> externalListeners = new ArrayList<UpdateListener>();
112             notifyAboutUpdate(externalListeners);
113             for(UpdateListener listener : externalListeners)
114                 listener.notifyAboutUpdate();
115         }
116
117         void notifyAboutUpdate(ArrayList<UpdateListener> externalListeners) {
118             THashSet<UpdateListener> listenersCopy;
119             synchronized(this) {
120                 listenersCopy = listeners;
121                 if (listenersCopy == null)
122                     return;
123                 listeners = null;
124             }
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);
131                 }
132                 for(UpdateListener l : listenersCopy)
133                     if(!l.stopListening())
134                         ;
135                     else if(l instanceof ModuleEntry)
136                         ((ModuleEntry)l).notifyAboutUpdate(externalListeners);
137                     else
138                         externalListeners.add(l);
139             }
140         }
141
142         private ModuleEntry initModuleEntryAndAddListener(UpdateListener listener) {
143             source = sourceRepository.getModuleSource(moduleName, this);
144             
145             if(source == null)
146                 compilationResult = DoesNotExist.getInstance();
147             else {
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);
153             }
154         
155             ModuleEntry oldEntry = moduleCache.putIfAbsent(moduleName, this);
156             if(oldEntry != null) {
157                 oldEntry.addListener(listener);
158                 return oldEntry;
159             }
160             
161             addListener(listener);
162             return this;
163         }
164         
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)
173                                 .getResult());
174                         Collection<ImportDeclaration> dependencies = module.getDependencies();
175                         THashMap<String, ModuleEntry> moduleEntries;
176                         try {
177                             moduleEntries = getModuleEntries(null, dependencies.toArray(new ImportDeclaration[dependencies.size()]), null, false);
178                         } catch (ImportFailureException e) {
179                             throw new InternalCompilerError(e);
180                         }
181                         for(RuntimeModule m : mapEntriesToRuntimeModules(moduleEntries).values())
182                             parentModules.add(m);
183                     }
184                     /*for(ImportDeclaration importAst : module.getDependencies()) {
185                         RuntimeModule parentModule =
186                                 ModuleRepository.this.getRuntimeModule(importAst.moduleName)
187                                 .getResult();
188                         if(parentModule != null)
189                             parentModules.add(parentModule);
190                     }*/
191                     RuntimeModule rm = new RuntimeModule(module, parentModules, module.getParentClassLoader());
192                     ModuleInitializer initializer = module.getModuleInitializer();
193                     if(initializer != null)
194                         try {
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())});
198                             e.printStackTrace();
199                         }
200                     runtimeModule = new Success<RuntimeModule>(rm); 
201                 }
202                 else
203                     runtimeModule = (Failable<RuntimeModule>)(Failable)compilationResult;
204             }
205             return runtimeModule;
206         }
207
208         public synchronized void dispose() {
209             listeners = null;
210             stopListening();
211             source = null;
212             compilationResult = null;
213             if (runtimeModule != null) {
214                 if (runtimeModule.didSucceed())
215                     runtimeModule.getResult().dispose();
216             }
217             runtimeModule = null;
218         }
219         
220         @Override
221         public String toString() {
222             return "ModuleEntry@" + moduleName + "@" + hashCode();
223         }
224     }
225     
226     public ModuleRepository(ModuleRepository parentRepository, ModuleSourceRepository sourceRepository) {
227         this.parentRepository = parentRepository;
228         this.sourceRepository = sourceRepository;
229     }
230
231     public ModuleRepository(ModuleSourceRepository sourceRepository) {
232         this(null, sourceRepository);
233     }
234     
235     public Failable<Module> getModule(String moduleName, UpdateListener listener) {
236         return getModuleEntry(moduleName, listener).compilationResult;
237     }
238     
239     public Failable<Module> getModule(String moduleName) {
240         return getModule(moduleName, null);
241     }
242     
243     public Failable<RuntimeModule> getRuntimeModule(String moduleName, UpdateListener listener) {
244         return getModuleEntry(moduleName, listener).getRuntimeModule();
245     }
246     
247     public Failable<RuntimeModule> getRuntimeModule(String moduleName) {
248         return getRuntimeModule(moduleName, null);
249     }
250
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
255          * in it.
256          */
257         ModuleEntry entry = moduleCache.get(moduleName);
258         if(entry == null)
259             entry = new ModuleEntry(moduleName).initModuleEntryAndAddListener(listener);
260         else
261             entry.addListener(listener);
262
263         if(entry.compilationResult == DoesNotExist.INSTANCE && parentRepository != null)
264             return parentRepository.getModuleEntry(moduleName, listener);
265         else
266             return entry;
267     }
268     
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;
276         
277         TObjectLongHashMap<String> originalImports = new TObjectLongHashMap<String>(); 
278         ArrayList<ImportDeclaration> stack = new ArrayList<ImportDeclaration>(imports.length);
279         for(ImportDeclaration import_ : imports) {
280             stack.add(import_);
281             originalImports.put(import_.moduleName, import_.location);
282         }
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());
292                     if(originalImport) {
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));
297                         }
298                     }
299                 }
300                 else {
301                     if(failures == null)
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));
307                 }
308             }
309         }
310         
311         if(failures != null && !robustly)
312             throw new ImportFailureException(failures);
313         
314         return result;
315     }
316
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>() {
320             @Override
321             public boolean execute(String a, ModuleEntry b) {
322                 result.put(a, b.compilationResult.getResult());
323                 return true;
324             }
325         });
326         return result;
327     }
328     
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>() {
332             @Override
333             public boolean execute(String a, ModuleEntry b) {
334                 result.put(a, b.getRuntimeModule().getResult());
335                 return true;
336             }
337         });
338         return result;
339     }
340     
341     public Environment createEnvironment(
342             ImportDeclaration[] imports,
343             UpdateListener listener) throws ImportFailureException {
344         return createEnvironment(null, imports, listener);
345     }
346     
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);
354     }
355     
356     public Environment createEnvironmentRobustly(
357             CompilationContext compilationContext,
358             ImportDeclaration[] imports,
359             UpdateListener listener) {
360         try {
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;
367         }
368     }
369     
370     public Environment createEnvironment(
371             EnvironmentSpecification specification,
372             UpdateListener listener) throws ImportFailureException {
373         return createEnvironment(specification.imports.toArray(new ImportDeclaration[specification.imports.size()]), listener);
374     }
375     
376     public RuntimeEnvironment createRuntimeEnvironment(
377             EnvironmentSpecification environmentSpecification, ClassLoader parentClassLoader) throws ImportFailureException {
378         return createRuntimeEnvironment(environmentSpecification, parentClassLoader, null);
379     }
380     
381     public RuntimeEnvironment createRuntimeEnvironment(EnvironmentSpecification environmentSpecification) throws ImportFailureException {
382         return createRuntimeEnvironment(environmentSpecification, getClass().getClassLoader());
383     }
384     
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()]),
391                 parentClassLoader,
392                 listener);
393     }
394     
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);
404     }
405     
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));
414         
415         return new ConcreteEnvironment(moduleMap, spec.toNamespace());
416     }
417     
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);
423         else
424             addToNamespace(moduleMap, namespace.getNamespace(localName), moduleName, filter);
425     }
426     
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);
439                 }
440         }
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);
449                 }
450         }
451     }
452
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);
459         else
460             throw new ValueNotFound(((Failure)module).toString());
461     }
462
463     public Object getValue(String fullValueName) throws ValueNotFound {
464         int p = fullValueName.lastIndexOf('/');
465         if(p < 0)
466             throw new ValueNotFound(fullValueName + " is not a valid full value name.");
467         return getValue(fullValueName.substring(0, p), fullValueName.substring(p+1));
468     }
469
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);
474             if(value == null)
475                 throw new ValueNotFound("Module " + moduleName + " does not contain value " + valueName + ".");
476             return value;
477         }
478         else if(module == DoesNotExist.INSTANCE)
479             throw new ValueNotFound("Didn't find module " + moduleName);
480         else
481             throw new ValueNotFound(((Failure)module).toString());
482     }
483     
484     public SCLValue getValueRef(String fullValueName) throws ValueNotFound {
485         int p = fullValueName.lastIndexOf('/');
486         if(p < 0)
487             throw new ValueNotFound(fullValueName + " is not a valid full value name.");
488         return getValueRef(fullValueName.substring(0, p), fullValueName.substring(p+1));
489     }
490     
491     public ModuleSourceRepository getSourceRepository() {
492         return sourceRepository;
493     }
494     
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;
500     }
501     
502     /**
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.
506      */
507     public void flush() {
508         if (parentRepository != null)
509             parentRepository.flush();
510         if (moduleCache != null)
511             for (ModuleEntry entry : moduleCache.values())
512                 entry.dispose();
513         moduleCache = new ConcurrentHashMap<String, ModuleEntry>();
514     }
515
516     /**
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.
519      */
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());
526             }
527         }
528         return result;
529     }
530
531     public ModuleCompilationOptionsAdvisor getAdvisor() {
532         return advisor;
533     }
534
535     public void setAdvisor(ModuleCompilationOptionsAdvisor advisor) {
536         this.advisor = advisor;
537     }
538
539 }
540