aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/viatra-runtime/src/main/java/tools/refinery/viatra/runtime/matchers/psystem/rewriters/PQueryFlattener.java
blob: 76311d8fdf15e13c4f3f0a6ec83967b8469b8c59 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/*******************************************************************************
 * Copyright (c) 2010-2014, Marton Bur, Akos Horvath, Zoltan Ujhelyi, Istvan Rath and Daniel Varro
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-v20.html.
 * 
 * SPDX-License-Identifier: EPL-2.0
 *******************************************************************************/
package tools.refinery.viatra.runtime.matchers.psystem.rewriters;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import tools.refinery.viatra.runtime.matchers.psystem.PBody;
import tools.refinery.viatra.runtime.matchers.psystem.PConstraint;
import tools.refinery.viatra.runtime.matchers.psystem.basicenumerables.PositivePatternCall;
import tools.refinery.viatra.runtime.matchers.psystem.queries.PDisjunction;
import tools.refinery.viatra.runtime.matchers.psystem.queries.PQuery;
import tools.refinery.viatra.runtime.matchers.psystem.queries.PQuery.PQueryStatus;
import tools.refinery.viatra.runtime.matchers.psystem.rewriters.IConstraintFilter.AllowAllFilter;
import tools.refinery.viatra.runtime.matchers.psystem.rewriters.IConstraintFilter.ExportedParameterFilter;
import tools.refinery.viatra.runtime.matchers.psystem.rewriters.IVariableRenamer.HierarchicalName;
import tools.refinery.viatra.runtime.matchers.psystem.rewriters.IVariableRenamer.SameName;
import tools.refinery.viatra.runtime.matchers.util.Preconditions;
import tools.refinery.viatra.runtime.matchers.util.Sets;

/**
 * This rewriter class holds the query flattening logic
 * 
 * @author Marton Bur
 * 
 */
public class PQueryFlattener extends PDisjunctionRewriter {

    /**
     * Utility function to produce the permutation of every possible mapping of values.
     * 
     * @param values
     * @return
     */
    private static <K, V> Set<Map<K, V>> permutation(Map<K, Set<V>> values) {
        // An ordering of keys is defined here which will help restoring the appropriate values after the execution of
        // the cartesian product
        List<K> keyList = new ArrayList<>(values.keySet());

        // Produce list of value sets with the ordering defined by keyList
        List<Set<V>> valuesList = new ArrayList<Set<V>>(keyList.size());
        for (K key : keyList) {
            valuesList.add(values.get(key));
        }

        // Cartesian product will obey ordering of the list
        Set<List<V>> valueMappings = Sets.cartesianProduct(valuesList);

        // Build result
        Set<Map<K, V>> result = new LinkedHashSet<>();
        for (List<V> valueList : valueMappings) {
            Map<K, V> map = new HashMap<>();
            for (int i = 0; i < keyList.size(); i++) {
                map.put(keyList.get(i), valueList.get(i));
            }
            result.add(map);
        }

        return result;
    }

    private IFlattenCallPredicate flattenCallPredicate;

    public PQueryFlattener(IFlattenCallPredicate flattenCallPredicate) {
        this.flattenCallPredicate = flattenCallPredicate;
    }

    @Override
    public PDisjunction rewrite(PDisjunction disjunction) {
        PQuery query = disjunction.getQuery();

        // Check for recursion
        Set<PQuery> allReferredQueries = disjunction.getAllReferredQueries();
        for (PQuery referredQuery : allReferredQueries) {
            if (referredQuery.getAllReferredQueries().contains(referredQuery)) {
                throw new RewriterException("Recursive queries are not supported, can't flatten query named \"{1}\"",
                        new String[] { query.getFullyQualifiedName() }, "Unsupported recursive query", query);
            }
        }

        return this.doFlatten(disjunction);
    }

    /**
     * Return the list of dependencies (including the root) in chronological order
     * 
     * @param rootDisjunction
     * @return
     */
    private List<PDisjunction> disjunctionDependencies(PDisjunction rootDisjunction) {
        // Disjunctions are first collected into a list usign a depth-first approach,
        // which can be iterated backwards while removing duplicates
        Deque<PDisjunction> stack = new ArrayDeque<>();
        LinkedList<PDisjunction> list = new LinkedList<>();
        stack.push(rootDisjunction);
        list.add(rootDisjunction);

        while (!stack.isEmpty()) {
            PDisjunction disjunction = stack.pop();
            // Collect dependencies
            for (PBody pBody : disjunction.getBodies()) {
                for (PConstraint constraint : pBody.getConstraints()) {
                    if (constraint instanceof PositivePatternCall) {
                        PositivePatternCall positivePatternCall = (PositivePatternCall) constraint;
                        if (flattenCallPredicate.shouldFlatten(positivePatternCall)) {
                            // If the above preconditions meet, the call should be flattened
                            PDisjunction calledDisjunction = positivePatternCall.getReferredQuery().getDisjunctBodies();
                            stack.push(calledDisjunction);
                            list.add(calledDisjunction);
                        }
                    }
                }
            }
        }

        // Remove duplicates (keeping the last instance) and reverse order
        Set<PDisjunction> visited = new HashSet<PDisjunction>();
        List<PDisjunction> result = new ArrayList<PDisjunction>(list.size());
        
        list.descendingIterator().forEachRemaining(item -> {
            if (!visited.contains(item)) {
                result.add(item);
                visited.add(item);
            }
            
        });

        return result;
    }

