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