Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 71cf3bcfcdd32a53515ae2328b089f2185b26484 (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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/*******************************************************************************
 * Copyright (c) 2004-2008 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 org.eclipse.viatra.query.runtime.rete.matcher;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.viatra.query.runtime.matchers.backend.IQueryBackend;
import org.eclipse.viatra.query.runtime.matchers.backend.IQueryResultProvider;
import org.eclipse.viatra.query.runtime.matchers.backend.IUpdateable;
import org.eclipse.viatra.query.runtime.matchers.context.IQueryRuntimeContext;
import org.eclipse.viatra.query.runtime.matchers.tuple.ITuple;
import org.eclipse.viatra.query.runtime.matchers.tuple.Tuple;
import org.eclipse.viatra.query.runtime.matchers.tuple.TupleMask;
import org.eclipse.viatra.query.runtime.matchers.tuple.Tuples;
import org.eclipse.viatra.query.runtime.matchers.util.Accuracy;
import org.eclipse.viatra.query.runtime.matchers.util.CollectionsFactory;
import org.eclipse.viatra.query.runtime.rete.index.Indexer;
import org.eclipse.viatra.query.runtime.rete.index.IterableIndexer;
import org.eclipse.viatra.query.runtime.rete.network.Node;
import org.eclipse.viatra.query.runtime.rete.network.ProductionNode;
import org.eclipse.viatra.query.runtime.rete.network.Receiver;
import org.eclipse.viatra.query.runtime.rete.remote.Address;
import org.eclipse.viatra.query.runtime.rete.single.CallbackNode;
import org.eclipse.viatra.query.runtime.rete.single.TransformerNode;
import org.eclipse.viatra.query.runtime.rete.traceability.RecipeTraceInfo;

/**
 * @author Gabor Bergmann
 *
 */
public class RetePatternMatcher extends TransformerNode implements IQueryResultProvider {

    protected ReteEngine engine;
    protected IQueryRuntimeContext context;
    protected ProductionNode productionNode;
    protected RecipeTraceInfo productionNodeTrace;
    protected Map<String, Integer> posMapping;
    protected Map<Object, Receiver> taggedChildren = CollectionsFactory.createMap();
    protected boolean connected = false; // is rete-wise connected to the
                                         // production node?

    /**
     * @param productionNode
     *            a production node that matches this pattern without any parameter bindings
     * @pre: Production must be local to the head container
     */
    public RetePatternMatcher(ReteEngine engine, RecipeTraceInfo productionNodeTrace) {
        super(engine.getReteNet().getHeadContainer());
        this.engine = engine;
        this.context = engine.getRuntimeContext();
        this.productionNodeTrace = productionNodeTrace;
        final Address<? extends Node> productionAddress = reteContainer.getProvisioner()
                .getOrCreateNodeByRecipe(productionNodeTrace);
        if (!reteContainer.isLocal(productionAddress))
            throw new IllegalArgumentException("@pre: Production must be local to the head container");
        this.productionNode = (ProductionNode) reteContainer.resolveLocal(productionAddress);
        this.posMapping = this.productionNode.getPosMapping();
        this.reteContainer.getCommunicationTracker().registerDependency(this.productionNode, this);
    }

    /**
     * @since 1.6
     */
    public ProductionNode getProductionNode() {
        return productionNode;
    }

    public Tuple matchOneRandomly(Object[] inputMapping, boolean[] fixed) {
        List<Tuple> allMatches = matchAll(inputMapping, fixed).collect(Collectors.toList());
        if (allMatches == null || allMatches.isEmpty())
            return null;
        else
            return allMatches.get((int) (Math.random() * allMatches.size()));
    }

    /**
     * @since 2.0
     */
    public Stream<Tuple> matchAll(Object[] inputMapping, boolean[] fixed) {
        // retrieving the projection
        TupleMask mask = TupleMask.fromKeepIndicators(fixed);
        Tuple inputSignature = mask.transform(Tuples.flatTupleOf(inputMapping));

        return matchAll(mask, inputSignature);

    }
    
    /**
     * @since 2.0
     */
    public Stream<Tuple> matchAll(TupleMask mask, ITuple inputSignature) {
        AllMatchFetcher fetcher = new AllMatchFetcher(engine.accessProjection(productionNodeTrace, mask),
                context.wrapTuple(inputSignature.toImmutable()));
        engine.reteNet.waitForReteTermination(fetcher);
        return fetcher.getMatches();
        
    }

    /**
     * @since 2.0
     */
    public Optional<Tuple> matchOne(Object[] inputMapping, boolean[] fixed) {
        // retrieving the projection
        TupleMask mask = TupleMask.fromKeepIndicators(fixed);
        Tuple inputSignature = mask.transform(Tuples.flatTupleOf(inputMapping));

        return matchOne(mask, inputSignature);
    }

    /**
     * @since 2.0
     */
    public Optional<Tuple> matchOne(TupleMask mask, ITuple inputSignature) {
        SingleMatchFetcher fetcher = new SingleMatchFetcher(engine.accessProjection(productionNodeTrace, mask),
                context.wrapTuple(inputSignature.toImmutable()));
        engine.reteNet.waitForReteTermination(fetcher);
        return Optional.ofNullable(fetcher.getMatch());
    }
    
    /**
     * Counts the number of occurrences of the pattern that match inputMapping on positions where fixed is true.
     *
     * @return the number of occurrences
     */
    public int count(Object[] inputMapping, boolean[] fixed) {
        TupleMask mask = TupleMask.fromKeepIndicators(fixed);
        Tuple inputSignature = mask.transform(Tuples.flatTupleOf(inputMapping));

        return count(mask, inputSignature);
    }
    
    /**
     * Counts the number of occurrences of the pattern that match inputMapping on positions where fixed is true.
     *
     * @return the number of occurrences
     * @since 1.7
     */
    public int count(TupleMask mask, ITuple inputSignature) {
        CountFetcher fetcher = new CountFetcher(engine.accessProjection(productionNodeTrace, mask),
                context.wrapTuple(inputSignature.toImmutable()));
        engine.reteNet.waitForReteTermination(fetcher);
        
        return fetcher.getCount();
    }
    
    /**
     * Counts the number of distinct tuples attainable from the match set by projecting match tuples according to the given mask. 
     * 
     *
     * @return the size of the projection
     * @since 2.1
     */
    public int projectionSize(TupleMask groupMask) {
        ProjectionSizeFetcher fetcher = new ProjectionSizeFetcher(
                (IterableIndexer) engine.accessProjection(productionNodeTrace, groupMask));
        engine.reteNet.waitForReteTermination(fetcher);
        
        return fetcher.getSize();
    }

    /**
     * Connects a new external receiver that will receive update notifications from now on. The receiver will
     * practically connect to the production node, the added value is unwrapping the updates for external use.
     *
     * @param synchronize
     *            if true, the contents of the production node will be inserted into the receiver after the connection
     *            is established.
     */
    public synchronized void connect(Receiver receiver, boolean synchronize) {
        if (!connected) { // connect to the production node as a RETE-child
            reteContainer.connect(productionNode, this);
            connected = true;
        }
        if (synchronize)
            reteContainer.connectAndSynchronize(this, receiver);
        else
            reteContainer.connect(this, receiver);
    }

    /**
     * Connects a new external receiver that will receive update notifications from now on. The receiver will
     * practically connect to the production node, the added value is unwrapping the updates for external use.
     *
     * The external receiver will be disconnectable later based on its tag.
     *
     * @param tag
     *            an identifier to recognize the child node by.
     *
     * @param synchronize
     *            if true, the contents of the production node will be inserted into the receiver after the connection
     *            is established.
     *
     */
    public synchronized void connect(Receiver receiver, Object tag, boolean synchronize) {
        taggedChildren.put(tag, receiver);
        connect(receiver, synchronize);
    }

    /**
     * Disconnects a child node.
     */
    public synchronized void disconnect(Receiver receiver) {
        reteContainer.disconnect(this, receiver);
    }

    /**
     * Disconnects the child node that was connected by specifying the given tag.
     *
     * @return if a child node was found registered with this tag.
     */
    public synchronized boolean disconnectByTag(Object tag) {
        final Receiver receiver = taggedChildren.remove(tag);
        final boolean found = receiver != null;
        if (found)
            disconnect(receiver);
        return found;
    }

    @Override
    protected Tuple transform(Tuple input) {
        return context.unwrapTuple(input);
    }

    abstract class AbstractMatchFetcher implements Runnable {
        Indexer indexer;
        Tuple signature;

        public AbstractMatchFetcher(Indexer indexer, Tuple signature) {
            super();
            this.indexer = indexer;
            this.signature = signature;
        }

        @Override
        public void run() {
            fetch(indexer.get(signature));
        }

        protected abstract void fetch(Collection<Tuple> matches);

    }

    class AllMatchFetcher extends AbstractMatchFetcher {

        public AllMatchFetcher(Indexer indexer, Tuple signature) {
            super(indexer, signature);
        }

        Stream<Tuple> matches = null;

        public Stream<Tuple> getMatches() {
            return matches;
        }

        @Override
        protected void fetch(Collection<Tuple> matches) {
            if (matches == null)
                this.matches = Stream.of();
            else {
                this.matches = matches.stream().map(context::unwrapTuple); 
            }

        }

    }

    class SingleMatchFetcher extends AbstractMatchFetcher {

        public SingleMatchFetcher(Indexer indexer, Tuple signature) {
            super(indexer, signature);
        }

        Tuple match = null;

        public Tuple getMatch() {
            return match;
        }

        @Override
        protected void fetch(Collection<Tuple> matches) {
            if (matches != null && !matches.isEmpty())
                match = context.unwrapTuple(matches.iterator().next());
        }

        // public void run() {
        // Collection<Tuple> unscopedMatches = indexer.get(signature);
        //
        // // checking scopes
        // if (unscopedMatches != null) {
        // for (Tuple um : /* productionNode */unscopedMatches) {
        // match = inputConnector.unwrapTuple(um);
        // return;
        //
        // // Tuple ps = inputConnector.unwrapTuple(um);
        // // boolean ok = true;
        // // if (!ignoreScope) for (int k = 0; (k < ps.getSize()) && ok; k++) {
        // // if (pcs[k].getParameterMode() == ParameterMode.INPUT) {
        // // // ok = ok && (inputMapping[k]==ps.elements[k]);
        // // // should now be true
        // // } else // ParameterMode.OUTPUT
        // // {
        // // IEntity scopeParent = (IEntity) pcs[k].getParameterScope().getParent();
        // // Integer containmentMode = pcs[k].getParameterScope().getContainmentMode();
        // // if (containmentMode == Scope.BELOW)
        // // ok = ok && ((IModelElement) ps.get(k)).isBelowNamespace(scopeParent);
        // // else
        // // /* case Scope.IN: */
        // // ok = ok && scopeParent.equals(((IModelElement) ps.get(k)).getNamespace());
        // // // note: getNamespace returns null instead of the
        // // // (imaginary) modelspace root entity for top level
        // // // elements;
        // // // this is not a problem here as Scope.IN implies
        // // // scopeParent != root.
        // //
        // // }
        // // }
        // //
        // // if (ok) {
        // // reteMatching = new ReteMatching(ps, posMapping);
        // // return;
        // // }
        // }
        // }
        //
        // }

    }

    class CountFetcher extends AbstractMatchFetcher {

        public CountFetcher(Indexer indexer, Tuple signature) {
            super(indexer, signature);
        }

        int count = 0;

        public int getCount() {
            return count;
        }

        @Override
        protected void fetch(Collection<Tuple> matches) {
            count = matches == null ? 0 : matches.size();
        }

    }
    
    class ProjectionSizeFetcher implements Runnable {
        IterableIndexer indexer;
        int size = 0;

        public ProjectionSizeFetcher(IterableIndexer indexer) {
            super();
            this.indexer = indexer;
        }

        @Override
        public void run() {
            size = indexer.getBucketCount();
        }

        public int getSize() {
            return size;
        }

    }

    private boolean[] notNull(Object[] parameters) {
        boolean[] notNull = new boolean[parameters.length];
        for (int i = 0; i < parameters.length; ++i)
            notNull[i] = parameters[i] != null;
        return notNull;
    }

    
    
    @Override
    public boolean hasMatch(Object[] parameters) {
        return countMatches(parameters) > 0;
    }

    @Override
    public boolean hasMatch(TupleMask parameterSeedMask, ITuple parameters) {
        return count(parameterSeedMask, parameters) > 0;
    }

    @Override
    public int countMatches(Object[] parameters) {
        return count(parameters, notNull(parameters));
    }

    @Override
    public int countMatches(TupleMask parameterSeedMask, ITuple parameters) {
        return count(parameterSeedMask, parameters);
    }


    @Override
    public Optional<Long> estimateCardinality(TupleMask groupMask, Accuracy requiredAccuracy) {
        return Optional.of((long)projectionSize(groupMask)); // always accurate
    }

    @Override
    public Optional<Tuple> getOneArbitraryMatch(Object[] parameters) {
        return matchOne(parameters, notNull(parameters));
    }

    @Override
    public Optional<Tuple> getOneArbitraryMatch(TupleMask parameterSeedMask, ITuple parameters) {
        return matchOne(parameterSeedMask, parameters);
    }
    
    @Override
    public Stream<Tuple> getAllMatches(Object[] parameters) {
        return matchAll(parameters, notNull(parameters));
    }

    @Override
    public Stream<Tuple> getAllMatches(TupleMask parameterSeedMask, ITuple parameters) {
        return matchAll(parameterSeedMask, parameters);
    }
    
    @Override
    public IQueryBackend getQueryBackend() {
        return engine;
    }

    @Override
    public void addUpdateListener(final IUpdateable listener, final Object listenerTag, boolean fireNow) {
        // As a listener is added as a delayed command, they should be executed to make sure everything is consistent on
        // return, see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=562369
        engine.constructionWrapper(() -> {
            final CallbackNode callbackNode = new CallbackNode(this.reteContainer, listener);
            connect(callbackNode, listenerTag, fireNow);
            return null;
        });
    }

    @Override
    public void removeUpdateListener(Object listenerTag) {
        engine.constructionWrapper(() -> {
            disconnectByTag(listenerTag);
            return null;
        });
    }

}

Back to the top