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.exceptions.InternalCompilerError;
10 import org.simantics.scl.compiler.common.names.Name;
11 import org.simantics.scl.compiler.constants.Constant;
12 import org.simantics.scl.compiler.constants.JavaTypeInstanceConstructor;
13 import org.simantics.scl.compiler.constants.SCLConstructor;
14 import org.simantics.scl.compiler.constants.StringConstant;
15 import org.simantics.scl.compiler.constants.generic.CallJava;
16 import org.simantics.scl.compiler.constants.generic.ClassRef;
17 import org.simantics.scl.compiler.constants.generic.ConvertToListFilter;
18 import org.simantics.scl.compiler.constants.generic.MethodRef;
19 import org.simantics.scl.compiler.constants.generic.MethodRef.FieldRef;
20 import org.simantics.scl.compiler.constants.generic.OutputFilter;
21 import org.simantics.scl.compiler.constants.generic.ParameterStackItem;
22 import org.simantics.scl.compiler.constants.generic.Pop2OutputFilter;
23 import org.simantics.scl.compiler.constants.generic.PopOutputFilter;
24 import org.simantics.scl.compiler.constants.generic.StackItem;
25 import org.simantics.scl.compiler.constants.generic.ThreadLocalStackItem;
26 import org.simantics.scl.compiler.constants.singletons.SafeCoerce;
27 import org.simantics.scl.compiler.elaboration.contexts.TranslationContext;
28 import org.simantics.scl.compiler.elaboration.contexts.TypeTranslationContext;
29 import org.simantics.scl.compiler.elaboration.errors.NotPatternException;
30 import org.simantics.scl.compiler.elaboration.expressions.EApply;
31 import org.simantics.scl.compiler.elaboration.expressions.EGetConstraint;
32 import org.simantics.scl.compiler.elaboration.expressions.EIntegerLiteral;
33 import org.simantics.scl.compiler.elaboration.expressions.EListLiteral;
34 import org.simantics.scl.compiler.elaboration.expressions.ELiteral;
35 import org.simantics.scl.compiler.elaboration.expressions.EPreCHRRulesetConstructor;
36 import org.simantics.scl.compiler.elaboration.expressions.EVar;
37 import org.simantics.scl.compiler.elaboration.expressions.Expression;
38 import org.simantics.scl.compiler.elaboration.expressions.Variable;
39 import org.simantics.scl.compiler.elaboration.expressions.annotations.AnnotationUtils;
40 import org.simantics.scl.compiler.elaboration.fundeps.Fundep;
41 import org.simantics.scl.compiler.elaboration.java.JavaMethodDeclaration;
42 import org.simantics.scl.compiler.elaboration.macros.StandardMacroRule;
43 import org.simantics.scl.compiler.elaboration.modules.DeprecatedProperty;
44 import org.simantics.scl.compiler.elaboration.modules.DerivedProperty;
45 import org.simantics.scl.compiler.elaboration.modules.InlineProperty;
46 import org.simantics.scl.compiler.elaboration.modules.MethodImplementation;
47 import org.simantics.scl.compiler.elaboration.modules.PrivateProperty;
48 import org.simantics.scl.compiler.elaboration.modules.SCLValue;
49 import org.simantics.scl.compiler.elaboration.modules.TypeAlias;
50 import org.simantics.scl.compiler.elaboration.modules.TypeClass;
51 import org.simantics.scl.compiler.elaboration.modules.TypeClassInstance;
52 import org.simantics.scl.compiler.elaboration.modules.TypeClassMethod;
53 import org.simantics.scl.compiler.elaboration.modules.TypeDescriptor;
54 import org.simantics.scl.compiler.elaboration.query.Query;
55 import org.simantics.scl.compiler.elaboration.query.pre.QPreGuard;
56 import org.simantics.scl.compiler.elaboration.relations.ConcreteRelation;
57 import org.simantics.scl.compiler.elaboration.rules.MappingRelation;
58 import org.simantics.scl.compiler.elaboration.rules.SectionName;
59 import org.simantics.scl.compiler.elaboration.rules.TransformationRule;
60 import org.simantics.scl.compiler.environment.AmbiguousNameException;
61 import org.simantics.scl.compiler.environment.Environment;
62 import org.simantics.scl.compiler.environment.EnvironmentFactory;
63 import org.simantics.scl.compiler.environment.Environments;
64 import org.simantics.scl.compiler.errors.CompilationError;
65 import org.simantics.scl.compiler.errors.ErrorLog;
66 import org.simantics.scl.compiler.errors.ErrorSeverity;
67 import org.simantics.scl.compiler.errors.Locations;
68 import org.simantics.scl.compiler.internal.codegen.effects.EffectConstructor;
69 import org.simantics.scl.compiler.internal.codegen.effects.ThreadLocalVariable;
70 import org.simantics.scl.compiler.internal.codegen.types.JavaReferenceValidator;
71 import org.simantics.scl.compiler.internal.codegen.types.JavaReferenceValidatorFactory;
72 import org.simantics.scl.compiler.internal.codegen.types.JavaTypeTranslator;
73 import org.simantics.scl.compiler.internal.codegen.types.StandardTypeConstructor;
74 import org.simantics.scl.compiler.internal.codegen.utils.Constants;
75 import org.simantics.scl.compiler.internal.codegen.utils.JavaNamingPolicy;
76 import org.simantics.scl.compiler.internal.codegen.utils.MethodBuilderBase;
77 import org.simantics.scl.compiler.internal.deriving.InstanceDeriver;
78 import org.simantics.scl.compiler.internal.deriving.InstanceDerivers;
79 import org.simantics.scl.compiler.internal.elaboration.profiling.BranchPointInjector;
80 import org.simantics.scl.compiler.internal.elaboration.utils.StronglyConnectedComponents;
81 import org.simantics.scl.compiler.internal.header.ModuleHeader;
82 import org.simantics.scl.compiler.internal.parsing.declarations.ConstructorAst;
83 import org.simantics.scl.compiler.internal.parsing.declarations.DAnnotationAst;
84 import org.simantics.scl.compiler.internal.parsing.declarations.DClassAst;
85 import org.simantics.scl.compiler.internal.parsing.declarations.DDataAst;
86 import org.simantics.scl.compiler.internal.parsing.declarations.DDerivingInstanceAst;
87 import org.simantics.scl.compiler.internal.parsing.declarations.DEffectAst;
88 import org.simantics.scl.compiler.internal.parsing.declarations.DFixityAst;
89 import org.simantics.scl.compiler.internal.parsing.declarations.DInstanceAst;
90 import org.simantics.scl.compiler.internal.parsing.declarations.DMappingRelationAst;
91 import org.simantics.scl.compiler.internal.parsing.declarations.DRelationAst;
92 import org.simantics.scl.compiler.internal.parsing.declarations.DRuleAst;
93 import org.simantics.scl.compiler.internal.parsing.declarations.DRulesetAst;
94 import org.simantics.scl.compiler.internal.parsing.declarations.DTypeAst;
95 import org.simantics.scl.compiler.internal.parsing.declarations.DValueAst;
96 import org.simantics.scl.compiler.internal.parsing.declarations.DValueTypeAst;
97 import org.simantics.scl.compiler.internal.parsing.exceptions.SCLSyntaxErrorException;
98 import org.simantics.scl.compiler.internal.parsing.translation.ProcessedDClassAst;
99 import org.simantics.scl.compiler.internal.parsing.translation.ProcessedDInstanceAst;
100 import org.simantics.scl.compiler.internal.parsing.translation.RelationRepository;
101 import org.simantics.scl.compiler.internal.parsing.translation.ValueRepository;
102 import org.simantics.scl.compiler.internal.parsing.types.TypeAst;
103 import org.simantics.scl.compiler.module.ConcreteModule;
104 import org.simantics.scl.compiler.module.ImportDeclaration;
105 import org.simantics.scl.compiler.module.InvalidModulePathException;
106 import org.simantics.scl.compiler.module.ModuleUtils;
107 import org.simantics.scl.compiler.module.repository.ImportFailure;
108 import org.simantics.scl.compiler.module.repository.ImportFailureException;
109 import org.simantics.scl.compiler.types.TCon;
110 import org.simantics.scl.compiler.types.TForAll;
111 import org.simantics.scl.compiler.types.TFun;
112 import org.simantics.scl.compiler.types.TPred;
113 import org.simantics.scl.compiler.types.TVar;
114 import org.simantics.scl.compiler.types.Type;
115 import org.simantics.scl.compiler.types.Types;
116 import org.simantics.scl.compiler.types.kinds.Kind;
117 import org.simantics.scl.compiler.types.kinds.Kinds;
118 import org.simantics.scl.compiler.types.util.MultiFunction;
119 import org.simantics.scl.runtime.profiling.BranchPoint;
121 import gnu.trove.list.array.TIntArrayList;
122 import gnu.trove.map.hash.THashMap;
123 import gnu.trove.map.hash.TObjectIntHashMap;
124 import gnu.trove.procedure.TObjectObjectProcedure;
125 import gnu.trove.set.hash.THashSet;
126 import gnu.trove.set.hash.TIntHashSet;
128 public class Elaboration {
130 private final CompilationContext compilationContext;
131 private final ErrorLog errorLog;
132 private final String moduleName;
133 private final ModuleHeader moduleHeader;
134 private final ArrayList<ImportDeclaration> importsAst;
135 private final JavaReferenceValidatorFactory jrvFactory;
136 final JavaReferenceValidator<Object, Object, Object, Object> javaReferenceValidator;
137 private final ValueRepository valueDefinitionsAst;
138 private final RelationRepository relationDefinitionsAst;
141 ConcreteModule module;
142 Environment importedEnvironment;
143 ArrayList<SupplementedValueType> supplementedTypeAnnotations = new ArrayList<SupplementedValueType>();
145 JavaTypeTranslator javaTypeTranslator;
146 ArrayList<StandardTypeConstructor> dataTypes = new ArrayList<StandardTypeConstructor>();
147 THashMap<String, ClassRef> classRefs = new THashMap<String, ClassRef>();
148 THashMap<String, BranchPoint[]> branchPoints;
150 public Elaboration(CompilationContext compilationContext, CompilationTimer timer, EnvironmentFactory localEnvironmentFactory,
151 String moduleName, ModuleHeader moduleHeader, ArrayList<ImportDeclaration> importsAst,
152 JavaReferenceValidatorFactory jrvFactory,
153 ValueRepository valueDefinitionsAst,
154 RelationRepository relationDefinitionsAst) {
155 this.compilationContext = compilationContext;
156 this.errorLog = compilationContext.errorLog;
157 this.moduleName = moduleName;
158 this.moduleHeader = moduleHeader;
159 importsAst = processRelativeImports(importsAst);
160 this.importsAst = importsAst;
161 this.jrvFactory = jrvFactory;
162 this.javaReferenceValidator = moduleHeader == null || moduleHeader.classLoader == null
163 ? jrvFactory.getDefaultJavaReferenceValidator()
164 : jrvFactory.getJavaReferenceValidator(moduleHeader.classLoader);
165 if(javaReferenceValidator == null)
166 errorLog.log(moduleHeader.classLoaderLocation, "Didn't find the specified class loader.");
167 this.valueDefinitionsAst = valueDefinitionsAst;
168 this.relationDefinitionsAst = relationDefinitionsAst;
170 module = new ConcreteModule(moduleName);
171 compilationContext.module = module;
172 if(moduleHeader != null) {
173 if(moduleHeader.defaultLocalName != null)
174 module.setDefaultLocalName(moduleHeader.defaultLocalName);
175 if(moduleHeader.deprecated != null)
176 module.setDeprecation(moduleHeader.deprecated);
180 timer.suspendTimer();
181 importedEnvironment = localEnvironmentFactory.createEnvironment(
183 importsAst.toArray(new ImportDeclaration[importsAst.size()]));
185 timer.continueTimer();
186 compilationContext.environment = new EnvironmentOfModule(importedEnvironment, module);
187 } catch (ImportFailureException e) {
188 for(ImportFailure failure : e.failures)
189 errorLog.log(new CompilationError(failure.location, failure.toString(), ErrorSeverity.IMPORT_ERROR));
192 for(ImportDeclaration importAst : importsAst)
193 this.module.addDependency(new ImportDeclaration(
194 importAst.moduleName,
195 importAst.reexport ? importAst.localName : null,
198 localEnvironmentFactory.addBuiltinDependencies(module);
199 compilationContext.namingPolicy = new JavaNamingPolicy(moduleName);
202 private ArrayList<ImportDeclaration> processRelativeImports(ArrayList<ImportDeclaration> relativeImports) {
203 ArrayList<ImportDeclaration> absoluteImports = new ArrayList<ImportDeclaration>(relativeImports.size());
204 for(ImportDeclaration relativeImport : relativeImports) {
205 if(relativeImport.moduleName.startsWith(".")) {
207 String absoluteModuleName = ModuleUtils.resolveAbsolutePath(moduleName, relativeImport.moduleName);
208 ImportDeclaration absoluteImport = new ImportDeclaration(
209 relativeImport.location,
210 absoluteModuleName, relativeImport.localName,
211 relativeImport.reexport, relativeImport.spec);
212 absoluteImports.add(absoluteImport);
213 } catch (InvalidModulePathException e) {
214 errorLog.log(relativeImport.location, e.getMessage());
218 absoluteImports.add(relativeImport);
220 return absoluteImports;
223 public void addTypesToEnvironment(
224 ArrayList<DDataAst> dataTypesAst,
225 ArrayList<DTypeAst> typeAliasesAst,
226 ArrayList<DEffectAst> effectsAst,
227 ArrayList<DRulesetAst> rulesetsAst) {
228 for(DDataAst dataType : dataTypesAst) {
229 dataType.parameterKinds = new Kind[dataType.parameters.length];
230 Kind constructorKind = Kinds.STAR;
231 for(int i=dataType.parameters.length-1;i>=0;--i) {
232 Kind kind = Kinds.metaVar();
233 dataType.parameterKinds[i] = kind;
234 constructorKind = Kinds.arrow(kind, constructorKind);
237 StandardTypeConstructor typeConstructor = new StandardTypeConstructor(
238 Types.con(moduleName, dataType.name), constructorKind);
240 NameExistenceChecks.checkIfTypeExists(errorLog,
241 dataType.location, importedEnvironment, dataType.name);
242 addTypeDescriptor(dataType.location, dataType.name, typeConstructor);
243 dataType.typeConstructor = typeConstructor;
246 for(DTypeAst typeAlias : typeAliasesAst) {
247 TypeAlias alias = new TypeAlias(Types.con(moduleName, typeAlias.name), typeAlias.parameters.length);
248 NameExistenceChecks.checkIfTypeExists(errorLog,
249 typeAlias.location, importedEnvironment, typeAlias.name);
250 addTypeDescriptor(typeAlias.location, typeAlias.name, alias);
253 for(DEffectAst effect : effectsAst) {
254 EffectConstructor effectConstructor = new EffectConstructor(Types.con(moduleName, effect.name));
255 effectConstructor.addThreadLocalVariable(
256 new ThreadLocalVariable(
258 TypeDesc.forClass(effect.threadLocalType)
260 if(module.addEffectConstructor(effect.name, effectConstructor))
261 errorLog.log(effect.location, "Effect "+effect.name+" has already been defined in this module.");
263 for(DRulesetAst ruleset : rulesetsAst) {
264 ruleset.type = Types.con(moduleName, ruleset.name);
265 ruleset.className = compilationContext.namingPolicy.getDataTypeClassName(ruleset.name);
266 StandardTypeConstructor typeConstructor = new StandardTypeConstructor(ruleset.type, Kinds.STAR,
267 TypeDesc.forClass(ruleset.className), ruleset.documentation == null ? null : ruleset.documentation.documentation);
268 typeConstructor.external = true;
269 addTypeDescriptor(ruleset.location, ruleset.name, typeConstructor);
271 javaTypeTranslator = new JavaTypeTranslator(compilationContext.environment);
272 compilationContext.javaTypeTranslator = javaTypeTranslator;
275 private void addTypeDescriptor(long location, String name, TypeDescriptor typeDescriptor) {
276 if(module.addTypeDescriptor(name, typeDescriptor))
277 errorLog.log(location, "Type "+name+" has already been defined in this module.");
280 private static final int[] EMPTY_INT_ARRAY = new int[0];
282 public void processTypeAliases(ArrayList<DTypeAst> typeAliasesAst) {
283 TObjectIntHashMap<String> typeAliasMap = new TObjectIntHashMap<String>();
284 for(int i=0;i<typeAliasesAst.size();++i)
285 typeAliasMap.put(typeAliasesAst.get(i).name, i);
286 TIntHashSet tempIntSet = new TIntHashSet();
287 ArrayList<DTypeAst> orderedTypeAliases = new ArrayList<DTypeAst>(typeAliasesAst.size());
288 //for(int i=0;i<typeAliasesAst.size();++i)
289 // System.out.println(i + "# " + typeAliasesAst.get(i).name);
290 new StronglyConnectedComponents(typeAliasesAst.size()) {
292 protected int[] findDependencies(int u) {
293 typeAliasesAst.get(u).type.collectReferences(typeAliasMap, tempIntSet);
294 if(tempIntSet.isEmpty())
295 return EMPTY_INT_ARRAY;
296 if(tempIntSet.contains(u)) {
297 errorLog.log(typeAliasesAst.get(u).location, "Type alias has a self reference.");
298 tempIntSet.remove(u);
300 int[] result = tempIntSet.toArray();
302 //System.out.println(u + " -> " + Arrays.toString(result));
306 protected void reportComponent(int[] component) {
307 //System.out.println("component: " + Arrays.toString(component));
308 if(component.length > 1) {
309 StringBuilder b = new StringBuilder();
310 b.append("Recursively defined type alias (");
311 long minLocation = typeAliasesAst.get(component[0]).location;
312 boolean first = true;
313 for(int u : component) {
314 DTypeAst typeAlias = typeAliasesAst.get(u);
319 b.append(typeAlias.name);
320 if(Locations.beginOf(typeAlias.location) < Locations.beginOf(minLocation))
321 minLocation = typeAlias.location;
324 errorLog.log(minLocation, b.toString());
327 orderedTypeAliases.add(typeAliasesAst.get(component[0]));
331 if(errorLog.hasNoErrors()) {
332 for(DTypeAst typeAlias : orderedTypeAliases) {
333 TypeAlias alias = (TypeAlias)module.getTypeDescriptor(typeAlias.name);
334 TypeTranslationContext context = createTypeTranslationContext();
335 for(int i=0;i<typeAlias.parameters.length;++i)
336 context.pushTypeVar(typeAlias.parameters[i]);
337 alias.body = typeAlias.type.toType(context, Kinds.metaVar());
338 for(int i=0;i<typeAlias.parameters.length;++i)
339 alias.parameters[i] = context.popTypeVar(typeAlias.parameters[i], null);
344 public void processDataTypes(ArrayList<DDataAst> dataTypesAst) {
345 ArrayList<Runnable> fieldAccessorGenerators = new ArrayList<Runnable>();
346 for(DDataAst dataTypeAst : dataTypesAst) {
347 TypeTranslationContext context = createTypeTranslationContext();
348 TVar[] typeParameters = new TVar[dataTypeAst.parameters.length];
349 for(int i=0;i<dataTypeAst.parameters.length;++i)
350 typeParameters[i] = context.addTypeVar(dataTypeAst.parameters[i]);
351 Constructor[] constructors = new Constructor[dataTypeAst.constructors.length];
352 String className = null;
353 boolean external = false;
354 for(DAnnotationAst annotation : dataTypeAst.getAnnotations()) {
355 if(annotation.id.text.equals("@JavaType")) {
356 if(annotation.parameters.length != 1 ||
357 !(annotation.parameters[0] instanceof ELiteral) ||
358 !(((ELiteral)annotation.parameters[0]).getValue() instanceof StringConstant))
359 errorLog.log(annotation.location, "Invalid parameters. Expected @JavaType \"className\".");
361 className = ((StringConstant)((ELiteral)annotation.parameters[0]).getValue()).getValue().replace('.', '/');
368 boolean trivialDataType = dataTypeAst.constructors.length == 1 &&
369 dataTypeAst.constructors[0].parameters.length == 1;
370 if(className == null && !trivialDataType)
371 className = compilationContext.namingPolicy.getDataTypeClassName(dataTypeAst.name);
373 StandardTypeConstructor dataType = dataTypeAst.typeConstructor;
375 dataType.setType(Types.con(moduleName, dataTypeAst.name), typeParameters);
376 dataType.setConstructors(constructors);
378 dataType.setTypeDesc(TypeDesc.forClass(className));
379 if(!external || dataTypeAst.constructors.length > 0) {
380 dataType.isOpen = false;
382 dataType.external = external;
383 dataTypes.add(dataType);
384 for(int j=0;j<constructors.length;++j) {
385 ConstructorAst constructor = dataTypeAst.constructors[j];
386 String name = constructor.name.text;
387 Type[] parameterTypes = new Type[constructor.parameters.length];
388 for(int i=constructor.parameters.length-1;i>=0;--i)
389 parameterTypes[i] = context.toType(constructor.parameters[i]);
390 String javaName = constructors.length == 1 ? className
391 : compilationContext.namingPolicy.getConstructorClassName(name);
392 String[] fieldNames = null;
393 for(DAnnotationAst annotation : constructor.annotations)
394 if(annotation.id.text.equals("@JavaType")) {
396 javaName = ((StringConstant)((ELiteral)annotation.parameters[0])
397 .getValue()).getValue();
398 } catch(Exception e) {
399 errorLog.log(annotation.parameters[0].location, "Invalid annotation parameter.");
402 else if(annotation.id.text.equals("@FieldNames")) {
404 EListLiteral literal = (EListLiteral)annotation.parameters[0];
405 fieldNames = new String[literal.getComponents().length];
406 for(int i=0;i<fieldNames.length;++i) {
407 Expression component = literal.getComponents()[i];
408 if(component instanceof EVar)
409 fieldNames[i] = ((EVar)component).name;
410 else if(component instanceof ELiteral)
411 fieldNames[i] = ((StringConstant)((ELiteral)component).getValue()).getValue();
413 } catch(Exception e) {
414 errorLog.log(annotation.parameters[0].location, "Invalid annotation parameter.");
419 constructors[j] = new Constructor(constructor.location, dataType,
420 Name.create(moduleName, name),
421 parameterTypes, javaName);
422 constructors[j].fieldNames = fieldNames;
423 constructors[j].recordFieldNames = constructor.fieldNames;
425 if(constructors.length == 1) {
426 Constructor constructor = constructors[0];
427 if(constructor.recordFieldNames != null) {
428 fieldAccessorGenerators.add(new Runnable() {
431 Type in = Types.apply(dataType.name, dataType.parameters);
432 for(int i=0;i<constructor.recordFieldNames.length;++i) {
433 Type out = constructor.parameterTypes[i];
436 accessor = new SafeCoerce(dataType.parameters, in, out);
438 accessor = new CallJava(dataType.parameters, Types.NO_EFFECTS, out,
439 new Type[] {in}, new StackItem[] {new ParameterStackItem(0, in)},
440 new FieldRef(constructor.javaName, constructor.fieldNames != null ? constructor.fieldNames[i] : "c" + i,
441 javaTypeTranslator.toTypeDesc(out)),
443 module.addFieldAccessor(constructor.recordFieldNames[i], accessor);
451 for(Runnable fieldAccessorGenerator : fieldAccessorGenerators)
452 fieldAccessorGenerator.run();
455 public void processTypeClasses(ArrayList<ProcessedDClassAst> typeClassesAst) {
456 for(ProcessedDClassAst pClassAst : typeClassesAst) {
457 DClassAst classAst = pClassAst.orig;
459 if(module.getTypeClass(classAst.name) != null) {
460 errorLog.log(classAst.location, "Class "+classAst.name+" has already been defined in this module.");
464 TypeTranslationContext context = createTypeTranslationContext();
466 TPred[] classContext = new TPred[classAst.context.length];
467 for(int i=0;i<classContext.length;++i)
468 classContext[i] = context.toTFuncApply(classAst.context[i]);
470 TVar[] parameters = new TVar[classAst.parameters.length];
472 if(classAst.name.equals("Functor") || classAst.name.equals("Monad")) {
474 parameters[0] = context.resolveTypeVariable(pClassAst.orig.location, classAst.parameters[0], Kinds.STAR_TO_STAR);
477 for(int i=0;i<parameters.length;++i)
478 parameters[i] = context.resolveTypeVariable(pClassAst.orig.location, classAst.parameters[i], Kinds.metaVar());
481 TCon con = Types.con(moduleName, classAst.name);
482 TypeClass typeClass = new TypeClass(classAst.location,
485 compilationContext.namingPolicy.getTypeClassInterfaceName(con),
487 Fundep.mapFundeps(classAst.parameters, classAst.fundeps));
489 THashMap<String, TypeClassMethod> methods = typeClass.methods;
490 for(DValueTypeAst methodDecl : pClassAst.typeDeclarations) {
494 type = context.toType(methodDecl.type);
495 } catch(SCLSyntaxErrorException e) {
496 errorLog.log(e.location, e.getMessage());
499 for(EVar name : methodDecl.names) {
500 typeClass.methodNames.add(name.name);
501 methods.put(name.name,
502 new TypeClassMethod(typeClass, name.name,
503 compilationContext.namingPolicy.getMethodName(name.name),
504 type, Types.getArity(type),
508 } catch(RuntimeException e) {
509 errorLog.setExceptionPosition(methodDecl.location);
514 for(String methodName : pClassAst.defaultImplementations.getValueNames()) {
515 String fullName = "_" + classAst.name + "_default_" + methodName;
516 ArrayList<DValueAst> defs = pClassAst.defaultImplementations.getDefinition(methodName);
518 TypeClassMethod method = typeClass.methods.get(methodName);
520 errorLog.log(defs.get(0).location, "Method " + methodName + " is not defined in this class.");
523 method.setDefaultImplementation(Name.create(moduleName, fullName));
525 valueDefinitionsAst.addDefinitions(fullName, defs);
526 /*valueDefinitionsAst.addAnnotation(fullName, new DAnnotationAst(new EVar("@private"),
527 Collections.<Expression>emptyList()));*/
528 supplementedTypeAnnotations.add(new SupplementedValueType(defs.get(0).location, fullName, method.getType()));
531 module.addTypeClass(classAst.name, typeClass);
535 private TypeTranslationContext createTypeTranslationContext() {
536 return new TypeTranslationContext(compilationContext);
539 public void processDerivingInstances(ArrayList<DDerivingInstanceAst> derivingInstancesAst,
540 ArrayList<ProcessedDInstanceAst> instancesAst) {
541 for(DDerivingInstanceAst derivingInstance : derivingInstancesAst) {
542 String name = derivingInstance.name.name;
545 con = Environments.getTypeClassName(compilationContext.environment, name);
546 } catch (AmbiguousNameException e) {
547 errorLog.log(derivingInstance.name.location, e.getMessage());
551 errorLog.log(derivingInstance.name.location, "Couldn't resolve class " + name + ".");
554 InstanceDeriver deriver = InstanceDerivers.get(con);
556 errorLog.log(derivingInstance.location, "Doesn't know how to derive " + name + ".");
558 deriver.derive(errorLog, compilationContext.environment, instancesAst, derivingInstance);
562 public void processInstances(ArrayList<ProcessedDInstanceAst> instancesAst) {
563 THashSet<TPred> instanceClashCheckSet = new THashSet<TPred>();
564 for(ProcessedDInstanceAst pInstanceAst : instancesAst) {
565 DInstanceAst instanceAst = pInstanceAst.orig;
567 TypeTranslationContext context = createTypeTranslationContext();
569 String name = instanceAst.name.name;
572 typeClassCon = Environments.getTypeClassName(compilationContext.environment, name);
573 } catch (AmbiguousNameException e) {
574 errorLog.log(instanceAst.name.location, e.getMessage());
577 if(typeClassCon == null) {
578 errorLog.log(instanceAst.name.location, "Couldn't resolve class " + name + ".");
581 TypeClass typeClass = compilationContext.environment.getTypeClass(typeClassCon);
582 pInstanceAst.typeClass = typeClass;
584 if(instanceAst.types.length != typeClass.parameters.length) {
585 errorLog.log(instanceAst.location, "Wrong number of parameters to type class " + typeClassCon.name + ".");
588 Type[] parameters = new Type[instanceAst.types.length];
589 for(int i=0;i<parameters.length;++i)
590 parameters[i] = context.toType(instanceAst.types[i], typeClass.parameters[i].getKind() /* FIXME */);
591 TPred instance = Types.pred(typeClassCon, parameters);
593 if(!instanceClashCheckSet.add(instance)) {
594 errorLog.log(instanceAst.location, "Duplicate definition of the instance " + instance + ".");
598 TPred[] instanceContext = new TPred[instanceAst.context.length];
599 for(int i=0;i<instanceContext.length;++i)
600 instanceContext[i] = context.toTFuncApply(instanceAst.context[i]);
602 String javaName = compilationContext.namingPolicy.getInstanceClassName(instance);
603 String instancePrefix = instance.toName() + "$";
605 ValueRepository valueDefs = pInstanceAst.valueDefs;
607 THashMap<String, MethodImplementation> methodImplementations =
608 new THashMap<String, MethodImplementation>();
609 for(String valueName : valueDefs.getValueNames()) {
610 String fullName = instancePrefix + valueName;
611 long loc = valueDefs.getDefinition(valueName).get(0).location;
612 valueDefinitionsAst.addFrom(valueDefs, valueName, fullName);
613 valueDefinitionsAst.setDerived(fullName);
614 /*valueDefinitionsAst.addAnnotation(fullName, new DAnnotationAst(new EVar("@private"),
615 Collections.<Expression>emptyList()));*/
616 TypeClassMethod method = typeClass.methods.get(valueName);
618 errorLog.log(loc, "Method " + valueName + " is not defined in the type class " + typeClass.name.name + ".");
621 Type type = method.getBaseType().replace(typeClass.parameters, parameters);
622 for(int i=instanceContext.length-1;i>=0;--i)
623 type = Types.constrained(instanceContext[i], type);
624 //System.out.println(valueName + " :: " + type);
625 supplementedTypeAnnotations.add(
626 new SupplementedValueType(loc, fullName, type));
627 methodImplementations.put(valueName,
628 new MethodImplementation(Name.create(moduleName, fullName), false));
631 // Are all necessary methods defined
632 for(String methodName : typeClass.methods.keySet())
633 if(!methodImplementations.containsKey(methodName)) {
634 Name defaultImplementation = typeClass.methods.get(methodName).getDefaultImplementation();
635 if(defaultImplementation == null)
636 errorLog.log(instanceAst.location, "Method " + methodName + " is not defined.");
638 methodImplementations.put(methodName,
639 new MethodImplementation(defaultImplementation, true));
642 JavaTypeInstanceConstructor generator = new JavaTypeInstanceConstructor(javaName, instance, instanceContext);
643 if(instanceContext.length == 0)
644 generator.setHasStaticInstance(true);
646 TypeClassInstance typeClassInstance =
647 new TypeClassInstance(instanceAst.location, typeClass, generator,
648 generator.getTypeParameters(),
649 instanceContext, instance, methodImplementations,
652 generator.setInstance(typeClassInstance);
654 module.addTypeClassInstance(typeClassCon, typeClassInstance);
655 } catch(RuntimeException e) {
656 errorLog.setExceptionPosition(instanceAst.location);
661 // Generate superclass functions
662 for(ArrayList<TypeClassInstance> instanceArray : module.getTypeInstances().values())
663 for(TypeClassInstance instance : instanceArray) {
665 TypeClass typeClass = instance.typeClass;
666 int superCount = typeClass.context.length;
668 instance.superExpressions = new SCLValue[superCount];
669 for(int i=0;i<superCount;++i) {
670 TPred type = (TPred)typeClass.context[i]
671 .replace(typeClass.parameters, instance.instance.parameters);
672 SCLValue value = new SCLValue(Name.create(moduleName,
673 instance.javaName.substring(instance.javaName.indexOf('$')+1) + "_super" + i));
674 //value.addProperty(PrivateProperty.INSTANCE);
675 module.addValue(value);
676 Expression expression = new EGetConstraint(instance.location, type);
677 value.setExpression(expression);
678 value.setType(Types.forAll(instance.generatorParameters, Types.constrained(instance.context, type)));
679 value.getProperties().add(new InlineProperty(instance.context.length, 0xffffffff));
680 //TypeUnparsingContext tuc = new TypeUnparsingContext();
681 // TODO error handling
682 instance.superExpressions[i] = value;
684 } catch(RuntimeException e) {
685 errorLog.setExceptionPosition(instance.getLocation());
691 public void processJavaMethods(ArrayList<JavaMethodDeclaration> javaMethodDeclarations) {
692 for(JavaMethodDeclaration javaMethod : javaMethodDeclarations) {
693 String name = javaMethod.methodName.name;
694 String javaName = name;
695 ArrayList<DAnnotationAst> annotations =
696 valueDefinitionsAst.getAnnotations(name);
697 boolean isPrivate = false;
698 if(annotations != null) {
699 for(DAnnotationAst annotation : annotations)
700 if(annotation.id.text.equals("@JavaName")) {
701 String temp = AnnotationUtils.processStringAnnotation(errorLog, annotation);
705 else if(annotation.id.text.equals("@private")) {
706 AnnotationUtils.processTagAnnotation(errorLog, annotation);
711 Type type = createTypeTranslationContext().toType(javaMethod.type);
713 CallJava callJava = resolveMethod(
715 javaMethod.className,
718 if(callJava != null) {
719 NameExistenceChecks.checkIfValueExists(errorLog, javaMethod.location,
720 importedEnvironment, module, name);
721 SCLValue value = module.addValue(name, callJava);
722 value.definitionLocation = javaMethod.methodName.location;
724 value.addProperty(PrivateProperty.INSTANCE);
729 public void processRulesets(ArrayList<DRulesetAst> rulesetsAst) {
730 for(DRulesetAst ruleset : rulesetsAst) {
731 String constructorName = "create" + ruleset.name;
732 supplementedTypeAnnotations.add(new SupplementedValueType(ruleset.location, constructorName, Types.functionE(Types.PUNIT, Types.PROC, ruleset.type)));
734 valueDefinitionsAst.add(new DValueAst(new EVar(constructorName), new EPreCHRRulesetConstructor(ruleset)));
735 } catch (NotPatternException e) {
736 throw new InternalCompilerError(ruleset.location, e);
742 * Convert a java class method into a {@link CallJava} instance.
743 * Compilation errors are logged for failures in finding the named class or in accessing the method.
744 * The return value for errors is {@code null}.
746 * @param loc SCL source location
747 * @param className Name of the class
748 * @param methodName Name of the method
749 * @param type The expected SCL type of the method
750 * @return A new JavaCall instance, or null if the given method can not be instantiated.
752 private CallJava resolveMethod(long loc,
753 String className, String methodName, Type type) {
755 ClassRef classRef = classRefs.get(className);
756 if(classRef == null) {
757 if(classRefs.containsKey(className))
759 classRef = javaReferenceValidator.getClassRef(className);
760 classRefs.put(className, classRef);
761 if(classRef == null) {
762 errorLog.log(loc, "Didn't find class " + className + ".");
765 if(!javaReferenceValidator.isPublic(classRef.getClass())) {
766 errorLog.log(loc, "Class " + className + " is not public.");
773 List<MethodRef> methodRefs = classRef.getMethodRefs(methodName);
774 if(methodRefs.isEmpty()) {
775 errorLog.log(loc, "Didn't find any public method or field with name '" + methodName + "' from class " + className + ".");
779 ArrayList<CallJava> candidates = new ArrayList<CallJava>(2);
780 for(MethodRef methodRef : methodRefs) {
781 CallJava candidate = matchType(methodRef, type);
782 if(candidate != null)
783 candidates.add(candidate);
786 if(candidates.isEmpty()) {
787 StringBuilder b = new StringBuilder();
788 b.append("Didn't find any public method or field matching the type " + type + ". The following methods and fields were tried:");
789 for(MethodRef methodRef : methodRefs) {
793 b.append("\nbut expected something like:");
795 MultiFunction mFun = Types.matchFunction(type);
796 b.append("\n public static ");
797 b.append(javaTypeTranslator.toTypeDesc(mFun.returnType).getFullName()).append(' ').append(methodName).append('(');
798 boolean first = true;
799 for(Type parameter : mFun.parameterTypes) {
804 b.append(javaTypeTranslator.toTypeDesc(parameter).getFullName());
808 errorLog.log(loc, b.toString());
811 else if(candidates.size() == 1)
812 return candidates.get(0);
814 // Try to find the best match
815 ArrayList<CallJava> bestCandidates = new ArrayList<CallJava>(candidates.size());
816 loop: for(CallJava candidate : candidates) {
817 Iterator<CallJava> it = bestCandidates.iterator();
818 while(it.hasNext()) {
819 CallJava b = it.next();
820 switch(candidate.compareTo(javaReferenceValidator, b)) {
824 case CallJava.GREATER:
827 case CallJava.INCOMPARABLE:
831 bestCandidates.add(candidate);
834 if(bestCandidates.size() == 1) {
835 // System.out.println("Choose: " + bestCandidates.get(0).getMethodRef());
836 return bestCandidates.get(0);
839 StringBuilder b = new StringBuilder();
840 b.append("Found more than one incomparable public methods the type " + type + ":");
841 for(CallJava callJava : bestCandidates) {
843 b.append(callJava.getMethodRef());
845 errorLog.log(loc, b.toString());
851 private CallJava matchType(MethodRef methodRef, Type type) {
852 //System.out.println("-----------------------------------------------------");
853 //System.out.println("method: " + methodRef);
854 //System.out.println("type: " + type);
856 type = Types.canonical(type);
857 while(type instanceof TForAll)
858 type = Types.canonical(((TForAll)type).type);
860 TypeDesc[] expectedParameterTypes = methodRef.getParameterTypes();
862 ArrayList<Type> parameterTypes = new ArrayList<Type>();
863 Type effect = Types.NO_EFFECTS;
864 Type returnType = type;
866 StackItem[] stackItems = new StackItem[expectedParameterTypes.length];
867 TIntArrayList unresolvedItems = new TIntArrayList();
870 for(int i=0;i<expectedParameterTypes.length;++i) {
872 TypeDesc providedParameterType;
874 if(effect != Types.NO_EFFECTS || !(returnType instanceof TFun)) {
875 while(i < expectedParameterTypes.length)
876 unresolvedItems.add(i++);
879 TFun fun = (TFun)returnType;
880 parameterType = Types.canonical(fun.domain);
881 parameterTypes.add(parameterType);
882 effect = Types.canonical(fun.effect);
883 returnType = Types.canonical(fun.range);
884 providedParameterType = javaTypeTranslator.toTypeDesc(parameterType);
885 } while(providedParameterType.equals(TypeDesc.VOID));
888 TypeDesc expectedParameterType = expectedParameterTypes[i];
889 if(javaReferenceValidator.isAssignableFrom(expectedParameterType,
890 providedParameterType)) {
891 stackItems[i] = new ParameterStackItem(
892 parameterTypes.size()-1,
897 unresolvedItems.add(i++);
898 if(i == expectedParameterTypes.length) {
899 parameterTypes.remove(parameterTypes.size()-1);
900 returnType = Types.functionE(parameterType, effect, returnType);
905 //System.out.println("returnType: " + returnType);
906 if(!unresolvedItems.isEmpty()) {
907 ArrayList<TCon> concreteEffects = new ArrayList<TCon>();
908 effect.collectConcreteEffects(concreteEffects);
910 for(TCon eff : concreteEffects) {
911 EffectConstructor effC = compilationContext.environment.getEffectConstructor(eff);
912 for(ThreadLocalVariable var : effC.getThreadLocalVariables()) {
913 for(int i=0;i<unresolvedItems.size();++i) {
914 int id = unresolvedItems.get(i);
915 if(!expectedParameterTypes[id].equals(TypeDesc.OBJECT) &&
916 javaReferenceValidator.isAssignableFrom(expectedParameterTypes[id], var.type)) {
917 stackItems[id] = new ThreadLocalStackItem(var.variableName, var.type);
918 unresolvedItems.removeAt(i);
925 if(!unresolvedItems.isEmpty())
927 /*System.out.print("Unresolved: ");
928 boolean first = true;
929 for(int i=0;i<unresolvedItems.size();++i) {
933 System.out.print(", ");
934 System.out.print(expectedParameterTypes[unresolvedItems.get(i)]);
936 System.out.println();*/
938 OutputFilter filter = null;
940 TypeDesc providedReturnType = methodRef.getReturnType();
941 if(!providedReturnType.equals(Constants.FUNCTION)) {
942 while(returnType instanceof TFun && effect == Types.NO_EFFECTS) {
943 TFun fun = (TFun)returnType;
944 Type parameterType = Types.canonical(fun.domain);
945 if(!javaTypeTranslator.toTypeDesc(parameterType).equals(TypeDesc.VOID))
947 parameterTypes.add(parameterType);
948 effect = Types.canonical(fun.effect);
949 returnType = Types.canonical(fun.range);
952 TypeDesc expectedReturnType =
953 javaTypeTranslator.toTypeDesc(returnType);
954 if(!javaReferenceValidator.isAssignableFrom(expectedReturnType,
955 providedReturnType)) {
956 if(expectedReturnType.equals(TypeDesc.VOID)) {
957 if(providedReturnType.equals(TypeDesc.DOUBLE) || providedReturnType.equals(TypeDesc.LONG))
958 filter = Pop2OutputFilter.INSTANCE;
960 filter = PopOutputFilter.INSTANCE;
962 else if(expectedReturnType.equals(Constants.LIST)
963 && providedReturnType.equals(Constants.COLLECTION))
964 filter = ConvertToListFilter.INSTANCE;
970 CallJava result = new CallJava(
971 Types.freeVarsArray(type),
974 parameterTypes.toArray(new Type[parameterTypes.size()]),
978 //System.out.println(result.getType());
982 public void processMappingRelations(ArrayList<DMappingRelationAst> mappingRelationsAst) {
983 for(DMappingRelationAst mappingRelation : mappingRelationsAst) {
984 TypeAst[] parameterTypesAst = mappingRelation.parameterTypes;
985 Type[] parameterTypes = new Type[parameterTypesAst.length];
986 TypeTranslationContext typeTranslationContext = createTypeTranslationContext();
987 for(int i=0;i<parameterTypes.length;++i)
988 parameterTypes[i] = parameterTypesAst[i].toType(typeTranslationContext, Kinds.STAR);
989 MappingRelation mRel =
990 new MappingRelation(Name.create(moduleName, mappingRelation.name), parameterTypes);
991 mRel.location = mappingRelation.location;
992 if(module.addMappingRelation(mRel))
993 errorLog.log(mappingRelation.location, "Mapping relation " + mappingRelation.name +
994 " has already been defined.");
998 THashMap<String, DRuleAst> ruleAstMap = new THashMap<String, DRuleAst>();
1000 public void processRules(ArrayList<DRuleAst> rulesAst) {
1001 // Find implied mapping relations
1002 for(DRuleAst ruleA : rulesAst) {
1003 ArrayList<Query> whereSection = ruleA.getSections().get("where");
1004 if(whereSection != null)
1005 for(Query query : whereSection) {
1006 if(!(query instanceof QPreGuard))
1008 QPreGuard guard = (QPreGuard)query;
1009 if(!(guard.guard instanceof EApply))
1011 EApply apply = (EApply)guard.guard;
1012 if(!(apply.getFunction() instanceof EVar))
1015 String name = ((EVar)apply.getFunction()).name;
1016 if(module.getMappingRelation(name) != null)
1019 int arity = apply.getParameters().length;
1020 Type[] parameterTypes = new Type[arity];
1021 for(int i=0;i<arity;++i)
1022 parameterTypes[i] = Types.metaVar(Kinds.STAR);
1023 MappingRelation mRel =
1024 new MappingRelation(Name.create(moduleName, name), parameterTypes);
1025 mRel.location = query.location;
1026 module.addMappingRelation(mRel);
1028 if(ruleAstMap.put(ruleA.name, ruleA) != null)
1029 errorLog.log(ruleA.location, "Rule " + ruleA.name +
1030 " has already been defined.");
1034 for(String ruleName : ruleAstMap.keySet())
1035 processRule(ruleName);
1038 private TransformationRule processRule(String ruleName) {
1039 TransformationRule rule = module.getRule(ruleName);
1043 DRuleAst ruleAst = ruleAstMap.get(ruleName);
1044 if(ruleAst.alreadyProcessing) {
1045 errorLog.log(ruleAst.location, "Cyclic chain of rule extensions.");
1049 TransformationRule[] extendsRules;
1050 int length = ruleAst.extendsNames.length;
1052 extendsRules = TransformationRule.EMPTY_ARRAY;
1054 extendsRules = new TransformationRule[length];
1055 for(int i=0;i<length;++i) {
1057 String extendsName = ruleAst.extendsNames[i];
1058 TransformationRule extendsRule;
1059 if(ruleAstMap.containsKey(extendsName))
1060 extendsRule = processRule(extendsName);
1062 extendsRule = Environments.getRule(compilationContext.environment, extendsName);
1063 if(extendsRule == null)
1064 errorLog.log(ruleAst.location,
1065 "Couldn't resolve rule name " + extendsName + ".");
1067 extendsRules[i] = extendsRule;
1068 } catch(AmbiguousNameException e) {
1069 errorLog.log(ruleAst.location, e.getMessage());
1074 final THashMap<SectionName, Query[]> sections = new THashMap<SectionName, Query[]>();
1076 final TranslationContext context = createTranslationContext();
1078 THashMap<String, Variable> variables = context.getVariables();
1079 for(TransformationRule extendsRule : extendsRules) {
1080 if(extendsRule == null)
1082 for(Variable var : extendsRule.variables)
1083 if(variables.put(var.getName(), var) != null) {
1084 errorLog.log(ruleAst.location,
1085 "Variable " + var.getName() + " is defined in more than one base rule, which is not currently allowed.");
1089 context.pushExistentialFrame();
1090 ruleAst.getSections().forEachEntry(new TObjectObjectProcedure<String, ArrayList<Query>>() {
1092 public boolean execute(String sectionNameString, ArrayList<Query> queries) {
1093 Query[] resolvedQueries = new Query[queries.size()];
1094 for(int i=0;i<resolvedQueries.length;++i)
1095 resolvedQueries[i] = queries.get(i).resolve(context);
1097 SectionName sectionName = SectionName.getSectionName(sectionNameString);
1098 if(sectionName == null)
1099 context.getErrorLog().log(queries.get(0).location,
1100 "Invalid section name " + sectionNameString + ".");
1102 sections.put(sectionName, resolvedQueries);
1107 Variable[] variables = context.getVariables().values().toArray(new Variable[context.getVariables().size()]);
1109 rule = new TransformationRule(ruleAst.isAbstract,
1110 Name.create(moduleName, ruleAst.name),
1112 sections, variables);
1113 rule.location = ruleAst.location;
1114 module.addRule(rule);
1118 public void addDataTypesToEnvironment() {
1119 for(StandardTypeConstructor dataType : dataTypes) {
1120 int constructorTag = 0;
1121 for(Constructor constructor : dataType.constructors) {
1122 SCLValue value = new SCLValue(constructor.name);
1123 value.definitionLocation = constructor.loc;
1124 SCLConstructor sclConstructor =
1126 constructor.name.name,
1127 constructor.javaName,
1128 constructor.getTypeVariables(),
1130 constructor.getReturnType(),
1131 constructor.fieldNames == null
1132 ? SCLConstructor.DEFAULT_FIELD_NAMES[constructor.getParameterTypes().length]
1133 : constructor.fieldNames,
1134 constructor.recordFieldNames,
1135 constructor.getParameterTypes());
1136 if(dataType.constructors.length == 1 && (
1137 dataType.getTypeDesc() == null ||
1138 (dataType.constructors[0].javaName != null &&
1139 dataType.constructors[0].javaName.equals(MethodBuilderBase.getClassName(dataType.getTypeDesc())))))
1140 sclConstructor.setOnlyConstructor(true);
1141 value.setValue(sclConstructor);
1142 value.setType(constructor.getType());
1144 NameExistenceChecks.checkIfValueExists(errorLog, constructor.loc,
1145 importedEnvironment, module, constructor.name.name);
1146 if(module.addValue(value)) {
1147 errorLog.log(constructor.loc,
1148 "Value " + constructor.name.name + " is already defined.");
1154 public void addTypeClassesToEnvironment() {
1155 for(TypeClass typeClass : module.getTypeClasses()) {
1156 for(TypeClassMethod method : typeClass.methods.values()) {
1157 SCLValue value = method.createValue();
1158 value.definitionLocation = method.location;
1159 NameExistenceChecks.checkIfValueExists(errorLog, Locations.NO_LOCATION,
1160 importedEnvironment, module, value.getName().name);
1162 if(module.addValue(value)) {
1163 String name = method.getName();
1164 long location = Locations.NO_LOCATION;
1165 ArrayList<DValueAst> definitions = valueDefinitionsAst.getDefinition(name);
1166 if(definitions != null && !definitions.isEmpty())
1167 location = definitions.get(0).location;
1168 errorLog.log(location, "Value " + name + " is already defined.");
1174 public void preprocessValueDefinitions(ArrayList<DValueTypeAst> typeAnnotationsAst) {
1175 for(String name : valueDefinitionsAst.getValueNames()) {
1176 SCLValue value = new SCLValue(Name.create(moduleName, name));
1178 long location = valueDefinitionsAst.getLocation(name);
1179 NameExistenceChecks.checkIfValueExists(errorLog, location,
1180 importedEnvironment, module, value.getName().name);
1181 value.definitionLocation = location;
1182 if(module.addValue(value))
1183 errorLog.log(location, "Value " + name + " is already defined.");
1184 if(valueDefinitionsAst.isDerived(name))
1185 value.addProperty(DerivedProperty.INSTANCE);
1187 for(DValueTypeAst valueTypeAst : typeAnnotationsAst)
1188 for(EVar name : valueTypeAst.names) {
1189 SCLValue value = module.getValue(name.name);
1191 errorLog.log(valueTypeAst.location, name.name + " is not defined.");
1192 value = new SCLValue(Name.create(moduleName, name.name));
1193 module.addValue(value);
1195 value.definitionLocation = name.location;
1197 for(String name : relationDefinitionsAst.getRelationNames()) {
1198 ConcreteRelation relation = new ConcreteRelation(name);
1199 module.addRelation(name, relation);
1203 public void addValueDefinitionsToEnvironment(ArrayList<DValueTypeAst> typeAnnotationsAst) {
1204 THashMap<String, DValueTypeAst> typeMap = new THashMap<String, DValueTypeAst>();
1205 for(DValueTypeAst valueTypeAst : typeAnnotationsAst)
1206 for(EVar name : valueTypeAst.names) {
1207 if(typeMap.containsKey(name.name))
1208 errorLog.log(valueTypeAst.location, "Type of "+name.name+" has already been declared in this module.");
1210 typeMap.put(name.name, valueTypeAst);
1213 THashMap<String, EVar> exportMap = null;
1214 if(moduleHeader != null && moduleHeader.export != null) {
1215 exportMap = new THashMap<String, EVar>();
1216 for(EVar export : moduleHeader.export)
1217 if(exportMap.put(export.name, export) != null)
1218 errorLog.log(export.location, "The symbol " + export.name + " is exported multiple times.");
1221 for(String name : valueDefinitionsAst.getValueNames()) {
1222 ArrayList<DValueAst> defs = valueDefinitionsAst.getDefinition(name);
1223 if(defs.size() != 1 || !(defs.get(0).value instanceof EPreCHRRulesetConstructor))
1226 SCLValue value = module.getValue(name);
1227 TranslationContext context = createTranslationContext();
1228 Expression expression = context.translateCases2(defs);
1229 value.setExpression(expression);
1231 if(exportMap != null && exportMap.remove(name) == null)
1232 value.addProperty(PrivateProperty.INSTANCE);
1233 } catch(RuntimeException e) {
1234 errorLog.setExceptionPosition(defs.get(0).location);
1238 for(String name : valueDefinitionsAst.getValueNames()) {
1239 ArrayList<DValueAst> defs = valueDefinitionsAst.getDefinition(name);
1240 if(defs.size() == 1 && defs.get(0).value instanceof EPreCHRRulesetConstructor)
1243 SCLValue value = module.getValue(name);
1244 TranslationContext context = createTranslationContext();
1245 Expression expression = context.translateCases2(defs);
1246 value.setExpression(expression);
1248 DValueTypeAst valueTypeAst = typeMap.remove(name);
1249 if(valueTypeAst != null)
1250 value.setType(Types.closure(context.toType(valueTypeAst.type)));
1252 ArrayList<DAnnotationAst> annotations = valueDefinitionsAst.getAnnotations(name);
1253 if(annotations != null)
1254 for(DAnnotationAst annotation : annotations) {
1255 handleAnnotation(value, defs, annotation);
1257 if(exportMap != null && exportMap.remove(name) == null)
1258 value.addProperty(PrivateProperty.INSTANCE);
1259 } catch(RuntimeException e) {
1260 errorLog.setExceptionPosition(defs.get(0).location);
1264 if(exportMap != null)
1265 for(EVar export : exportMap.values())
1266 errorLog.log(export.location, "The symbol " + export.name + " is not defined in the module.");
1267 for(String name : relationDefinitionsAst.getRelationNames()) {
1268 ArrayList<DRelationAst> definitions = relationDefinitionsAst.getDefinition(name);
1269 if(definitions.size() > 1) {
1270 errorLog.log(definitions.get(1).location,
1271 "Does not yet support definition of relations by more than one rule.");
1275 DRelationAst definition = definitions.get(0);
1276 ConcreteRelation relation = (ConcreteRelation)module.getRelation(name);
1277 relation.location = definition.location;
1278 TranslationContext context = createTranslationContext();
1279 definition.translateTo(context, relation);
1283 private TranslationContext createTranslationContext() {
1284 return new TranslationContext(compilationContext, null);
1287 private void handleAnnotation(SCLValue value, ArrayList<DValueAst> defs, DAnnotationAst annotation) {
1288 if(annotation.id.text.equals("@macro")) {
1289 value.setMacroRule(new StandardMacroRule());
1291 else if(annotation.id.text.equals("@inline")) {
1293 int arity = defs.get(0).lhs.getFunctionDefinitionPatternArity();
1294 int phaseMask = 0xffffffff;
1295 if(annotation.parameters.length > 0) {
1296 phaseMask = Integer.parseInt(((EIntegerLiteral)annotation.parameters[0]).getValue());
1298 value.addProperty(new InlineProperty(arity, phaseMask));
1299 } catch(NotPatternException e) {
1300 errorLog.log(annotation.location, "Inline annotation is invalid: this is not a function.");
1303 else if(annotation.id.text.equals("@private")) {
1304 if(moduleHeader != null && moduleHeader.export != null)
1305 errorLog.log(annotation.location, "Annotation @private is not used when module header contains export property.");
1306 value.addProperty(PrivateProperty.INSTANCE);
1308 else if(annotation.id.text.equals("@deprecated")) {
1309 String description = "";
1310 if(annotation.parameters.length > 0) {
1311 if(annotation.parameters.length > 1)
1312 errorLog.log(annotation.location, "Invalid number of parameters, expected one string.");
1314 String temp = AnnotationUtils.extractString(annotation.parameters[0]);
1316 errorLog.log(annotation.location, "Invalid parameter, expected one string.");
1321 value.addProperty(new DeprecatedProperty(description));
1324 errorLog.log(annotation.location, "Unknown annotation.");
1327 public void addSupplementedTypeAnnotationsToEnvironment() {
1328 for(SupplementedValueType valueType : supplementedTypeAnnotations) {
1329 Type type = Types.closure(valueType.type);
1330 String name = valueType.name;
1331 SCLValue value = module.getValue(name);
1333 errorLog.log(valueType.position,
1334 name + " is not defined.");
1335 else if(value.getType()==null)
1336 value.setType(type);
1338 errorLog.log(valueType.position,
1339 "Type of "+name+" has already been declared in this module.");
1343 public void addFixityToEnvironment(ArrayList<DFixityAst> fixityAst) {
1344 for(DFixityAst fixity : fixityAst) {
1345 for(EVar symbol : fixity.symbols) {
1346 String name = symbol.name;
1347 SCLValue value = module.getValue(name);
1349 errorLog.log(symbol.location,
1350 name + " is not defined.");
1352 value.setPrecedence(fixity.precedence);
1357 public void addCoverageBranchPoints() {
1358 branchPoints = new THashMap<String, BranchPoint[]>();
1359 BranchPointInjector injector = new BranchPointInjector();
1360 for(String valueName : valueDefinitionsAst.getValueNames()) {
1361 for(DValueAst valueAst : valueDefinitionsAst.getDefinition(valueName))
1362 valueAst.value = injector.injectBranchPoint(valueAst.value);
1363 branchPoints.put(valueName, injector.getAndClearBranchPoints());