]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/elaboration/expressions/ERuleset.java
(refs #7375) Replace collectRefs by CollectRefsVisitor
[simantics/platform.git] / bundles / org.simantics.scl.compiler / src / org / simantics / scl / compiler / elaboration / expressions / ERuleset.java
1 package org.simantics.scl.compiler.elaboration.expressions;
2
3 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.Just;
4 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.addInteger;
5 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.apply;
6 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.as;
7 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.if_;
8 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.integer;
9 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.isZeroInteger;
10 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.lambda;
11 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.let;
12 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.letRec;
13 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.matchWithDefault;
14 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.newVar;
15 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.seq;
16 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.tuple;
17 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.var;
18 import static org.simantics.scl.compiler.elaboration.expressions.Expressions.vars;
19
20 import java.util.ArrayList;
21 import java.util.Set;
22
23 import org.simantics.scl.compiler.common.exceptions.InternalCompilerError;
24 import org.simantics.scl.compiler.common.names.Names;
25 import org.simantics.scl.compiler.elaboration.contexts.TranslationContext;
26 import org.simantics.scl.compiler.elaboration.contexts.TypingContext;
27 import org.simantics.scl.compiler.elaboration.expressions.printing.ExpressionToStringVisitor;
28 import org.simantics.scl.compiler.elaboration.query.Query;
29 import org.simantics.scl.compiler.elaboration.query.Query.Diff;
30 import org.simantics.scl.compiler.elaboration.query.Query.Diffable;
31 import org.simantics.scl.compiler.elaboration.query.compilation.DerivateException;
32 import org.simantics.scl.compiler.elaboration.relations.LocalRelation;
33 import org.simantics.scl.compiler.elaboration.relations.SCLRelation;
34 import org.simantics.scl.compiler.errors.Locations;
35 import org.simantics.scl.compiler.internal.elaboration.utils.ForcedClosure;
36 import org.simantics.scl.compiler.internal.elaboration.utils.StronglyConnectedComponents;
37 import org.simantics.scl.compiler.top.SCLCompilerConfiguration;
38 import org.simantics.scl.compiler.types.Type;
39 import org.simantics.scl.compiler.types.Types;
40 import org.simantics.scl.compiler.types.exceptions.MatchException;
41 import org.simantics.scl.compiler.types.kinds.Kinds;
42
43 import gnu.trove.impl.Constants;
44 import gnu.trove.map.hash.THashMap;
45 import gnu.trove.map.hash.TObjectIntHashMap;
46 import gnu.trove.set.hash.THashSet;
47 import gnu.trove.set.hash.TIntHashSet;
48
49 public class ERuleset extends SimplifiableExpression {
50     LocalRelation[] relations;
51     DatalogRule[] rules;
52     Expression in;
53     
54     public ERuleset(LocalRelation[] relations, DatalogRule[] rules, Expression in) {
55         this.relations = relations;
56         this.rules = rules;
57         this.in = in;
58     }
59
60     public static class DatalogRule {
61         public long location;
62         public LocalRelation headRelation;
63         public Expression[] headParameters;
64         public Query body;
65         public Variable[] variables;
66         
67         public DatalogRule(LocalRelation headRelation, Expression[] headParameters,
68                 Query body) {
69             this.headRelation = headRelation;
70             this.headParameters = headParameters;
71             this.body = body;
72         }
73         
74         public DatalogRule(long location, LocalRelation headRelation, Expression[] headParameters,
75                 Query body, Variable[] variables) {
76             this.location = location;
77             this.headRelation = headRelation;
78             this.headParameters = headParameters;
79             this.body = body;
80             this.variables = variables;
81         }
82
83         public void setLocationDeep(long loc) {
84             this.location = loc;
85             for(Expression parameter : headParameters)
86                 parameter.setLocationDeep(loc);
87             body.setLocationDeep(loc);
88         }
89         
90         @Override
91         public String toString() {
92             StringBuilder b = new StringBuilder();
93             ExpressionToStringVisitor visitor = new ExpressionToStringVisitor(b);
94             visitor.visit(this);
95             return b.toString();
96         }
97     }
98     
99     private void checkRuleTypes(TypingContext context) {
100         // Create relation variables
101         for(DatalogRule rule : rules) {
102             Type[] parameterTypes =  rule.headRelation.getParameterTypes();
103             Expression[] parameters = rule.headParameters;
104             for(Variable variable : rule.variables)
105                 variable.setType(Types.metaVar(Kinds.STAR));
106             for(int i=0;i<parameters.length;++i)
107                 parameters[i] = parameters[i].checkType(context, parameterTypes[i]);
108             rule.body.checkType(context);
109         }
110     }
111     
112     @Override
113     public Expression checkBasicType(TypingContext context, Type requiredType) {
114         checkRuleTypes(context);
115         in = in.checkBasicType(context, requiredType);
116         return compile(context);
117     }
118     
119     @Override
120     public Expression inferType(TypingContext context) {
121         checkRuleTypes(context);
122         in = in.inferType(context);
123         return compile(context);
124     }
125     
126     @Override
127     public Expression checkIgnoredType(TypingContext context) {
128         checkRuleTypes(context);
129         in = in.checkIgnoredType(context);
130         return compile(context);
131     }
132     
133     @Override
134     public void collectFreeVariables(THashSet<Variable> vars) {
135         for(DatalogRule rule : rules) {
136             for(Expression parameter : rule.headParameters)
137                 parameter.collectFreeVariables(vars);
138             rule.body.collectFreeVariables(vars);
139             for(Variable var : rule.variables)
140                 vars.remove(var);
141         }
142         in.collectFreeVariables(vars);
143     }
144
145     @Override
146     public void collectVars(TObjectIntHashMap<Variable> allVars,
147             TIntHashSet vars) {
148         for(DatalogRule rule : rules) {
149             for(Expression parameter : rule.headParameters)
150                 parameter.collectVars(allVars, vars);
151             rule.body.collectVars(allVars, vars);
152         }
153         in.collectVars(allVars, vars);
154     }
155
156     @Override
157     public void collectEffects(THashSet<Type> effects) {
158         throw new InternalCompilerError(location, getClass().getSimpleName() + " does not support collectEffects.");
159     }
160     
161     @Override
162     public Expression resolve(TranslationContext context) {
163         throw new InternalCompilerError();
164     }
165     
166     static class LocalRelationAux {
167         Variable handleFunc;
168     }
169     
170     public Expression compile(TypingContext context) {
171         // Create a map from relations to their ids
172         TObjectIntHashMap<SCLRelation> relationsToIds = new TObjectIntHashMap<SCLRelation>(relations.length,
173                 Constants.DEFAULT_LOAD_FACTOR, -1);
174         for(int i=0;i<relations.length;++i)
175             relationsToIds.put(relations[i], i);
176         
177         // Create a table from relations to the other relations they depend on
178         TIntHashSet[] refsSets = new TIntHashSet[relations.length];
179         int setCapacity = Math.min(Constants.DEFAULT_CAPACITY, relations.length);
180         for(int i=0;i<relations.length;++i)
181             refsSets[i] = new TIntHashSet(setCapacity);
182         
183         for(DatalogRule rule : rules) {
184             int headRelationId = relationsToIds.get(rule.headRelation);
185             TIntHashSet refsSet = refsSets[headRelationId];
186             rule.body.collectRelationRefs(relationsToIds, refsSet);
187             for(Expression parameter : rule.headParameters)
188                 parameter.collectRelationRefs(relationsToIds, refsSet);
189         }
190         
191         // Convert refsSets to an array
192         final int[][] refs = new int[relations.length][];
193         for(int i=0;i<relations.length;++i)
194             refs[i] = refsSets[i].toArray();
195         
196         // Find strongly connected components of the function refs
197         final ArrayList<int[]> components = new ArrayList<int[]>();
198         
199         new StronglyConnectedComponents(relations.length) {
200             @Override
201             protected void reportComponent(int[] component) {
202                 components.add(component);
203             }
204             
205             @Override
206             protected int[] findDependencies(int u) {
207                 return refs[u];
208             }
209         }.findComponents();
210         
211         // If there is just one component, compile it
212         if(components.size() == 1) {
213             return compileStratified(context);
214         }
215         
216         // Inverse of components array 
217         int[] strataPerRelation = new int[relations.length];
218         for(int i=0;i<components.size();++i)
219             for(int k : components.get(i))
220                 strataPerRelation[k] = i;
221         
222         // Collects rules belonging to each strata
223         @SuppressWarnings("unchecked")
224         ArrayList<DatalogRule>[] rulesPerStrata = new ArrayList[components.size()];
225         for(int i=0;i<components.size();++i)
226             rulesPerStrata[i] = new ArrayList<DatalogRule>();
227         for(DatalogRule rule : rules) {
228             int stratum = strataPerRelation[relationsToIds.get(rule.headRelation)];
229             rulesPerStrata[stratum].add(rule);
230         }
231         
232         // Create stratified system
233         Expression cur = this.in;
234         for(int stratum=components.size()-1;stratum >= 0;--stratum) {
235             int[] cs = components.get(stratum);
236             LocalRelation[] curRelations = new LocalRelation[cs.length];
237             for(int i=0;i<cs.length;++i)
238                 curRelations[i] = relations[cs[i]];
239             ArrayList<DatalogRule> curRules = rulesPerStrata[stratum];
240             cur = new ERuleset(curRelations, curRules.toArray(new DatalogRule[curRules.size()]), cur).compileStratified(context);
241         }
242         return cur;
243     }
244     
245     private Expression compileStratified(TypingContext context) {
246         Expression continuation = Expressions.tuple();
247         
248         // Create stacks
249         Variable[] stacks = new Variable[relations.length];
250         for(int i=0;i<relations.length;++i) {
251             LocalRelation relation = relations[i];
252             Type[] parameterTypes = relation.getParameterTypes();
253             stacks[i] = newVar("stack" + relation.getName(),
254                     Types.apply(Names.MList_T, Types.tuple(parameterTypes))
255                     );
256         }
257
258         // Simplify subexpressions and collect derivatives
259         THashMap<LocalRelation, Diffable> diffables = new THashMap<LocalRelation, Diffable>(relations.length);
260         for(int i=0;i<relations.length;++i) {
261             LocalRelation relation = relations[i];
262             Type[] parameterTypes = relation.getParameterTypes();
263             Variable[] parameters = new Variable[parameterTypes.length];
264             for(int j=0;j<parameterTypes.length;++j)
265                 parameters[j] = new Variable("p" + j, parameterTypes[j]);
266             diffables.put(relations[i], new Diffable(i, relation, parameters));
267         }
268         @SuppressWarnings("unchecked")
269         ArrayList<Expression>[] updateExpressions = (ArrayList<Expression>[])new ArrayList[relations.length];
270         for(int i=0;i<relations.length;++i)
271             updateExpressions[i] = new ArrayList<Expression>(2);
272         ArrayList<Expression> seedExpressions = new ArrayList<Expression>(); 
273         for(DatalogRule rule : rules) {
274             int id = diffables.get(rule.headRelation).id;
275             Expression appendExp = apply(context.getCompilationContext(), Types.PROC, Names.MList_add, Types.tuple(rule.headRelation.getParameterTypes()),
276                     var(stacks[id]),
277                     tuple(rule.headParameters)
278                     );
279             Diff[] diffs;
280             try {
281                 diffs = rule.body.derivate(diffables);
282             } catch(DerivateException e) {
283                 context.getErrorLog().log(e.location, "Recursion must not contain negations or aggragates.");
284                 return new EError();
285             }
286             for(Diff diff : diffs)
287                 updateExpressions[diff.id].add(((EWhen)new EWhen(rule.location, diff.query, appendExp, rule.variables).copy(context)).compile(context));
288             if(diffs.length == 0)
289                 seedExpressions.add(((EWhen)new EWhen(rule.location, rule.body, appendExp, rule.variables).copy(context)).compile(context));
290             else {
291                 Query query = rule.body.removeRelations((Set<SCLRelation>)(Set)diffables.keySet());
292                 if(query != Query.EMPTY_QUERY)
293                     seedExpressions.add(((EWhen)new EWhen(location, query, appendExp, rule.variables).copy(context)).compile(context));
294             }
295         }
296         
297         // Iterative solving of relations
298
299         Variable[] loops = new Variable[relations.length];
300         for(int i=0;i<loops.length;++i)
301             loops[i] = newVar("loop" + relations[i].getName(), Types.functionE(Types.INTEGER, Types.PROC, Types.UNIT));
302         continuation = seq(apply(Types.PROC, var(loops[0]), integer(relations.length-1)), continuation);
303         
304         Expression[] loopDefs = new Expression[relations.length];
305         for(int i=0;i<relations.length;++i) {
306             LocalRelation relation = relations[i];
307             Type[] parameterTypes = relation.getParameterTypes();
308             Variable[] parameters = diffables.get(relation).parameters;
309             
310             Variable counter = newVar("counter", Types.INTEGER);
311             
312             Type rowType = Types.tuple(parameterTypes);
313             Variable row = newVar("row", rowType);
314             
315             Expression handleRow = tuple();
316             for(Expression updateExpression : updateExpressions[i])
317                 handleRow = seq(updateExpression, handleRow);
318             handleRow = if_(
319                     apply(context.getCompilationContext(), Types.PROC, Names.MSet_add, rowType,
320                             var(relation.table), var(row)),
321                     handleRow,
322                     tuple()
323                     );
324             handleRow = seq(handleRow, apply(Types.PROC, var(loops[i]), integer(relations.length-1)));
325             Expression failure =
326                     if_(isZeroInteger(var(counter)),
327                         tuple(),
328                         apply(Types.PROC, var(loops[(i+1)%relations.length]), addInteger(var(counter), integer(-1)))
329                        );
330             Expression body = matchWithDefault(
331                     apply(context.getCompilationContext(), Types.PROC, Names.MList_removeLast, rowType, var(stacks[i])),
332                     Just(as(row, tuple(vars(parameters)))), handleRow,
333                     failure);
334             
335             loopDefs[i] = lambda(Types.PROC, counter, body); 
336         }
337         continuation = letRec(loops, loopDefs, continuation);
338         
339         // Seed relations
340         for(Expression seedExpression : seedExpressions)
341             continuation = seq(seedExpression, continuation);
342         
343         // Create stacks
344         for(int i=0;i<stacks.length;++i)
345             continuation = let(stacks[i],
346                     apply(context.getCompilationContext(), Types.PROC, Names.MList_create, Types.tuple(relations[i].getParameterTypes()), tuple()),
347                     continuation);
348         
349         continuation = ForcedClosure.forceClosure(continuation, SCLCompilerConfiguration.EVERY_DATALOG_STRATUM_IN_SEPARATE_METHOD);
350         
351         // Create relations
352         for(LocalRelation relation : relations)
353             continuation = let(relation.table,
354                     apply(context.getCompilationContext(), Types.PROC, Names.MSet_create, Types.tuple(relation.getParameterTypes()), tuple()),
355                     continuation);
356         
357         return seq(continuation, in);
358     }
359
360     @Override
361     protected void updateType() throws MatchException {
362         setType(in.getType());
363     }
364     
365     @Override
366     public void setLocationDeep(long loc) {
367         if(location == Locations.NO_LOCATION) {
368             location = loc;
369             for(DatalogRule rule : rules)
370                 rule.setLocationDeep(loc);
371         }
372     }
373     
374     @Override
375     public void accept(ExpressionVisitor visitor) {
376         visitor.visit(this);
377     }
378
379     public DatalogRule[] getRules() {
380         return rules;
381     }
382     
383     public Expression getIn() {
384         return in;
385     }
386     
387     @Override
388     public Expression accept(ExpressionTransformer transformer) {
389         return transformer.transform(this);
390     }
391
392 }