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.names.Names;
8 import org.simantics.scl.compiler.common.precedence.Associativity;
9 import org.simantics.scl.compiler.common.precedence.Precedence;
10 import org.simantics.scl.compiler.compilation.CompilationContext;
11 import org.simantics.scl.compiler.elaboration.chr.CHRRuleset;
12 import org.simantics.scl.compiler.elaboration.chr.relations.CHRConstraint;
13 import org.simantics.scl.compiler.elaboration.expressions.Case;
14 import org.simantics.scl.compiler.elaboration.expressions.EAmbiguous;
15 import org.simantics.scl.compiler.elaboration.expressions.EConstant;
16 import org.simantics.scl.compiler.elaboration.expressions.EError;
17 import org.simantics.scl.compiler.elaboration.expressions.EFieldAccess;
18 import org.simantics.scl.compiler.elaboration.expressions.ELambda;
19 import org.simantics.scl.compiler.elaboration.expressions.EVar;
20 import org.simantics.scl.compiler.elaboration.expressions.EVariable;
21 import org.simantics.scl.compiler.elaboration.expressions.Expression;
22 import org.simantics.scl.compiler.elaboration.expressions.Variable;
23 import org.simantics.scl.compiler.elaboration.expressions.accessor.FieldAccessor;
24 import org.simantics.scl.compiler.elaboration.expressions.accessor.IdAccessor;
25 import org.simantics.scl.compiler.elaboration.expressions.block.LetStatement;
26 import org.simantics.scl.compiler.elaboration.modules.SCLValue;
27 import org.simantics.scl.compiler.elaboration.query.pre.PreQuery;
28 import org.simantics.scl.compiler.elaboration.relations.SCLRelation;
29 import org.simantics.scl.compiler.environment.AmbiguousNameException;
30 import org.simantics.scl.compiler.environment.Environments;
31 import org.simantics.scl.compiler.environment.LocalEnvironment;
32 import org.simantics.scl.compiler.environment.Namespace;
33 import org.simantics.scl.compiler.environment.filter.AcceptAllNamespaceFilter;
34 import org.simantics.scl.compiler.errors.Locations;
35 import org.simantics.scl.compiler.internal.parsing.declarations.DValueAst;
36 import org.simantics.scl.compiler.top.SCLCompilerConfiguration;
37 import org.simantics.scl.compiler.types.Type;
39 import gnu.trove.list.array.TIntArrayList;
40 import gnu.trove.map.hash.THashMap;
41 import gnu.trove.procedure.TObjectProcedure;
42 import gnu.trove.set.hash.THashSet;
44 public class TranslationContext extends TypeTranslationContext implements EnvironmentalContext {
46 public static class ExistentialFrame {
47 THashSet<String> variables = new THashSet<String>(4);
48 ArrayList<Variable> blanks = new ArrayList<Variable>(2);
49 public boolean disallowNewExistentials;
51 public EVariable createBlank(long location) {
52 Variable variable = new Variable("_");
54 EVariable result = new EVariable(variable);
55 result.location = location;
60 THashMap<String, Variable> variables = new THashMap<String, Variable>();
61 ArrayList<Entry> variableEntries = new ArrayList<Entry>();
62 LocalEnvironment localEnvironment;
63 TIntArrayList frames = new TIntArrayList();
64 ArrayList<THashSet<String>> frameNameSets = new ArrayList<THashSet<String>>();
65 ArrayList<ExistentialFrame> existentialFrames = new ArrayList<ExistentialFrame>(2);
66 SCLValue bindFunction;
68 public PreQuery currentPreQuery;
70 THashMap<String, SCLRelation> relations = new THashMap<String, SCLRelation>();
71 TIntArrayList relationFrames = new TIntArrayList();
72 ArrayList<RelationEntry> relationEntries = new ArrayList<RelationEntry>();
74 THashMap<String, CHRConstraint> chrConstraints = new THashMap<String, CHRConstraint>();
75 TIntArrayList chrConstraintFrames = new TIntArrayList();
76 ArrayList<CHRConstraintEntry> chrConstraintEntries = new ArrayList<CHRConstraintEntry>();
81 public Entry(String name, Variable variable) {
83 this.variable = variable;
87 static class RelationEntry {
90 public RelationEntry(String name, SCLRelation relation) {
92 this.relation = relation;
96 static class CHRConstraintEntry {
98 CHRConstraint constraint;
99 public CHRConstraintEntry(String name, CHRConstraint constraint) {
101 this.constraint = constraint;
105 public TranslationContext(CompilationContext compilationContext, LocalEnvironment localEnvironment) {
106 super(compilationContext);
107 this.localEnvironment = localEnvironment;
110 public static boolean isConstructorName(String name) {
111 int p = name.lastIndexOf('.');
112 char firstChar = name.charAt(p<0 ? 0 : p+1);
113 return Character.isUpperCase(firstChar);
116 /* Tries to resolve name as a local variable. It is assumed
117 * that name does not contain '.'.
119 private Expression resolveLocalVariable(long location, String name) {
120 Variable variable = variables.get(name);
122 return new EVariable(location, variable);
124 char c = name.charAt(0);
127 ExistentialFrame existentialFrame = getCurrentExistentialFrame();
128 if(existentialFrame == null || existentialFrame.disallowNewExistentials) {
129 errorLog.log(location, "New existential variables can be defined only in queries.");
130 return new EError(location);
132 variable = new Variable(name);
133 variables.put(name, variable);
134 existentialFrame.variables.add(name);
135 return new EVariable(variable);
138 if(name.length()==1) {
139 ExistentialFrame existentialFrame = getCurrentExistentialFrame();
140 if(existentialFrame == null || existentialFrame.disallowNewExistentials) {
141 errorLog.log(location, "Blank variables can be used only in queries.");
142 return new EError(location);
144 return existentialFrame.createBlank(location);
152 public ExistentialFrame getCurrentExistentialFrame() {
153 int size = existentialFrames.size();
157 return existentialFrames.get(size-1);
160 private Expression resolveFieldAccess(Expression base, int pos, String name) {
162 int p = findSeparator(name, pos+1);
163 FieldAccessor accessor = new IdAccessor(
165 name.substring(pos+1, p==-1 ? name.length() : p-1));
166 base = new EFieldAccess(base, accessor);
172 private static int findSeparator(String name, int fromIndex) {
173 ++fromIndex; // the first character (that can be #) is never a separator
174 while(fromIndex < name.length()) {
175 char c = name.charAt(fromIndex);
176 if(c == '.' || c == '#')
183 public Expression resolveValue(long location, Namespace namespace, String name) {
185 SCLValue value = namespace.getValue(name);
188 String deprecatedDescription = value.isDeprecated();
189 if(deprecatedDescription != null)
190 errorLog.logWarning(location, "Deprecated value " + value.getName().name + "." + (deprecatedDescription.isEmpty() ? "" : " " + deprecatedDescription));
191 return new EConstant(location, value);
192 } catch (AmbiguousNameException e) {
193 if(SCLCompilerConfiguration.ALLOW_OVERLOADING)
194 return resolveAmbigious(location, e.conflictingModules, name);
196 errorLog.log(location, e.getMessage());
197 return new EError(location);
202 private Expression resolveAmbigious(long location, String[] conflictingModules, String name) {
203 EAmbiguous.Alternative[] alternatives = new EAmbiguous.Alternative[conflictingModules.length];
204 for(int i=0;i<conflictingModules.length;++i) {
205 Name altName = Name.create(conflictingModules[i], name);
206 SCLValue altValue = environment.getValue(altName);
207 alternatives[i] = new EAmbiguous.Alternative() {
209 public Type getType() {
210 return altValue.getType();
214 public Expression realize() {
215 EConstant expression = new EConstant(altValue);
216 expression.location = location;
221 public String toString() {
222 return altValue.getName().toString().replace('/', '.');
226 EAmbiguous expression = new EAmbiguous(alternatives);
227 expression.location = location;
231 public Expression resolveVariable(long location, Namespace namespace, String name, int begin) {
232 int end = findSeparator(name, begin);
233 String part = end == -1 ? (begin == 0 ? name : name.substring(begin)) : name.substring(begin, end);
236 Expression result = resolveLocalVariable(location, part);
238 return end == -1 ? result : resolveFieldAccess(result, end, name);
240 // FIXME.. support for records
241 if(localEnvironment != null) {
242 result = localEnvironment.resolve(environment, name);
244 result.setLocationDeep(location);
249 if(end != -1 && name.charAt(end) == '.') {
250 Namespace childNamespace = namespace.getNamespace(part);
251 if(childNamespace != null)
252 return resolveVariable(location, childNamespace, name, end+1);
255 Expression result = null;
257 for(int end2 = name.length();end2 > end;end2 = name.lastIndexOf('.', end2-1)) {
258 part = name.substring(begin, end2);
259 result = resolveValue(location, namespace, part);
261 end = end2 == name.length() ? -1 : end2;
267 result = resolveValue(location, namespace, part);
269 return end == -1 ? result : resolveFieldAccess(result, end, name);
271 reportResolveFailure(location, namespace, part);
272 return new EError(location);
275 private void reportResolveFailure(long location, Namespace namespace, String name) {
276 StringBuilder message = new StringBuilder();
277 message.append("Couldn't resolve ").append(name).append(".");
279 final THashSet<String> candidateNames = new THashSet<String>(4);
280 namespace.findValuesForPrefix("", AcceptAllNamespaceFilter.INSTANCE,
281 new TObjectProcedure<SCLValue>() {
283 public boolean execute(SCLValue value) {
285 new Exception().printStackTrace();
288 String valueName = value.getName().name;
289 if(name.equalsIgnoreCase(valueName))
290 candidateNames.add(valueName);
294 if(localEnvironment != null)
295 localEnvironment.forNames(new TObjectProcedure<String>() {
297 public boolean execute(String valueName) {
298 if(name.equalsIgnoreCase(valueName))
299 candidateNames.add(valueName);
304 if(candidateNames.size() > 0) {
305 message.append(" Did you mean ");
306 String[] ns = candidateNames.toArray(new String[candidateNames.size()]);
308 for(int i=0;i<ns.length;++i) {
310 message.append(", ");
312 message.append("or ");
314 message.append(ns[i]);
319 errorLog.log(location, message.toString());
322 public Expression resolveVariable(long location, String name) {
323 return resolveVariable(location, environment.getLocalNamespace(), name, 0);
326 public Expression resolvePattern(EVar name) {
327 char firstChar = name.name.charAt(0);
328 if(firstChar == '_' && name.name.length()==1) {
329 return new EVariable(new Variable("_"));
331 else if(!Character.isUpperCase(firstChar)) {
332 if(!frameNameSets.get(frameNameSets.size()-1).add(name.name))
333 errorLog.log(name.location, "Repeated variable "+name.name+" in pattern.");
334 return new EVariable(name.location, newVariable(name.name));
337 return resolveVariable(name.location, name.name);
341 * Starts a new environment frame. New variables defined in this frame shadow
342 * the old variables and when the frame is popped, the old variables are again
345 public void pushFrame() {
346 frames.add(variableEntries.size());
347 frameNameSets.add(new THashSet<String>());
351 * Ends an environment frame. See {@link #pushFrame}.
353 public void popFrame() {
354 int frame = frames.removeAt(frames.size()-1);
355 int i = variableEntries.size();
358 Entry entry = variableEntries.remove(i);
359 if(entry.variable == null)
360 variables.remove(entry.name);
362 variables.put(entry.name, entry.variable);
364 frameNameSets.remove(frameNameSets.size()-1);
367 public void pushRelationFrame() {
368 relationFrames.add(relationEntries.size());
371 public void popRelationFrame() {
372 int frame = relationFrames.removeAt(relationFrames.size()-1);
373 int i = relationEntries.size();
376 RelationEntry entry = relationEntries.remove(i);
377 if(entry.relation == null)
378 relations.remove(entry.name);
380 relations.put(entry.name, entry.relation);
384 public void pushCHRConstraintFrame() {
385 chrConstraintFrames.add(chrConstraintEntries.size());
388 public void popCHRConstraintFrame(ArrayList<CHRConstraint> constraints) {
389 int frame = chrConstraintFrames.removeAt(chrConstraintFrames.size()-1);
390 int i = chrConstraintEntries.size();
393 CHRConstraintEntry entry = chrConstraintEntries.remove(i);
394 CHRConstraint newConstraint;
395 if(entry.constraint == null)
396 newConstraint = chrConstraints.remove(entry.name);
398 newConstraint = chrConstraints.put(entry.name, entry.constraint);
399 if(newConstraint.implicitlyDeclared)
400 constraints.add(newConstraint);
404 public void pushExistentialFrame() {
406 existentialFrames.add(new ExistentialFrame());
409 public Variable[] popExistentialFrame() {
411 ExistentialFrame frame = existentialFrames.remove(existentialFrames.size()-1);
412 Variable[] result = new Variable[frame.variables.size() + frame.blanks.size()];
414 for(String name : frame.variables)
415 result[i++] = variables.remove(name);
416 for(Variable blank : frame.blanks)
421 public Variable newVariable(String name) {
422 Variable variable = new Variable(name);
423 Variable oldVariable = variables.put(name, variable);
424 variableEntries.add(new Entry(name, oldVariable));
428 public THashMap<String, Variable> getVariables() {
432 public void newRelation(String name, SCLRelation relation) {
433 SCLRelation oldRelation = relations.put(name, relation);
434 relationEntries.add(new RelationEntry(name, oldRelation));
437 public void newCHRConstraint(String name, CHRConstraint constraint) {
438 CHRConstraint oldConstraint = chrConstraints.put(name, constraint);
439 chrConstraintEntries.add(new CHRConstraintEntry(name, oldConstraint));
442 public Precedence getPrecedence(Name op) {
443 Precedence prec = environment.getValue(op).getPrecedence();
445 return new Precedence(1, Associativity.NONASSOC);
450 public Case translateCase(Expression lhs, Expression rhs) {
451 ArrayList<Expression> parameters = new ArrayList<Expression>(4);
452 lhs.getParameters(this, parameters);
453 Expression[] patterns = new Expression[parameters.size()];
455 for(int i=0;i<patterns.length;++i) {
456 Expression pattern = parameters.get(i);
457 pattern = pattern.resolveAsPattern(this);
458 patterns[i] = pattern;
460 rhs = rhs.resolve(this);
462 Case case_ = new Case(patterns, rhs);
463 case_.setLhs(lhs.location);
467 public Expression translateCases2(ArrayList<DValueAst> definitions) {
468 Case[] cases = new Case[definitions.size()];
469 for(int i=0;i<cases.length;++i) {
470 DValueAst def = definitions.get(i);
471 cases[i] = translateCase(def.lhs, def.value);
473 // check arity consistency
474 int arity = cases[0].patterns.length;
475 for(int i=1;i<cases.length;++i)
476 if(cases[i].patterns.length != arity)
477 errorLog.log(definitions.get(i).lhs.location,
478 "Inconsistent arity. " +
479 "This case has arity " + cases[i].patterns.length +
480 " while previous cases had arity " + arity + ".");
481 if(cases.length == 1 && cases[0].patterns.length == 0)
482 return cases[0].value;
485 Locations.combine(definitions.get(0).location, definitions.get(definitions.size()-1).location),
489 public Expression translateCases(ArrayList<LetStatement> definitions) {
490 Case[] cases = new Case[definitions.size()];
491 for(int i=0;i<cases.length;++i) {
492 LetStatement def = definitions.get(i);
493 cases[i] = translateCase(def.pattern, def.value);
495 // check arity concistency
496 int arity = cases[0].patterns.length;
497 for(int i=1;i<cases.length;++i)
498 if(cases[i].patterns.length != arity)
499 errorLog.log(definitions.get(i).pattern.location,
500 "Inconsistent arity. " +
501 "This case has arity " + cases[i].patterns.length +
502 " while previous cases had arity " + arity + ".");
505 errorLog.log(cases[1].value.location, "Cannot give multiple cases for arity 0 function.");
506 return cases[0].value;
509 Locations.combine(definitions.get(0).location, definitions.get(definitions.size()-1).location),
513 public SCLValue getBindFunction() {
514 if(bindFunction == null) {
515 bindFunction = getEnvironment().getValue(Names.Prelude_bind);
520 public SCLRelation resolveRelation(long location, String name) {
521 SCLRelation relation = relations.get(name);
526 relation = Environments.getRelation(environment, name);
527 /*if(relation == null) {
528 errorLog.log(location, "Couldn't resolve relation " + name + ".");
532 } catch (AmbiguousNameException e) {
533 errorLog.log(location, e.getMessage());
538 public CHRConstraint resolveCHRConstraint(String name) {
539 return chrConstraints.get(name);
543 public SCLValue getValue(Name name) {
544 return environment.getValue(name);
547 public CHRRuleset resolveRuleset(String name) throws AmbiguousNameException {
548 return Environments.getRuleset(environment, name);
551 public void disallowNewExistentials() {
552 getCurrentExistentialFrame().disallowNewExistentials = true;