1 package org.simantics.scl.compiler.elaboration.contexts;
3 import java.util.ArrayList;
4 import java.util.Arrays;
6 import org.simantics.scl.compiler.common.names.Name;
7 import org.simantics.scl.compiler.common.precedence.Associativity;
8 import org.simantics.scl.compiler.common.precedence.Precedence;
9 import org.simantics.scl.compiler.compilation.CompilationContext;
10 import org.simantics.scl.compiler.elaboration.chr.CHRRuleset;
11 import org.simantics.scl.compiler.elaboration.chr.relations.CHRConstraint;
12 import org.simantics.scl.compiler.elaboration.expressions.Case;
13 import org.simantics.scl.compiler.elaboration.expressions.EAmbiguous;
14 import org.simantics.scl.compiler.elaboration.expressions.EConstant;
15 import org.simantics.scl.compiler.elaboration.expressions.EError;
16 import org.simantics.scl.compiler.elaboration.expressions.EFieldAccess;
17 import org.simantics.scl.compiler.elaboration.expressions.ELambda;
18 import org.simantics.scl.compiler.elaboration.expressions.EVar;
19 import org.simantics.scl.compiler.elaboration.expressions.EVariable;
20 import org.simantics.scl.compiler.elaboration.expressions.Expression;
21 import org.simantics.scl.compiler.elaboration.expressions.Variable;
22 import org.simantics.scl.compiler.elaboration.expressions.accessor.FieldAccessor;
23 import org.simantics.scl.compiler.elaboration.expressions.accessor.IdAccessor;
24 import org.simantics.scl.compiler.elaboration.expressions.block.LetStatement;
25 import org.simantics.scl.compiler.elaboration.modules.SCLValue;
26 import org.simantics.scl.compiler.elaboration.query.pre.PreQuery;
27 import org.simantics.scl.compiler.elaboration.relations.SCLRelation;
28 import org.simantics.scl.compiler.environment.AmbiguousNameException;
29 import org.simantics.scl.compiler.environment.Environments;
30 import org.simantics.scl.compiler.environment.LocalEnvironment;
31 import org.simantics.scl.compiler.environment.Namespace;
32 import org.simantics.scl.compiler.environment.filter.AcceptAllNamespaceFilter;
33 import org.simantics.scl.compiler.errors.Locations;
34 import org.simantics.scl.compiler.internal.parsing.declarations.DValueAst;
35 import org.simantics.scl.compiler.module.debug.ModuleDebugInfo;
36 import org.simantics.scl.compiler.module.debug.SymbolReference;
37 import org.simantics.scl.compiler.top.SCLCompilerConfiguration;
38 import org.simantics.scl.compiler.types.Type;
40 import gnu.trove.list.array.TIntArrayList;
41 import gnu.trove.map.hash.THashMap;
42 import gnu.trove.procedure.TObjectProcedure;
43 import gnu.trove.set.hash.THashSet;
45 public class TranslationContext extends TypeTranslationContext implements EnvironmentalContext {
47 public static class ExistentialFrame {
48 THashSet<String> variables = new THashSet<String>(4);
49 ArrayList<Variable> blanks = new ArrayList<Variable>(2);
50 public boolean disallowNewExistentials;
52 public EVariable createBlank(long location) {
53 Variable variable = new Variable("_");
55 EVariable result = new EVariable(variable);
56 result.location = location;
61 THashMap<String, Variable> variables = new THashMap<String, Variable>();
62 ArrayList<Entry> variableEntries = new ArrayList<Entry>();
63 LocalEnvironment localEnvironment;
64 TIntArrayList frames = new TIntArrayList();
65 ArrayList<THashSet<String>> frameNameSets = new ArrayList<THashSet<String>>();
66 ArrayList<ExistentialFrame> existentialFrames = new ArrayList<ExistentialFrame>(2);
67 SCLValue bindFunction;
69 public PreQuery currentPreQuery;
71 THashMap<String, SCLRelation> relations = new THashMap<String, SCLRelation>();
72 TIntArrayList relationFrames = new TIntArrayList();
73 ArrayList<RelationEntry> relationEntries = new ArrayList<RelationEntry>();
75 THashMap<String, CHRConstraint> chrConstraints = new THashMap<String, CHRConstraint>();
76 TIntArrayList chrConstraintFrames = new TIntArrayList();
77 ArrayList<CHRConstraintEntry> chrConstraintEntries = new ArrayList<CHRConstraintEntry>();
79 public CHRRuleset currentRuleset;
81 public ModuleDebugInfo moduleDebugInfo;
83 private String definitionName;
88 public Entry(String name, Variable variable) {
90 this.variable = variable;
94 static class RelationEntry {
97 public RelationEntry(String name, SCLRelation relation) {
99 this.relation = relation;
103 static class CHRConstraintEntry {
105 CHRConstraint constraint;
106 public CHRConstraintEntry(String name, CHRConstraint constraint) {
108 this.constraint = constraint;
112 public TranslationContext(CompilationContext compilationContext, LocalEnvironment localEnvironment, String definitionName) {
113 super(compilationContext);
114 this.localEnvironment = localEnvironment;
115 this.moduleDebugInfo = compilationContext.moduleDebugInfo;
116 this.definitionName = definitionName;
119 public static boolean isConstructorName(String name) {
120 int p = name.lastIndexOf('.');
121 char firstChar = name.charAt(p<0 ? 0 : p+1);
122 return Character.isUpperCase(firstChar) || firstChar == '(';
125 /* Tries to resolve name as a local variable. It is assumed
126 * that name does not contain '.'.
128 private Expression resolveLocalVariable(long location, String name) {
129 Variable variable = variables.get(name);
131 return new EVariable(location, variable);
133 char c = name.charAt(0);
136 ExistentialFrame existentialFrame = getCurrentExistentialFrame();
137 if(existentialFrame == null || existentialFrame.disallowNewExistentials) {
138 errorLog.log(location, "New existential variables can be defined only in queries.");
139 return new EError(location);
141 variable = new Variable(name);
142 variables.put(name, variable);
143 existentialFrame.variables.add(name);
144 return new EVariable(variable);
147 if(name.length()==1) {
148 ExistentialFrame existentialFrame = getCurrentExistentialFrame();
149 if(existentialFrame == null || existentialFrame.disallowNewExistentials) {
150 errorLog.log(location, "Blank variables can be used only in queries.");
151 return new EError(location);
153 return existentialFrame.createBlank(location);
161 public ExistentialFrame getCurrentExistentialFrame() {
162 int size = existentialFrames.size();
166 return existentialFrames.get(size-1);
169 private Expression resolveFieldAccess(long location, Expression base, int pos, String name) {
171 int p = findSeparator(name, pos+1);
172 int endPos = p==-1 ? name.length() : p;
173 FieldAccessor accessor = new IdAccessor(
175 name.substring(pos+1, endPos));
176 accessor.location = Locations.sublocation(location, pos+1, endPos);
177 base = new EFieldAccess(base, accessor);
178 base.location = Locations.sublocation(location, 0, endPos);
184 private static int findSeparator(String name, int fromIndex) {
185 ++fromIndex; // the first character (that can be #) is never a separator
186 while(fromIndex < name.length()) {
187 char c = name.charAt(fromIndex);
188 if(c == '.' || c == '#')
195 public Expression resolveValue(long location, Namespace namespace, String name) {
197 SCLValue value = namespace.getValue(name);
200 String deprecatedDescription = value.isDeprecated();
201 if(deprecatedDescription != null)
202 errorLog.logWarning(location, "Deprecated value " + value.getName().name + "." + (deprecatedDescription.isEmpty() ? "" : " " + deprecatedDescription));
203 if(moduleDebugInfo != null)
204 moduleDebugInfo.symbolReferences.add(new SymbolReference(value.getName(), Name.create(compilationContext.module.getName(), definitionName), location));
205 return new EConstant(location, value);
206 } catch (AmbiguousNameException e) {
207 if(SCLCompilerConfiguration.ALLOW_OVERLOADING)
208 return resolveAmbigious(location, e.conflictingModules, name);
210 errorLog.log(location, e.getMessage());
211 return new EError(location);
216 private Expression resolveAmbigious(long location, String[] conflictingModules, String name) {
217 EAmbiguous.Alternative[] alternatives = new EAmbiguous.Alternative[conflictingModules.length];
218 for(int i=0;i<conflictingModules.length;++i) {
219 Name altName = Name.create(conflictingModules[i], name);
220 SCLValue altValue = environment.getValue(altName);
221 alternatives[i] = new EAmbiguous.Alternative() {
223 public Type getType() {
224 return altValue.getType();
228 public Expression realize() {
229 EConstant expression = new EConstant(altValue);
230 expression.location = location;
231 if(moduleDebugInfo != null)
232 moduleDebugInfo.symbolReferences.add(new SymbolReference(altValue.getName(), Name.create(compilationContext.module.getName(), definitionName), location));
237 public String toString() {
238 return altValue.getName().toString().replace('/', '.');
242 EAmbiguous expression = new EAmbiguous(alternatives);
243 expression.location = location;
247 public Expression resolveVariable(long location, Namespace namespace, String name, int begin) {
248 int end = findSeparator(name, begin);
249 String part = end == -1 ? (begin == 0 ? name : name.substring(begin)) : name.substring(begin, end);
252 Expression result = resolveLocalVariable(location, part);
254 return end == -1 ? result : resolveFieldAccess(location, result, end, name);
256 // FIXME.. support for records
257 if(localEnvironment != null) {
258 result = localEnvironment.resolve(environment, name);
260 result.setLocationDeep(location);
265 if(end != -1 && name.charAt(end) == '.') {
266 Namespace childNamespace = namespace.getNamespace(part);
267 if(childNamespace != null)
268 return resolveVariable(location, childNamespace, name, end+1);
271 Expression result = null;
273 for(int end2 = name.length();end2 > end;end2 = name.lastIndexOf('.', end2-1)) {
274 part = name.substring(begin, end2);
275 result = resolveValue(location, namespace, part);
277 end = end2 == name.length() ? -1 : end2;
283 result = resolveValue(location, namespace, part);
285 return end == -1 ? result : resolveFieldAccess(location, result, end, name);
287 reportResolveFailure(location, namespace, part);
288 return new EError(location);
291 private void reportResolveFailure(long location, Namespace namespace, String name) {
292 StringBuilder message = new StringBuilder();
293 message.append("Couldn't resolve ").append(name).append(".");
295 final THashSet<String> candidateNames = new THashSet<String>(4);
296 namespace.findValuesForPrefix("", AcceptAllNamespaceFilter.INSTANCE,
297 new TObjectProcedure<SCLValue>() {
299 public boolean execute(SCLValue value) {
301 new Exception().printStackTrace();
304 String valueName = value.getName().name;
305 if(name.equalsIgnoreCase(valueName))
306 candidateNames.add(valueName);
310 if(localEnvironment != null)
311 localEnvironment.forNames(new TObjectProcedure<String>() {
313 public boolean execute(String valueName) {
314 if(name.equalsIgnoreCase(valueName))
315 candidateNames.add(valueName);
320 if(candidateNames.size() > 0) {
321 message.append(" Did you mean ");
322 String[] ns = candidateNames.toArray(new String[candidateNames.size()]);
324 for(int i=0;i<ns.length;++i) {
326 message.append(", ");
328 message.append("or ");
330 message.append(ns[i]);
335 errorLog.log(location, message.toString());
338 public Expression resolveVariable(long location, String name) {
339 return resolveVariable(location, environment.getLocalNamespace(), name, 0);
342 public Expression resolvePattern(EVar name) {
343 char firstChar = name.name.charAt(0);
344 if(firstChar == '_' && name.name.length()==1) {
345 return new EVariable(new Variable("_"));
347 else if(!Character.isUpperCase(firstChar)) {
348 if(!frameNameSets.get(frameNameSets.size()-1).add(name.name))
349 errorLog.log(name.location, "Repeated variable "+name.name+" in pattern.");
350 return new EVariable(name.location, newVariable(name.name));
353 return resolveVariable(name.location, name.name);
357 * Starts a new environment frame. New variables defined in this frame shadow
358 * the old variables and when the frame is popped, the old variables are again
361 public void pushFrame() {
362 frames.add(variableEntries.size());
363 frameNameSets.add(new THashSet<String>());
367 * Ends an environment frame. See {@link #pushFrame}.
369 public void popFrame() {
370 int frame = frames.removeAt(frames.size()-1);
371 int i = variableEntries.size();
374 Entry entry = variableEntries.remove(i);
375 if(entry.variable == null)
376 variables.remove(entry.name);
378 variables.put(entry.name, entry.variable);
380 frameNameSets.remove(frameNameSets.size()-1);
383 public void pushRelationFrame() {
384 relationFrames.add(relationEntries.size());
387 public void popRelationFrame() {
388 int frame = relationFrames.removeAt(relationFrames.size()-1);
389 int i = relationEntries.size();
392 RelationEntry entry = relationEntries.remove(i);
393 if(entry.relation == null)
394 relations.remove(entry.name);
396 relations.put(entry.name, entry.relation);
400 public void pushCHRConstraintFrame() {
401 chrConstraintFrames.add(chrConstraintEntries.size());
404 public void popCHRConstraintFrame(CHRRuleset ruleset) {
405 int frame = chrConstraintFrames.removeAt(chrConstraintFrames.size()-1);
406 int i = chrConstraintEntries.size();
409 CHRConstraintEntry entry = chrConstraintEntries.remove(i);
410 CHRConstraint newConstraint;
411 if(entry.constraint == null)
412 newConstraint = chrConstraints.remove(entry.name);
414 newConstraint = chrConstraints.put(entry.name, entry.constraint);
415 if(newConstraint.implicitlyDeclared)
416 ruleset.addConstraint(newConstraint);
420 public void pushExistentialFrame() {
422 existentialFrames.add(new ExistentialFrame());
425 public Variable[] popExistentialFrame() {
427 ExistentialFrame frame = existentialFrames.remove(existentialFrames.size()-1);
428 Variable[] result = new Variable[frame.variables.size() + frame.blanks.size()];
430 for(String name : frame.variables)
431 result[i++] = variables.remove(name);
432 for(Variable blank : frame.blanks)
437 public Variable newVariable(String name) {
438 Variable variable = new Variable(name);
439 Variable oldVariable = variables.put(name, variable);
440 variableEntries.add(new Entry(name, oldVariable));
444 public THashMap<String, Variable> getVariables() {
448 public void newRelation(String name, SCLRelation relation) {
449 SCLRelation oldRelation = relations.put(name, relation);
450 relationEntries.add(new RelationEntry(name, oldRelation));
453 public void newCHRConstraint(String name, CHRConstraint constraint) {
454 CHRConstraint oldConstraint = chrConstraints.put(name, constraint);
455 chrConstraintEntries.add(new CHRConstraintEntry(name, oldConstraint));
458 public Precedence getPrecedence(Name op) {
459 Precedence prec = environment.getValue(op).getPrecedence();
461 return new Precedence(1, Associativity.NONASSOC);
466 public Case translateCase(Expression lhs, Expression rhs) {
467 ArrayList<Expression> parameters = new ArrayList<Expression>(4);
468 lhs.getParameters(this, parameters);
469 Expression[] patterns = new Expression[parameters.size()];
471 for(int i=0;i<patterns.length;++i) {
472 Expression pattern = parameters.get(i);
473 pattern = pattern.resolveAsPattern(this);
474 patterns[i] = pattern;
476 rhs = rhs.resolve(this);
478 Case case_ = new Case(patterns, rhs);
479 case_.setLhs(lhs.location);
483 public Expression translateCases2(ArrayList<DValueAst> definitions) {
484 Case[] cases = new Case[definitions.size()];
485 for(int i=0;i<cases.length;++i) {
486 DValueAst def = definitions.get(i);
487 cases[i] = translateCase(def.lhs, def.value);
489 // check arity consistency
490 int arity = cases[0].patterns.length;
491 for(int i=1;i<cases.length;++i)
492 if(cases[i].patterns.length != arity)
493 errorLog.log(definitions.get(i).lhs.location,
494 "Inconsistent arity. " +
495 "This case has arity " + cases[i].patterns.length +
496 " while previous cases had arity " + arity + ".");
497 if(cases.length == 1 && cases[0].patterns.length == 0)
498 return cases[0].value;
501 Locations.combine(definitions.get(0).location, definitions.get(definitions.size()-1).location),
505 public Expression translateCases(ArrayList<LetStatement> definitions) {
506 Case[] cases = new Case[definitions.size()];
507 for(int i=0;i<cases.length;++i) {
508 LetStatement def = definitions.get(i);
509 cases[i] = translateCase(def.pattern, def.value);
511 // check arity concistency
512 int arity = cases[0].patterns.length;
513 for(int i=1;i<cases.length;++i)
514 if(cases[i].patterns.length != arity)
515 errorLog.log(definitions.get(i).pattern.location,
516 "Inconsistent arity. " +
517 "This case has arity " + cases[i].patterns.length +
518 " while previous cases had arity " + arity + ".");
521 errorLog.log(cases[1].value.location, "Cannot give multiple cases for arity 0 function.");
522 return cases[0].value;
525 Locations.combine(definitions.get(0).location, definitions.get(definitions.size()-1).location),
529 public SCLRelation resolveRelation(long location, String name) {
530 SCLRelation relation = relations.get(name);
535 relation = Environments.getRelation(environment, name);
536 /*if(relation == null) {
537 errorLog.log(location, "Couldn't resolve relation " + name + ".");
541 } catch (AmbiguousNameException e) {
542 errorLog.log(location, e.getMessage());
547 public CHRConstraint resolveCHRConstraint(String name) {
548 return chrConstraints.get(name);
552 public SCLValue getValue(Name name) {
553 return environment.getValue(name);
556 public CHRRuleset resolveRuleset(String name) throws AmbiguousNameException {
557 return Environments.getRuleset(environment, name);
560 public void disallowNewExistentials() {
561 getCurrentExistentialFrame().disallowNewExistentials = true;