535cc8c8b6cc1f17311945523447bc2f01c2da3b
[simantics/platform.git] / bundles / org.simantics.scl.compiler / src / org / simantics / scl / compiler / elaboration / contexts / TranslationContext.java
1 package org.simantics.scl.compiler.elaboration.contexts;
2
3 import java.util.ArrayList;
4 import java.util.Arrays;
5
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;
39
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;
44
45 public class TranslationContext extends TypeTranslationContext implements EnvironmentalContext {
46
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;
51         
52         public EVariable createBlank(long location) {
53             Variable variable = new Variable("_");
54             blanks.add(variable);
55             EVariable result = new EVariable(variable);
56             result.location = location;
57             return result;
58         }
59     }
60     
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;
68     
69     public PreQuery currentPreQuery;
70     
71     THashMap<String, SCLRelation> relations = new THashMap<String, SCLRelation>();
72     TIntArrayList relationFrames = new TIntArrayList();
73     ArrayList<RelationEntry> relationEntries = new ArrayList<RelationEntry>();
74     
75     THashMap<String, CHRConstraint> chrConstraints = new THashMap<String, CHRConstraint>();
76     TIntArrayList chrConstraintFrames = new TIntArrayList();
77     ArrayList<CHRConstraintEntry> chrConstraintEntries = new ArrayList<CHRConstraintEntry>();
78     
79     public CHRRuleset currentRuleset;
80     
81     public ModuleDebugInfo moduleDebugInfo;
82     
83     private String definitionName;
84     
85     static class Entry {
86         String name;
87         Variable variable;
88         public Entry(String name, Variable variable) {
89             this.name = name;
90             this.variable = variable;
91         }
92     }
93     
94     static class RelationEntry {
95         String name;
96         SCLRelation relation;
97         public RelationEntry(String name, SCLRelation relation) {
98             this.name = name;
99             this.relation = relation;
100         }
101     }
102     
103     static class CHRConstraintEntry {
104         String name;
105         CHRConstraint constraint;
106         public CHRConstraintEntry(String name, CHRConstraint constraint) {
107             this.name = name;
108             this.constraint = constraint;
109         }
110     }
111     
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;
117     }
118     
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 == '(';
123     }
124     
125     /* Tries to resolve name as a local variable. It is assumed
126      * that name does not contain '.'.
127      */
128     private Expression resolveLocalVariable(long location, String name) {
129         Variable variable = variables.get(name);
130         if(variable != null)
131             return new EVariable(location, variable);
132         
133         char c = name.charAt(0);
134         switch(c) {
135         case '?': {
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);
140             }
141             variable = new Variable(name);
142             variables.put(name, variable);
143             existentialFrame.variables.add(name);
144             return new EVariable(variable);
145         }
146         case '_': {
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);
152                 }
153                 return existentialFrame.createBlank(location);
154             }
155             break;
156         }
157         }
158         return null;
159     }
160     
161     public ExistentialFrame getCurrentExistentialFrame() {
162         int size = existentialFrames.size(); 
163         if(size == 0)
164             return null;
165         else
166             return existentialFrames.get(size-1);
167     }
168     
169     private Expression resolveFieldAccess(long location, Expression base, int pos, String name) {
170         while(pos != -1) {
171             int p = findSeparator(name, pos+1);
172             int endPos = p==-1 ? name.length() : p;
173             FieldAccessor accessor = new IdAccessor(
174                     name.charAt(pos),
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);
179             pos = p;
180         }
181         return base;
182     }
183     
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 == '#')
189                 return fromIndex;
190             ++fromIndex;
191         }
192         return -1;
193     }
194     
195     public Expression resolveValue(long location, Namespace namespace, String name) {
196         try {
197             SCLValue value = namespace.getValue(name);
198             if(value == null)
199                 return null;
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);
209             else {
210                 errorLog.log(location, e.getMessage());
211                 return new EError(location);
212             }
213         }
214     }
215     
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() {
222                 @Override
223                 public Type getType() {
224                     return altValue.getType();
225                 }
226
227                 @Override
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));
233                     return expression;
234                 }
235
236                 @Override
237                 public String toString() {
238                     return altValue.getName().toString().replace('/', '.');
239                 }
240             };
241         }
242         EAmbiguous expression = new EAmbiguous(alternatives);
243         expression.location = location;
244         return expression;
245     }
246     
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);
250
251         if(begin == 0) {
252             Expression result = resolveLocalVariable(location, part);
253             if(result != null)
254                 return end == -1 ? result : resolveFieldAccess(location, result, end, name);
255             
256             // FIXME.. support for records
257             if(localEnvironment != null) {
258                 result = localEnvironment.resolve(environment, name);
259                 if(result != null) {
260                     result.setLocationDeep(location);
261                     return result;
262                 }
263             }
264         }
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);
269         }
270         {
271             Expression result = null;
272             if(end != -1) {
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);
276                     if(result != null) {
277                         end = end2 == name.length() ? -1 : end2;
278                         break;
279                     }
280                 }
281             }
282             if(result == null)
283                 result = resolveValue(location, namespace, part);
284             if(result != null)
285                 return end == -1 ? result : resolveFieldAccess(location, result, end, name);
286         }
287         reportResolveFailure(location, namespace, part);
288         return new EError(location);
289     }
290     
291     private void reportResolveFailure(long location, Namespace namespace, String name) {
292         StringBuilder message = new StringBuilder();
293         message.append("Couldn't resolve ").append(name).append(".");
294
295         final THashSet<String> candidateNames = new THashSet<String>(4);
296         namespace.findValuesForPrefix("", AcceptAllNamespaceFilter.INSTANCE,
297                 new TObjectProcedure<SCLValue>() {
298             @Override
299             public boolean execute(SCLValue value) {
300                 if(value == null) {
301                     new Exception().printStackTrace();
302                     return true;
303                 }
304                 String valueName = value.getName().name;
305                 if(name.equalsIgnoreCase(valueName))
306                     candidateNames.add(valueName);
307                 return true;
308             }
309         });
310         if(localEnvironment != null)
311             localEnvironment.forNames(new TObjectProcedure<String>() {
312                 @Override
313                 public boolean execute(String valueName) {
314                     if(name.equalsIgnoreCase(valueName))
315                         candidateNames.add(valueName);
316                     return true;
317                 }
318             });
319
320         if(candidateNames.size() > 0) {
321             message.append(" Did you mean ");
322             String[] ns = candidateNames.toArray(new String[candidateNames.size()]);
323             Arrays.sort(ns);
324             for(int i=0;i<ns.length;++i) {
325                 if(i > 0) {
326                     message.append(", ");
327                     if(i == ns.length-1)
328                         message.append("or ");
329                 }
330                 message.append(ns[i]);
331             }
332             message.append('?');
333         }
334
335         errorLog.log(location, message.toString());
336     }
337     
338     public Expression resolveVariable(long location, String name) {
339         return resolveVariable(location, environment.getLocalNamespace(), name, 0);
340     }
341     
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("_"));
346         }
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));
351         }
352         else 
353             return resolveVariable(name.location, name.name);
354     }
355
356     /**
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
359      * visible.
360      */
361     public void pushFrame() {
362         frames.add(variableEntries.size());
363         frameNameSets.add(new THashSet<String>());
364     }
365     
366     /**
367      * Ends an environment frame. See {@link #pushFrame}.
368      */
369     public void popFrame() {
370         int frame = frames.removeAt(frames.size()-1);
371         int i = variableEntries.size();
372         while(i > frame) {
373             --i;
374             Entry entry = variableEntries.remove(i);
375             if(entry.variable == null)
376                 variables.remove(entry.name);
377             else
378                 variables.put(entry.name, entry.variable);
379         }
380         frameNameSets.remove(frameNameSets.size()-1);
381     }
382
383     public void pushRelationFrame() {
384         relationFrames.add(relationEntries.size());
385     }
386     
387     public void popRelationFrame() {
388         int frame = relationFrames.removeAt(relationFrames.size()-1);
389         int i = relationEntries.size();
390         while(i > frame) {
391             --i;
392             RelationEntry entry = relationEntries.remove(i);
393             if(entry.relation == null)
394                 relations.remove(entry.name);
395             else
396                 relations.put(entry.name, entry.relation);
397         }
398     }
399     
400     public void pushCHRConstraintFrame() {
401         chrConstraintFrames.add(chrConstraintEntries.size());
402     }
403     
404     public void popCHRConstraintFrame(ArrayList<CHRConstraint> constraints) {
405         int frame = chrConstraintFrames.removeAt(chrConstraintFrames.size()-1);
406         int i = chrConstraintEntries.size();
407         while(i > frame) {
408             --i;
409             CHRConstraintEntry entry = chrConstraintEntries.remove(i);
410             CHRConstraint newConstraint;
411             if(entry.constraint == null)
412                 newConstraint = chrConstraints.remove(entry.name);
413             else
414                 newConstraint = chrConstraints.put(entry.name, entry.constraint);
415             if(newConstraint.implicitlyDeclared)
416                 constraints.add(newConstraint);
417         }
418     }
419     
420     public void pushExistentialFrame() {
421         pushFrame();
422         existentialFrames.add(new ExistentialFrame());
423     }
424     
425     public Variable[] popExistentialFrame() {
426         popFrame();
427         ExistentialFrame frame = existentialFrames.remove(existentialFrames.size()-1);
428         Variable[] result = new Variable[frame.variables.size() + frame.blanks.size()];
429         int i=0;
430         for(String name : frame.variables)
431             result[i++] = variables.remove(name);
432         for(Variable blank : frame.blanks)
433             result[i++] = blank;
434         return result;
435     }
436     
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));
441         return variable;
442     }
443     
444     public THashMap<String, Variable> getVariables() {
445         return variables;
446     }
447     
448     public void newRelation(String name, SCLRelation relation) {
449         SCLRelation oldRelation = relations.put(name, relation);
450         relationEntries.add(new RelationEntry(name, oldRelation));
451     }
452     
453     public void newCHRConstraint(String name, CHRConstraint constraint) {
454         CHRConstraint oldConstraint = chrConstraints.put(name, constraint);
455         chrConstraintEntries.add(new CHRConstraintEntry(name, oldConstraint));
456     }
457             
458     public Precedence getPrecedence(Name op) {
459         Precedence prec = environment.getValue(op).getPrecedence();
460         if(prec == null)
461             return new Precedence(1, Associativity.NONASSOC);
462         else
463             return prec;
464     }
465     
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()];
470         pushFrame();
471         for(int i=0;i<patterns.length;++i) {
472             Expression pattern = parameters.get(i);
473             pattern = pattern.resolveAsPattern(this);
474             patterns[i] = pattern;
475         }
476         rhs = rhs.resolve(this);
477         popFrame();
478         Case case_ = new Case(patterns, rhs);
479         case_.setLhs(lhs.location);
480         return case_;
481     }
482     
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);
488         }
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;
499         else
500             return new ELambda(
501                     Locations.combine(definitions.get(0).location, definitions.get(definitions.size()-1).location),
502                     cases);
503     }
504     
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);
510         }
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 + ".");
519         if(arity == 0) {
520             if(cases.length > 1)
521                 errorLog.log(cases[1].value.location, "Cannot give multiple cases for arity 0 function.");
522             return cases[0].value;
523         }
524         return new ELambda(
525                 Locations.combine(definitions.get(0).location, definitions.get(definitions.size()-1).location),
526                 cases);
527     }
528
529     public SCLRelation resolveRelation(long location, String name) {
530         SCLRelation relation = relations.get(name);
531         if(relation != null)
532             return relation;
533         
534         try {
535             relation = Environments.getRelation(environment, name);
536             /*if(relation == null) {
537                 errorLog.log(location, "Couldn't resolve relation " + name + ".");
538                 return null;
539             }*/
540             return relation;
541         } catch (AmbiguousNameException e) {
542             errorLog.log(location, e.getMessage());
543             return null;
544         }
545     }
546     
547     public CHRConstraint resolveCHRConstraint(String name) {
548         return chrConstraints.get(name);
549     }
550
551     @Override
552     public SCLValue getValue(Name name) {
553         return environment.getValue(name);
554     }
555
556     public CHRRuleset resolveRuleset(String name) throws AmbiguousNameException {
557         return Environments.getRuleset(environment, name);
558     }
559
560     public void disallowNewExistentials() {
561         getCurrentExistentialFrame().disallowNewExistentials = true;
562     }
563 }