]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/compilation/Elaboration.java
(refs #7541) Added support for module deprecation
[simantics/platform.git] / bundles / org.simantics.scl.compiler / src / org / simantics / scl / compiler / compilation / Elaboration.java
1 package org.simantics.scl.compiler.compilation;
2
3 import java.util.ArrayList;
4 import java.util.Iterator;
5 import java.util.List;
6
7 import org.cojen.classfile.TypeDesc;
8 import org.simantics.scl.compiler.common.datatypes.Constructor;
9 import org.simantics.scl.compiler.common.exceptions.InternalCompilerError;
10 import org.simantics.scl.compiler.common.names.Name;
11 import org.simantics.scl.compiler.constants.Constant;
12 import org.simantics.scl.compiler.constants.JavaTypeInstanceConstructor;
13 import org.simantics.scl.compiler.constants.SCLConstructor;
14 import org.simantics.scl.compiler.constants.StringConstant;
15 import org.simantics.scl.compiler.constants.generic.CallJava;
16 import org.simantics.scl.compiler.constants.generic.ClassRef;
17 import org.simantics.scl.compiler.constants.generic.ConvertToListFilter;
18 import org.simantics.scl.compiler.constants.generic.MethodRef;
19 import org.simantics.scl.compiler.constants.generic.MethodRef.FieldRef;
20 import org.simantics.scl.compiler.constants.generic.OutputFilter;
21 import org.simantics.scl.compiler.constants.generic.ParameterStackItem;
22 import org.simantics.scl.compiler.constants.generic.Pop2OutputFilter;
23 import org.simantics.scl.compiler.constants.generic.PopOutputFilter;
24 import org.simantics.scl.compiler.constants.generic.StackItem;
25 import org.simantics.scl.compiler.constants.generic.ThreadLocalStackItem;
26 import org.simantics.scl.compiler.constants.singletons.SafeCoerce;
27 import org.simantics.scl.compiler.elaboration.contexts.TranslationContext;
28 import org.simantics.scl.compiler.elaboration.contexts.TypeTranslationContext;
29 import org.simantics.scl.compiler.elaboration.errors.NotPatternException;
30 import org.simantics.scl.compiler.elaboration.expressions.EApply;
31 import org.simantics.scl.compiler.elaboration.expressions.EGetConstraint;
32 import org.simantics.scl.compiler.elaboration.expressions.EIntegerLiteral;
33 import org.simantics.scl.compiler.elaboration.expressions.EListLiteral;
34 import org.simantics.scl.compiler.elaboration.expressions.ELiteral;
35 import org.simantics.scl.compiler.elaboration.expressions.EPreCHRRulesetConstructor;
36 import org.simantics.scl.compiler.elaboration.expressions.EVar;
37 import org.simantics.scl.compiler.elaboration.expressions.Expression;
38 import org.simantics.scl.compiler.elaboration.expressions.Variable;
39 import org.simantics.scl.compiler.elaboration.expressions.annotations.AnnotationUtils;
40 import org.simantics.scl.compiler.elaboration.fundeps.Fundep;
41 import org.simantics.scl.compiler.elaboration.java.JavaMethodDeclaration;
42 import org.simantics.scl.compiler.elaboration.macros.StandardMacroRule;
43 import org.simantics.scl.compiler.elaboration.modules.DeprecatedProperty;
44 import org.simantics.scl.compiler.elaboration.modules.DerivedProperty;
45 import org.simantics.scl.compiler.elaboration.modules.InlineProperty;
46 import org.simantics.scl.compiler.elaboration.modules.MethodImplementation;
47 import org.simantics.scl.compiler.elaboration.modules.PrivateProperty;
48 import org.simantics.scl.compiler.elaboration.modules.SCLValue;
49 import org.simantics.scl.compiler.elaboration.modules.TypeAlias;
50 import org.simantics.scl.compiler.elaboration.modules.TypeClass;
51 import org.simantics.scl.compiler.elaboration.modules.TypeClassInstance;
52 import org.simantics.scl.compiler.elaboration.modules.TypeClassMethod;
53 import org.simantics.scl.compiler.elaboration.modules.TypeDescriptor;
54 import org.simantics.scl.compiler.elaboration.query.Query;
55 import org.simantics.scl.compiler.elaboration.query.pre.QPreGuard;
56 import org.simantics.scl.compiler.elaboration.relations.ConcreteRelation;
57 import org.simantics.scl.compiler.elaboration.rules.MappingRelation;
58 import org.simantics.scl.compiler.elaboration.rules.SectionName;
59 import org.simantics.scl.compiler.elaboration.rules.TransformationRule;
60 import org.simantics.scl.compiler.environment.AmbiguousNameException;
61 import org.simantics.scl.compiler.environment.Environment;
62 import org.simantics.scl.compiler.environment.EnvironmentFactory;
63 import org.simantics.scl.compiler.environment.Environments;
64 import org.simantics.scl.compiler.errors.CompilationError;
65 import org.simantics.scl.compiler.errors.ErrorLog;
66 import org.simantics.scl.compiler.errors.ErrorSeverity;
67 import org.simantics.scl.compiler.errors.Locations;
68 import org.simantics.scl.compiler.internal.codegen.effects.EffectConstructor;
69 import org.simantics.scl.compiler.internal.codegen.effects.ThreadLocalVariable;
70 import org.simantics.scl.compiler.internal.codegen.types.JavaReferenceValidator;
71 import org.simantics.scl.compiler.internal.codegen.types.JavaReferenceValidatorFactory;
72 import org.simantics.scl.compiler.internal.codegen.types.JavaTypeTranslator;
73 import org.simantics.scl.compiler.internal.codegen.types.StandardTypeConstructor;
74 import org.simantics.scl.compiler.internal.codegen.utils.Constants;
75 import org.simantics.scl.compiler.internal.codegen.utils.JavaNamingPolicy;
76 import org.simantics.scl.compiler.internal.codegen.utils.MethodBuilderBase;
77 import org.simantics.scl.compiler.internal.deriving.InstanceDeriver;
78 import org.simantics.scl.compiler.internal.deriving.InstanceDerivers;
79 import org.simantics.scl.compiler.internal.elaboration.profiling.BranchPointInjector;
80 import org.simantics.scl.compiler.internal.elaboration.utils.StronglyConnectedComponents;
81 import org.simantics.scl.compiler.internal.header.ModuleHeader;
82 import org.simantics.scl.compiler.internal.parsing.declarations.ConstructorAst;
83 import org.simantics.scl.compiler.internal.parsing.declarations.DAnnotationAst;
84 import org.simantics.scl.compiler.internal.parsing.declarations.DClassAst;
85 import org.simantics.scl.compiler.internal.parsing.declarations.DDataAst;
86 import org.simantics.scl.compiler.internal.parsing.declarations.DDerivingInstanceAst;
87 import org.simantics.scl.compiler.internal.parsing.declarations.DEffectAst;
88 import org.simantics.scl.compiler.internal.parsing.declarations.DFixityAst;
89 import org.simantics.scl.compiler.internal.parsing.declarations.DInstanceAst;
90 import org.simantics.scl.compiler.internal.parsing.declarations.DMappingRelationAst;
91 import org.simantics.scl.compiler.internal.parsing.declarations.DRelationAst;
92 import org.simantics.scl.compiler.internal.parsing.declarations.DRuleAst;
93 import org.simantics.scl.compiler.internal.parsing.declarations.DRulesetAst;
94 import org.simantics.scl.compiler.internal.parsing.declarations.DTypeAst;
95 import org.simantics.scl.compiler.internal.parsing.declarations.DValueAst;
96 import org.simantics.scl.compiler.internal.parsing.declarations.DValueTypeAst;
97 import org.simantics.scl.compiler.internal.parsing.exceptions.SCLSyntaxErrorException;
98 import org.simantics.scl.compiler.internal.parsing.translation.ProcessedDClassAst;
99 import org.simantics.scl.compiler.internal.parsing.translation.ProcessedDInstanceAst;
100 import org.simantics.scl.compiler.internal.parsing.translation.RelationRepository;
101 import org.simantics.scl.compiler.internal.parsing.translation.ValueRepository;
102 import org.simantics.scl.compiler.internal.parsing.types.TypeAst;
103 import org.simantics.scl.compiler.module.ConcreteModule;
104 import org.simantics.scl.compiler.module.ImportDeclaration;
105 import org.simantics.scl.compiler.module.InvalidModulePathException;
106 import org.simantics.scl.compiler.module.ModuleUtils;
107 import org.simantics.scl.compiler.module.repository.ImportFailure;
108 import org.simantics.scl.compiler.module.repository.ImportFailureException;
109 import org.simantics.scl.compiler.types.TCon;
110 import org.simantics.scl.compiler.types.TForAll;
111 import org.simantics.scl.compiler.types.TFun;
112 import org.simantics.scl.compiler.types.TPred;
113 import org.simantics.scl.compiler.types.TVar;
114 import org.simantics.scl.compiler.types.Type;
115 import org.simantics.scl.compiler.types.Types;
116 import org.simantics.scl.compiler.types.kinds.Kind;
117 import org.simantics.scl.compiler.types.kinds.Kinds;
118 import org.simantics.scl.compiler.types.util.MultiFunction;
119 import org.simantics.scl.runtime.profiling.BranchPoint;
120
121 import gnu.trove.list.array.TIntArrayList;
122 import gnu.trove.map.hash.THashMap;
123 import gnu.trove.map.hash.TObjectIntHashMap;
124 import gnu.trove.procedure.TObjectObjectProcedure;
125 import gnu.trove.set.hash.THashSet;
126 import gnu.trove.set.hash.TIntHashSet;
127
128 public class Elaboration {
129     // inputs
130     private final CompilationContext compilationContext;
131     private final ErrorLog errorLog;
132     private final String moduleName;
133     private final ModuleHeader moduleHeader;
134     private final ArrayList<ImportDeclaration> importsAst;
135     private final JavaReferenceValidatorFactory jrvFactory;
136     final JavaReferenceValidator<Object, Object, Object, Object> javaReferenceValidator;
137     private final ValueRepository valueDefinitionsAst;
138     private final RelationRepository relationDefinitionsAst;
139
140     // creates
141     ConcreteModule module;
142     Environment importedEnvironment;
143     ArrayList<SupplementedValueType> supplementedTypeAnnotations = new ArrayList<SupplementedValueType>();
144     
145     JavaTypeTranslator javaTypeTranslator;
146     ArrayList<StandardTypeConstructor> dataTypes = new ArrayList<StandardTypeConstructor>();
147     THashMap<String, ClassRef> classRefs = new THashMap<String, ClassRef>();
148     THashMap<String, BranchPoint[]> branchPoints; 
149     
150     public Elaboration(CompilationContext compilationContext, CompilationTimer timer, EnvironmentFactory localEnvironmentFactory,
151             String moduleName, ModuleHeader moduleHeader, ArrayList<ImportDeclaration> importsAst,
152             JavaReferenceValidatorFactory jrvFactory,
153             ValueRepository valueDefinitionsAst,
154             RelationRepository relationDefinitionsAst) {
155         this.compilationContext = compilationContext;
156         this.errorLog = compilationContext.errorLog;
157         this.moduleName = moduleName;
158         this.moduleHeader = moduleHeader;
159         importsAst = processRelativeImports(importsAst);
160         this.importsAst = importsAst;
161         this.jrvFactory = jrvFactory;
162         this.javaReferenceValidator = moduleHeader == null || moduleHeader.classLoader == null
163                 ? jrvFactory.getDefaultJavaReferenceValidator()
164                 : jrvFactory.getJavaReferenceValidator(moduleHeader.classLoader);
165         if(javaReferenceValidator == null)
166             errorLog.log(moduleHeader.classLoaderLocation, "Didn't find the specified class loader.");
167         this.valueDefinitionsAst = valueDefinitionsAst;
168         this.relationDefinitionsAst = relationDefinitionsAst;
169
170         module = new ConcreteModule(moduleName);
171         compilationContext.module = module;
172         if(moduleHeader != null) {
173             if(moduleHeader.defaultLocalName != null)
174                 module.setDefaultLocalName(moduleHeader.defaultLocalName);
175             if(moduleHeader.deprecated != null)
176                 module.setDeprecation(moduleHeader.deprecated);
177         }
178         try {
179             if(timer != null)
180                 timer.suspendTimer();
181             importedEnvironment = localEnvironmentFactory.createEnvironment(
182                     compilationContext,
183                     importsAst.toArray(new ImportDeclaration[importsAst.size()]));
184             if(timer != null)
185                 timer.continueTimer();
186             compilationContext.environment = new EnvironmentOfModule(importedEnvironment, module);
187         } catch (ImportFailureException e) {
188             for(ImportFailure failure : e.failures)
189                 errorLog.log(new CompilationError(failure.location, failure.toString(), ErrorSeverity.IMPORT_ERROR));
190             return;
191         }
192         for(ImportDeclaration importAst : importsAst)
193             this.module.addDependency(new ImportDeclaration(
194                     importAst.moduleName,
195                     importAst.reexport ? importAst.localName : null,
196                     false,
197                     importAst.spec));
198         localEnvironmentFactory.addBuiltinDependencies(module);
199         compilationContext.namingPolicy = new JavaNamingPolicy(moduleName);
200     }
201     
202     private ArrayList<ImportDeclaration> processRelativeImports(ArrayList<ImportDeclaration> relativeImports) {
203         ArrayList<ImportDeclaration> absoluteImports = new ArrayList<ImportDeclaration>(relativeImports.size());
204         for(ImportDeclaration relativeImport : relativeImports) {
205             if(relativeImport.moduleName.startsWith(".")) {
206                                 try {
207                                         String absoluteModuleName = ModuleUtils.resolveAbsolutePath(moduleName, relativeImport.moduleName);
208                     ImportDeclaration absoluteImport = new ImportDeclaration(
209                             absoluteModuleName, relativeImport.localName,
210                             relativeImport.reexport, relativeImport.spec);
211                     absoluteImport.location = relativeImport.location;
212                     absoluteImports.add(absoluteImport);
213                                 } catch (InvalidModulePathException e) {
214                                         errorLog.log(relativeImport.location, e.getMessage());
215                                 }
216             }
217             else
218                 absoluteImports.add(relativeImport);
219         }
220         return absoluteImports;
221     }
222
223     public void addTypesToEnvironment(
224             ArrayList<DDataAst> dataTypesAst,
225             ArrayList<DTypeAst> typeAliasesAst,
226             ArrayList<DEffectAst> effectsAst,
227             ArrayList<DRulesetAst> rulesetsAst) {
228         for(DDataAst dataType : dataTypesAst) {
229             dataType.parameterKinds = new Kind[dataType.parameters.length];
230             Kind constructorKind = Kinds.STAR;
231             for(int i=dataType.parameters.length-1;i>=0;--i) {
232                 Kind kind = Kinds.metaVar();
233                 dataType.parameterKinds[i] = kind;
234                 constructorKind = Kinds.arrow(kind, constructorKind);
235             }
236             
237             StandardTypeConstructor typeConstructor = new StandardTypeConstructor(
238                     Types.con(moduleName, dataType.name), constructorKind);
239
240             NameExistenceChecks.checkIfTypeExists(errorLog,
241                     dataType.location, importedEnvironment, dataType.name);
242             addTypeDescriptor(dataType.location, dataType.name, typeConstructor);
243             dataType.typeConstructor = typeConstructor;
244         }
245         
246         for(DTypeAst typeAlias : typeAliasesAst) {
247             TypeAlias alias = new TypeAlias(Types.con(moduleName, typeAlias.name), typeAlias.parameters.length);
248             NameExistenceChecks.checkIfTypeExists(errorLog,
249                     typeAlias.location, importedEnvironment, typeAlias.name);
250             addTypeDescriptor(typeAlias.location, typeAlias.name, alias);
251         }
252         
253         for(DEffectAst effect : effectsAst) {
254             EffectConstructor effectConstructor = new EffectConstructor(Types.con(moduleName, effect.name));
255             effectConstructor.addThreadLocalVariable(
256                     new ThreadLocalVariable(
257                             effect.variableName,
258                             TypeDesc.forClass(effect.threadLocalType)
259                             ));
260             if(module.addEffectConstructor(effect.name, effectConstructor))
261                 errorLog.log(effect.location, "Effect "+effect.name+" has already been defined in this module.");
262         }
263         for(DRulesetAst ruleset : rulesetsAst) {
264             ruleset.type = Types.con(moduleName, ruleset.name);
265             ruleset.className = compilationContext.namingPolicy.getDataTypeClassName(ruleset.name);
266             StandardTypeConstructor typeConstructor = new StandardTypeConstructor(ruleset.type, Kinds.STAR,
267                     TypeDesc.forClass(ruleset.className), ruleset.documentation == null ? null : ruleset.documentation.documentation);
268             typeConstructor.external = true;
269             addTypeDescriptor(ruleset.location, ruleset.name, typeConstructor);
270         }
271         javaTypeTranslator = new JavaTypeTranslator(compilationContext.environment);
272         compilationContext.javaTypeTranslator = javaTypeTranslator;
273     }
274         
275     private void addTypeDescriptor(long location, String name, TypeDescriptor typeDescriptor) {
276         if(module.addTypeDescriptor(name, typeDescriptor))
277             errorLog.log(location, "Type "+name+" has already been defined in this module.");
278     }
279     
280     private static final int[] EMPTY_INT_ARRAY = new int[0];
281     
282     public void processTypeAliases(ArrayList<DTypeAst> typeAliasesAst) {
283         TObjectIntHashMap<String> typeAliasMap = new TObjectIntHashMap<String>();
284         for(int i=0;i<typeAliasesAst.size();++i)
285             typeAliasMap.put(typeAliasesAst.get(i).name, i); 
286         TIntHashSet tempIntSet = new TIntHashSet();
287         ArrayList<DTypeAst> orderedTypeAliases = new ArrayList<DTypeAst>(typeAliasesAst.size()); 
288         //for(int i=0;i<typeAliasesAst.size();++i)
289         //    System.out.println(i + "# " + typeAliasesAst.get(i).name);
290         new StronglyConnectedComponents(typeAliasesAst.size()) {
291             @Override
292             protected int[] findDependencies(int u) {
293                 typeAliasesAst.get(u).type.collectReferences(typeAliasMap, tempIntSet);
294                 if(tempIntSet.isEmpty())
295                     return EMPTY_INT_ARRAY;
296                 if(tempIntSet.contains(u)) {
297                     errorLog.log(typeAliasesAst.get(u).location, "Type alias has a self reference.");
298                     tempIntSet.remove(u);
299                 }
300                 int[] result = tempIntSet.toArray();
301                 tempIntSet.clear();
302                 //System.out.println(u + " -> " + Arrays.toString(result));
303                 return result; 
304             }
305             @Override
306             protected void reportComponent(int[] component) {
307                 //System.out.println("component: " + Arrays.toString(component));
308                 if(component.length > 1) {
309                     StringBuilder b = new StringBuilder();
310                     b.append("Recursively defined type alias (");
311                     long minLocation = typeAliasesAst.get(component[0]).location;
312                     boolean first = true;
313                     for(int u : component) {
314                         DTypeAst typeAlias = typeAliasesAst.get(u);
315                         if(first)
316                             first = false;
317                         else
318                             b.append(", ");
319                         b.append(typeAlias.name);
320                         if(Locations.beginOf(typeAlias.location) < Locations.beginOf(minLocation))
321                             minLocation = typeAlias.location;
322                     }
323                     b.append(").");
324                     errorLog.log(minLocation, b.toString());
325                 }
326                 else
327                     orderedTypeAliases.add(typeAliasesAst.get(component[0]));
328             }
329         }.findComponents();
330         
331         if(errorLog.hasNoErrors()) {
332             for(DTypeAst typeAlias : orderedTypeAliases) {
333                 TypeAlias alias = (TypeAlias)module.getTypeDescriptor(typeAlias.name);
334                 TypeTranslationContext context = createTypeTranslationContext();
335                 for(int i=0;i<typeAlias.parameters.length;++i)
336                     context.pushTypeVar(typeAlias.parameters[i]);
337                 alias.body = typeAlias.type.toType(context, Kinds.metaVar());
338                 for(int i=0;i<typeAlias.parameters.length;++i)
339                     alias.parameters[i] = context.popTypeVar(typeAlias.parameters[i], null);
340             }
341         }
342     }
343     
344     public void processDataTypes(ArrayList<DDataAst> dataTypesAst) {
345         ArrayList<Runnable> fieldAccessorGenerators = new ArrayList<Runnable>(); 
346         for(DDataAst dataTypeAst : dataTypesAst) {
347             TypeTranslationContext context = createTypeTranslationContext();
348             TVar[] typeParameters = new TVar[dataTypeAst.parameters.length];
349             for(int i=0;i<dataTypeAst.parameters.length;++i)
350                 typeParameters[i] = context.addTypeVar(dataTypeAst.parameters[i]);
351             Constructor[] constructors = new Constructor[dataTypeAst.constructors.length];
352             String className = null;
353             boolean external = false;
354             for(DAnnotationAst annotation : dataTypeAst.getAnnotations()) {
355                 if(annotation.id.text.equals("@JavaType")) {
356                     if(annotation.parameters.length != 1 || 
357                             !(annotation.parameters[0] instanceof ELiteral) ||
358                             !(((ELiteral)annotation.parameters[0]).getValue() instanceof StringConstant))
359                         errorLog.log(annotation.location, "Invalid parameters. Expected @JavaType \"className\".");
360                     else {
361                         className = ((StringConstant)((ELiteral)annotation.parameters[0]).getValue()).getValue().replace('.', '/');
362                         external = true;                        
363                         break;
364                     }
365                 }
366             }
367             
368             boolean trivialDataType = dataTypeAst.constructors.length == 1 &&
369                     dataTypeAst.constructors[0].parameters.length == 1;
370             if(className == null && !trivialDataType)
371                 className = compilationContext.namingPolicy.getDataTypeClassName(dataTypeAst.name);
372             
373             StandardTypeConstructor dataType = dataTypeAst.typeConstructor;
374             
375             dataType.setType(Types.con(moduleName, dataTypeAst.name), typeParameters);
376             dataType.setConstructors(constructors);
377             if(!trivialDataType)
378                 dataType.setTypeDesc(TypeDesc.forClass(className));            
379             if(!external || dataTypeAst.constructors.length > 0) {
380                 dataType.isOpen = false;
381             }
382             dataType.external = external;
383             dataTypes.add(dataType);
384             for(int j=0;j<constructors.length;++j) {
385                 ConstructorAst constructor = dataTypeAst.constructors[j];
386                 String name = constructor.name.text;
387                 Type[] parameterTypes = new Type[constructor.parameters.length];
388                 for(int i=constructor.parameters.length-1;i>=0;--i)
389                     parameterTypes[i] = context.toType(constructor.parameters[i]);
390                 String javaName = constructors.length == 1 ? className 
391                         : compilationContext.namingPolicy.getConstructorClassName(name);
392                 String[] fieldNames = null;
393                 for(DAnnotationAst annotation : constructor.annotations)
394                     if(annotation.id.text.equals("@JavaType")) {
395                         try {
396                             javaName = ((StringConstant)((ELiteral)annotation.parameters[0])
397                                     .getValue()).getValue();
398                         } catch(Exception e) {
399                             errorLog.log(annotation.parameters[0].location, "Invalid annotation parameter.");
400                         }
401                     }
402                     else if(annotation.id.text.equals("@FieldNames")) {
403                         try {
404                             EListLiteral literal = (EListLiteral)annotation.parameters[0];
405                             fieldNames = new String[literal.getComponents().length];
406                             for(int i=0;i<fieldNames.length;++i) {
407                                 Expression component = literal.getComponents()[i];
408                                 if(component instanceof EVar)
409                                     fieldNames[i] = ((EVar)component).name;
410                                 else if(component instanceof ELiteral)
411                                     fieldNames[i] = ((StringConstant)((ELiteral)component).getValue()).getValue();
412                             }
413                         } catch(Exception e) {
414                             errorLog.log(annotation.parameters[0].location, "Invalid annotation parameter.");
415                             fieldNames = null;
416                         }
417                     }   
418                 
419                 constructors[j] = new Constructor(constructor.location, dataType,
420                         Name.create(moduleName, name), 
421                         parameterTypes, javaName);
422                 constructors[j].fieldNames = fieldNames;
423                 constructors[j].recordFieldNames = constructor.fieldNames;
424             }
425             if(constructors.length == 1) {
426                 Constructor constructor = constructors[0];
427                 if(constructor.recordFieldNames != null) {
428                     fieldAccessorGenerators.add(new Runnable() {
429                         @Override
430                         public void run() {
431                             Type in = Types.apply(dataType.name, dataType.parameters);
432                             for(int i=0;i<constructor.recordFieldNames.length;++i) {
433                                 Type out = constructor.parameterTypes[i];
434                                 Constant accessor;
435                                 if(trivialDataType)
436                                     accessor = new SafeCoerce(dataType.parameters, in, out);
437                                 else
438                                     accessor = new CallJava(dataType.parameters, Types.NO_EFFECTS, out,
439                                             new Type[] {in}, new StackItem[] {new ParameterStackItem(0, in)},
440                                             new FieldRef(constructor.javaName, constructor.fieldNames != null ? constructor.fieldNames[i] : "c" + i,
441                                                     javaTypeTranslator.toTypeDesc(out)),
442                                             null);
443                                 module.addFieldAccessor(constructor.recordFieldNames[i], accessor);
444                             }
445                         }
446                     });
447                 }
448             }
449         }
450         
451         for(Runnable fieldAccessorGenerator : fieldAccessorGenerators)
452             fieldAccessorGenerator.run();
453     }
454     
455     public void processTypeClasses(ArrayList<ProcessedDClassAst> typeClassesAst) {
456         for(ProcessedDClassAst pClassAst : typeClassesAst) {
457             DClassAst classAst = pClassAst.orig;
458             
459             if(module.getTypeClass(classAst.name) != null) {
460                 errorLog.log(classAst.location, "Class "+classAst.name+" has already been defined in this module.");
461                 continue;
462             }
463             
464             TypeTranslationContext context = createTypeTranslationContext();            
465             
466             TPred[] classContext = new TPred[classAst.context.length];
467             for(int i=0;i<classContext.length;++i)
468                 classContext[i] = context.toTFuncApply(classAst.context[i]);
469             
470             TVar[] parameters = new TVar[classAst.parameters.length];
471             
472             if(classAst.name.equals("Functor") || classAst.name.equals("Monad")) {
473                 // FIXME hack
474                 parameters[0] = context.resolveTypeVariable(pClassAst.orig.location, classAst.parameters[0], Kinds.STAR_TO_STAR);
475             }
476             else {
477                 for(int i=0;i<parameters.length;++i)
478                     parameters[i] = context.resolveTypeVariable(pClassAst.orig.location, classAst.parameters[i], Kinds.metaVar());
479             }
480                         
481             TCon con = Types.con(moduleName, classAst.name);
482             TypeClass typeClass = new TypeClass(classAst.location, 
483                     classContext, 
484                     con, 
485                     compilationContext.namingPolicy.getTypeClassInterfaceName(con),
486                     parameters,
487                     Fundep.mapFundeps(classAst.parameters, classAst.fundeps));
488             
489             THashMap<String, TypeClassMethod> methods = typeClass.methods;
490             for(DValueTypeAst methodDecl : pClassAst.typeDeclarations) {
491                 try {
492                     Type type;
493                     try {
494                         type = context.toType(methodDecl.type);
495                     } catch(SCLSyntaxErrorException e) {
496                         errorLog.log(e.location, e.getMessage());
497                         continue;
498                     }
499                     for(EVar name : methodDecl.names) {
500                         typeClass.methodNames.add(name.name);
501                         methods.put(name.name,
502                                 new TypeClassMethod(typeClass, name.name, 
503                                         compilationContext.namingPolicy.getMethodName(name.name),
504                                         type, Types.getArity(type),
505                                         name.location)
506                                 );
507                     }
508                 } catch(RuntimeException e) {
509                     errorLog.setExceptionPosition(methodDecl.location);
510                     throw e;
511                 }
512             }
513             
514             for(String methodName : pClassAst.defaultImplementations.getValueNames()) {
515                 String fullName = "_" + classAst.name + "_default_" + methodName;                
516                 ArrayList<DValueAst> defs = pClassAst.defaultImplementations.getDefinition(methodName);
517                 
518                 TypeClassMethod method = typeClass.methods.get(methodName);
519                 if(method == null) {
520                     errorLog.log(defs.get(0).location, "Method " + methodName + " is not defined in this class.");
521                     continue;
522                 }
523                 method.setDefaultImplementation(Name.create(moduleName, fullName));
524                 
525                 valueDefinitionsAst.addDefinitions(fullName, defs);
526                 /*valueDefinitionsAst.addAnnotation(fullName, new DAnnotationAst(new EVar("@private"), 
527                         Collections.<Expression>emptyList()));*/
528                 supplementedTypeAnnotations.add(new SupplementedValueType(defs.get(0).location, fullName, method.getType()));                
529             }
530             
531             module.addTypeClass(classAst.name, typeClass);
532         }
533     }
534
535     private TypeTranslationContext createTypeTranslationContext() {
536         return new TypeTranslationContext(compilationContext);
537     }
538     
539     public void processDerivingInstances(ArrayList<DDerivingInstanceAst> derivingInstancesAst,
540             ArrayList<ProcessedDInstanceAst> instancesAst) {
541         for(DDerivingInstanceAst derivingInstance : derivingInstancesAst) {
542             String name = derivingInstance.name.name;
543             TCon con;
544             try {
545                 con = Environments.getTypeClassName(compilationContext.environment, name);
546             } catch (AmbiguousNameException e) {
547                 errorLog.log(derivingInstance.name.location, e.getMessage());
548                 continue;
549             }
550             if(con == null) {
551                 errorLog.log(derivingInstance.name.location, "Couldn't resolve class " + name + ".");
552                 continue;
553             }
554             InstanceDeriver deriver = InstanceDerivers.get(con);
555             if(deriver == null)
556                 errorLog.log(derivingInstance.location, "Doesn't know how to derive " + name + ".");
557             else
558                 deriver.derive(errorLog, compilationContext.environment, instancesAst, derivingInstance);
559         }
560     }
561     
562     public void processInstances(ArrayList<ProcessedDInstanceAst> instancesAst) {
563         THashSet<TPred> instanceClashCheckSet = new THashSet<TPred>(); 
564         for(ProcessedDInstanceAst pInstanceAst : instancesAst) {
565             DInstanceAst instanceAst = pInstanceAst.orig;
566             try {
567                 TypeTranslationContext context = createTypeTranslationContext();
568                 
569                 String name = instanceAst.name.name;
570                 TCon typeClassCon;
571                 try {
572                     typeClassCon = Environments.getTypeClassName(compilationContext.environment, name);
573                 } catch (AmbiguousNameException e) {
574                     errorLog.log(instanceAst.name.location, e.getMessage());
575                     continue;
576                 }
577                 if(typeClassCon == null) {
578                     errorLog.log(instanceAst.name.location, "Couldn't resolve class " + name + ".");
579                     continue;
580                 }
581                 TypeClass typeClass = compilationContext.environment.getTypeClass(typeClassCon);
582                 pInstanceAst.typeClass = typeClass;
583                 
584                 if(instanceAst.types.length != typeClass.parameters.length) {
585                     errorLog.log(instanceAst.location, "Wrong number of parameters to type class " + typeClassCon.name + ".");
586                     continue;
587                 }
588                 Type[] parameters = new Type[instanceAst.types.length];
589                 for(int i=0;i<parameters.length;++i)
590                     parameters[i] = context.toType(instanceAst.types[i], typeClass.parameters[i].getKind() /* FIXME */);
591                 TPred instance = Types.pred(typeClassCon, parameters);
592                 
593                 if(!instanceClashCheckSet.add(instance)) {
594                     errorLog.log(instanceAst.location, "Duplicate definition of the instance " + instance + ".");
595                     continue;
596                 }
597                 
598                 TPred[] instanceContext = new TPred[instanceAst.context.length];
599                 for(int i=0;i<instanceContext.length;++i)
600                     instanceContext[i] = context.toTFuncApply(instanceAst.context[i]);
601                 
602                 String javaName = compilationContext.namingPolicy.getInstanceClassName(instance);
603                 String instancePrefix = instance.toName() + "$";
604     
605                 ValueRepository valueDefs = pInstanceAst.valueDefs;
606     
607                 THashMap<String, MethodImplementation> methodImplementations =
608                         new THashMap<String, MethodImplementation>();
609                 for(String valueName : valueDefs.getValueNames()) {
610                     String fullName = instancePrefix + valueName;
611                     long loc = valueDefs.getDefinition(valueName).get(0).location;
612                     valueDefinitionsAst.addFrom(valueDefs, valueName, fullName);
613                     valueDefinitionsAst.setDerived(fullName);
614                     /*valueDefinitionsAst.addAnnotation(fullName, new DAnnotationAst(new EVar("@private"), 
615                             Collections.<Expression>emptyList()));*/
616                     TypeClassMethod method = typeClass.methods.get(valueName);
617                     if(method == null) {
618                         errorLog.log(loc, "Method " + valueName + " is not defined in the type class " + typeClass.name.name + ".");
619                         continue;
620                     }
621                     Type type = method.getBaseType().replace(typeClass.parameters, parameters);
622                     for(int i=instanceContext.length-1;i>=0;--i)
623                         type = Types.constrained(instanceContext[i], type);
624                     //System.out.println(valueName + " :: " + type);
625                     supplementedTypeAnnotations.add(
626                             new SupplementedValueType(loc, fullName, type));
627                     methodImplementations.put(valueName,
628                             new MethodImplementation(Name.create(moduleName, fullName), false));
629                 }
630                 
631                 // Are all necessary methods defined
632                 for(String methodName : typeClass.methods.keySet())
633                     if(!methodImplementations.containsKey(methodName)) {
634                         Name defaultImplementation = typeClass.methods.get(methodName).getDefaultImplementation();
635                         if(defaultImplementation == null)
636                             errorLog.log(instanceAst.location, "Method " + methodName + " is not defined.");
637                         else
638                             methodImplementations.put(methodName, 
639                                     new MethodImplementation(defaultImplementation, true));
640                     }
641                 
642                 JavaTypeInstanceConstructor generator = new JavaTypeInstanceConstructor(javaName, instance, instanceContext);
643                 if(instanceContext.length == 0)
644                     generator.setHasStaticInstance(true);
645                 
646                 TypeClassInstance typeClassInstance = 
647                         new TypeClassInstance(instanceAst.location, typeClass, generator,
648                                 generator.getTypeParameters(),
649                                 instanceContext, instance, methodImplementations,
650                                 javaName);
651                 
652                 generator.setInstance(typeClassInstance);
653                 
654                 module.addTypeClassInstance(typeClassCon, typeClassInstance);
655             } catch(RuntimeException e) {
656                 errorLog.setExceptionPosition(instanceAst.location);
657                 throw e;
658             }
659         }
660         
661         // Generate superclass functions
662         for(ArrayList<TypeClassInstance> instanceArray : module.getTypeInstances().values())
663             for(TypeClassInstance instance : instanceArray) {
664                 try {
665                     TypeClass typeClass = instance.typeClass;
666                     int superCount = typeClass.context.length;
667                     
668                     instance.superExpressions = new SCLValue[superCount];
669                     for(int i=0;i<superCount;++i) {
670                         TPred type = (TPred)typeClass.context[i]
671                                 .replace(typeClass.parameters, instance.instance.parameters);
672                         SCLValue value = new SCLValue(Name.create(moduleName, 
673                                 instance.javaName.substring(instance.javaName.indexOf('$')+1) + "_super" + i));
674                         //value.addProperty(PrivateProperty.INSTANCE);
675                         module.addValue(value);
676                         Expression expression = new EGetConstraint(instance.location, type);
677                         value.setExpression(expression);
678                         value.setType(Types.forAll(instance.generatorParameters, Types.constrained(instance.context, type)));
679                         value.getProperties().add(new InlineProperty(instance.context.length, 0xffffffff));
680                         //TypeUnparsingContext tuc = new TypeUnparsingContext();
681                         // TODO error handling
682                         instance.superExpressions[i] = value;
683                     }
684                 } catch(RuntimeException e) {
685                     errorLog.setExceptionPosition(instance.getLocation());
686                     throw e;
687                 }
688             }
689     }
690     
691     public void processJavaMethods(ArrayList<JavaMethodDeclaration> javaMethodDeclarations) {
692         for(JavaMethodDeclaration javaMethod : javaMethodDeclarations) {
693             String name = javaMethod.methodName.name;
694             String javaName = name;
695             ArrayList<DAnnotationAst> annotations = 
696                     valueDefinitionsAst.getAnnotations(name);
697             boolean isPrivate = false;
698             if(annotations != null) {
699                 for(DAnnotationAst annotation : annotations)
700                     if(annotation.id.text.equals("@JavaName")) {
701                         String temp = AnnotationUtils.processStringAnnotation(errorLog, annotation);
702                         if(temp != null)
703                             javaName = temp;
704                     }
705                     else if(annotation.id.text.equals("@private")) {
706                         AnnotationUtils.processTagAnnotation(errorLog, annotation);
707                         isPrivate = true;
708                     }
709             }
710             
711             Type type = createTypeTranslationContext().toType(javaMethod.type);
712
713             CallJava callJava = resolveMethod(
714                     javaMethod.location,
715                     javaMethod.className,
716                     javaName,
717                     type);
718             if(callJava != null) {
719                 NameExistenceChecks.checkIfValueExists(errorLog, javaMethod.location,
720                         importedEnvironment, module, name);
721                 SCLValue value = module.addValue(name, callJava);
722                 value.definitionLocation = javaMethod.methodName.location;
723                 if(isPrivate)
724                     value.addProperty(PrivateProperty.INSTANCE);
725             }
726         }
727     }
728     
729     public void processRulesets(ArrayList<DRulesetAst> rulesetsAst) {
730         for(DRulesetAst ruleset : rulesetsAst) {
731             String constructorName = "create" + ruleset.name;
732             supplementedTypeAnnotations.add(new SupplementedValueType(ruleset.location, constructorName, Types.functionE(Types.PUNIT, Types.PROC, ruleset.type)));
733             try {
734                 valueDefinitionsAst.add(new DValueAst(new EVar(constructorName), new EPreCHRRulesetConstructor(ruleset)));
735             } catch (NotPatternException e) {
736                 throw new InternalCompilerError(ruleset.location, e);
737             }
738         }
739     }
740     
741     /**
742      * Convert a java class method into a {@link CallJava} instance.
743      * Compilation errors are logged for failures in finding the named class or in accessing the method.
744      * The return value for errors is {@code null}.
745      * 
746      * @param loc  SCL source location
747      * @param className  Name of the class
748      * @param methodName  Name of the method
749      * @param type  The expected SCL type of the method 
750      * @return  A new JavaCall instance, or null if the given method can not be instantiated.
751      */
752     private CallJava resolveMethod(long loc,
753             String className, String methodName, Type type) {
754         // Resolve class
755         ClassRef classRef = classRefs.get(className);
756         if(classRef == null) {
757             if(classRefs.containsKey(className))
758                 return null;
759             classRef = javaReferenceValidator.getClassRef(className);
760             classRefs.put(className, classRef);
761             if(classRef == null) {
762                 errorLog.log(loc, "Didn't find class " + className + ".");
763                 return null;
764             }
765             if(!javaReferenceValidator.isPublic(classRef.getClass())) {
766                 errorLog.log(loc, "Class " + className + " is not public.");
767                 return null;
768             }
769             
770         }
771         
772         // Resolve method
773         List<MethodRef> methodRefs = classRef.getMethodRefs(methodName);
774         if(methodRefs.isEmpty()) {
775             errorLog.log(loc, "Didn't find any public method or field with name '" + methodName + "' from class " + className + ".");
776             return null;
777         }
778         
779         ArrayList<CallJava> candidates = new ArrayList<CallJava>(2); 
780         for(MethodRef methodRef : methodRefs) {
781             CallJava candidate = matchType(methodRef, type);
782             if(candidate != null)
783                 candidates.add(candidate);
784         }
785
786         if(candidates.isEmpty()) {
787             StringBuilder b = new StringBuilder();
788             b.append("Didn't find any public method or field matching the type " + type + ". The following methods and fields were tried:");
789             for(MethodRef methodRef : methodRefs) {
790                 b.append("\n    ");
791                 b.append(methodRef);
792             }
793             b.append("\nbut expected something like:");
794             {
795                 MultiFunction mFun = Types.matchFunction(type);
796                 b.append("\n    public static ");
797                 b.append(javaTypeTranslator.toTypeDesc(mFun.returnType).getFullName()).append(' ').append(methodName).append('(');
798                 boolean first = true;
799                 for(Type parameter : mFun.parameterTypes) {
800                     if(first)
801                         first = false;
802                     else
803                         b.append(", ");
804                     b.append(javaTypeTranslator.toTypeDesc(parameter).getFullName());
805                 }
806                 b.append(')');
807             }
808             errorLog.log(loc, b.toString());
809             return null;
810         }
811         else if(candidates.size() == 1)
812             return candidates.get(0);
813         else {
814             // Try to find the best match
815             ArrayList<CallJava> bestCandidates = new ArrayList<CallJava>(candidates.size());
816             loop: for(CallJava candidate : candidates) {
817                 Iterator<CallJava> it = bestCandidates.iterator();
818                 while(it.hasNext()) {
819                     CallJava b = it.next();
820                     switch(candidate.compareTo(javaReferenceValidator, b)) {
821                     case CallJava.LESS:
822                     case CallJava.EQUAL:
823                         continue loop;
824                     case CallJava.GREATER:
825                         it.remove();
826                         break;
827                     case CallJava.INCOMPARABLE:
828                         break;
829                     }
830                 }
831                 bestCandidates.add(candidate);
832             }
833             
834             if(bestCandidates.size() == 1) {
835                 // System.out.println("Choose: " + bestCandidates.get(0).getMethodRef());
836                 return bestCandidates.get(0);
837             }
838             else { 
839                 StringBuilder b = new StringBuilder();
840                 b.append("Found more than one incomparable public methods the type " + type + ":");
841                 for(CallJava callJava : bestCandidates) {
842                     b.append("\n    ");
843                     b.append(callJava.getMethodRef());
844                 }
845                 errorLog.log(loc, b.toString());
846                 return null;
847             }
848         }
849     }
850
851     private CallJava matchType(MethodRef methodRef, Type type) {
852         //System.out.println("-----------------------------------------------------");
853         //System.out.println("method: " + methodRef);
854         //System.out.println("type: " + type);
855
856         type = Types.canonical(type);
857         while(type instanceof TForAll)
858             type = Types.canonical(((TForAll)type).type);
859             
860         TypeDesc[] expectedParameterTypes = methodRef.getParameterTypes();
861         
862         ArrayList<Type> parameterTypes = new ArrayList<Type>();
863         Type effect = Types.NO_EFFECTS;
864         Type returnType = type;
865         
866         StackItem[] stackItems = new StackItem[expectedParameterTypes.length];
867         TIntArrayList unresolvedItems = new TIntArrayList();
868         
869         loop:
870         for(int i=0;i<expectedParameterTypes.length;++i) {
871             Type parameterType;
872             TypeDesc providedParameterType;
873             do {
874                 if(effect != Types.NO_EFFECTS || !(returnType instanceof TFun)) {
875                     while(i < expectedParameterTypes.length)
876                         unresolvedItems.add(i++);
877                     break loop;
878                 }
879                 TFun fun = (TFun)returnType;
880                 parameterType = Types.canonical(fun.domain);
881                 parameterTypes.add(parameterType);
882                 effect = Types.canonical(fun.effect);
883                 returnType = Types.canonical(fun.range);
884                 providedParameterType = javaTypeTranslator.toTypeDesc(parameterType);
885             } while(providedParameterType.equals(TypeDesc.VOID));
886             
887             while(true) {
888                 TypeDesc expectedParameterType = expectedParameterTypes[i];
889                 if(javaReferenceValidator.isAssignableFrom(expectedParameterType,
890                         providedParameterType)) {
891                     stackItems[i] = new ParameterStackItem(
892                             parameterTypes.size()-1, 
893                             parameterType);
894                     break;
895                 }
896                 else
897                     unresolvedItems.add(i++);
898                 if(i == expectedParameterTypes.length) {
899                     parameterTypes.remove(parameterTypes.size()-1);
900                     returnType = Types.functionE(parameterType, effect, returnType);
901                     break;
902                 }
903             } 
904         }
905         //System.out.println("returnType: " + returnType);
906         if(!unresolvedItems.isEmpty()) {
907             ArrayList<TCon> concreteEffects = new ArrayList<TCon>();
908             effect.collectConcreteEffects(concreteEffects);
909             
910             for(TCon eff : concreteEffects) {
911                 EffectConstructor effC = compilationContext.environment.getEffectConstructor(eff);
912                 for(ThreadLocalVariable var : effC.getThreadLocalVariables()) {
913                     for(int i=0;i<unresolvedItems.size();++i) {
914                         int id = unresolvedItems.get(i);
915                         if(!expectedParameterTypes[id].equals(TypeDesc.OBJECT) &&
916                                 javaReferenceValidator.isAssignableFrom(expectedParameterTypes[id], var.type)) {
917                             stackItems[id] = new ThreadLocalStackItem(var.variableName, var.type);
918                             unresolvedItems.removeAt(i);
919                             --i;
920                         }
921                     }
922                 }
923             }
924             
925             if(!unresolvedItems.isEmpty())
926                 return null;
927             /*System.out.print("Unresolved: ");
928             boolean first = true;
929             for(int i=0;i<unresolvedItems.size();++i) {
930                 if(first)
931                     first = false;
932                 else
933                     System.out.print(", ");
934                 System.out.print(expectedParameterTypes[unresolvedItems.get(i)]);
935             }
936             System.out.println();*/            
937         }   
938         OutputFilter filter = null;
939         {
940             TypeDesc providedReturnType = methodRef.getReturnType();
941             if(!providedReturnType.equals(Constants.FUNCTION)) {
942                 while(returnType instanceof TFun && effect == Types.NO_EFFECTS) {
943                     TFun fun = (TFun)returnType;
944                     Type parameterType = Types.canonical(fun.domain);
945                     if(!javaTypeTranslator.toTypeDesc(parameterType).equals(TypeDesc.VOID))
946                         return null;                    
947                     parameterTypes.add(parameterType);
948                     effect = Types.canonical(fun.effect);
949                     returnType = Types.canonical(fun.range);
950                 }
951             }
952             TypeDesc expectedReturnType = 
953                     javaTypeTranslator.toTypeDesc(returnType);
954             if(!javaReferenceValidator.isAssignableFrom(expectedReturnType,
955                     providedReturnType)) {
956                 if(expectedReturnType.equals(TypeDesc.VOID)) {
957                     if(providedReturnType.equals(TypeDesc.DOUBLE) || providedReturnType.equals(TypeDesc.LONG))
958                         filter = Pop2OutputFilter.INSTANCE;
959                     else
960                         filter = PopOutputFilter.INSTANCE;
961                 }
962                 else if(expectedReturnType.equals(Constants.LIST)
963                         && providedReturnType.equals(Constants.COLLECTION))
964                     filter = ConvertToListFilter.INSTANCE;
965                 else
966                     return null;
967             }
968         }
969         
970         CallJava result = new CallJava(
971                 Types.freeVarsArray(type),
972                 effect,
973                 returnType,
974                 parameterTypes.toArray(new Type[parameterTypes.size()]),
975                 stackItems, 
976                 methodRef,
977                 filter);
978         //System.out.println(result.getType());
979         return result;
980     }
981
982     public void processMappingRelations(ArrayList<DMappingRelationAst> mappingRelationsAst) {
983         for(DMappingRelationAst mappingRelation : mappingRelationsAst) {
984             TypeAst[] parameterTypesAst = mappingRelation.parameterTypes;
985             Type[] parameterTypes = new Type[parameterTypesAst.length];
986             TypeTranslationContext typeTranslationContext = createTypeTranslationContext();
987             for(int i=0;i<parameterTypes.length;++i)
988                 parameterTypes[i] = parameterTypesAst[i].toType(typeTranslationContext, Kinds.STAR);
989             MappingRelation mRel = 
990                     new MappingRelation(Name.create(moduleName, mappingRelation.name), parameterTypes);
991             mRel.location = mappingRelation.location;
992             if(module.addMappingRelation(mRel))
993                 errorLog.log(mappingRelation.location, "Mapping relation " + mappingRelation.name + 
994                         " has already been defined.");
995         }
996     }
997
998     THashMap<String, DRuleAst> ruleAstMap = new THashMap<String, DRuleAst>();
999     
1000     public void processRules(ArrayList<DRuleAst> rulesAst) {
1001         // Find implied mapping relations
1002         for(DRuleAst ruleA : rulesAst) {
1003             ArrayList<Query> whereSection = ruleA.getSections().get("where");
1004             if(whereSection != null)
1005                 for(Query query : whereSection) {
1006                     if(!(query instanceof QPreGuard))
1007                         continue;
1008                     QPreGuard guard = (QPreGuard)query;
1009                     if(!(guard.guard instanceof EApply))
1010                         continue;
1011                     EApply apply = (EApply)guard.guard;
1012                     if(!(apply.getFunction() instanceof EVar))
1013                         continue;
1014
1015                     String name = ((EVar)apply.getFunction()).name;
1016                     if(module.getMappingRelation(name) != null)
1017                         continue;
1018
1019                     int arity = apply.getParameters().length;
1020                     Type[] parameterTypes = new Type[arity];
1021                     for(int i=0;i<arity;++i)
1022                         parameterTypes[i] = Types.metaVar(Kinds.STAR);
1023                     MappingRelation mRel = 
1024                             new MappingRelation(Name.create(moduleName, name), parameterTypes);
1025                     mRel.location = query.location;
1026                     module.addMappingRelation(mRel);
1027                 }
1028             if(ruleAstMap.put(ruleA.name, ruleA) != null)
1029                 errorLog.log(ruleA.location, "Rule " + ruleA.name + 
1030                         " has already been defined.");
1031         }
1032         
1033         // 
1034         for(String ruleName : ruleAstMap.keySet())
1035             processRule(ruleName);
1036     }
1037     
1038     private TransformationRule processRule(String ruleName) {
1039         TransformationRule rule = module.getRule(ruleName);
1040         if(rule != null)
1041             return rule;
1042         
1043         DRuleAst ruleAst = ruleAstMap.get(ruleName);
1044         if(ruleAst.alreadyProcessing) {
1045             errorLog.log(ruleAst.location, "Cyclic chain of rule extensions.");
1046             return null;
1047         }
1048         
1049         TransformationRule[] extendsRules;
1050         int length = ruleAst.extendsNames.length;
1051         if(length == 0)
1052             extendsRules = TransformationRule.EMPTY_ARRAY;
1053         else {
1054             extendsRules = new TransformationRule[length];
1055             for(int i=0;i<length;++i) {
1056                 try {
1057                     String extendsName = ruleAst.extendsNames[i];
1058                     TransformationRule extendsRule;
1059                     if(ruleAstMap.containsKey(extendsName))
1060                         extendsRule = processRule(extendsName);
1061                     else {
1062                         extendsRule = Environments.getRule(compilationContext.environment, extendsName);
1063                         if(extendsRule == null)
1064                             errorLog.log(ruleAst.location,
1065                                     "Couldn't resolve rule name " + extendsName + ".");
1066                     }
1067                     extendsRules[i] = extendsRule;
1068                 } catch(AmbiguousNameException e) {
1069                     errorLog.log(ruleAst.location, e.getMessage());
1070                 }
1071             }
1072         }
1073         
1074         final THashMap<SectionName, Query[]> sections = new THashMap<SectionName, Query[]>();
1075
1076         final TranslationContext context = createTranslationContext();
1077         if(length > 0) {
1078             THashMap<String, Variable> variables = context.getVariables();
1079             for(TransformationRule extendsRule : extendsRules) {
1080                 if(extendsRule == null)
1081                     continue;
1082                 for(Variable var : extendsRule.variables)
1083                     if(variables.put(var.getName(), var) != null) {
1084                         errorLog.log(ruleAst.location, 
1085                                 "Variable " + var.getName() + " is defined in more than one base rule, which is not currently allowed.");
1086                     }
1087             }
1088         }
1089         context.pushExistentialFrame();
1090         ruleAst.getSections().forEachEntry(new TObjectObjectProcedure<String, ArrayList<Query>>() {
1091             @Override
1092             public boolean execute(String sectionNameString, ArrayList<Query> queries) {
1093                 Query[] resolvedQueries = new Query[queries.size()];
1094                 for(int i=0;i<resolvedQueries.length;++i)
1095                     resolvedQueries[i] = queries.get(i).resolve(context);
1096
1097                 SectionName sectionName = SectionName.getSectionName(sectionNameString);
1098                 if(sectionName == null)
1099                     context.getErrorLog().log(queries.get(0).location,
1100                             "Invalid section name " + sectionNameString + ".");
1101                 else
1102                     sections.put(sectionName, resolvedQueries);
1103                 return true;
1104             }
1105         });
1106         
1107         Variable[] variables = context.getVariables().values().toArray(new Variable[context.getVariables().size()]);
1108
1109         rule = new TransformationRule(ruleAst.isAbstract,
1110                 Name.create(moduleName, ruleAst.name),
1111                 extendsRules,
1112                 sections, variables);
1113         rule.location = ruleAst.location;
1114         module.addRule(rule);
1115         return rule;
1116     }
1117
1118     public void addDataTypesToEnvironment() {
1119         for(StandardTypeConstructor dataType : dataTypes) {
1120             int constructorTag = 0;
1121             for(Constructor constructor : dataType.constructors) {
1122                 SCLValue value = new SCLValue(constructor.name);
1123                 value.definitionLocation = constructor.loc;
1124                 SCLConstructor sclConstructor = 
1125                         new SCLConstructor(
1126                                 constructor.name.name,
1127                                 constructor.javaName, 
1128                                 constructor.getTypeVariables(),
1129                                 constructorTag++,
1130                                 constructor.getReturnType(),
1131                                 constructor.fieldNames == null 
1132                                         ? SCLConstructor.DEFAULT_FIELD_NAMES[constructor.getParameterTypes().length] 
1133                                         : constructor.fieldNames,
1134                                 constructor.recordFieldNames,
1135                                 constructor.getParameterTypes());
1136                 if(dataType.constructors.length == 1 && (
1137                         dataType.getTypeDesc() == null ||
1138                         (dataType.constructors[0].javaName != null &&
1139                         dataType.constructors[0].javaName.equals(MethodBuilderBase.getClassName(dataType.getTypeDesc())))))
1140                     sclConstructor.setOnlyConstructor(true);
1141                 value.setValue(sclConstructor);
1142                 value.setType(constructor.getType());
1143                 
1144                 NameExistenceChecks.checkIfValueExists(errorLog, constructor.loc,
1145                         importedEnvironment, module, constructor.name.name);
1146                 if(module.addValue(value)) {
1147                     errorLog.log(constructor.loc,
1148                             "Value " + constructor.name.name + " is already defined.");
1149                 }
1150             }
1151         }
1152     }
1153     
1154     public void addTypeClassesToEnvironment() {
1155         for(TypeClass typeClass : module.getTypeClasses()) {
1156             for(TypeClassMethod method : typeClass.methods.values()) {
1157                 SCLValue value = method.createValue();
1158                 value.definitionLocation = method.location;
1159                 NameExistenceChecks.checkIfValueExists(errorLog, Locations.NO_LOCATION,
1160                         importedEnvironment, module, value.getName().name);
1161
1162                 if(module.addValue(value)) {
1163                     String name = method.getName();
1164                     long location = Locations.NO_LOCATION;
1165                     ArrayList<DValueAst> definitions = valueDefinitionsAst.getDefinition(name);
1166                     if(definitions != null && !definitions.isEmpty())
1167                         location = definitions.get(0).location;
1168                     errorLog.log(location, "Value " + name + " is already defined.");
1169                 }
1170             }
1171         }
1172     }
1173     
1174     public void preprocessValueDefinitions(ArrayList<DValueTypeAst> typeAnnotationsAst) {
1175         for(String name : valueDefinitionsAst.getValueNames()) {
1176             SCLValue value = new SCLValue(Name.create(moduleName, name));
1177             
1178             long location = valueDefinitionsAst.getLocation(name);
1179             NameExistenceChecks.checkIfValueExists(errorLog, location,
1180                     importedEnvironment, module, value.getName().name);
1181             value.definitionLocation = location;
1182             if(module.addValue(value))
1183                 errorLog.log(location, "Value " + name + " is already defined.");
1184             if(valueDefinitionsAst.isDerived(name))
1185                 value.addProperty(DerivedProperty.INSTANCE);
1186         }
1187         for(DValueTypeAst valueTypeAst : typeAnnotationsAst)
1188             for(EVar name : valueTypeAst.names) {
1189                 SCLValue value = module.getValue(name.name); 
1190                 if(value == null) {
1191                     errorLog.log(valueTypeAst.location, name.name + " is not defined.");
1192                     value = new SCLValue(Name.create(moduleName, name.name));
1193                     module.addValue(value);
1194                 }
1195                 value.definitionLocation = name.location;
1196             }
1197         for(String name : relationDefinitionsAst.getRelationNames()) {
1198             ConcreteRelation relation = new ConcreteRelation(name);
1199             module.addRelation(name, relation);
1200         }
1201     }
1202     
1203     public void addValueDefinitionsToEnvironment(ArrayList<DValueTypeAst> typeAnnotationsAst) {
1204         THashMap<String, DValueTypeAst> typeMap = new THashMap<String, DValueTypeAst>();
1205         for(DValueTypeAst valueTypeAst : typeAnnotationsAst)
1206             for(EVar name : valueTypeAst.names) {
1207                 if(typeMap.containsKey(name.name))
1208                     errorLog.log(valueTypeAst.location, "Type of "+name.name+" has already been declared in this module.");
1209                 else
1210                     typeMap.put(name.name, valueTypeAst);
1211             }
1212         
1213         THashMap<String, EVar> exportMap = null;
1214         if(moduleHeader != null && moduleHeader.export != null) {
1215             exportMap = new THashMap<String, EVar>();
1216             for(EVar export : moduleHeader.export)
1217                 if(exportMap.put(export.name, export) != null)
1218                     errorLog.log(export.location, "The symbol " + export.name + " is exported multiple times.");
1219         }
1220         
1221         for(String name : valueDefinitionsAst.getValueNames()) {
1222             ArrayList<DValueAst> defs = valueDefinitionsAst.getDefinition(name);
1223             if(defs.size() != 1 || !(defs.get(0).value instanceof EPreCHRRulesetConstructor))
1224                 continue;
1225             try {
1226                 SCLValue value = module.getValue(name);
1227                 TranslationContext context = createTranslationContext();
1228                 Expression expression = context.translateCases2(defs);
1229                 value.setExpression(expression);
1230                 
1231                 if(exportMap != null && exportMap.remove(name) == null)
1232                     value.addProperty(PrivateProperty.INSTANCE);
1233             } catch(RuntimeException e) {
1234                 errorLog.setExceptionPosition(defs.get(0).location);
1235                 throw e;
1236             }
1237         }
1238         for(String name : valueDefinitionsAst.getValueNames()) {
1239             ArrayList<DValueAst> defs = valueDefinitionsAst.getDefinition(name);
1240             if(defs.size() == 1 && defs.get(0).value instanceof EPreCHRRulesetConstructor)
1241                 continue;
1242             try {
1243                 SCLValue value = module.getValue(name);
1244                 TranslationContext context = createTranslationContext();
1245                 Expression expression = context.translateCases2(defs);
1246                 value.setExpression(expression);
1247                 
1248                 DValueTypeAst valueTypeAst = typeMap.remove(name);
1249                 if(valueTypeAst != null)
1250                     value.setType(Types.closure(context.toType(valueTypeAst.type)));
1251                 
1252                 ArrayList<DAnnotationAst> annotations = valueDefinitionsAst.getAnnotations(name);
1253                 if(annotations != null)
1254                     for(DAnnotationAst annotation : annotations) {
1255                         handleAnnotation(value, defs, annotation);
1256                     }
1257                 if(exportMap != null && exportMap.remove(name) == null)
1258                     value.addProperty(PrivateProperty.INSTANCE);
1259             } catch(RuntimeException e) {
1260                 errorLog.setExceptionPosition(defs.get(0).location);
1261                 throw e;
1262             }
1263         }
1264         if(exportMap != null)
1265             for(EVar export : exportMap.values())
1266                 errorLog.log(export.location, "The symbol " + export.name + " is not defined in the module.");
1267         for(String name : relationDefinitionsAst.getRelationNames()) {
1268             ArrayList<DRelationAst> definitions = relationDefinitionsAst.getDefinition(name);
1269             if(definitions.size() > 1) {
1270                 errorLog.log(definitions.get(1).location,
1271                         "Does not yet support definition of relations by more than one rule.");
1272                 continue;
1273             }
1274             
1275             DRelationAst definition = definitions.get(0);
1276             ConcreteRelation relation = (ConcreteRelation)module.getRelation(name);
1277             relation.location = definition.location;
1278             TranslationContext context = createTranslationContext();
1279             definition.translateTo(context, relation);
1280         }
1281     }
1282     
1283     private TranslationContext createTranslationContext() {
1284         return new TranslationContext(compilationContext, null);
1285     }
1286     
1287     private void handleAnnotation(SCLValue value, ArrayList<DValueAst> defs, DAnnotationAst annotation) {
1288         if(annotation.id.text.equals("@macro")) {
1289             value.setMacroRule(new StandardMacroRule());
1290         }
1291         else if(annotation.id.text.equals("@inline")) {
1292             try {
1293                 int arity = defs.get(0).lhs.getFunctionDefinitionPatternArity();
1294                 int phaseMask = 0xffffffff;
1295                 if(annotation.parameters.length > 0) {
1296                     phaseMask = Integer.parseInt(((EIntegerLiteral)annotation.parameters[0]).getValue());
1297                 }
1298                 value.addProperty(new InlineProperty(arity, phaseMask));
1299             } catch(NotPatternException e) {
1300                 errorLog.log(annotation.location, "Inline annotation is invalid: this is not a function.");
1301             }
1302         }
1303         else if(annotation.id.text.equals("@private")) {
1304             if(moduleHeader != null && moduleHeader.export != null)
1305                 errorLog.log(annotation.location, "Annotation @private is not used when module header contains export property.");
1306             value.addProperty(PrivateProperty.INSTANCE);
1307         }
1308         else if(annotation.id.text.equals("@deprecated")) {
1309             String description = "";
1310             if(annotation.parameters.length > 0) {
1311                 if(annotation.parameters.length > 1)
1312                     errorLog.log(annotation.location, "Invalid number of parameters, expected one string.");
1313                 else {
1314                     String temp = AnnotationUtils.extractString(annotation.parameters[0]);
1315                     if(temp == null)
1316                         errorLog.log(annotation.location, "Invalid parameter, expected one string.");
1317                     else
1318                         description = temp;
1319                 }
1320             }
1321             value.addProperty(new DeprecatedProperty(description));
1322         }
1323         else
1324             errorLog.log(annotation.location, "Unknown annotation.");
1325     }
1326
1327     public void addSupplementedTypeAnnotationsToEnvironment() {
1328         for(SupplementedValueType valueType : supplementedTypeAnnotations) {
1329             Type type = Types.closure(valueType.type);
1330             String name = valueType.name;
1331             SCLValue value = module.getValue(name);
1332             if(value == null)
1333                 errorLog.log(valueType.position,
1334                         name + " is not defined.");
1335             else if(value.getType()==null)
1336                 value.setType(type);
1337             else
1338                 errorLog.log(valueType.position, 
1339                         "Type of "+name+" has already been declared in this module.");
1340         }
1341     }
1342     
1343     public void addFixityToEnvironment(ArrayList<DFixityAst> fixityAst) {
1344         for(DFixityAst fixity : fixityAst) {
1345             for(EVar symbol : fixity.symbols) {
1346                 String name = symbol.name;
1347                 SCLValue value = module.getValue(name);
1348                 if(value == null)
1349                     errorLog.log(symbol.location,
1350                             name + " is not defined.");
1351                 else
1352                     value.setPrecedence(fixity.precedence);
1353             }
1354         }
1355     }
1356
1357     public void addCoverageBranchPoints() {
1358         branchPoints = new THashMap<String, BranchPoint[]>();
1359         BranchPointInjector injector = new BranchPointInjector(); 
1360         for(String valueName : valueDefinitionsAst.getValueNames()) {
1361             for(DValueAst valueAst : valueDefinitionsAst.getDefinition(valueName))
1362                 valueAst.value = injector.injectBranchPoint(valueAst.value);
1363             branchPoints.put(valueName, injector.getAndClearBranchPoints());
1364         }
1365     }
1366 }