    /**
     * This function holds the actual flattening logic for a PQuery
     * 
     * @param rootDisjunction
     *            to be flattened
     * @return the flattened bodies of the pQuery
     */
    private PDisjunction doFlatten(PDisjunction rootDisjunction) {

        Map<PDisjunction, Set<PBody>> flatBodyMapping = new HashMap<>();

        List<PDisjunction> dependencies = disjunctionDependencies(rootDisjunction);

        for (PDisjunction disjunction : dependencies) {
            Set<PBody> flatBodies = new LinkedHashSet<>();
            for (PBody body : disjunction.getBodies()) {
                if (isFlatteningNeeded(body)) {
                    Map<PositivePatternCall, Set<PBody>> flattenedBodies = new HashMap<>();
                    for (PConstraint pConstraint : body.getConstraints()) {

                        if (pConstraint instanceof PositivePatternCall) {
                            PositivePatternCall positivePatternCall = (PositivePatternCall) pConstraint;
                            if (flattenCallPredicate.shouldFlatten(positivePatternCall)) {
                                // If the above preconditions meet, do the flattening and return the disjoint bodies
                                PDisjunction calledDisjunction = positivePatternCall.getReferredQuery()
                                        .getDisjunctBodies();

                                Set<PBody> flattenedBodySet = flatBodyMapping.get(calledDisjunction);
                                Preconditions.checkArgument(!flattenedBodySet.isEmpty());
                                flattenedBodies.put(positivePatternCall, flattenedBodySet);
                            }
                        }
                    }
                    flatBodies.addAll(createSetOfFlatPBodies(body, flattenedBodies));
                } else {
                    flatBodies.add(prepareFlatPBody(body));
                }
            }
            flatBodyMapping.put(disjunction, flatBodies);
        }

        return new PDisjunction(rootDisjunction.getQuery(), flatBodyMapping.get(rootDisjunction));
    }

    /**
     * Creates the flattened bodies based on the caller body and the called (and already flattened) disjunctions
     * 
     * @param pBody
     *            the body to flatten
     * @param flattenedDisjunctions
     *            the
     * @param flattenedCalls
     * @return
     */
    private Set<PBody> createSetOfFlatPBodies(PBody pBody, Map<PositivePatternCall, Set<PBody>> flattenedCalls) {
        PQuery pQuery = pBody.getPattern();

        Set<Map<PositivePatternCall, PBody>> conjunctedCalls = permutation(flattenedCalls);

        // The result set containing the merged conjuncted bodies
        Set<PBody> conjunctedBodies = new HashSet<>();

        for (Map<PositivePatternCall, PBody> calledBodies : conjunctedCalls) {
            FlattenerCopier copier = createBodyCopier(pQuery, calledBodies);

            int i = 0;
            HierarchicalName hierarchicalNamingTool = new HierarchicalName();
            for (PositivePatternCall patternCall : calledBodies.keySet()) {
                // Merge each called body
                hierarchicalNamingTool.setCallCount(i++);
                copier.mergeBody(patternCall, hierarchicalNamingTool, new ExportedParameterFilter());
            }

            // Merge the caller's constraints to the conjunct body
            copier.mergeBody(pBody);

            PBody copiedBody = copier.getCopiedBody();
            copiedBody.setStatus(PQueryStatus.OK);
            conjunctedBodies.add(copiedBody);
        }

        return conjunctedBodies;
    }

    private FlattenerCopier createBodyCopier(PQuery query, Map<PositivePatternCall, PBody> calledBodies) {
        FlattenerCopier flattenerCopier = new FlattenerCopier(query, calledBodies);
        flattenerCopier.setTraceCollector(getTraceCollector());
        return flattenerCopier;
    }

    private PBody prepareFlatPBody(PBody pBody) {
        PBodyCopier copier = createBodyCopier(pBody.getPattern(), Collections.<PositivePatternCall, PBody> emptyMap());
        copier.mergeBody(pBody, new SameName(), new AllowAllFilter());
        // the copying of the body here is necessary for only one containing PDisjunction can be assigned to a PBody
        return copier.getCopiedBody();
    }

    private boolean isFlatteningNeeded(PBody pBody) {
        // Check if the body contains positive pattern call AND if it should be flattened
        for (PConstraint pConstraint : pBody.getConstraints()) {
            if (pConstraint instanceof PositivePatternCall) {
                return flattenCallPredicate.shouldFlatten((PositivePatternCall) pConstraint);
            }
        }
        return false;
    }

}