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.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.repository.ImportFailure;
96 import org.simantics.scl.compiler.module.repository.ImportFailureException;
97 import org.simantics.scl.compiler.types.TCon;
98 import org.simantics.scl.compiler.types.TForAll;
99 import org.simantics.scl.compiler.types.TFun;
100 import org.simantics.scl.compiler.types.TPred;
101 import org.simantics.scl.compiler.types.TVar;
102 import org.simantics.scl.compiler.types.Type;
103 import org.simantics.scl.compiler.types.Types;
104 import org.simantics.scl.compiler.types.kinds.Kind;
105 import org.simantics.scl.compiler.types.kinds.Kinds;
106 import org.simantics.scl.compiler.types.util.MultiFunction;
107 import org.simantics.scl.runtime.profiling.BranchPoint;
109 import gnu.trove.list.array.TIntArrayList;
110 import gnu.trove.map.hash.THashMap;
111 import gnu.trove.map.hash.TObjectIntHashMap;
112 import gnu.trove.procedure.TObjectObjectProcedure;
113 import gnu.trove.set.hash.THashSet;
114 import gnu.trove.set.hash.TIntHashSet;
116 public class Elaboration {
118 private final CompilationContext compilationContext;
119 private final ErrorLog errorLog;
120 private final String moduleName;
121 private final ModuleHeader moduleHeader;
122 private final ArrayList<ImportDeclaration> importsAst;
123 private final JavaReferenceValidatorFactory jrvFactory;
124 final JavaReferenceValidator<Object, Object, Object, Object> javaReferenceValidator;
125 private final ValueRepository valueDefinitionsAst;
126 private final RelationRepository relationDefinitionsAst;
129 ConcreteModule module;
130 Environment importedEnvironment;
131 ArrayList<SupplementedValueType> supplementedTypeAnnotations = new ArrayList<SupplementedValueType>();
133 JavaTypeTranslator javaTypeTranslator;
134 ArrayList<StandardTypeConstructor> dataTypes = new ArrayList<StandardTypeConstructor>();
135 THashMap<String, ClassRef> classRefs = new THashMap<String, ClassRef>();
136 THashMap<String, BranchPoint[]> branchPoints;
138 public Elaboration(CompilationContext compilationContext, CompilationTimer timer, EnvironmentFactory localEnvironmentFactory,
139 String moduleName, ModuleHeader moduleHeader, ArrayList<ImportDeclaration> importsAst,
140 JavaReferenceValidatorFactory jrvFactory,
141 ValueRepository valueDefinitionsAst,
142 RelationRepository relationDefinitionsAst) {
143 this.compilationContext = compilationContext;
144 this.errorLog = compilationContext.errorLog;
145 this.moduleName = moduleName;
146 this.moduleHeader = moduleHeader;
147 importsAst = processRelativeImports(importsAst);
148 this.importsAst = importsAst;
149 this.jrvFactory = jrvFactory;
150 this.javaReferenceValidator = moduleHeader == null || moduleHeader.classLoader == null
151 ? jrvFactory.getDefaultJavaReferenceValidator()
152 : jrvFactory.getJavaReferenceValidator(moduleHeader.classLoader);
153 if(javaReferenceValidator == null)
154 errorLog.log(moduleHeader.classLoaderLocation, "Didn't find the specified class loader.");
155 this.valueDefinitionsAst = valueDefinitionsAst;
156 this.relationDefinitionsAst = relationDefinitionsAst;
158 module = new ConcreteModule(moduleName);
159 compilationContext.module = module;
162 timer.suspendTimer();
163 importedEnvironment = localEnvironmentFactory.createEnvironment(
164 importsAst.toArray(new ImportDeclaration[importsAst.size()]));
166 timer.continueTimer();
167 compilationContext.environment = new EnvironmentOfModule(importedEnvironment, module);
168 } catch (ImportFailureException e) {
169 for(ImportFailure failure : e.failures)
170 errorLog.log(failure.location, failure.toString());
173 for(ImportDeclaration importAst : importsAst)
174 this.module.addDependency(new ImportDeclaration(
175 importAst.moduleName,
176 importAst.reexport ? importAst.localName : null,
179 localEnvironmentFactory.addBuiltinDependencies(module);
180 compilationContext.namingPolicy = new JavaNamingPolicy(moduleName);
183 private ArrayList<ImportDeclaration> processRelativeImports(ArrayList<ImportDeclaration> relativeImports) {
184 ArrayList<ImportDeclaration> absoluteImports = new ArrayList<ImportDeclaration>(relativeImports.size());
185 for(ImportDeclaration relativeImport : relativeImports) {
186 if(relativeImport.moduleName.startsWith(".")) {
187 String absoluteModuleName = convertRelativeModulePath(relativeImport.location, relativeImport.moduleName);
188 if(absoluteModuleName != null) {
189 ImportDeclaration absoluteImport = new ImportDeclaration(
190 absoluteModuleName, relativeImport.localName,
191 relativeImport.reexport, relativeImport.spec);
192 absoluteImport.location = relativeImport.location;
193 absoluteImports.add(absoluteImport);
197 absoluteImports.add(relativeImport);
199 return absoluteImports;
202 private String convertRelativeModulePath(long location, String relativeModuleName) {
203 String originalRelativeModuleName = relativeModuleName;
204 int p = moduleName.lastIndexOf('/');
205 String parentPackage = p < 0 ? "" : moduleName.substring(0, p);
206 while(relativeModuleName.startsWith(".")) {
207 if(relativeModuleName.startsWith("./")) {
208 relativeModuleName = relativeModuleName.substring(2);
210 else if(relativeModuleName.startsWith("../")) {
211 relativeModuleName = relativeModuleName.substring(3);
212 if(parentPackage.isEmpty()) {
213 errorLog.log(location, "Couldn't resolve the relative module name " + originalRelativeModuleName + " when the current module name is " + moduleName + ".");
216 p = parentPackage.lastIndexOf('/');
217 parentPackage = p < 0 ? "" : parentPackage.substring(0, p);
220 errorLog.log(location, "Couldn't resolve the relative module name " + originalRelativeModuleName + ". It has an invalid syntax.");
224 return parentPackage + "/" + relativeModuleName;
227 public void addTypesToEnvironment(
228 ArrayList<DDataAst> dataTypesAst,
229 ArrayList<DTypeAst> typeAliasesAst,
230 ArrayList<DEffectAst> effectsAst) {
231 for(DDataAst dataType : dataTypesAst) {
232 dataType.parameterKinds = new Kind[dataType.parameters.length];
233 Kind constructorKind = Kinds.STAR;
234 for(int i=dataType.parameters.length-1;i>=0;--i) {
235 Kind kind = Kinds.metaVar();
236 dataType.parameterKinds[i] = kind;
237 constructorKind = Kinds.arrow(kind, constructorKind);
240 StandardTypeConstructor typeConstructor = new StandardTypeConstructor(
241 Types.con(moduleName, dataType.name), constructorKind);
243 NameExistenceChecks.checkIfTypeExists(errorLog,
244 dataType.location, importedEnvironment, dataType.name);
245 if(module.addTypeDescriptor(dataType.name, typeConstructor))
246 errorLog.log(dataType.location, "Type "+dataType.name+" has already been defined in this module.");
247 dataType.typeConstructor = typeConstructor;
250 for(DTypeAst typeAlias : typeAliasesAst) {
251 TypeAlias alias = new TypeAlias(Types.con(moduleName, typeAlias.name), typeAlias.parameters.length);
252 NameExistenceChecks.checkIfTypeExists(errorLog,
253 typeAlias.location, importedEnvironment, typeAlias.name);
254 if(module.addTypeDescriptor(typeAlias.name, alias)) {
255 errorLog.log(typeAlias.location, "Type alias "+typeAlias.name+" has already been defined in this module.");
259 for(DEffectAst effect : effectsAst) {
260 EffectConstructor effectConstructor = new EffectConstructor(Types.con(moduleName, effect.name));
261 effectConstructor.addThreadLocalVariable(
262 new ThreadLocalVariable(
264 TypeDesc.forClass(effect.threadLocalType)
266 if(module.addEffectConstructor(effect.name, effectConstructor))
267 errorLog.log(effect.location, "Type "+effect.name+" has already been defined in this module.");
269 javaTypeTranslator = new JavaTypeTranslator(compilationContext.environment);
270 compilationContext.javaTypeTranslator = javaTypeTranslator;
273 private static final int[] EMPTY_INT_ARRAY = new int[0];
275 public void processTypeAliases(ArrayList<DTypeAst> typeAliasesAst) {
276 TObjectIntHashMap<String> typeAliasMap = new TObjectIntHashMap<String>();
277 for(int i=0;i<typeAliasesAst.size();++i)
278 typeAliasMap.put(typeAliasesAst.get(i).name, i);
279 TIntHashSet tempIntSet = new TIntHashSet();
280 ArrayList<DTypeAst> orderedTypeAliases = new ArrayList<DTypeAst>(typeAliasesAst.size());
281 //for(int i=0;i<typeAliasesAst.size();++i)
282 // System.out.println(i + "# " + typeAliasesAst.get(i).name);
283 new StronglyConnectedComponents(typeAliasesAst.size()) {
285 protected int[] findDependencies(int u) {
286 typeAliasesAst.get(u).type.collectReferences(typeAliasMap, tempIntSet);
287 if(tempIntSet.isEmpty())
288 return EMPTY_INT_ARRAY;
289 if(tempIntSet.contains(u)) {
290 errorLog.log(typeAliasesAst.get(u).location, "Type alias has a self reference.");
291 tempIntSet.remove(u);
293 int[] result = tempIntSet.toArray();
295 //System.out.println(u + " -> " + Arrays.toString(result));
299 protected void reportComponent(int[] component) {
300 //System.out.println("component: " + Arrays.toString(component));
301 if(component.length > 1) {
302 StringBuilder b = new StringBuilder();
303 b.append("Recursively defined type alias (");
304 long minLocation = typeAliasesAst.get(component[0]).location;
305 boolean first = true;
306 for(int u : component) {
307 DTypeAst typeAlias = typeAliasesAst.get(u);
312 b.append(typeAlias.name);
313 if(Locations.beginOf(typeAlias.location) < Locations.beginOf(minLocation))
314 minLocation = typeAlias.location;
317 errorLog.log(minLocation, b.toString());
320 orderedTypeAliases.add(typeAliasesAst.get(component[0]));
324 if(errorLog.hasNoErrors()) {
325 for(DTypeAst typeAlias : orderedTypeAliases) {
326 TypeAlias alias = (TypeAlias)module.getTypeDescriptor(typeAlias.name);
327 TypeTranslationContext context = createTypeTranslationContext();
328 for(int i=0;i<typeAlias.parameters.length;++i)
329 context.pushTypeVar(typeAlias.parameters[i]);
330 alias.body = typeAlias.type.toType(context, Kinds.metaVar());
331 for(int i=0;i<typeAlias.parameters.length;++i)
332 alias.parameters[i] = context.popTypeVar(typeAlias.parameters[i], null);
337 public void processDataTypes(ArrayList<DDataAst> dataTypesAst) {
338 for(DDataAst dataTypeAst : dataTypesAst) {
339 TypeTranslationContext context = createTypeTranslationContext();
340 TVar[] typeParameters = new TVar[dataTypeAst.parameters.length];
341 for(int i=0;i<dataTypeAst.parameters.length;++i)
342 typeParameters[i] = context.addTypeVar(dataTypeAst.parameters[i]);
343 Constructor[] constructors = new Constructor[dataTypeAst.constructors.length];
344 String className = null;
345 boolean external = false;
346 for(DAnnotationAst annotation : dataTypeAst.getAnnotations()) {
347 if(annotation.id.text.equals("@JavaType")) {
348 if(annotation.parameters.length != 1 ||
349 !(annotation.parameters[0] instanceof ELiteral) ||
350 !(((ELiteral)annotation.parameters[0]).getValue() instanceof StringConstant))
351 errorLog.log(annotation.location, "Invalid parameters. Expected @JavaType \"className\".");
353 className = ((StringConstant)((ELiteral)annotation.parameters[0]).getValue()).getValue().replace('.', '/');
360 boolean trivialDataType = dataTypeAst.constructors.length == 1 &&
361 dataTypeAst.constructors[0].parameters.length == 1;
362 if(className == null && !trivialDataType)
363 className = compilationContext.namingPolicy.getDataTypeClassName(dataTypeAst.name);
365 StandardTypeConstructor dataType = dataTypeAst.typeConstructor;
367 dataType.setType(Types.con(moduleName, dataTypeAst.name), typeParameters);
368 dataType.setConstructors(constructors);
370 dataType.setTypeDesc(TypeDesc.forClass(className));
371 if(!external || dataTypeAst.constructors.length > 0) {
372 dataType.isOpen = false;
374 dataType.external = external;
375 dataTypes.add(dataType);
376 for(int j=0;j<constructors.length;++j) {
377 ConstructorAst constructor = dataTypeAst.constructors[j];
378 String name = constructor.name;
379 Type[] parameterTypes = new Type[constructor.parameters.length];
380 for(int i=constructor.parameters.length-1;i>=0;--i)
381 parameterTypes[i] = context.toType(constructor.parameters[i]);
382 String javaName = constructors.length == 1 ? className
383 : compilationContext.namingPolicy.getConstructorClassName(name);
384 String[] fieldNames = null;
385 for(DAnnotationAst annotation : constructor.annotations)
386 if(annotation.id.text.equals("@JavaType")) {
388 javaName = ((StringConstant)((ELiteral)annotation.parameters[0])
389 .getValue()).getValue();
390 } catch(Exception e) {
391 errorLog.log(annotation.parameters[0].location, "Invalid annotation parameter.");
394 else if(annotation.id.text.equals("@FieldNames")) {
396 EListLiteral literal = (EListLiteral)annotation.parameters[0];
397 fieldNames = new String[literal.getComponents().length];
398 for(int i=0;i<fieldNames.length;++i) {
399 Expression component = literal.getComponents()[i];
400 if(component instanceof EVar)
401 fieldNames[i] = ((EVar)component).name;
402 else if(component instanceof ELiteral)
403 fieldNames[i] = ((StringConstant)((ELiteral)component).getValue()).getValue();
405 } catch(Exception e) {
406 errorLog.log(annotation.parameters[0].location, "Invalid annotation parameter.");
411 constructors[j] = new Constructor(constructor.location, dataType,
412 Name.create(moduleName, name),
413 parameterTypes, javaName);
414 constructors[j].fieldNames = fieldNames;
415 constructors[j].recordFieldNames = constructor.fieldNames;
420 public void processTypeClasses(ArrayList<ProcessedDClassAst> typeClassesAst) {
421 for(ProcessedDClassAst pClassAst : typeClassesAst) {
422 DClassAst classAst = pClassAst.orig;
424 if(module.getTypeClass(classAst.name) != null) {
425 errorLog.log(classAst.location, "Class "+classAst.name+" has already been defined in this module.");
429 TypeTranslationContext context = createTypeTranslationContext();
431 TPred[] classContext = new TPred[classAst.context.length];
432 for(int i=0;i<classContext.length;++i)
433 classContext[i] = context.toTFuncApply(classAst.context[i]);
435 TVar[] parameters = new TVar[classAst.parameters.length];
437 if(classAst.name.equals("Functor") || classAst.name.equals("Monad")) {
439 parameters[0] = context.resolveTypeVariable(pClassAst.orig.location, classAst.parameters[0], Kinds.STAR_TO_STAR);
442 for(int i=0;i<parameters.length;++i)
443 parameters[i] = context.resolveTypeVariable(pClassAst.orig.location, classAst.parameters[i], Kinds.metaVar());
446 TCon con = Types.con(moduleName, classAst.name);
447 TypeClass typeClass = new TypeClass(classAst.location,
450 compilationContext.namingPolicy.getTypeClassInterfaceName(con),
452 Fundep.mapFundeps(classAst.parameters, classAst.fundeps));
454 THashMap<String, TypeClassMethod> methods = typeClass.methods;
455 for(DValueTypeAst methodDecl : pClassAst.typeDeclarations) {
459 type = context.toType(methodDecl.type);
460 } catch(SCLSyntaxErrorException e) {
461 errorLog.log(e.location, e.getMessage());
464 for(EVar name : methodDecl.names) {
465 typeClass.methodNames.add(name.name);
466 methods.put(name.name,
467 new TypeClassMethod(typeClass, name.name,
468 compilationContext.namingPolicy.getMethodName(name.name),
469 type, Types.getArity(type),
473 } catch(RuntimeException e) {
474 errorLog.setExceptionPosition(methodDecl.location);
479 for(String methodName : pClassAst.defaultImplementations.getValueNames()) {
480 String fullName = "_" + classAst.name + "_default_" + methodName;
481 ArrayList<DValueAst> defs = pClassAst.defaultImplementations.getDefinition(methodName);
483 TypeClassMethod method = typeClass.methods.get(methodName);
485 errorLog.log(defs.get(0).location, "Method " + methodName + " is not defined in this class.");
488 method.setDefaultImplementation(Name.create(moduleName, fullName));
490 valueDefinitionsAst.addDefinitions(fullName, defs);
491 /*valueDefinitionsAst.addAnnotation(fullName, new DAnnotationAst(new EVar("@private"),
492 Collections.<Expression>emptyList()));*/
493 supplementedTypeAnnotations.add(new SupplementedValueType(defs.get(0).location, fullName, method.getType()));
496 module.addTypeClass(classAst.name, typeClass);
500 private TypeTranslationContext createTypeTranslationContext() {
501 return new TypeTranslationContext(compilationContext);
504 public void processDerivingInstances(ArrayList<DDerivingInstanceAst> derivingInstancesAst,
505 ArrayList<ProcessedDInstanceAst> instancesAst) {
506 for(DDerivingInstanceAst derivingInstance : derivingInstancesAst) {
507 String name = derivingInstance.name.name;
510 con = Environments.getTypeClassName(compilationContext.environment, name);
511 } catch (AmbiguousNameException e) {
512 errorLog.log(derivingInstance.name.location, e.getMessage());
516 errorLog.log(derivingInstance.name.location, "Couldn't resolve class " + name + ".");
519 InstanceDeriver deriver = InstanceDerivers.get(con);
521 errorLog.log(derivingInstance.location, "Doesn't know how to derive " + name + ".");
523 deriver.derive(errorLog, compilationContext.environment, instancesAst, derivingInstance);
527 public void processInstances(ArrayList<ProcessedDInstanceAst> instancesAst) {
528 THashSet<TPred> instanceClashCheckSet = new THashSet<TPred>();
529 for(ProcessedDInstanceAst pInstanceAst : instancesAst) {
530 DInstanceAst instanceAst = pInstanceAst.orig;
532 TypeTranslationContext context = createTypeTranslationContext();
534 String name = instanceAst.name.name;
537 typeClassCon = Environments.getTypeClassName(compilationContext.environment, name);
538 } catch (AmbiguousNameException e) {
539 errorLog.log(instanceAst.name.location, e.getMessage());
542 if(typeClassCon == null) {
543 errorLog.log(instanceAst.name.location, "Couldn't resolve class " + name + ".");
546 TypeClass typeClass = compilationContext.environment.getTypeClass(typeClassCon);
547 pInstanceAst.typeClass = typeClass;
549 if(instanceAst.types.length != typeClass.parameters.length) {
550 errorLog.log(instanceAst.location, "Wrong number of parameters to type class " + typeClassCon.name + ".");
553 Type[] parameters = new Type[instanceAst.types.length];
554 for(int i=0;i<parameters.length;++i)
555 parameters[i] = context.toType(instanceAst.types[i], typeClass.parameters[i].getKind() /* FIXME */);
556 TPred instance = Types.pred(typeClassCon, parameters);
558 if(!instanceClashCheckSet.add(instance)) {
559 errorLog.log(instanceAst.location, "Duplicate definition of the instance " + instance + ".");
563 TPred[] instanceContext = new TPred[instanceAst.context.length];
564 for(int i=0;i<instanceContext.length;++i)
565 instanceContext[i] = context.toTFuncApply(instanceAst.context[i]);
567 String javaName = compilationContext.namingPolicy.getInstanceClassName(instance);
568 String instancePrefix = instance.toName() + "$";
570 ValueRepository valueDefs = pInstanceAst.valueDefs;
572 THashMap<String, MethodImplementation> methodImplementations =
573 new THashMap<String, MethodImplementation>();
574 for(String valueName : valueDefs.getValueNames()) {
575 String fullName = instancePrefix + valueName;
576 long loc = valueDefs.getDefinition(valueName).get(0).location;
577 valueDefinitionsAst.addFrom(valueDefs, valueName, fullName);
578 /*valueDefinitionsAst.addAnnotation(fullName, new DAnnotationAst(new EVar("@private"),
579 Collections.<Expression>emptyList()));*/
580 TypeClassMethod method = typeClass.methods.get(valueName);
582 errorLog.log(loc, "Method " + valueName + " is not defined in the type class " + typeClass.name.name + ".");
585 Type type = method.getBaseType().replace(typeClass.parameters, parameters);
586 for(int i=instanceContext.length-1;i>=0;--i)
587 type = Types.constrained(instanceContext[i], type);
588 //System.out.println(valueName + " :: " + type);
589 supplementedTypeAnnotations.add(
590 new SupplementedValueType(loc, fullName, type));
591 methodImplementations.put(valueName,
592 new MethodImplementation(Name.create(moduleName, fullName), false));
595 // Are all necessary methods defined
596 for(String methodName : typeClass.methods.keySet())
597 if(!methodImplementations.containsKey(methodName)) {
598 Name defaultImplementation = typeClass.methods.get(methodName).getDefaultImplementation();
599 if(defaultImplementation == null)
600 errorLog.log(instanceAst.location, "Method " + methodName + " is not defined.");
602 methodImplementations.put(methodName,
603 new MethodImplementation(defaultImplementation, true));
606 JavaTypeInstanceConstructor generator = new JavaTypeInstanceConstructor(javaName, instance, instanceContext);
607 if(instanceContext.length == 0)
608 generator.setHasStaticInstance(true);
610 TypeClassInstance typeClassInstance =
611 new TypeClassInstance(instanceAst.location, typeClass, generator,
612 generator.getTypeParameters(),
613 instanceContext, instance, methodImplementations,
616 generator.setInstance(typeClassInstance);
618 module.addTypeClassInstance(typeClassCon, typeClassInstance);
619 } catch(RuntimeException e) {
620 errorLog.setExceptionPosition(instanceAst.location);
625 // Generate superclass functions
626 for(ArrayList<TypeClassInstance> instanceArray : module.getTypeInstances().values())
627 for(TypeClassInstance instance : instanceArray) {
629 TypeClass typeClass = instance.typeClass;
630 int superCount = typeClass.context.length;
632 instance.superExpressions = new SCLValue[superCount];
633 for(int i=0;i<superCount;++i) {
634 TPred type = (TPred)typeClass.context[i]
635 .replace(typeClass.parameters, instance.instance.parameters);
636 SCLValue value = new SCLValue(Name.create(moduleName,
637 instance.javaName.substring(instance.javaName.indexOf('$')+1) + "_super" + i));
638 //value.addProperty(PrivateProperty.INSTANCE);
639 module.addValue(value);
640 Expression expression = new EGetConstraint(instance.location, type);
641 value.setExpression(expression);
642 value.setType(Types.forAll(instance.generatorParameters, Types.constrained(instance.context, type)));
643 value.getProperties().add(new InlineProperty(instance.context.length, 0xffffffff));
644 //TypeUnparsingContext tuc = new TypeUnparsingContext();
645 // TODO error handling
646 instance.superExpressions[i] = value;
648 } catch(RuntimeException e) {
649 errorLog.setExceptionPosition(instance.getLocation());
655 public void processJavaMethods(ArrayList<JavaMethodDeclaration> javaMethodDeclarations) {
656 for(JavaMethodDeclaration javaMethod : javaMethodDeclarations) {
657 String name = javaMethod.methodName.name;
658 String javaName = name;
659 ArrayList<DAnnotationAst> annotations =
660 valueDefinitionsAst.getAnnotations(name);
661 boolean isPrivate = false;
662 if(annotations != null) {
663 for(DAnnotationAst annotation : annotations)
664 if(annotation.id.text.equals("@JavaName")) {
665 String temp = AnnotationUtils.processStringAnnotation(errorLog, annotation);
669 else if(annotation.id.text.equals("@private")) {
670 AnnotationUtils.processTagAnnotation(errorLog, annotation);
675 Type type = createTypeTranslationContext().toType(javaMethod.type);
677 CallJava callJava = resolveMethod(
679 javaMethod.className,
682 if(callJava != null) {
683 NameExistenceChecks.checkIfValueExists(errorLog, javaMethod.location,
684 importedEnvironment, name);
685 SCLValue value = module.addValue(name, callJava);
686 value.definitionLocation = javaMethod.methodName.location;
688 value.addProperty(PrivateProperty.INSTANCE);
694 * Convert a java class method into a {@link CallJava} instance.
695 * Compilation errors are logged for failures in finding the named class or in accessing the method.
696 * The return value for errors is {@code null}.
698 * @param loc SCL source location
699 * @param className Name of the class
700 * @param methodName Name of the method
701 * @param type The expected SCL type of the method
702 * @return A new JavaCall instance, or null if the given method can not be instantiated.
704 private CallJava resolveMethod(long loc,
705 String className, String methodName, Type type) {
707 ClassRef classRef = classRefs.get(className);
708 if(classRef == null) {
709 if(classRefs.containsKey(className))
711 classRef = javaReferenceValidator.getClassRef(className);
712 classRefs.put(className, classRef);
713 if(classRef == null) {
714 errorLog.log(loc, "Didn't find class " + className + ".");
717 if(!javaReferenceValidator.isPublic(classRef.getClass())) {
718 errorLog.log(loc, "Class " + className + " is not public.");
725 List<MethodRef> methodRefs = classRef.getMethodRefs(methodName);
726 if(methodRefs.isEmpty()) {
727 errorLog.log(loc, "Didn't find any public method or field with name '" + methodName + "' from class " + className + ".");
731 ArrayList<CallJava> candidates = new ArrayList<CallJava>(2);
732 for(MethodRef methodRef : methodRefs) {
733 CallJava candidate = matchType(methodRef, type);
734 if(candidate != null)
735 candidates.add(candidate);
738 if(candidates.isEmpty()) {
739 StringBuilder b = new StringBuilder();
740 b.append("Didn't find any public method or field matching the type " + type + ". The following methods and fields were tried:");
741 for(MethodRef methodRef : methodRefs) {
745 b.append("\nbut expected something like:");
747 MultiFunction mFun = Types.matchFunction(type);
748 b.append("\n public static ");
749 b.append(javaTypeTranslator.toTypeDesc(mFun.returnType).getFullName()).append(' ').append(methodName).append('(');
750 boolean first = true;
751 for(Type parameter : mFun.parameterTypes) {
756 b.append(javaTypeTranslator.toTypeDesc(parameter).getFullName());
760 errorLog.log(loc, b.toString());
763 else if(candidates.size() == 1)
764 return candidates.get(0);
766 // Try to find the best match
767 ArrayList<CallJava> bestCandidates = new ArrayList<CallJava>(candidates.size());
768 loop: for(CallJava candidate : candidates) {
769 Iterator<CallJava> it = bestCandidates.iterator();
770 while(it.hasNext()) {
771 CallJava b = it.next();
772 switch(candidate.compareTo(javaReferenceValidator, b)) {
776 case CallJava.GREATER:
779 case CallJava.INCOMPARABLE:
783 bestCandidates.add(candidate);
786 if(bestCandidates.size() == 1) {
787 // System.out.println("Choose: " + bestCandidates.get(0).getMethodRef());
788 return bestCandidates.get(0);
791 StringBuilder b = new StringBuilder();
792 b.append("Found more than one incomparable public methods the type " + type + ":");
793 for(CallJava callJava : bestCandidates) {
795 b.append(callJava.getMethodRef());
797 errorLog.log(loc, b.toString());
803 private CallJava matchType(MethodRef methodRef, Type type) {
804 //System.out.println("-----------------------------------------------------");
805 //System.out.println("method: " + methodRef);
806 //System.out.println("type: " + type);
808 type = Types.canonical(type);
809 while(type instanceof TForAll)
810 type = Types.canonical(((TForAll)type).type);
812 TypeDesc[] expectedParameterTypes = methodRef.getParameterTypes();
814 ArrayList<Type> parameterTypes = new ArrayList<Type>();
815 Type effect = Types.NO_EFFECTS;
816 Type returnType = type;
818 StackItem[] stackItems = new StackItem[expectedParameterTypes.length];
819 TIntArrayList unresolvedItems = new TIntArrayList();
822 for(int i=0;i<expectedParameterTypes.length;++i) {
824 TypeDesc providedParameterType;
826 if(effect != Types.NO_EFFECTS || !(returnType instanceof TFun)) {
827 while(i < expectedParameterTypes.length)
828 unresolvedItems.add(i++);
831 TFun fun = (TFun)returnType;
832 parameterType = Types.canonical(fun.domain);
833 parameterTypes.add(parameterType);
834 effect = Types.canonical(fun.effect);
835 returnType = Types.canonical(fun.range);
836 providedParameterType = javaTypeTranslator.toTypeDesc(parameterType);
837 } while(providedParameterType.equals(TypeDesc.VOID));
840 TypeDesc expectedParameterType = expectedParameterTypes[i];
841 if(javaReferenceValidator.isAssignableFrom(expectedParameterType,
842 providedParameterType)) {
843 stackItems[i] = new ParameterStackItem(
844 parameterTypes.size()-1,
849 unresolvedItems.add(i++);
850 if(i == expectedParameterTypes.length) {
851 parameterTypes.remove(parameterTypes.size()-1);
852 returnType = Types.functionE(parameterType, effect, returnType);
857 //System.out.println("returnType: " + returnType);
858 if(!unresolvedItems.isEmpty()) {
859 ArrayList<TCon> concreteEffects = new ArrayList<TCon>();
860 effect.collectConcreteEffects(concreteEffects);
862 for(TCon eff : concreteEffects) {
863 EffectConstructor effC = compilationContext.environment.getEffectConstructor(eff);
864 for(ThreadLocalVariable var : effC.getThreadLocalVariables()) {
865 for(int i=0;i<unresolvedItems.size();++i) {
866 int id = unresolvedItems.get(i);
867 if(!expectedParameterTypes[id].equals(TypeDesc.OBJECT) &&
868 javaReferenceValidator.isAssignableFrom(expectedParameterTypes[id], var.type)) {
869 stackItems[id] = new ThreadLocalStackItem(var.variableName, var.type);
870 unresolvedItems.removeAt(i);
877 if(!unresolvedItems.isEmpty())
879 /*System.out.print("Unresolved: ");
880 boolean first = true;
881 for(int i=0;i<unresolvedItems.size();++i) {
885 System.out.print(", ");
886 System.out.print(expectedParameterTypes[unresolvedItems.get(i)]);
888 System.out.println();*/
890 OutputFilter filter = null;
892 TypeDesc providedReturnType = methodRef.getReturnType();
893 if(!providedReturnType.equals(Constants.FUNCTION)) {
894 while(returnType instanceof TFun && effect == Types.NO_EFFECTS) {
895 TFun fun = (TFun)returnType;
896 Type parameterType = Types.canonical(fun.domain);
897 if(!javaTypeTranslator.toTypeDesc(parameterType).equals(TypeDesc.VOID))
899 parameterTypes.add(parameterType);
900 effect = Types.canonical(fun.effect);
901 returnType = Types.canonical(fun.range);
904 TypeDesc expectedReturnType =
905 javaTypeTranslator.toTypeDesc(returnType);
906 if(!javaReferenceValidator.isAssignableFrom(expectedReturnType,
907 providedReturnType)) {
908 if(expectedReturnType.equals(TypeDesc.VOID)) {
909 if(providedReturnType.equals(TypeDesc.DOUBLE) || providedReturnType.equals(TypeDesc.LONG))
910 filter = Pop2OutputFilter.INSTANCE;
912 filter = PopOutputFilter.INSTANCE;
914 else if(expectedReturnType.equals(Constants.LIST)
915 && providedReturnType.equals(Constants.COLLECTION))
916 filter = ConvertToListFilter.INSTANCE;
922 CallJava result = new CallJava(
923 Types.freeVarsArray(type),
926 parameterTypes.toArray(new Type[parameterTypes.size()]),
930 //System.out.println(result.getType());
934 public void processMappingRelations(ArrayList<DMappingRelationAst> mappingRelationsAst) {
935 for(DMappingRelationAst mappingRelation : mappingRelationsAst) {
936 TypeAst[] parameterTypesAst = mappingRelation.parameterTypes;
937 Type[] parameterTypes = new Type[parameterTypesAst.length];
938 TypeTranslationContext typeTranslationContext = createTypeTranslationContext();
939 for(int i=0;i<parameterTypes.length;++i)
940 parameterTypes[i] = parameterTypesAst[i].toType(typeTranslationContext, Kinds.STAR);
941 MappingRelation mRel =
942 new MappingRelation(Name.create(moduleName, mappingRelation.name), parameterTypes);
943 mRel.location = mappingRelation.location;
944 if(module.addMappingRelation(mRel))
945 errorLog.log(mappingRelation.location, "Mapping relation " + mappingRelation.name +
946 " has already been defined.");
950 THashMap<String, DRuleAst> ruleAstMap = new THashMap<String, DRuleAst>();
952 public void processRules(ArrayList<DRuleAst> rulesAst) {
953 // Find implied mapping relations
954 for(DRuleAst ruleA : rulesAst) {
955 ArrayList<Query> whereSection = ruleA.getSections().get("where");
956 if(whereSection != null)
957 for(Query query : whereSection) {
958 if(!(query instanceof QPreGuard))
960 QPreGuard guard = (QPreGuard)query;
961 if(!(guard.guard instanceof EApply))
963 EApply apply = (EApply)guard.guard;
964 if(!(apply.getFunction() instanceof EVar))
967 String name = ((EVar)apply.getFunction()).name;
968 if(module.getMappingRelation(name) != null)
971 int arity = apply.getParameters().length;
972 Type[] parameterTypes = new Type[arity];
973 for(int i=0;i<arity;++i)
974 parameterTypes[i] = Types.metaVar(Kinds.STAR);
975 MappingRelation mRel =
976 new MappingRelation(Name.create(moduleName, name), parameterTypes);
977 mRel.location = query.location;
978 module.addMappingRelation(mRel);
980 if(ruleAstMap.put(ruleA.name, ruleA) != null)
981 errorLog.log(ruleA.location, "Rule " + ruleA.name +
982 " has already been defined.");
986 for(String ruleName : ruleAstMap.keySet())
987 processRule(ruleName);
990 private TransformationRule processRule(String ruleName) {
991 TransformationRule rule = module.getRule(ruleName);
995 DRuleAst ruleAst = ruleAstMap.get(ruleName);
996 if(ruleAst.alreadyProcessing) {
997 errorLog.log(ruleAst.location, "Cyclic chain of rule extensions.");
1001 TransformationRule[] extendsRules;
1002 int length = ruleAst.extendsNames.length;
1004 extendsRules = TransformationRule.EMPTY_ARRAY;
1006 extendsRules = new TransformationRule[length];
1007 for(int i=0;i<length;++i) {
1009 String extendsName = ruleAst.extendsNames[i];
1010 TransformationRule extendsRule;
1011 if(ruleAstMap.containsKey(extendsName))
1012 extendsRule = processRule(extendsName);
1014 extendsRule = Environments.getRule(compilationContext.environment, extendsName);
1015 if(extendsRule == null)
1016 errorLog.log(ruleAst.location,
1017 "Couldn't resolve rule name " + extendsName + ".");
1019 extendsRules[i] = extendsRule;
1020 } catch(AmbiguousNameException e) {
1021 errorLog.log(ruleAst.location, e.getMessage());
1026 final THashMap<SectionName, Query[]> sections = new THashMap<SectionName, Query[]>();
1028 final TranslationContext context = createTranslationContext();
1030 THashMap<String, Variable> variables = context.getVariables();
1031 for(TransformationRule extendsRule : extendsRules) {
1032 if(extendsRule == null)
1034 for(Variable var : extendsRule.variables)
1035 if(variables.put(var.getName(), var) != null) {
1036 errorLog.log(ruleAst.location,
1037 "Variable " + var.getName() + " is defined in more than one base rule, which is not currently allowed.");
1041 context.pushExistentialFrame();
1042 ruleAst.getSections().forEachEntry(new TObjectObjectProcedure<String, ArrayList<Query>>() {
1044 public boolean execute(String sectionNameString, ArrayList<Query> queries) {
1045 Query[] resolvedQueries = new Query[queries.size()];
1046 for(int i=0;i<resolvedQueries.length;++i)
1047 resolvedQueries[i] = queries.get(i).resolve(context);
1049 SectionName sectionName = SectionName.getSectionName(sectionNameString);
1050 if(sectionName == null)
1051 context.getErrorLog().log(queries.get(0).location,
1052 "Invalid section name " + sectionNameString + ".");
1054 sections.put(sectionName, resolvedQueries);
1059 Variable[] variables = context.getVariables().values().toArray(new Variable[context.getVariables().size()]);
1061 rule = new TransformationRule(ruleAst.isAbstract,
1062 Name.create(moduleName, ruleAst.name),
1064 sections, variables);
1065 rule.location = ruleAst.location;
1066 module.addRule(rule);
1070 public void addDataTypesToEnvironment() {
1071 for(StandardTypeConstructor dataType : dataTypes) {
1072 int constructorTag = 0;
1073 for(Constructor constructor : dataType.constructors) {
1074 SCLValue value = new SCLValue(constructor.name);
1075 SCLConstructor sclConstructor =
1077 constructor.name.name,
1078 constructor.javaName,
1079 constructor.getTypeVariables(),
1081 constructor.getReturnType(),
1082 constructor.fieldNames == null
1083 ? SCLConstructor.DEFAULT_FIELD_NAMES[constructor.getParameterTypes().length]
1084 : constructor.fieldNames,
1085 constructor.recordFieldNames,
1086 constructor.getParameterTypes());
1087 if(dataType.constructors.length == 1 && (
1088 dataType.getTypeDesc() == null ||
1089 dataType.constructors[0].javaName.equals(MethodBuilderBase.getClassName(dataType.getTypeDesc()))))
1090 sclConstructor.setOnlyConstructor(true);
1091 value.setValue(sclConstructor);
1092 value.setType(constructor.getType());
1094 NameExistenceChecks.checkIfValueExists(errorLog, constructor.loc,
1095 importedEnvironment, constructor.name.name);
1096 if(module.addValue(value)) {
1097 errorLog.log(constructor.loc,
1098 "Value " + constructor.name.name + " is already defined.");
1104 public void addTypeClassesToEnvironment() {
1105 for(TypeClass typeClass : module.getTypeClasses()) {
1106 for(TypeClassMethod method : typeClass.methods.values()) {
1107 SCLValue value = method.createValue();
1108 value.definitionLocation = method.location;
1109 NameExistenceChecks.checkIfValueExists(errorLog, Locations.NO_LOCATION,
1110 importedEnvironment, value.getName().name);
1112 if(module.addValue(value)) {
1113 String name = method.getName();
1114 long location = Locations.NO_LOCATION;
1115 ArrayList<DValueAst> definitions = valueDefinitionsAst.getDefinition(name);
1116 if(definitions != null && !definitions.isEmpty())
1117 location = definitions.get(0).location;
1118 errorLog.log(location, "Value " + name + " is already defined.");
1124 public void preprocessValueDefinitions(ArrayList<DValueTypeAst> typeAnnotationsAst) {
1125 for(String name : valueDefinitionsAst.getValueNames()) {
1126 SCLValue value = new SCLValue(Name.create(moduleName, name));
1128 long location = valueDefinitionsAst.getLocation(name);
1129 NameExistenceChecks.checkIfValueExists(errorLog, location,
1130 importedEnvironment, value.getName().name);
1131 value.definitionLocation = location;
1132 if(module.addValue(value))
1133 errorLog.log(location, "Value " + name + " is already defined.");
1135 for(DValueTypeAst valueTypeAst : typeAnnotationsAst)
1136 for(EVar name : valueTypeAst.names) {
1137 SCLValue value = module.getValue(name.name);
1139 errorLog.log(valueTypeAst.location, name.name + " is not defined.");
1140 value = new SCLValue(Name.create(moduleName, name.name));
1141 module.addValue(value);
1143 value.definitionLocation = name.location;
1145 for(String name : relationDefinitionsAst.getRelationNames()) {
1146 ConcreteRelation relation = new ConcreteRelation(name);
1147 module.addRelation(name, relation);
1151 public void addValueDefinitionsToEnvironment(ArrayList<DValueTypeAst> typeAnnotationsAst) {
1152 THashMap<String, DValueTypeAst> typeMap = new THashMap<String, DValueTypeAst>();
1153 for(DValueTypeAst valueTypeAst : typeAnnotationsAst)
1154 for(EVar name : valueTypeAst.names) {
1155 if(typeMap.containsKey(name.name))
1156 errorLog.log(valueTypeAst.location, "Type of "+name.name+" has already been declared in this module.");
1158 typeMap.put(name.name, valueTypeAst);
1161 for(String name : valueDefinitionsAst.getValueNames()) {
1162 ArrayList<DValueAst> defs = valueDefinitionsAst.getDefinition(name);
1164 SCLValue value = module.getValue(name);
1165 TranslationContext context = createTranslationContext();
1166 Expression expression = context.translateCases2(defs);
1167 value.setExpression(expression);
1169 DValueTypeAst valueTypeAst = typeMap.remove(name);
1170 if(valueTypeAst != null)
1171 value.setType(Types.closure(context.toType(valueTypeAst.type)));
1173 ArrayList<DAnnotationAst> annotations = valueDefinitionsAst.getAnnotations(name);
1174 if(annotations != null)
1175 for(DAnnotationAst annotation : annotations) {
1176 handleAnnotation(value, defs, annotation);
1178 } catch(RuntimeException e) {
1179 errorLog.setExceptionPosition(defs.get(0).location);
1183 for(String name : relationDefinitionsAst.getRelationNames()) {
1184 ArrayList<DRelationAst> definitions = relationDefinitionsAst.getDefinition(name);
1185 if(definitions.size() > 1) {
1186 errorLog.log(definitions.get(1).location,
1187 "Does not yet support definition of relations by more than one rule.");
1191 DRelationAst definition = definitions.get(0);
1192 ConcreteRelation relation = (ConcreteRelation)module.getRelation(name);
1193 relation.location = definition.location;
1194 TranslationContext context = createTranslationContext();
1195 definition.translateTo(context, relation);
1199 private TranslationContext createTranslationContext() {
1200 return new TranslationContext(compilationContext, null);
1203 private void handleAnnotation(SCLValue value, ArrayList<DValueAst> defs, DAnnotationAst annotation) {
1204 if(annotation.id.text.equals("@macro")) {
1205 value.setMacroRule(new StandardMacroRule());
1207 else if(annotation.id.text.equals("@inline")) {
1209 int arity = defs.get(0).lhs.getFunctionDefinitionPatternArity();
1210 int phaseMask = 0xffffffff;
1211 if(annotation.parameters.length > 0) {
1212 phaseMask = Integer.parseInt(((EIntegerLiteral)annotation.parameters[0]).getValue());
1214 value.addProperty(new InlineProperty(arity, phaseMask));
1215 } catch(NotPatternException e) {
1216 errorLog.log(annotation.location, "Inline annotation is invalid: this is not a function.");
1219 else if(annotation.id.text.equals("@private")) {
1220 value.addProperty(PrivateProperty.INSTANCE);
1222 else if(annotation.id.text.equals("@deprecated")) {
1223 String description = "";
1224 if(annotation.parameters.length > 0) {
1225 if(annotation.parameters.length > 1)
1226 errorLog.log(annotation.location, "Invalid number of parameters, expected one string.");
1228 String temp = AnnotationUtils.extractString(annotation.parameters[0]);
1230 errorLog.log(annotation.location, "Invalid parameter, expected one string.");
1235 value.addProperty(new DeprecatedProperty(description));
1238 errorLog.log(annotation.location, "Unknown annotation.");
1241 public void addSupplementedTypeAnnotationsToEnvironment() {
1242 for(SupplementedValueType valueType : supplementedTypeAnnotations) {
1243 Type type = Types.closure(valueType.type);
1244 String name = valueType.name;
1245 SCLValue value = module.getValue(name);
1247 errorLog.log(valueType.position,
1248 name + " is not defined.");
1249 else if(value.getType()==null)
1250 value.setType(type);
1252 errorLog.log(valueType.position,
1253 "Type of "+name+" has already been declared in this module.");
1257 public void addFixityToEnvironment(ArrayList<DFixityAst> fixityAst) {
1258 for(DFixityAst fixity : fixityAst) {
1259 for(EVar symbol : fixity.symbols) {
1260 String name = symbol.name;
1261 SCLValue value = module.getValue(name);
1263 errorLog.log(symbol.location,
1264 name + " is not defined.");
1266 value.setPrecedence(fixity.precedence);
1271 public void addCoverageBranchPoints() {
1272 branchPoints = new THashMap<String, BranchPoint[]>();
1273 BranchPointInjector injector = new BranchPointInjector();
1274 for(String valueName : valueDefinitionsAst.getValueNames()) {
1275 for(DValueAst valueAst : valueDefinitionsAst.getDefinition(valueName))
1276 valueAst.value = injector.injectBranchPoint(valueAst.value);
1277 branchPoints.put(valueName, injector.getAndClearBranchPoints());