1 package org.simantics.scl.compiler.compilation;
3 import java.util.ArrayList;
4 import java.util.Iterator;
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.Constant;
11 import org.simantics.scl.compiler.constants.JavaTypeInstanceConstructor;
12 import org.simantics.scl.compiler.constants.SCLConstructor;
13 import org.simantics.scl.compiler.constants.StringConstant;
14 import org.simantics.scl.compiler.constants.generic.CallJava;
15 import org.simantics.scl.compiler.constants.generic.ClassRef;
16 import org.simantics.scl.compiler.constants.generic.ConvertToListFilter;
17 import org.simantics.scl.compiler.constants.generic.MethodRef;
18 import org.simantics.scl.compiler.constants.generic.MethodRef.FieldRef;
19 import org.simantics.scl.compiler.constants.generic.OutputFilter;
20 import org.simantics.scl.compiler.constants.generic.ParameterStackItem;
21 import org.simantics.scl.compiler.constants.generic.Pop2OutputFilter;
22 import org.simantics.scl.compiler.constants.generic.PopOutputFilter;
23 import org.simantics.scl.compiler.constants.generic.StackItem;
24 import org.simantics.scl.compiler.constants.generic.ThreadLocalStackItem;
25 import org.simantics.scl.compiler.constants.singletons.SafeCoerce;
26 import org.simantics.scl.compiler.elaboration.contexts.TranslationContext;
27 import org.simantics.scl.compiler.elaboration.contexts.TypeTranslationContext;
28 import org.simantics.scl.compiler.elaboration.errors.NotPatternException;
29 import org.simantics.scl.compiler.elaboration.expressions.EApply;
30 import org.simantics.scl.compiler.elaboration.expressions.EGetConstraint;
31 import org.simantics.scl.compiler.elaboration.expressions.EIntegerLiteral;
32 import org.simantics.scl.compiler.elaboration.expressions.EListLiteral;
33 import org.simantics.scl.compiler.elaboration.expressions.ELiteral;
34 import org.simantics.scl.compiler.elaboration.expressions.EVar;
35 import org.simantics.scl.compiler.elaboration.expressions.Expression;
36 import org.simantics.scl.compiler.elaboration.expressions.Variable;
37 import org.simantics.scl.compiler.elaboration.expressions.annotations.AnnotationUtils;
38 import org.simantics.scl.compiler.elaboration.fundeps.Fundep;
39 import org.simantics.scl.compiler.elaboration.java.JavaMethodDeclaration;
40 import org.simantics.scl.compiler.elaboration.macros.StandardMacroRule;
41 import org.simantics.scl.compiler.elaboration.modules.DeprecatedProperty;
42 import org.simantics.scl.compiler.elaboration.modules.InlineProperty;
43 import org.simantics.scl.compiler.elaboration.modules.MethodImplementation;
44 import org.simantics.scl.compiler.elaboration.modules.PrivateProperty;
45 import org.simantics.scl.compiler.elaboration.modules.SCLValue;
46 import org.simantics.scl.compiler.elaboration.modules.TypeAlias;
47 import org.simantics.scl.compiler.elaboration.modules.TypeClass;
48 import org.simantics.scl.compiler.elaboration.modules.TypeClassInstance;
49 import org.simantics.scl.compiler.elaboration.modules.TypeClassMethod;
50 import org.simantics.scl.compiler.elaboration.query.Query;
51 import org.simantics.scl.compiler.elaboration.query.pre.QPreGuard;
52 import org.simantics.scl.compiler.elaboration.relations.ConcreteRelation;
53 import org.simantics.scl.compiler.elaboration.rules.MappingRelation;
54 import org.simantics.scl.compiler.elaboration.rules.SectionName;
55 import org.simantics.scl.compiler.elaboration.rules.TransformationRule;
56 import org.simantics.scl.compiler.environment.AmbiguousNameException;
57 import org.simantics.scl.compiler.environment.Environment;
58 import org.simantics.scl.compiler.environment.EnvironmentFactory;
59 import org.simantics.scl.compiler.environment.Environments;
60 import org.simantics.scl.compiler.errors.ErrorLog;
61 import org.simantics.scl.compiler.errors.Locations;
62 import org.simantics.scl.compiler.internal.codegen.effects.EffectConstructor;
63 import org.simantics.scl.compiler.internal.codegen.effects.ThreadLocalVariable;
64 import org.simantics.scl.compiler.internal.codegen.types.JavaReferenceValidator;
65 import org.simantics.scl.compiler.internal.codegen.types.JavaReferenceValidatorFactory;
66 import org.simantics.scl.compiler.internal.codegen.types.JavaTypeTranslator;
67 import org.simantics.scl.compiler.internal.codegen.types.StandardTypeConstructor;
68 import org.simantics.scl.compiler.internal.codegen.utils.Constants;
69 import org.simantics.scl.compiler.internal.codegen.utils.JavaNamingPolicy;
70 import org.simantics.scl.compiler.internal.codegen.utils.MethodBuilderBase;
71 import org.simantics.scl.compiler.internal.deriving.InstanceDeriver;
72 import org.simantics.scl.compiler.internal.deriving.InstanceDerivers;
73 import org.simantics.scl.compiler.internal.elaboration.profiling.BranchPointInjector;
74 import org.simantics.scl.compiler.internal.elaboration.utils.StronglyConnectedComponents;
75 import org.simantics.scl.compiler.internal.header.ModuleHeader;
76 import org.simantics.scl.compiler.internal.parsing.declarations.ConstructorAst;
77 import org.simantics.scl.compiler.internal.parsing.declarations.DAnnotationAst;
78 import org.simantics.scl.compiler.internal.parsing.declarations.DClassAst;
79 import org.simantics.scl.compiler.internal.parsing.declarations.DDataAst;
80 import org.simantics.scl.compiler.internal.parsing.declarations.DDerivingInstanceAst;
81 import org.simantics.scl.compiler.internal.parsing.declarations.DEffectAst;
82 import org.simantics.scl.compiler.internal.parsing.declarations.DFixityAst;
83 import org.simantics.scl.compiler.internal.parsing.declarations.DInstanceAst;
84 import org.simantics.scl.compiler.internal.parsing.declarations.DMappingRelationAst;
85 import org.simantics.scl.compiler.internal.parsing.declarations.DRelationAst;
86 import org.simantics.scl.compiler.internal.parsing.declarations.DRuleAst;
87 import org.simantics.scl.compiler.internal.parsing.declarations.DTypeAst;
88 import org.simantics.scl.compiler.internal.parsing.declarations.DValueAst;
89 import org.simantics.scl.compiler.internal.parsing.declarations.DValueTypeAst;
90 import org.simantics.scl.compiler.internal.parsing.exceptions.SCLSyntaxErrorException;
91 import org.simantics.scl.compiler.internal.parsing.translation.ProcessedDClassAst;
92 import org.simantics.scl.compiler.internal.parsing.translation.ProcessedDInstanceAst;
93 import org.simantics.scl.compiler.internal.parsing.translation.RelationRepository;
94 import org.simantics.scl.compiler.internal.parsing.translation.ValueRepository;
95 import org.simantics.scl.compiler.internal.parsing.types.TypeAst;
96 import org.simantics.scl.compiler.module.ConcreteModule;
97 import org.simantics.scl.compiler.module.ImportDeclaration;
98 import org.simantics.scl.compiler.module.InvalidModulePathException;
99 import org.simantics.scl.compiler.module.ModuleUtils;
100 import org.simantics.scl.compiler.module.repository.ImportFailure;
101 import org.simantics.scl.compiler.module.repository.ImportFailureException;
102 import org.simantics.scl.compiler.types.TCon;
103 import org.simantics.scl.compiler.types.TForAll;
104 import org.simantics.scl.compiler.types.TFun;
105 import org.simantics.scl.compiler.types.TPred;
106 import org.simantics.scl.compiler.types.TVar;
107 import org.simantics.scl.compiler.types.Type;
108 import org.simantics.scl.compiler.types.Types;
109 import org.simantics.scl.compiler.types.kinds.Kind;
110 import org.simantics.scl.compiler.types.kinds.Kinds;
111 import org.simantics.scl.compiler.types.util.MultiFunction;
112 import org.simantics.scl.runtime.profiling.BranchPoint;
114 import gnu.trove.list.array.TIntArrayList;
115 import gnu.trove.map.hash.THashMap;
116 import gnu.trove.map.hash.TObjectIntHashMap;
117 import gnu.trove.procedure.TObjectObjectProcedure;
118 import gnu.trove.set.hash.THashSet;
119 import gnu.trove.set.hash.TIntHashSet;
121 public class Elaboration {
123 private final CompilationContext compilationContext;
124 private final ErrorLog errorLog;
125 private final String moduleName;
126 private final ModuleHeader moduleHeader;
127 private final ArrayList<ImportDeclaration> importsAst;
128 private final JavaReferenceValidatorFactory jrvFactory;
129 final JavaReferenceValidator<Object, Object, Object, Object> javaReferenceValidator;
130 private final ValueRepository valueDefinitionsAst;
131 private final RelationRepository relationDefinitionsAst;
134 ConcreteModule module;
135 Environment importedEnvironment;
136 ArrayList<SupplementedValueType> supplementedTypeAnnotations = new ArrayList<SupplementedValueType>();
138 JavaTypeTranslator javaTypeTranslator;
139 ArrayList<StandardTypeConstructor> dataTypes = new ArrayList<StandardTypeConstructor>();
140 THashMap<String, ClassRef> classRefs = new THashMap<String, ClassRef>();
141 THashMap<String, BranchPoint[]> branchPoints;
143 public Elaboration(CompilationContext compilationContext, CompilationTimer timer, EnvironmentFactory localEnvironmentFactory,
144 String moduleName, ModuleHeader moduleHeader, ArrayList<ImportDeclaration> importsAst,
145 JavaReferenceValidatorFactory jrvFactory,
146 ValueRepository valueDefinitionsAst,
147 RelationRepository relationDefinitionsAst) {
148 this.compilationContext = compilationContext;
149 this.errorLog = compilationContext.errorLog;
150 this.moduleName = moduleName;
151 this.moduleHeader = moduleHeader;
152 importsAst = processRelativeImports(importsAst);
153 this.importsAst = importsAst;
154 this.jrvFactory = jrvFactory;
155 this.javaReferenceValidator = moduleHeader == null || moduleHeader.classLoader == null
156 ? jrvFactory.getDefaultJavaReferenceValidator()
157 : jrvFactory.getJavaReferenceValidator(moduleHeader.classLoader);
158 if(javaReferenceValidator == null)
159 errorLog.log(moduleHeader.classLoaderLocation, "Didn't find the specified class loader.");
160 this.valueDefinitionsAst = valueDefinitionsAst;
161 this.relationDefinitionsAst = relationDefinitionsAst;
163 module = new ConcreteModule(moduleName);
164 compilationContext.module = module;
165 if(moduleHeader != null && moduleHeader.defaultLocalName != null)
166 module.setDefaultLocalName(moduleHeader.defaultLocalName);
169 timer.suspendTimer();
170 importedEnvironment = localEnvironmentFactory.createEnvironment(
171 importsAst.toArray(new ImportDeclaration[importsAst.size()]));
173 timer.continueTimer();
174 compilationContext.environment = new EnvironmentOfModule(importedEnvironment, module);
175 } catch (ImportFailureException e) {
176 for(ImportFailure failure : e.failures)
177 errorLog.log(failure.location, failure.toString());
180 for(ImportDeclaration importAst : importsAst)
181 this.module.addDependency(new ImportDeclaration(
182 importAst.moduleName,
183 importAst.reexport ? importAst.localName : null,
186 localEnvironmentFactory.addBuiltinDependencies(module);
187 compilationContext.namingPolicy = new JavaNamingPolicy(moduleName);
190 private ArrayList<ImportDeclaration> processRelativeImports(ArrayList<ImportDeclaration> relativeImports) {
191 ArrayList<ImportDeclaration> absoluteImports = new ArrayList<ImportDeclaration>(relativeImports.size());
192 for(ImportDeclaration relativeImport : relativeImports) {
193 if(relativeImport.moduleName.startsWith(".")) {
195 String absoluteModuleName = ModuleUtils.resolveAbsolutePath(moduleName, relativeImport.moduleName);
196 ImportDeclaration absoluteImport = new ImportDeclaration(
197 absoluteModuleName, relativeImport.localName,
198 relativeImport.reexport, relativeImport.spec);
199 absoluteImport.location = relativeImport.location;
200 absoluteImports.add(absoluteImport);
201 } catch (InvalidModulePathException e) {
202 errorLog.log(relativeImport.location, e.getMessage());
206 absoluteImports.add(relativeImport);
208 return absoluteImports;
211 public void addTypesToEnvironment(
212 ArrayList<DDataAst> dataTypesAst,
213 ArrayList<DTypeAst> typeAliasesAst,
214 ArrayList<DEffectAst> effectsAst) {
215 for(DDataAst dataType : dataTypesAst) {
216 dataType.parameterKinds = new Kind[dataType.parameters.length];
217 Kind constructorKind = Kinds.STAR;
218 for(int i=dataType.parameters.length-1;i>=0;--i) {
219 Kind kind = Kinds.metaVar();
220 dataType.parameterKinds[i] = kind;
221 constructorKind = Kinds.arrow(kind, constructorKind);
224 StandardTypeConstructor typeConstructor = new StandardTypeConstructor(
225 Types.con(moduleName, dataType.name), constructorKind);
227 NameExistenceChecks.checkIfTypeExists(errorLog,
228 dataType.location, importedEnvironment, dataType.name);
229 if(module.addTypeDescriptor(dataType.name, typeConstructor))
230 errorLog.log(dataType.location, "Type "+dataType.name+" has already been defined in this module.");
231 dataType.typeConstructor = typeConstructor;
234 for(DTypeAst typeAlias : typeAliasesAst) {
235 TypeAlias alias = new TypeAlias(Types.con(moduleName, typeAlias.name), typeAlias.parameters.length);
236 NameExistenceChecks.checkIfTypeExists(errorLog,
237 typeAlias.location, importedEnvironment, typeAlias.name);
238 if(module.addTypeDescriptor(typeAlias.name, alias)) {
239 errorLog.log(typeAlias.location, "Type alias "+typeAlias.name+" has already been defined in this module.");
243 for(DEffectAst effect : effectsAst) {
244 EffectConstructor effectConstructor = new EffectConstructor(Types.con(moduleName, effect.name));
245 effectConstructor.addThreadLocalVariable(
246 new ThreadLocalVariable(
248 TypeDesc.forClass(effect.threadLocalType)
250 if(module.addEffectConstructor(effect.name, effectConstructor))
251 errorLog.log(effect.location, "Type "+effect.name+" has already been defined in this module.");
253 javaTypeTranslator = new JavaTypeTranslator(compilationContext.environment);
254 compilationContext.javaTypeTranslator = javaTypeTranslator;
257 private static final int[] EMPTY_INT_ARRAY = new int[0];
259 public void processTypeAliases(ArrayList<DTypeAst> typeAliasesAst) {
260 TObjectIntHashMap<String> typeAliasMap = new TObjectIntHashMap<String>();
261 for(int i=0;i<typeAliasesAst.size();++i)
262 typeAliasMap.put(typeAliasesAst.get(i).name, i);
263 TIntHashSet tempIntSet = new TIntHashSet();
264 ArrayList<DTypeAst> orderedTypeAliases = new ArrayList<DTypeAst>(typeAliasesAst.size());
265 //for(int i=0;i<typeAliasesAst.size();++i)
266 // System.out.println(i + "# " + typeAliasesAst.get(i).name);
267 new StronglyConnectedComponents(typeAliasesAst.size()) {
269 protected int[] findDependencies(int u) {
270 typeAliasesAst.get(u).type.collectReferences(typeAliasMap, tempIntSet);
271 if(tempIntSet.isEmpty())
272 return EMPTY_INT_ARRAY;
273 if(tempIntSet.contains(u)) {
274 errorLog.log(typeAliasesAst.get(u).location, "Type alias has a self reference.");
275 tempIntSet.remove(u);
277 int[] result = tempIntSet.toArray();
279 //System.out.println(u + " -> " + Arrays.toString(result));
283 protected void reportComponent(int[] component) {
284 //System.out.println("component: " + Arrays.toString(component));
285 if(component.length > 1) {
286 StringBuilder b = new StringBuilder();
287 b.append("Recursively defined type alias (");
288 long minLocation = typeAliasesAst.get(component[0]).location;
289 boolean first = true;
290 for(int u : component) {
291 DTypeAst typeAlias = typeAliasesAst.get(u);
296 b.append(typeAlias.name);
297 if(Locations.beginOf(typeAlias.location) < Locations.beginOf(minLocation))
298 minLocation = typeAlias.location;
301 errorLog.log(minLocation, b.toString());
304 orderedTypeAliases.add(typeAliasesAst.get(component[0]));
308 if(errorLog.hasNoErrors()) {
309 for(DTypeAst typeAlias : orderedTypeAliases) {
310 TypeAlias alias = (TypeAlias)module.getTypeDescriptor(typeAlias.name);
311 TypeTranslationContext context = createTypeTranslationContext();
312 for(int i=0;i<typeAlias.parameters.length;++i)
313 context.pushTypeVar(typeAlias.parameters[i]);
314 alias.body = typeAlias.type.toType(context, Kinds.metaVar());
315 for(int i=0;i<typeAlias.parameters.length;++i)
316 alias.parameters[i] = context.popTypeVar(typeAlias.parameters[i], null);
321 public void processDataTypes(ArrayList<DDataAst> dataTypesAst) {
322 ArrayList<Runnable> fieldAccessorGenerators = new ArrayList<Runnable>();
323 for(DDataAst dataTypeAst : dataTypesAst) {
324 TypeTranslationContext context = createTypeTranslationContext();
325 TVar[] typeParameters = new TVar[dataTypeAst.parameters.length];
326 for(int i=0;i<dataTypeAst.parameters.length;++i)
327 typeParameters[i] = context.addTypeVar(dataTypeAst.parameters[i]);
328 Constructor[] constructors = new Constructor[dataTypeAst.constructors.length];
329 String className = null;
330 boolean external = false;
331 for(DAnnotationAst annotation : dataTypeAst.getAnnotations()) {
332 if(annotation.id.text.equals("@JavaType")) {
333 if(annotation.parameters.length != 1 ||
334 !(annotation.parameters[0] instanceof ELiteral) ||
335 !(((ELiteral)annotation.parameters[0]).getValue() instanceof StringConstant))
336 errorLog.log(annotation.location, "Invalid parameters. Expected @JavaType \"className\".");
338 className = ((StringConstant)((ELiteral)annotation.parameters[0]).getValue()).getValue().replace('.', '/');
345 boolean trivialDataType = dataTypeAst.constructors.length == 1 &&
346 dataTypeAst.constructors[0].parameters.length == 1;
347 if(className == null && !trivialDataType)
348 className = compilationContext.namingPolicy.getDataTypeClassName(dataTypeAst.name);
350 StandardTypeConstructor dataType = dataTypeAst.typeConstructor;
352 dataType.setType(Types.con(moduleName, dataTypeAst.name), typeParameters);
353 dataType.setConstructors(constructors);
355 dataType.setTypeDesc(TypeDesc.forClass(className));
356 if(!external || dataTypeAst.constructors.length > 0) {
357 dataType.isOpen = false;
359 dataType.external = external;
360 dataTypes.add(dataType);
361 for(int j=0;j<constructors.length;++j) {
362 ConstructorAst constructor = dataTypeAst.constructors[j];
363 String name = constructor.name;
364 Type[] parameterTypes = new Type[constructor.parameters.length];
365 for(int i=constructor.parameters.length-1;i>=0;--i)
366 parameterTypes[i] = context.toType(constructor.parameters[i]);
367 String javaName = constructors.length == 1 ? className
368 : compilationContext.namingPolicy.getConstructorClassName(name);
369 String[] fieldNames = null;
370 for(DAnnotationAst annotation : constructor.annotations)
371 if(annotation.id.text.equals("@JavaType")) {
373 javaName = ((StringConstant)((ELiteral)annotation.parameters[0])
374 .getValue()).getValue();
375 } catch(Exception e) {
376 errorLog.log(annotation.parameters[0].location, "Invalid annotation parameter.");
379 else if(annotation.id.text.equals("@FieldNames")) {
381 EListLiteral literal = (EListLiteral)annotation.parameters[0];
382 fieldNames = new String[literal.getComponents().length];
383 for(int i=0;i<fieldNames.length;++i) {
384 Expression component = literal.getComponents()[i];
385 if(component instanceof EVar)
386 fieldNames[i] = ((EVar)component).name;
387 else if(component instanceof ELiteral)
388 fieldNames[i] = ((StringConstant)((ELiteral)component).getValue()).getValue();
390 } catch(Exception e) {
391 errorLog.log(annotation.parameters[0].location, "Invalid annotation parameter.");
396 constructors[j] = new Constructor(constructor.location, dataType,
397 Name.create(moduleName, name),
398 parameterTypes, javaName);
399 constructors[j].fieldNames = fieldNames;
400 constructors[j].recordFieldNames = constructor.fieldNames;
402 if(constructors.length == 1) {
403 Constructor constructor = constructors[0];
404 if(constructor.recordFieldNames != null) {
405 fieldAccessorGenerators.add(new Runnable() {
408 Type in = Types.apply(dataType.name, dataType.parameters);
409 for(int i=0;i<constructor.recordFieldNames.length;++i) {
410 Type out = constructor.parameterTypes[i];
413 accessor = new SafeCoerce(dataType.parameters, in, out);
415 accessor = new CallJava(dataType.parameters, Types.NO_EFFECTS, out,
416 new Type[] {in}, new StackItem[] {new ParameterStackItem(0, in)},
417 new FieldRef(constructor.javaName, constructor.fieldNames != null ? constructor.fieldNames[i] : "c" + i,
418 javaTypeTranslator.toTypeDesc(out)),
420 module.addFieldAccessor(constructor.recordFieldNames[i], accessor);
428 for(Runnable fieldAccessorGenerator : fieldAccessorGenerators)
429 fieldAccessorGenerator.run();
432 public void processTypeClasses(ArrayList<ProcessedDClassAst> typeClassesAst) {
433 for(ProcessedDClassAst pClassAst : typeClassesAst) {
434 DClassAst classAst = pClassAst.orig;
436 if(module.getTypeClass(classAst.name) != null) {
437 errorLog.log(classAst.location, "Class "+classAst.name+" has already been defined in this module.");
441 TypeTranslationContext context = createTypeTranslationContext();
443 TPred[] classContext = new TPred[classAst.context.length];
444 for(int i=0;i<classContext.length;++i)
445 classContext[i] = context.toTFuncApply(classAst.context[i]);
447 TVar[] parameters = new TVar[classAst.parameters.length];
449 if(classAst.name.equals("Functor") || classAst.name.equals("Monad")) {
451 parameters[0] = context.resolveTypeVariable(pClassAst.orig.location, classAst.parameters[0], Kinds.STAR_TO_STAR);
454 for(int i=0;i<parameters.length;++i)
455 parameters[i] = context.resolveTypeVariable(pClassAst.orig.location, classAst.parameters[i], Kinds.metaVar());
458 TCon con = Types.con(moduleName, classAst.name);
459 TypeClass typeClass = new TypeClass(classAst.location,
462 compilationContext.namingPolicy.getTypeClassInterfaceName(con),
464 Fundep.mapFundeps(classAst.parameters, classAst.fundeps));
466 THashMap<String, TypeClassMethod> methods = typeClass.methods;
467 for(DValueTypeAst methodDecl : pClassAst.typeDeclarations) {
471 type = context.toType(methodDecl.type);
472 } catch(SCLSyntaxErrorException e) {
473 errorLog.log(e.location, e.getMessage());
476 for(EVar name : methodDecl.names) {
477 typeClass.methodNames.add(name.name);
478 methods.put(name.name,
479 new TypeClassMethod(typeClass, name.name,
480 compilationContext.namingPolicy.getMethodName(name.name),
481 type, Types.getArity(type),
485 } catch(RuntimeException e) {
486 errorLog.setExceptionPosition(methodDecl.location);
491 for(String methodName : pClassAst.defaultImplementations.getValueNames()) {
492 String fullName = "_" + classAst.name + "_default_" + methodName;
493 ArrayList<DValueAst> defs = pClassAst.defaultImplementations.getDefinition(methodName);
495 TypeClassMethod method = typeClass.methods.get(methodName);
497 errorLog.log(defs.get(0).location, "Method " + methodName + " is not defined in this class.");
500 method.setDefaultImplementation(Name.create(moduleName, fullName));
502 valueDefinitionsAst.addDefinitions(fullName, defs);
503 /*valueDefinitionsAst.addAnnotation(fullName, new DAnnotationAst(new EVar("@private"),
504 Collections.<Expression>emptyList()));*/
505 supplementedTypeAnnotations.add(new SupplementedValueType(defs.get(0).location, fullName, method.getType()));
508 module.addTypeClass(classAst.name, typeClass);
512 private TypeTranslationContext createTypeTranslationContext() {
513 return new TypeTranslationContext(compilationContext);
516 public void processDerivingInstances(ArrayList<DDerivingInstanceAst> derivingInstancesAst,
517 ArrayList<ProcessedDInstanceAst> instancesAst) {
518 for(DDerivingInstanceAst derivingInstance : derivingInstancesAst) {
519 String name = derivingInstance.name.name;
522 con = Environments.getTypeClassName(compilationContext.environment, name);
523 } catch (AmbiguousNameException e) {
524 errorLog.log(derivingInstance.name.location, e.getMessage());
528 errorLog.log(derivingInstance.name.location, "Couldn't resolve class " + name + ".");
531 InstanceDeriver deriver = InstanceDerivers.get(con);
533 errorLog.log(derivingInstance.location, "Doesn't know how to derive " + name + ".");
535 deriver.derive(errorLog, compilationContext.environment, instancesAst, derivingInstance);
539 public void processInstances(ArrayList<ProcessedDInstanceAst> instancesAst) {
540 THashSet<TPred> instanceClashCheckSet = new THashSet<TPred>();
541 for(ProcessedDInstanceAst pInstanceAst : instancesAst) {
542 DInstanceAst instanceAst = pInstanceAst.orig;
544 TypeTranslationContext context = createTypeTranslationContext();
546 String name = instanceAst.name.name;
549 typeClassCon = Environments.getTypeClassName(compilationContext.environment, name);
550 } catch (AmbiguousNameException e) {
551 errorLog.log(instanceAst.name.location, e.getMessage());
554 if(typeClassCon == null) {
555 errorLog.log(instanceAst.name.location, "Couldn't resolve class " + name + ".");
558 TypeClass typeClass = compilationContext.environment.getTypeClass(typeClassCon);
559 pInstanceAst.typeClass = typeClass;
561 if(instanceAst.types.length != typeClass.parameters.length) {
562 errorLog.log(instanceAst.location, "Wrong number of parameters to type class " + typeClassCon.name + ".");
565 Type[] parameters = new Type[instanceAst.types.length];
566 for(int i=0;i<parameters.length;++i)
567 parameters[i] = context.toType(instanceAst.types[i], typeClass.parameters[i].getKind() /* FIXME */);
568 TPred instance = Types.pred(typeClassCon, parameters);
570 if(!instanceClashCheckSet.add(instance)) {
571 errorLog.log(instanceAst.location, "Duplicate definition of the instance " + instance + ".");
575 TPred[] instanceContext = new TPred[instanceAst.context.length];
576 for(int i=0;i<instanceContext.length;++i)
577 instanceContext[i] = context.toTFuncApply(instanceAst.context[i]);
579 String javaName = compilationContext.namingPolicy.getInstanceClassName(instance);
580 String instancePrefix = instance.toName() + "$";
582 ValueRepository valueDefs = pInstanceAst.valueDefs;
584 THashMap<String, MethodImplementation> methodImplementations =
585 new THashMap<String, MethodImplementation>();
586 for(String valueName : valueDefs.getValueNames()) {
587 String fullName = instancePrefix + valueName;
588 long loc = valueDefs.getDefinition(valueName).get(0).location;
589 valueDefinitionsAst.addFrom(valueDefs, valueName, fullName);
590 /*valueDefinitionsAst.addAnnotation(fullName, new DAnnotationAst(new EVar("@private"),
591 Collections.<Expression>emptyList()));*/
592 TypeClassMethod method = typeClass.methods.get(valueName);
594 errorLog.log(loc, "Method " + valueName + " is not defined in the type class " + typeClass.name.name + ".");
597 Type type = method.getBaseType().replace(typeClass.parameters, parameters);
598 for(int i=instanceContext.length-1;i>=0;--i)
599 type = Types.constrained(instanceContext[i], type);
600 //System.out.println(valueName + " :: " + type);
601 supplementedTypeAnnotations.add(
602 new SupplementedValueType(loc, fullName, type));
603 methodImplementations.put(valueName,
604 new MethodImplementation(Name.create(moduleName, fullName), false));
607 // Are all necessary methods defined
608 for(String methodName : typeClass.methods.keySet())
609 if(!methodImplementations.containsKey(methodName)) {
610 Name defaultImplementation = typeClass.methods.get(methodName).getDefaultImplementation();
611 if(defaultImplementation == null)
612 errorLog.log(instanceAst.location, "Method " + methodName + " is not defined.");
614 methodImplementations.put(methodName,
615 new MethodImplementation(defaultImplementation, true));
618 JavaTypeInstanceConstructor generator = new JavaTypeInstanceConstructor(javaName, instance, instanceContext);
619 if(instanceContext.length == 0)
620 generator.setHasStaticInstance(true);
622 TypeClassInstance typeClassInstance =
623 new TypeClassInstance(instanceAst.location, typeClass, generator,
624 generator.getTypeParameters(),
625 instanceContext, instance, methodImplementations,
628 generator.setInstance(typeClassInstance);
630 module.addTypeClassInstance(typeClassCon, typeClassInstance);
631 } catch(RuntimeException e) {
632 errorLog.setExceptionPosition(instanceAst.location);
637 // Generate superclass functions
638 for(ArrayList<TypeClassInstance> instanceArray : module.getTypeInstances().values())
639 for(TypeClassInstance instance : instanceArray) {
641 TypeClass typeClass = instance.typeClass;
642 int superCount = typeClass.context.length;
644 instance.superExpressions = new SCLValue[superCount];
645 for(int i=0;i<superCount;++i) {
646 TPred type = (TPred)typeClass.context[i]
647 .replace(typeClass.parameters, instance.instance.parameters);
648 SCLValue value = new SCLValue(Name.create(moduleName,
649 instance.javaName.substring(instance.javaName.indexOf('$')+1) + "_super" + i));
650 //value.addProperty(PrivateProperty.INSTANCE);
651 module.addValue(value);
652 Expression expression = new EGetConstraint(instance.location, type);
653 value.setExpression(expression);
654 value.setType(Types.forAll(instance.generatorParameters, Types.constrained(instance.context, type)));
655 value.getProperties().add(new InlineProperty(instance.context.length, 0xffffffff));
656 //TypeUnparsingContext tuc = new TypeUnparsingContext();
657 // TODO error handling
658 instance.superExpressions[i] = value;
660 } catch(RuntimeException e) {
661 errorLog.setExceptionPosition(instance.getLocation());
667 public void processJavaMethods(ArrayList<JavaMethodDeclaration> javaMethodDeclarations) {
668 for(JavaMethodDeclaration javaMethod : javaMethodDeclarations) {
669 String name = javaMethod.methodName.name;
670 String javaName = name;
671 ArrayList<DAnnotationAst> annotations =
672 valueDefinitionsAst.getAnnotations(name);
673 boolean isPrivate = false;
674 if(annotations != null) {
675 for(DAnnotationAst annotation : annotations)
676 if(annotation.id.text.equals("@JavaName")) {
677 String temp = AnnotationUtils.processStringAnnotation(errorLog, annotation);
681 else if(annotation.id.text.equals("@private")) {
682 AnnotationUtils.processTagAnnotation(errorLog, annotation);
687 Type type = createTypeTranslationContext().toType(javaMethod.type);
689 CallJava callJava = resolveMethod(
691 javaMethod.className,
694 if(callJava != null) {
695 NameExistenceChecks.checkIfValueExists(errorLog, javaMethod.location,
696 importedEnvironment, name);
697 SCLValue value = module.addValue(name, callJava);
698 value.definitionLocation = javaMethod.methodName.location;
700 value.addProperty(PrivateProperty.INSTANCE);
706 * Convert a java class method into a {@link CallJava} instance.
707 * Compilation errors are logged for failures in finding the named class or in accessing the method.
708 * The return value for errors is {@code null}.
710 * @param loc SCL source location
711 * @param className Name of the class
712 * @param methodName Name of the method
713 * @param type The expected SCL type of the method
714 * @return A new JavaCall instance, or null if the given method can not be instantiated.
716 private CallJava resolveMethod(long loc,
717 String className, String methodName, Type type) {
719 ClassRef classRef = classRefs.get(className);
720 if(classRef == null) {
721 if(classRefs.containsKey(className))
723 classRef = javaReferenceValidator.getClassRef(className);
724 classRefs.put(className, classRef);
725 if(classRef == null) {
726 errorLog.log(loc, "Didn't find class " + className + ".");
729 if(!javaReferenceValidator.isPublic(classRef.getClass())) {
730 errorLog.log(loc, "Class " + className + " is not public.");
737 List<MethodRef> methodRefs = classRef.getMethodRefs(methodName);
738 if(methodRefs.isEmpty()) {
739 errorLog.log(loc, "Didn't find any public method or field with name '" + methodName + "' from class " + className + ".");
743 ArrayList<CallJava> candidates = new ArrayList<CallJava>(2);
744 for(MethodRef methodRef : methodRefs) {
745 CallJava candidate = matchType(methodRef, type);
746 if(candidate != null)
747 candidates.add(candidate);
750 if(candidates.isEmpty()) {
751 StringBuilder b = new StringBuilder();
752 b.append("Didn't find any public method or field matching the type " + type + ". The following methods and fields were tried:");
753 for(MethodRef methodRef : methodRefs) {
757 b.append("\nbut expected something like:");
759 MultiFunction mFun = Types.matchFunction(type);
760 b.append("\n public static ");
761 b.append(javaTypeTranslator.toTypeDesc(mFun.returnType).getFullName()).append(' ').append(methodName).append('(');
762 boolean first = true;
763 for(Type parameter : mFun.parameterTypes) {
768 b.append(javaTypeTranslator.toTypeDesc(parameter).getFullName());
772 errorLog.log(loc, b.toString());
775 else if(candidates.size() == 1)
776 return candidates.get(0);
778 // Try to find the best match
779 ArrayList<CallJava> bestCandidates = new ArrayList<CallJava>(candidates.size());
780 loop: for(CallJava candidate : candidates) {
781 Iterator<CallJava> it = bestCandidates.iterator();
782 while(it.hasNext()) {
783 CallJava b = it.next();
784 switch(candidate.compareTo(javaReferenceValidator, b)) {
788 case CallJava.GREATER:
791 case CallJava.INCOMPARABLE:
795 bestCandidates.add(candidate);
798 if(bestCandidates.size() == 1) {
799 // System.out.println("Choose: " + bestCandidates.get(0).getMethodRef());
800 return bestCandidates.get(0);
803 StringBuilder b = new StringBuilder();
804 b.append("Found more than one incomparable public methods the type " + type + ":");
805 for(CallJava callJava : bestCandidates) {
807 b.append(callJava.getMethodRef());
809 errorLog.log(loc, b.toString());
815 private CallJava matchType(MethodRef methodRef, Type type) {
816 //System.out.println("-----------------------------------------------------");
817 //System.out.println("method: " + methodRef);
818 //System.out.println("type: " + type);
820 type = Types.canonical(type);
821 while(type instanceof TForAll)
822 type = Types.canonical(((TForAll)type).type);
824 TypeDesc[] expectedParameterTypes = methodRef.getParameterTypes();
826 ArrayList<Type> parameterTypes = new ArrayList<Type>();
827 Type effect = Types.NO_EFFECTS;
828 Type returnType = type;
830 StackItem[] stackItems = new StackItem[expectedParameterTypes.length];
831 TIntArrayList unresolvedItems = new TIntArrayList();
834 for(int i=0;i<expectedParameterTypes.length;++i) {
836 TypeDesc providedParameterType;
838 if(effect != Types.NO_EFFECTS || !(returnType instanceof TFun)) {
839 while(i < expectedParameterTypes.length)
840 unresolvedItems.add(i++);
843 TFun fun = (TFun)returnType;
844 parameterType = Types.canonical(fun.domain);
845 parameterTypes.add(parameterType);
846 effect = Types.canonical(fun.effect);
847 returnType = Types.canonical(fun.range);
848 providedParameterType = javaTypeTranslator.toTypeDesc(parameterType);
849 } while(providedParameterType.equals(TypeDesc.VOID));
852 TypeDesc expectedParameterType = expectedParameterTypes[i];
853 if(javaReferenceValidator.isAssignableFrom(expectedParameterType,
854 providedParameterType)) {
855 stackItems[i] = new ParameterStackItem(
856 parameterTypes.size()-1,
861 unresolvedItems.add(i++);
862 if(i == expectedParameterTypes.length) {
863 parameterTypes.remove(parameterTypes.size()-1);
864 returnType = Types.functionE(parameterType, effect, returnType);
869 //System.out.println("returnType: " + returnType);
870 if(!unresolvedItems.isEmpty()) {
871 ArrayList<TCon> concreteEffects = new ArrayList<TCon>();
872 effect.collectConcreteEffects(concreteEffects);
874 for(TCon eff : concreteEffects) {
875 EffectConstructor effC = compilationContext.environment.getEffectConstructor(eff);
876 for(ThreadLocalVariable var : effC.getThreadLocalVariables()) {
877 for(int i=0;i<unresolvedItems.size();++i) {
878 int id = unresolvedItems.get(i);
879 if(!expectedParameterTypes[id].equals(TypeDesc.OBJECT) &&
880 javaReferenceValidator.isAssignableFrom(expectedParameterTypes[id], var.type)) {
881 stackItems[id] = new ThreadLocalStackItem(var.variableName, var.type);
882 unresolvedItems.removeAt(i);
889 if(!unresolvedItems.isEmpty())
891 /*System.out.print("Unresolved: ");
892 boolean first = true;
893 for(int i=0;i<unresolvedItems.size();++i) {
897 System.out.print(", ");
898 System.out.print(expectedParameterTypes[unresolvedItems.get(i)]);
900 System.out.println();*/
902 OutputFilter filter = null;
904 TypeDesc providedReturnType = methodRef.getReturnType();
905 if(!providedReturnType.equals(Constants.FUNCTION)) {
906 while(returnType instanceof TFun && effect == Types.NO_EFFECTS) {
907 TFun fun = (TFun)returnType;
908 Type parameterType = Types.canonical(fun.domain);
909 if(!javaTypeTranslator.toTypeDesc(parameterType).equals(TypeDesc.VOID))
911 parameterTypes.add(parameterType);
912 effect = Types.canonical(fun.effect);
913 returnType = Types.canonical(fun.range);
916 TypeDesc expectedReturnType =
917 javaTypeTranslator.toTypeDesc(returnType);
918 if(!javaReferenceValidator.isAssignableFrom(expectedReturnType,
919 providedReturnType)) {
920 if(expectedReturnType.equals(TypeDesc.VOID)) {
921 if(providedReturnType.equals(TypeDesc.DOUBLE) || providedReturnType.equals(TypeDesc.LONG))
922 filter = Pop2OutputFilter.INSTANCE;
924 filter = PopOutputFilter.INSTANCE;
926 else if(expectedReturnType.equals(Constants.LIST)
927 && providedReturnType.equals(Constants.COLLECTION))
928 filter = ConvertToListFilter.INSTANCE;
934 CallJava result = new CallJava(
935 Types.freeVarsArray(type),
938 parameterTypes.toArray(new Type[parameterTypes.size()]),
942 //System.out.println(result.getType());
946 public void processMappingRelations(ArrayList<DMappingRelationAst> mappingRelationsAst) {
947 for(DMappingRelationAst mappingRelation : mappingRelationsAst) {
948 TypeAst[] parameterTypesAst = mappingRelation.parameterTypes;
949 Type[] parameterTypes = new Type[parameterTypesAst.length];
950 TypeTranslationContext typeTranslationContext = createTypeTranslationContext();
951 for(int i=0;i<parameterTypes.length;++i)
952 parameterTypes[i] = parameterTypesAst[i].toType(typeTranslationContext, Kinds.STAR);
953 MappingRelation mRel =
954 new MappingRelation(Name.create(moduleName, mappingRelation.name), parameterTypes);
955 mRel.location = mappingRelation.location;
956 if(module.addMappingRelation(mRel))
957 errorLog.log(mappingRelation.location, "Mapping relation " + mappingRelation.name +
958 " has already been defined.");
962 THashMap<String, DRuleAst> ruleAstMap = new THashMap<String, DRuleAst>();
964 public void processRules(ArrayList<DRuleAst> rulesAst) {
965 // Find implied mapping relations
966 for(DRuleAst ruleA : rulesAst) {
967 ArrayList<Query> whereSection = ruleA.getSections().get("where");
968 if(whereSection != null)
969 for(Query query : whereSection) {
970 if(!(query instanceof QPreGuard))
972 QPreGuard guard = (QPreGuard)query;
973 if(!(guard.guard instanceof EApply))
975 EApply apply = (EApply)guard.guard;
976 if(!(apply.getFunction() instanceof EVar))
979 String name = ((EVar)apply.getFunction()).name;
980 if(module.getMappingRelation(name) != null)
983 int arity = apply.getParameters().length;
984 Type[] parameterTypes = new Type[arity];
985 for(int i=0;i<arity;++i)
986 parameterTypes[i] = Types.metaVar(Kinds.STAR);
987 MappingRelation mRel =
988 new MappingRelation(Name.create(moduleName, name), parameterTypes);
989 mRel.location = query.location;
990 module.addMappingRelation(mRel);
992 if(ruleAstMap.put(ruleA.name, ruleA) != null)
993 errorLog.log(ruleA.location, "Rule " + ruleA.name +
994 " has already been defined.");
998 for(String ruleName : ruleAstMap.keySet())
999 processRule(ruleName);
1002 private TransformationRule processRule(String ruleName) {
1003 TransformationRule rule = module.getRule(ruleName);
1007 DRuleAst ruleAst = ruleAstMap.get(ruleName);
1008 if(ruleAst.alreadyProcessing) {
1009 errorLog.log(ruleAst.location, "Cyclic chain of rule extensions.");
1013 TransformationRule[] extendsRules;
1014 int length = ruleAst.extendsNames.length;
1016 extendsRules = TransformationRule.EMPTY_ARRAY;
1018 extendsRules = new TransformationRule[length];
1019 for(int i=0;i<length;++i) {
1021 String extendsName = ruleAst.extendsNames[i];
1022 TransformationRule extendsRule;
1023 if(ruleAstMap.containsKey(extendsName))
1024 extendsRule = processRule(extendsName);
1026 extendsRule = Environments.getRule(compilationContext.environment, extendsName);
1027 if(extendsRule == null)
1028 errorLog.log(ruleAst.location,
1029 "Couldn't resolve rule name " + extendsName + ".");
1031 extendsRules[i] = extendsRule;
1032 } catch(AmbiguousNameException e) {
1033 errorLog.log(ruleAst.location, e.getMessage());
1038 final THashMap<SectionName, Query[]> sections = new THashMap<SectionName, Query[]>();
1040 final TranslationContext context = createTranslationContext();
1042 THashMap<String, Variable> variables = context.getVariables();
1043 for(TransformationRule extendsRule : extendsRules) {
1044 if(extendsRule == null)
1046 for(Variable var : extendsRule.variables)
1047 if(variables.put(var.getName(), var) != null) {
1048 errorLog.log(ruleAst.location,
1049 "Variable " + var.getName() + " is defined in more than one base rule, which is not currently allowed.");
1053 context.pushExistentialFrame();
1054 ruleAst.getSections().forEachEntry(new TObjectObjectProcedure<String, ArrayList<Query>>() {
1056 public boolean execute(String sectionNameString, ArrayList<Query> queries) {
1057 Query[] resolvedQueries = new Query[queries.size()];
1058 for(int i=0;i<resolvedQueries.length;++i)
1059 resolvedQueries[i] = queries.get(i).resolve(context);
1061 SectionName sectionName = SectionName.getSectionName(sectionNameString);
1062 if(sectionName == null)
1063 context.getErrorLog().log(queries.get(0).location,
1064 "Invalid section name " + sectionNameString + ".");
1066 sections.put(sectionName, resolvedQueries);
1071 Variable[] variables = context.getVariables().values().toArray(new Variable[context.getVariables().size()]);
1073 rule = new TransformationRule(ruleAst.isAbstract,
1074 Name.create(moduleName, ruleAst.name),
1076 sections, variables);
1077 rule.location = ruleAst.location;
1078 module.addRule(rule);
1082 public void addDataTypesToEnvironment() {
1083 for(StandardTypeConstructor dataType : dataTypes) {
1084 int constructorTag = 0;
1085 for(Constructor constructor : dataType.constructors) {
1086 SCLValue value = new SCLValue(constructor.name);
1087 SCLConstructor sclConstructor =
1089 constructor.name.name,
1090 constructor.javaName,
1091 constructor.getTypeVariables(),
1093 constructor.getReturnType(),
1094 constructor.fieldNames == null
1095 ? SCLConstructor.DEFAULT_FIELD_NAMES[constructor.getParameterTypes().length]
1096 : constructor.fieldNames,
1097 constructor.recordFieldNames,
1098 constructor.getParameterTypes());
1099 if(dataType.constructors.length == 1 && (
1100 dataType.getTypeDesc() == null ||
1101 dataType.constructors[0].javaName.equals(MethodBuilderBase.getClassName(dataType.getTypeDesc()))))
1102 sclConstructor.setOnlyConstructor(true);
1103 value.setValue(sclConstructor);
1104 value.setType(constructor.getType());
1106 NameExistenceChecks.checkIfValueExists(errorLog, constructor.loc,
1107 importedEnvironment, constructor.name.name);
1108 if(module.addValue(value)) {
1109 errorLog.log(constructor.loc,
1110 "Value " + constructor.name.name + " is already defined.");
1116 public void addTypeClassesToEnvironment() {
1117 for(TypeClass typeClass : module.getTypeClasses()) {
1118 for(TypeClassMethod method : typeClass.methods.values()) {
1119 SCLValue value = method.createValue();
1120 value.definitionLocation = method.location;
1121 NameExistenceChecks.checkIfValueExists(errorLog, Locations.NO_LOCATION,
1122 importedEnvironment, value.getName().name);
1124 if(module.addValue(value)) {
1125 String name = method.getName();
1126 long location = Locations.NO_LOCATION;
1127 ArrayList<DValueAst> definitions = valueDefinitionsAst.getDefinition(name);
1128 if(definitions != null && !definitions.isEmpty())
1129 location = definitions.get(0).location;
1130 errorLog.log(location, "Value " + name + " is already defined.");
1136 public void preprocessValueDefinitions(ArrayList<DValueTypeAst> typeAnnotationsAst) {
1137 for(String name : valueDefinitionsAst.getValueNames()) {
1138 SCLValue value = new SCLValue(Name.create(moduleName, name));
1140 long location = valueDefinitionsAst.getLocation(name);
1141 NameExistenceChecks.checkIfValueExists(errorLog, location,
1142 importedEnvironment, value.getName().name);
1143 value.definitionLocation = location;
1144 if(module.addValue(value))
1145 errorLog.log(location, "Value " + name + " is already defined.");
1147 for(DValueTypeAst valueTypeAst : typeAnnotationsAst)
1148 for(EVar name : valueTypeAst.names) {
1149 SCLValue value = module.getValue(name.name);
1151 errorLog.log(valueTypeAst.location, name.name + " is not defined.");
1152 value = new SCLValue(Name.create(moduleName, name.name));
1153 module.addValue(value);
1155 value.definitionLocation = name.location;
1157 for(String name : relationDefinitionsAst.getRelationNames()) {
1158 ConcreteRelation relation = new ConcreteRelation(name);
1159 module.addRelation(name, relation);
1163 public void addValueDefinitionsToEnvironment(ArrayList<DValueTypeAst> typeAnnotationsAst) {
1164 THashMap<String, DValueTypeAst> typeMap = new THashMap<String, DValueTypeAst>();
1165 for(DValueTypeAst valueTypeAst : typeAnnotationsAst)
1166 for(EVar name : valueTypeAst.names) {
1167 if(typeMap.containsKey(name.name))
1168 errorLog.log(valueTypeAst.location, "Type of "+name.name+" has already been declared in this module.");
1170 typeMap.put(name.name, valueTypeAst);
1173 for(String name : valueDefinitionsAst.getValueNames()) {
1174 ArrayList<DValueAst> defs = valueDefinitionsAst.getDefinition(name);
1176 SCLValue value = module.getValue(name);
1177 TranslationContext context = createTranslationContext();
1178 Expression expression = context.translateCases2(defs);
1179 value.setExpression(expression);
1181 DValueTypeAst valueTypeAst = typeMap.remove(name);
1182 if(valueTypeAst != null)
1183 value.setType(Types.closure(context.toType(valueTypeAst.type)));
1185 ArrayList<DAnnotationAst> annotations = valueDefinitionsAst.getAnnotations(name);
1186 if(annotations != null)
1187 for(DAnnotationAst annotation : annotations) {
1188 handleAnnotation(value, defs, annotation);
1190 } catch(RuntimeException e) {
1191 errorLog.setExceptionPosition(defs.get(0).location);
1195 for(String name : relationDefinitionsAst.getRelationNames()) {
1196 ArrayList<DRelationAst> definitions = relationDefinitionsAst.getDefinition(name);
1197 if(definitions.size() > 1) {
1198 errorLog.log(definitions.get(1).location,
1199 "Does not yet support definition of relations by more than one rule.");
1203 DRelationAst definition = definitions.get(0);
1204 ConcreteRelation relation = (ConcreteRelation)module.getRelation(name);
1205 relation.location = definition.location;
1206 TranslationContext context = createTranslationContext();
1207 definition.translateTo(context, relation);
1211 private TranslationContext createTranslationContext() {
1212 return new TranslationContext(compilationContext, null);
1215 private void handleAnnotation(SCLValue value, ArrayList<DValueAst> defs, DAnnotationAst annotation) {
1216 if(annotation.id.text.equals("@macro")) {
1217 value.setMacroRule(new StandardMacroRule());
1219 else if(annotation.id.text.equals("@inline")) {
1221 int arity = defs.get(0).lhs.getFunctionDefinitionPatternArity();
1222 int phaseMask = 0xffffffff;
1223 if(annotation.parameters.length > 0) {
1224 phaseMask = Integer.parseInt(((EIntegerLiteral)annotation.parameters[0]).getValue());
1226 value.addProperty(new InlineProperty(arity, phaseMask));
1227 } catch(NotPatternException e) {
1228 errorLog.log(annotation.location, "Inline annotation is invalid: this is not a function.");
1231 else if(annotation.id.text.equals("@private")) {
1232 value.addProperty(PrivateProperty.INSTANCE);
1234 else if(annotation.id.text.equals("@deprecated")) {
1235 String description = "";
1236 if(annotation.parameters.length > 0) {
1237 if(annotation.parameters.length > 1)
1238 errorLog.log(annotation.location, "Invalid number of parameters, expected one string.");
1240 String temp = AnnotationUtils.extractString(annotation.parameters[0]);
1242 errorLog.log(annotation.location, "Invalid parameter, expected one string.");
1247 value.addProperty(new DeprecatedProperty(description));
1250 errorLog.log(annotation.location, "Unknown annotation.");
1253 public void addSupplementedTypeAnnotationsToEnvironment() {
1254 for(SupplementedValueType valueType : supplementedTypeAnnotations) {
1255 Type type = Types.closure(valueType.type);
1256 String name = valueType.name;
1257 SCLValue value = module.getValue(name);
1259 errorLog.log(valueType.position,
1260 name + " is not defined.");
1261 else if(value.getType()==null)
1262 value.setType(type);
1264 errorLog.log(valueType.position,
1265 "Type of "+name+" has already been declared in this module.");
1269 public void addFixityToEnvironment(ArrayList<DFixityAst> fixityAst) {
1270 for(DFixityAst fixity : fixityAst) {
1271 for(EVar symbol : fixity.symbols) {
1272 String name = symbol.name;
1273 SCLValue value = module.getValue(name);
1275 errorLog.log(symbol.location,
1276 name + " is not defined.");
1278 value.setPrecedence(fixity.precedence);
1283 public void addCoverageBranchPoints() {
1284 branchPoints = new THashMap<String, BranchPoint[]>();
1285 BranchPointInjector injector = new BranchPointInjector();
1286 for(String valueName : valueDefinitionsAst.getValueNames()) {
1287 for(DValueAst valueAst : valueDefinitionsAst.getDefinition(valueName))
1288 valueAst.value = injector.injectBranchPoint(valueAst.value);
1289 branchPoints.put(valueName, injector.getAndClearBranchPoints());