]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/module/repository/ModuleRepository.java
5078d00802ba7fb257c37daa13cf49c43eb51e37
[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.WeakHashMap;
8 import java.util.concurrent.ConcurrentHashMap;
9
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;
37
38 import gnu.trove.map.hash.THashMap;
39 import gnu.trove.procedure.TObjectObjectProcedure;
40 import gnu.trove.set.hash.THashSet;
41
42 /**
43  * Manages compilation and caching of SCL modules.
44  * 
45  * @author Hannu Niemistö
46  */
47 public class ModuleRepository {
48     private final ModuleRepository parentRepository;
49     private final ModuleSourceRepository sourceRepository;
50     private ConcurrentHashMap<String, ModuleEntry> moduleCache = new ConcurrentHashMap<String, ModuleEntry>();
51     
52     private static final ThreadLocal<THashSet<String>> PENDING_MODULES = new ThreadLocal<THashSet<String>>();
53     
54     private ModuleCompilationOptionsAdvisor advisor = null;
55     
56     private static void beginModuleCompilation(String moduleName) {
57         THashSet<String> set = PENDING_MODULES.get();
58         if(set == null) {
59             set = new THashSet<String>();
60             PENDING_MODULES.set(set);
61         }
62         if(!set.add(moduleName))
63             throw new IllegalArgumentException("Cyclic module dependency detected at " + moduleName + ".");
64     }
65     
66     private static void finishModuleCompilation(String moduleName) {
67         PENDING_MODULES.get().remove(moduleName);
68     }
69     
70     private class ModuleEntry implements UpdateListener {
71         final String moduleName;
72         WeakHashMap<UpdateListener,Object> listeners = new WeakHashMap<UpdateListener,Object>();
73         
74         ModuleSource source;
75         Failable<Module> compilationResult;
76         Failable<RuntimeModule> runtimeModule; // created lazily
77
78         public ModuleEntry(String moduleName) {
79             this.moduleName = moduleName;
80         }
81         
82         synchronized void addListener(UpdateListener listener) {
83             if(listener != null)
84                 listeners.put(listener, null);
85         }
86         
87         @Override
88         public void notifyAboutUpdate() {
89             if (listeners == null)
90                 return;
91             ArrayList<UpdateListener> externalListeners = new ArrayList<UpdateListener>();
92             notifyAboutUpdate(externalListeners);
93             for(UpdateListener listener : externalListeners)
94                 listener.notifyAboutUpdate();
95         }
96
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);
104                 }
105                 for(UpdateListener l : listeners.keySet())
106                     if(l instanceof ModuleEntry)
107                         ((ModuleEntry)l).notifyAboutUpdate(externalListeners);
108                     else
109                         externalListeners.add(l);
110             }
111         }
112
113         private ModuleEntry initModuleEntryAndAddListener(UpdateListener listener) {
114             source = sourceRepository.getModuleSource(moduleName, this);
115             
116             if(source == null)
117                 compilationResult = DoesNotExist.getInstance();
118             else {
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);
124             }
125         
126             ModuleEntry oldEntry = moduleCache.putIfAbsent(moduleName, this);
127             if(oldEntry != null) {
128                 oldEntry.addListener(listener);
129                 return oldEntry;
130             }
131             
132             addListener(listener);
133             return this;
134         }
135         
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)
144                                 .getResult());
145                         Collection<ImportDeclaration> dependencies = module.getDependencies();
146                         THashMap<String, ModuleEntry> moduleEntries;
147                         try {
148                             moduleEntries = getModuleEntries(dependencies.toArray(new ImportDeclaration[dependencies.size()]), null);
149                         } catch (ImportFailureException e) {
150                             throw new InternalCompilerError(e);
151                         }
152                         for(RuntimeModule m : mapEntriesToRuntimeModules(moduleEntries).values())
153                             parentModules.add(m);
154                     }
155                     /*for(ImportDeclaration importAst : module.getDependencies()) {
156                         RuntimeModule parentModule =
157                                 ModuleRepository.this.getRuntimeModule(importAst.moduleName)
158                                 .getResult();
159                         if(parentModule != null)
160                             parentModules.add(parentModule);
161                     }*/
162                     RuntimeModule rm = new RuntimeModule(module, parentModules, source.getClassLoader());
163                     ModuleInitializer initializer = module.getModuleInitializer();
164                     if(initializer != null)
165                         try {
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())});
169                             e.printStackTrace();
170                         }
171                     runtimeModule = new Success<RuntimeModule>(rm); 
172                 }
173                 else
174                     runtimeModule = (Failable<RuntimeModule>)(Failable)compilationResult;
175             }
176             return runtimeModule;
177         }
178
179         public void dispose() {
180             listeners.clear();
181             listeners = null;
182             source = null;
183             compilationResult = null;
184             runtimeModule.getResult().dispose();
185             runtimeModule = null;
186         }
187         
188         @Override
189         public String toString() {
190             return "ModuleEntry@" + moduleName + "@" + hashCode();
191         }
192     }
193     
194     public ModuleRepository(ModuleRepository parentRepository, ModuleSourceRepository sourceRepository) {
195         this.parentRepository = parentRepository;
196         this.sourceRepository = sourceRepository;
197     }
198
199     public ModuleRepository(ModuleSourceRepository sourceRepository) {
200         this(null, sourceRepository);
201     }
202     
203     public Failable<Module> getModule(String moduleName, UpdateListener listener) {
204         return getModuleEntry(moduleName, listener).compilationResult;
205     }
206     
207     public Failable<Module> getModule(String moduleName) {
208         return getModule(moduleName, null);
209     }
210     
211     public Failable<RuntimeModule> getRuntimeModule(String moduleName, UpdateListener listener) {
212         return getModuleEntry(moduleName, listener).getRuntimeModule();
213     }
214     
215     public Failable<RuntimeModule> getRuntimeModule(String moduleName) {
216         return getRuntimeModule(moduleName, null);
217     }
218     
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
223          * in it.
224          */
225         ModuleEntry entry = moduleCache.get(moduleName);
226         if(entry == null)
227             entry = new ModuleEntry(moduleName).initModuleEntryAndAddListener(listener);
228         else
229             entry.addListener(listener);
230
231         if(entry.compilationResult == DoesNotExist.INSTANCE && parentRepository != null)
232             return parentRepository.getModuleEntry(moduleName, listener);
233         else
234             return entry;
235     }
236     
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;
242         
243         ArrayList<ImportDeclaration> stack = new ArrayList<ImportDeclaration>(imports.length);
244         for(ImportDeclaration import_ : imports)
245             stack.add(import_);
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());
254                 }
255                 else {
256                     if(failures == null)
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));
262                 }
263             }
264         }
265         
266         if(failures != null)
267             throw new ImportFailureException(failures);
268         
269         return result;
270     }
271
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>() {
275             @Override
276             public boolean execute(String a, ModuleEntry b) {
277                 result.put(a, b.compilationResult.getResult());
278                 return true;
279             }
280         });
281         return result;
282     }
283     
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>() {
287             @Override
288             public boolean execute(String a, ModuleEntry b) {
289                 result.put(a, b.getRuntimeModule().getResult());
290                 return true;
291             }
292         });
293         return result;
294     }
295     
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);
302     }
303     
304     public Environment createEnvironment(
305             EnvironmentSpecification specification,
306             UpdateListener listener) throws ImportFailureException {
307         return createEnvironment(specification.imports.toArray(new ImportDeclaration[specification.imports.size()]), listener);
308     }
309     
310     public RuntimeEnvironment createRuntimeEnvironment(
311             EnvironmentSpecification environmentSpecification, ClassLoader parentClassLoader) throws ImportFailureException {
312         return createRuntimeEnvironment(environmentSpecification, parentClassLoader, null);
313     }
314     
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()]),
321                 parentClassLoader,
322                 listener);
323     }
324     
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);
334     }
335     
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));
343         
344         return new ConcreteEnvironment(moduleMap, spec.toNamespace());
345     }
346     
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);
352         else
353             addToNamespace(moduleMap, namespace.getNamespace(localName), moduleName, filter);
354     }
355     
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);
368                 }
369         }
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);
378                 }
379         }
380     }
381
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);
388         else
389             throw new ValueNotFound(((Failure)module).toString());
390     }
391
392     public Object getValue(String fullValueName) throws ValueNotFound {
393         int p = fullValueName.lastIndexOf('/');
394         if(p < 0)
395             throw new ValueNotFound(fullValueName + " is not a valid full value name.");
396         return getValue(fullValueName.substring(0, p), fullValueName.substring(p+1));
397     }
398
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);
403             if(value == null)
404                 throw new ValueNotFound("Module " + moduleName + " does not contain value " + valueName + ".");
405             return value;
406         }
407         else if(module == DoesNotExist.INSTANCE)
408             throw new ValueNotFound("Didn't find module " + moduleName);
409         else
410             throw new ValueNotFound(((Failure)module).toString());
411     }
412     
413     public SCLValue getValueRef(String fullValueName) throws ValueNotFound {
414         int p = fullValueName.lastIndexOf('/');
415         if(p < 0)
416             throw new ValueNotFound(fullValueName + " is not a valid full value name.");
417         return getValueRef(fullValueName.substring(0, p), fullValueName.substring(p+1));
418     }
419     
420     public ModuleSourceRepository getSourceRepository() {
421         return sourceRepository;
422     }
423     
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;
429     }
430     
431     public void flush() {
432         if (parentRepository != null)
433             parentRepository.flush();
434         if (moduleCache != null) {
435             for (ModuleEntry entry : moduleCache.values()) {
436                 entry.dispose();
437             }
438             moduleCache.clear();
439         }
440         moduleCache = null;
441     }
442
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());
449             }
450         }
451         return result;
452     }
453
454     public ModuleCompilationOptionsAdvisor getAdvisor() {
455         return advisor;
456     }
457
458     public void setAdvisor(ModuleCompilationOptionsAdvisor advisor) {
459         this.advisor = advisor;
460     }
461 \r
462 }
463