aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/viatra-runtime/src/main/java/tools/refinery/viatra/runtime/matchers/psystem/PBody.java
blob: c38dc23a6c2b4b9b090a3b747b9eea3d4e2dbdcb (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
/*******************************************************************************
 * 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.matchers.psystem;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.stream.Collectors;

import tools.refinery.viatra.runtime.matchers.context.IQueryMetaContext;
import tools.refinery.viatra.runtime.matchers.planning.helpers.TypeHelper;
import tools.refinery.viatra.runtime.matchers.psystem.basicdeferred.ExportedParameter;
import tools.refinery.viatra.runtime.matchers.psystem.basicenumerables.ConstantValue;
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.util.Preconditions;

/**
 * A set of constraints representing a pattern body
 * 
 * @author Gabor Bergmann
 * 
 */
public class PBody implements PTraceable {
    
    public static final String VIRTUAL_VARIABLE_PREFIX = ".virtual";
    private static final String VIRTUAL_VARIABLE_PATTERN = VIRTUAL_VARIABLE_PREFIX + "{%d}";
    
    private PQuery query;

    /**
     * If null, then parent query status is reused
     */
    private PQueryStatus status = PQueryStatus.UNINITIALIZED;

    private Set<PVariable> allVariables;
    private Set<PVariable> uniqueVariables;
    private List<ExportedParameter> symbolicParameters;
    private Map<Object, PVariable> variablesByName;
    private Set<PConstraint> constraints;
    private int nextVirtualNodeID;
    private PDisjunction containerDisjunction;

    public PBody(PQuery query) {
        super();
        this.query = query;
        allVariables = new LinkedHashSet<>();
        uniqueVariables = new LinkedHashSet<>();
        variablesByName = new HashMap<>();
        constraints = new LinkedHashSet<>();
    }

    /**
     * @return whether the submission of the new variable was successful
     */
    private boolean addVariable(PVariable var) {
        checkMutability();
        Object name = var.getName();
        if (!variablesByName.containsKey(name)) {
            allVariables.add(var);
            if (var.isUnique())
                uniqueVariables.add(var);
            variablesByName.put(name, var);
            return true;
        } else {
            return false;
        }
    }

    /**
     * Use this method to add a newly created constraint to the pSystem.
     * 
     * @return whether the submission of the new constraint was successful
     */
    boolean registerConstraint(PConstraint constraint) {
        checkMutability();
        return constraints.add(constraint);
    }

    /**
     * Use this method to remove an obsolete constraint from the pSystem.
     * 
     * @return whether the removal of the constraint was successful
     */
    boolean unregisterConstraint(PConstraint constraint) {
        checkMutability();
        return constraints.remove(constraint);
    }

    @SuppressWarnings("unchecked")
    public <ConstraintType> Set<ConstraintType> getConstraintsOfType(Class<ConstraintType> constraintClass) {
        Set<ConstraintType> result = new HashSet<ConstraintType>();
        for (PConstraint pConstraint : constraints) {
            if (constraintClass.isInstance(pConstraint))
                result.add((ConstraintType) pConstraint);
        }
        return result;
    }

    public PVariable newVirtualVariable() {
        checkMutability();
        String name;
        do {
            
            name = String.format(VIRTUAL_VARIABLE_PATTERN, nextVirtualNodeID++);
        } while (variablesByName.containsKey(name));
        PVariable var = new PVariable(this, name, true);
        addVariable(var);
        return var;
    }
    
    public PVariable newVirtualVariable(String name) {
        checkMutability();
        Preconditions.checkArgument(!variablesByName.containsKey(name), "ID %s already used for a virtual variable", name);
        PVariable var = new PVariable(this, name, true);
        addVariable(var);
        return var;
    }

    public PVariable newConstantVariable(Object value) {
        checkMutability();
        PVariable virtual = newVirtualVariable();
        new ConstantValue(this, virtual, value);
        return virtual;
    }

    public Set<PVariable> getAllVariables() {
        return allVariables;
    }

    public Set<PVariable> getUniqueVariables() {
        return uniqueVariables;
    }

    private PVariable getVariableByName(Object name) {
        return variablesByName.get(name).getUnifiedIntoRoot();
    }

    /**
     * Find a PVariable by name
     * 
     * @param name
     * @return the found variable
     * @throws IllegalArgumentException
     *             if no PVariable is found with the selected name
     */
    public PVariable getVariableByNameChecked(Object name) {
        if (!variablesByName.containsKey(name))
            throw new IllegalArgumentException(String.format("Cannot find PVariable %s", name));
        return getVariableByName(name);
    }

    /**
     * Finds and returns a PVariable by name. If no PVariable exists with the name in the body, a new one is created. If
     * the name of the variable starts with {@value #VIRTUAL_VARIABLE_PREFIX}, the created variable will be considered
     * virtual.
     * 
     * @param name
     * @return a PVariable with the selected name; never null
     */
    public PVariable getOrCreateVariableByName(String name) {
        checkMutability();
        if (!variablesByName.containsKey(name)) {
            addVariable(new PVariable(this, name, name.startsWith(VIRTUAL_VARIABLE_PREFIX)));
        }
        return getVariableByName(name);
    }

    public Set<PConstraint> getConstraints() {
        return constraints;
    }

    public PQuery getPattern() {
        return query;
    }

    void noLongerUnique(PVariable pVariable) {
        assert (!pVariable.isUnique());
        uniqueVariables.remove(pVariable);
    }

    /**
     * Returns the symbolic parameters of the body. </p>
     * 
     * <p>
     * <strong>Warning</strong>: if two PVariables are unified, the returned list changes. If you want to have a stable
     * version, consider using {@link #getSymbolicParameters()}.
     * 
     * @return a non-null, but possibly empty list
     */
    public List<PVariable> getSymbolicParameterVariables() {
        return getSymbolicParameters().stream().map(ExportedParameter::getParameterVariable)
                .collect(Collectors.toList());
    }

    /**
     * Returns the exported parameter constraints of the body.
     * 
     * @return a non-null, but possibly empty list
     */
    public List<ExportedParameter> getSymbolicParameters() {
        if (symbolicParameters == null) 
            symbolicParameters = new ArrayList<>();
        return symbolicParameters;
    }

    /**
     * Sets the exported parameter constraints of the body, if this instance is mutable.
     * @param symbolicParameters the new value
     */
    public void setSymbolicParameters(List<ExportedParameter> symbolicParameters) {
        checkMutability();
        this.symbolicParameters = new ArrayList<>(symbolicParameters);
    }

    /**
     * Sets a specific status for the body. If set, the parent PQuery status will not be checked; if set to null, its corresponding PQuery
     * status is checked for mutability.
     * 
     * @param status
     *            the status to set
     */
    public void setStatus(PQueryStatus status) {
        this.status = status;
    }

    public boolean isMutable() {
        if (status == null) {
            return query.isMutable();
        } else {
            return status.equals(PQueryStatus.UNINITIALIZED);
        }
    }
    
    void checkMutability() {
        if (status == null) {
            query.checkMutability();
        } else {
            Preconditions.checkState(status.equals(PQueryStatus.UNINITIALIZED), "Initialized queries are not mutable");
        }
    }

    /**
     * Returns the disjunction the body is contained with. This disjunction may either be the
     * {@link PQuery#getDisjunctBodies() canonical disjunction of the corresponding query} or something equivalent.
     * 
     * @return the container disjunction of the body. Can be null if body is not in a disjunction yet.
     */
    public PDisjunction getContainerDisjunction() {
        return containerDisjunction;
    }

    /**
     * @param containerDisjunction the containerDisjunction to set
     */
    public void setContainerDisjunction(PDisjunction containerDisjunction) {
        Preconditions.checkArgument(query.equals(containerDisjunction.getQuery()), "Disjunction of pattern %s incompatible with body %s", containerDisjunction.getQuery().getFullyQualifiedName(), query.getFullyQualifiedName());
        Preconditions.checkState(this.containerDisjunction == null, "Disjunction is already set.");
        this.containerDisjunction = containerDisjunction;
    }

    /**
     * All unary input keys directly prescribed by constraints, grouped by variable.
     * <p> to supertype inference or subsumption applied at this point.
     */
    public Map<PVariable, Set<TypeJudgement>> getAllUnaryTypeRestrictions(IQueryMetaContext context) {
        Map<PVariable, Set<TypeJudgement>> currentRestrictions = allUnaryTypeRestrictions.get(context);
        if (currentRestrictions == null) {
            currentRestrictions = TypeHelper.inferUnaryTypes(getConstraints(), context);
            allUnaryTypeRestrictions.put(context, currentRestrictions);
        }
        return currentRestrictions;
    }
    private WeakHashMap<IQueryMetaContext, Map<PVariable, Set<TypeJudgement>>> allUnaryTypeRestrictions = new WeakHashMap<IQueryMetaContext, Map<PVariable,Set<TypeJudgement>>>();   
    
}