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>();
78 public CHRRuleset currentRuleset;
83 public Entry(String name, Variable variable) {
85 this.variable = variable;
89 static class RelationEntry {
92 public RelationEntry(String name, SCLRelation relation) {
94 this.relation = relation;
98 static class CHRConstraintEntry {
100 CHRConstraint constraint;
101 public CHRConstraintEntry(String name, CHRConstraint constraint) {
103 this.constraint = constraint;
107 public TranslationContext(CompilationContext compilationContext, LocalEnvironment localEnvironment) {
108 super(compilationContext);
109 this.localEnvironment = localEnvironment;
112 public static boolean isConstructorName(String name) {
113 int p = name.lastIndexOf('.');
114 char firstChar = name.charAt(p<0 ? 0 : p+1);
115 return Character.isUpperCase(firstChar);
118 /* Tries to resolve name as a local variable. It is assumed
119 * that name does not contain '.'.
121 private Expression resolveLocalVariable(long location, String name) {
122 Variable variable = variables.get(name);
124 return new EVariable(location, variable);
126 char c = name.charAt(0);
129 ExistentialFrame existentialFrame = getCurrentExistentialFrame();
130 if(existentialFrame == null || existentialFrame.disallowNewExistentials) {
131 errorLog.log(location, "New existential variables can be defined only in queries.");
132 return new EError(location);
134 variable = new Variable(name);
135 variables.put(name, variable);
136 existentialFrame.variables.add(name);
137 return new EVariable(variable);
140 if(name.length()==1) {
141 ExistentialFrame existentialFrame = getCurrentExistentialFrame();
142 if(existentialFrame == null || existentialFrame.disallowNewExistentials) {
143 errorLog.log(location, "Blank variables can be used only in queries.");
144 return new EError(location);
146 return existentialFrame.createBlank(location);
154 public ExistentialFrame getCurrentExistentialFrame() {
155 int size = existentialFrames.size();
159 return existentialFrames.get(size-1);
162 private Expression resolveFieldAccess(long location, Expression base, int pos, String name) {
164 int p = findSeparator(name, pos+1);
165 int endPos = p==-1 ? name.length() : p;
166 FieldAccessor accessor = new IdAccessor(
168 name.substring(pos+1, endPos));
169 accessor.location = Locations.sublocation(location, pos+1, endPos);
170 base = new EFieldAccess(base, accessor);
171 base.location = Locations.sublocation(location, 0, endPos);
177 private static int findSeparator(String name, int fromIndex) {
178 ++fromIndex; // the first character (that can be #) is never a separator
179 while(fromIndex < name.length()) {
180 char c = name.charAt(fromIndex);
181 if(c == '.' || c == '#')
188 public Expression resolveValue(long location, Namespace namespace, String name) {
190 SCLValue value = namespace.getValue(name);
193 String deprecatedDescription = value.isDeprecated();
194 if(deprecatedDescription != null)
195 errorLog.logWarning(location, "Deprecated value " + value.getName().name + "." + (deprecatedDescription.isEmpty() ? "" : " " + deprecatedDescription));
196 return new EConstant(location, value);
197 } catch (AmbiguousNameException e) {
198 if(SCLCompilerConfiguration.ALLOW_OVERLOADING)
199 return resolveAmbigious(location, e.conflictingModules, name);
201 errorLog.log(location, e.getMessage());
202 return new EError(location);
207 private Expression resolveAmbigious(long location, String[] conflictingModules, String name) {
208 EAmbiguous.Alternative[] alternatives = new EAmbiguous.Alternative[conflictingModules.length];
209 for(int i=0;i<conflictingModules.length;++i) {
210 Name altName = Name.create(conflictingModules[i], name);
211 SCLValue altValue = environment.getValue(altName);
212 alternatives[i] = new EAmbiguous.Alternative() {
214 public Type getType() {
215 return altValue.getType();
219 public Expression realize() {
220 EConstant expression = new EConstant(altValue);
221 expression.location = location;
226 public String toString() {
227 return altValue.getName().toString().replace('/', '.');
231 EAmbiguous expression = new EAmbiguous(alternatives);
232 expression.location = location;
236 public Expression resolveVariable(long location, Namespace namespace, String name, int begin) {
237 int end = findSeparator(name, begin);
238 String part = end == -1 ? (begin == 0 ? name : name.substring(begin)) : name.substring(begin, end);
241 Expression result = resolveLocalVariable(location, part);
243 return end == -1 ? result : resolveFieldAccess(location, result, end, name);
245 // FIXME.. support for records
246 if(localEnvironment != null) {
247 result = localEnvironment.resolve(environment, name);
249 result.setLocationDeep(location);
254 if(end != -1 && name.charAt(end) == '.') {
255 Namespace childNamespace = namespace.getNamespace(part);
256 if(childNamespace != null)
257 return resolveVariable(location, childNamespace, name, end+1);
260 Expression result = null;
262 for(int end2 = name.length();end2 > end;end2 = name.lastIndexOf('.', end2-1)) {
263 part = name.substring(begin, end2);
264 result = resolveValue(location, namespace, part);
266 end = end2 == name.length() ? -1 : end2;
272 result = resolveValue(location, namespace, part);
274 return end == -1 ? result : resolveFieldAccess(location, result, end, name);
276 reportResolveFailure(location, namespace, part);
277 return new EError(location);
280 private void reportResolveFailure(long location, Namespace namespace, String name) {
281 StringBuilder message = new StringBuilder();
282 message.append("Couldn't resolve ").append(name).append(".");
284 final THashSet<String> candidateNames = new THashSet<String>(4);
285 namespace.findValuesForPrefix("", AcceptAllNamespaceFilter.INSTANCE,
286 new TObjectProcedure<SCLValue>() {
288 public boolean execute(SCLValue value) {
290 new Exception().printStackTrace();
293 String valueName = value.getName().name;
294 if(name.equalsIgnoreCase(valueName))
295 candidateNames.add(valueName);
299 if(localEnvironment != null)
300 localEnvironment.forNames(new TObjectProcedure<String>() {
302 public boolean execute(String valueName) {
303 if(name.equalsIgnoreCase(valueName))
304 candidateNames.add(valueName);
309 if(candidateNames.size() > 0) {
310 message.append(" Did you mean ");
311 String[] ns = candidateNames.toArray(new String[candidateNames.size()]);
313 for(int i=0;i<ns.length;++i) {
315 message.append(", ");
317 message.append("or ");
319 message.append(ns[i]);
324 errorLog.log(location, message.toString());
327 public Expression resolveVariable(long location, String name) {
328 return resolveVariable(location, environment.getLocalNamespace(), name, 0);
331 public Expression resolvePattern(EVar name) {
332 char firstChar = name.name.charAt(0);
333 if(firstChar == '_' && name.name.length()==1) {
334 return new EVariable(new Variable("_"));
336 else if(!Character.isUpperCase(firstChar)) {
337 if(!frameNameSets.get(frameNameSets.size()-1).add(name.name))
338 errorLog.log(name.location, "Repeated variable "+name.name+" in pattern.");
339 return new EVariable(name.location, newVariable(name.name));
342 return resolveVariable(name.location, name.name);
346 * Starts a new environment frame. New variables defined in this frame shadow
347 * the old variables and when the frame is popped, the old variables are again
350 public void pushFrame() {
351 frames.add(variableEntries.size());
352 frameNameSets.add(new THashSet<String>());
356 * Ends an environment frame. See {@link #pushFrame}.
358 public void popFrame() {
359 int frame = frames.removeAt(frames.size()-1);
360 int i = variableEntries.size();
363 Entry entry = variableEntries.remove(i);
364 if(entry.variable == null)
365 variables.remove(entry.name);
367 variables.put(entry.name, entry.variable);
369 frameNameSets.remove(frameNameSets.size()-1);
372 public void pushRelationFrame() {
373 relationFrames.add(relationEntries.size());
376 public void popRelationFrame() {
377 int frame = relationFrames.removeAt(relationFrames.size()-1);
378 int i = relationEntries.size();
381 RelationEntry entry = relationEntries.remove(i);
382 if(entry.relation == null)
383 relations.remove(entry.name);
385 relations.put(entry.name, entry.relation);
389 public void pushCHRConstraintFrame() {
390 chrConstraintFrames.add(chrConstraintEntries.size());
393 public void popCHRConstraintFrame(ArrayList<CHRConstraint> constraints) {
394 int frame = chrConstraintFrames.removeAt(chrConstraintFrames.size()-1);
395 int i = chrConstraintEntries.size();
398 CHRConstraintEntry entry = chrConstraintEntries.remove(i);
399 CHRConstraint newConstraint;
400 if(entry.constraint == null)
401 newConstraint = chrConstraints.remove(entry.name);
403 newConstraint = chrConstraints.put(entry.name, entry.constraint);
404 if(newConstraint.implicitlyDeclared)
405 constraints.add(newConstraint);
409 public void pushExistentialFrame() {
411 existentialFrames.add(new ExistentialFrame());
414 public Variable[] popExistentialFrame() {
416 ExistentialFrame frame = existentialFrames.remove(existentialFrames.size()-1);
417 Variable[] result = new Variable[frame.variables.size() + frame.blanks.size()];
419 for(String name : frame.variables)
420 result[i++] = variables.remove(name);
421 for(Variable blank : frame.blanks)
426 public Variable newVariable(String name) {
427 Variable variable = new Variable(name);
428 Variable oldVariable = variables.put(name, variable);
429 variableEntries.add(new Entry(name, oldVariable));
433 public THashMap<String, Variable> getVariables() {
437 public void newRelation(String name, SCLRelation relation) {
438 SCLRelation oldRelation = relations.put(name, relation);
439 relationEntries.add(new RelationEntry(name, oldRelation));
442 public void newCHRConstraint(String name, CHRConstraint constraint) {
443 CHRConstraint oldConstraint = chrConstraints.put(name, constraint);
444 chrConstraintEntries.add(new CHRConstraintEntry(name, oldConstraint));
447 public Precedence getPrecedence(Name op) {
448 Precedence prec = environment.getValue(op).getPrecedence();
450 return new Precedence(1, Associativity.NONASSOC);
455 public Case translateCase(Expression lhs, Expression rhs) {
456 ArrayList<Expression> parameters = new ArrayList<Expression>(4);
457 lhs.getParameters(this, parameters);
458 Expression[] patterns = new Expression[parameters.size()];
460 for(int i=0;i<patterns.length;++i) {
461 Expression pattern = parameters.get(i);
462 pattern = pattern.resolveAsPattern(this);
463 patterns[i] = pattern;
465 rhs = rhs.resolve(this);
467 Case case_ = new Case(patterns, rhs);
468 case_.setLhs(lhs.location);
472 public Expression translateCases2(ArrayList<DValueAst> definitions) {
473 Case[] cases = new Case[definitions.size()];
474 for(int i=0;i<cases.length;++i) {
475 DValueAst def = definitions.get(i);
476 cases[i] = translateCase(def.lhs, def.value);
478 // check arity consistency
479 int arity = cases[0].patterns.length;
480 for(int i=1;i<cases.length;++i)
481 if(cases[i].patterns.length != arity)
482 errorLog.log(definitions.get(i).lhs.location,
483 "Inconsistent arity. " +
484 "This case has arity " + cases[i].patterns.length +
485 " while previous cases had arity " + arity + ".");
486 if(cases.length == 1 && cases[0].patterns.length == 0)
487 return cases[0].value;
490 Locations.combine(definitions.get(0).location, definitions.get(definitions.size()-1).location),
494 public Expression translateCases(ArrayList<LetStatement> definitions) {
495 Case[] cases = new Case[definitions.size()];
496 for(int i=0;i<cases.length;++i) {
497 LetStatement def = definitions.get(i);
498 cases[i] = translateCase(def.pattern, def.value);
500 // check arity concistency
501 int arity = cases[0].patterns.length;
502 for(int i=1;i<cases.length;++i)
503 if(cases[i].patterns.length != arity)
504 errorLog.log(definitions.get(i).pattern.location,
505 "Inconsistent arity. " +
506 "This case has arity " + cases[i].patterns.length +
507 " while previous cases had arity " + arity + ".");
510 errorLog.log(cases[1].value.location, "Cannot give multiple cases for arity 0 function.");
511 return cases[0].value;
514 Locations.combine(definitions.get(0).location, definitions.get(definitions.size()-1).location),
518 public SCLRelation resolveRelation(long location, String name) {
519 SCLRelation relation = relations.get(name);
524 relation = Environments.getRelation(environment, name);
525 /*if(relation == null) {
526 errorLog.log(location, "Couldn't resolve relation " + name + ".");
530 } catch (AmbiguousNameException e) {
531 errorLog.log(location, e.getMessage());
536 public CHRConstraint resolveCHRConstraint(String name) {
537 return chrConstraints.get(name);
541 public SCLValue getValue(Name name) {
542 return environment.getValue(name);
545 public CHRRuleset resolveRuleset(String name) throws AmbiguousNameException {
546 return Environments.getRuleset(environment, name);
549 public void disallowNewExistentials() {
550 getCurrentExistentialFrame().disallowNewExistentials = true;