aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/viatra-runtime/src/main/java/tools/refinery/viatra/runtime/api/impl/BaseMatcher.java
blob: ad79aafdc168a71136b4c5bf2e5721ca7c1864fe (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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*******************************************************************************
 * Copyright (c) 2004-2010 Gabor Bergmann 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.api.impl;

import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import tools.refinery.viatra.runtime.api.IPatternMatch;
import tools.refinery.viatra.runtime.api.IQuerySpecification;
import tools.refinery.viatra.runtime.api.ViatraQueryEngine;
import tools.refinery.viatra.runtime.api.ViatraQueryMatcher;
import tools.refinery.viatra.runtime.internal.apiimpl.QueryResultWrapper;
import tools.refinery.viatra.runtime.matchers.backend.IMatcherCapability;
import tools.refinery.viatra.runtime.matchers.backend.IQueryResultProvider;
import tools.refinery.viatra.runtime.matchers.tuple.Tuple;
import tools.refinery.viatra.runtime.matchers.util.Preconditions;

/**
 * Base implementation of ViatraQueryMatcher.
 *
 * @author Bergmann Gábor
 *
 * @param <Match>
 */
public abstract class BaseMatcher<Match extends IPatternMatch> extends QueryResultWrapper implements ViatraQueryMatcher<Match> {

    // FIELDS AND CONSTRUCTOR

    protected ViatraQueryEngine engine;
    protected IQuerySpecification<? extends BaseMatcher<Match>> querySpecification;
    private IMatcherCapability capabilities;

    /**
     * @since 1.4
     */
    public BaseMatcher(IQuerySpecification<? extends BaseMatcher<Match>> querySpecification) {
        this.querySpecification = querySpecification;
        this.querySpecification.getInternalQueryRepresentation().ensureInitialized();
    }
    
    /**
     * @since 1.4
     */
    @Override
    protected
    void setBackend(ViatraQueryEngine engine, IQueryResultProvider resultProvider, IMatcherCapability capabilities){
        this.backend = resultProvider;
        this.engine = engine;
        this.capabilities = capabilities;
    }

    // ARRAY-BASED INTERFACE

    /** Converts the array representation of a pattern match to an immutable Match object. */
    protected abstract Match arrayToMatch(Object[] parameters);
    /** Converts the array representation of a pattern match to a mutable Match object. */
    protected abstract Match arrayToMatchMutable(Object[] parameters);

    /** Converts the Match object of a pattern match to the array representation. */
    protected Object[] matchToArray(Match partialMatch) {
        return partialMatch.toArray();
    }
    // TODO make me public for performance reasons
    protected abstract Match tupleToMatch(Tuple t);

    private Object[] fEmptyArray;

    protected Object[] emptyArray() {
        if (fEmptyArray == null)
            fEmptyArray = new Object[getSpecification().getParameterNames().size()];
        return fEmptyArray;
    }

    // REFLECTION

    @Override
    public Integer getPositionOfParameter(String parameterName) {
        return getSpecification().getPositionOfParameter(parameterName);
    }

    @Override
    public List<String> getParameterNames() {
        return getSpecification().getParameterNames();
    }

    // BASE IMPLEMENTATION

    @Override
    public Collection<Match> getAllMatches() {
        return rawStreamAllMatches(emptyArray()).collect(Collectors.toSet());
    }
    
    @Override
    public Stream<Match> streamAllMatches() {
        return rawStreamAllMatches(emptyArray());
    }

    /**
     * Returns a stream of all matches of the pattern that conform to the given fixed values of some parameters.
     *
     * @param parameters
     *            array where each non-null element binds the corresponding pattern parameter to a fixed value.
     * @pre size of input array must be equal to the number of parameters.
     * @return matches represented as a Match object.
     * @since 2.0
     */
    protected Stream<Match> rawStreamAllMatches(Object[] parameters) {
        // clones the tuples into a match object to protect the Tuples from modifications outside of the ReteMatcher
        return backend.getAllMatches(parameters).map(this::tupleToMatch);
    }

    @Override
    public Collection<Match> getAllMatches(Match partialMatch) {
        return rawStreamAllMatches(partialMatch.toArray()).collect(Collectors.toSet());
    }
    
    @Override
    public Stream<Match> streamAllMatches(Match partialMatch) {
        return rawStreamAllMatches(partialMatch.toArray());
    }

    // with input binding as pattern-specific parameters: not declared in interface

    @Override
    public Optional<Match> getOneArbitraryMatch() {
        return rawGetOneArbitraryMatch(emptyArray());
    }

    /**
     * Returns an arbitrarily chosen match of the pattern that conforms to the given fixed values of some parameters.
     * Neither determinism nor randomness of selection is guaranteed.
     *
     * @param parameters
     *            array where each non-null element binds the corresponding pattern parameter to a fixed value.
     * @pre size of input array must be equal to the number of parameters.
     * @return a match represented as a Match object, or null if no match is found.
     * @since 2.0
     */
    protected Optional<Match> rawGetOneArbitraryMatch(Object[] parameters) {
        return backend.getOneArbitraryMatch(parameters).map(this::tupleToMatch);
    }

    @Override
    public Optional<Match> getOneArbitraryMatch(Match partialMatch) {
        return rawGetOneArbitraryMatch(partialMatch.toArray());
    }

    // with input binding as pattern-specific parameters: not declared in interface

    /**
     * Indicates whether the given combination of specified pattern parameters constitute a valid pattern match, under
     * any possible substitution of the unspecified parameters.
     *
     * @param parameters
     *            array where each non-null element binds the corresponding pattern parameter to a fixed value.
     * @return true if the input is a valid (partial) match of the pattern.
     */
    protected boolean rawHasMatch(Object[] parameters) {
        return backend.hasMatch(parameters);
    }

    @Override
    public boolean hasMatch() {
        return rawHasMatch(emptyArray());
    }
    
    @Override
    public boolean hasMatch(Match partialMatch) {
        return rawHasMatch(partialMatch.toArray());
    }

    // with input binding as pattern-specific parameters: not declared in interface

    @Override
    public int countMatches() {
        return rawCountMatches(emptyArray());
    }

    /**
     * Returns the number of all matches of the pattern that conform to the given fixed values of some parameters.
     *
     * @param parameters
     *            array where each non-null element binds the corresponding pattern parameter to a fixed value.
     * @pre size of input array must be equal to the number of parameters.
     * @return the number of pattern matches found.
     */
    protected int rawCountMatches(Object[] parameters) {
        return backend.countMatches(parameters);
    }

    @Override
    public int countMatches(Match partialMatch) {
        return rawCountMatches(partialMatch.toArray());
    }

    // with input binding as pattern-specific parameters: not declared in interface

    /**
     * Executes the given processor on each match of the pattern that conforms to the given fixed values of some
     * parameters.
     *
     * @param parameters
     *            array where each non-null element binds the corresponding pattern parameter to a fixed value.
     * @pre size of input array must be equal to the number of parameters.
     * @param action
     *            the action that will process each pattern match.
     * @since 2.0
     */
    protected void rawForEachMatch(Object[] parameters, Consumer<? super Match> processor) {
        backend.getAllMatches(parameters).map(this::tupleToMatch).forEach(processor);
    }

    @Override
    public void forEachMatch(Consumer<? super Match> processor) {
        rawForEachMatch(emptyArray(), processor);
    }

    @Override
    public void forEachMatch(Match match, Consumer<? super Match> processor) {
        rawForEachMatch(match.toArray(), processor);
    }

    // with input binding as pattern-specific parameters: not declared in interface

    @Override
    public boolean forOneArbitraryMatch(Consumer<? super Match> processor) {
        return rawForOneArbitraryMatch(emptyArray(), processor);
    }

    @Override
    public boolean forOneArbitraryMatch(Match partialMatch, Consumer<? super Match> processor) {
        return rawForOneArbitraryMatch(partialMatch.toArray(), processor);
    }

    /**
     * Executes the given processor on an arbitrarily chosen match of the pattern that conforms to the given fixed
     * values of some parameters. Neither determinism nor randomness of selection is guaranteed.
     *
     * @param parameters
     *            array where each non-null element binds the corresponding pattern parameter to a fixed value.
     * @pre size of input array must be equal to the number of parameters.
     * @param processor
     *            the action that will process the selected match.
     * @return true if the pattern has at least one match with the given parameter values, false if the processor was
     *         not invoked
     * @since 2.0
     */
    protected boolean rawForOneArbitraryMatch(Object[] parameters, Consumer<? super Match> processor) {
        return backend.getOneArbitraryMatch(parameters).map(this::tupleToMatch).map(m -> {
            processor.accept(m);
            return true;
        }).orElse(false);
    }

    // with input binding as pattern-specific parameters: not declared in interface


    @Override
    public Match newEmptyMatch() {
        return arrayToMatchMutable(new Object[getParameterNames().size()]);
    }

    @Override
    public Match newMatch(Object... parameters) {
        return arrayToMatch(parameters);
    }

    @Override
    public Set<Object> getAllValues(final String parameterName) {
        return rawStreamAllValues(getPositionOfParameter(parameterName), emptyArray()).collect(Collectors.toSet());
    }

    @Override
    public Set<Object> getAllValues(final String parameterName, Match partialMatch) {
        return rawStreamAllValues(getPositionOfParameter(parameterName), partialMatch.toArray()).collect(Collectors.toSet());
    }
    
    /**
     * Retrieve a stream of values that occur in matches for the given parameterName, that conforms to the given fixed
     * values of some parameters.
     *
     * @param position
     *            position of the parameter for which values are returned
     * @param parameters
     *            a parameter array corresponding to a partial match of the pattern where each non-null field binds the
     *            corresponding pattern parameter to a fixed value.
     * @return the stream of all values in the given position
     * @throws IllegalArgumentException
     *             if length of parameters array does not equal to number of parameters
     * @throws IndexOutOfBoundsException
     *             if position is not appropriate for the current parameter size
     * @since 2.0
     */
    protected Stream<Object> rawStreamAllValues(final int position, Object[] parameters) {
        Preconditions.checkElementIndex(position, getParameterNames().size());
        Preconditions.checkArgument(parameters.length == getParameterNames().size());
        return rawStreamAllMatches(parameters).map(match -> match.get(position));
    }

    /**
     * Uses an existing set to accumulate all values of the parameter with the given name. Since it is a protected
     * method, no error checking or input validation is performed!
     *
     * @param position
     *            position of the parameter for which values are returned
     * @param parameters
     *            a parameter array corresponding to a partial match of the pattern where each non-null field binds the
     *            corresponding pattern parameter to a fixed value.
     * @param accumulator
     *            the existing set to fill with the values
     */
    @SuppressWarnings("unchecked")
    protected <T> void rawAccumulateAllValues(final int position, Object[] parameters, final Set<T> accumulator) {
        rawForEachMatch(parameters, match -> accumulator.add((T) match.get(position)));
    }
    
    @Override
    public ViatraQueryEngine getEngine() {
        return engine;
    }

    @Override
    public IQuerySpecification<? extends BaseMatcher<Match>> getSpecification() {
        return querySpecification;
    }

    @Override
    public String getPatternName() {
        return querySpecification.getFullyQualifiedName();
    }

    /**
     * @since 1.4
     */
    public IMatcherCapability getCapabilities() {
        return capabilities;
    }
}