Repository navigation
Expand file tree
/
Copy pathVirtualContainerTest.java
More file actions
597 lines (551 loc) · 23.2 KB
/
Copy pathVirtualContainerTest.java
File metadata and controls
597 lines (551 loc) · 23.2 KB
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
/**
* SysML 2 Pilot Implementation
* Copyright (c) 2026 Obeo
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Eclipse Public License, version 2, as published by
* the Eclipse Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Eclipse Public License for more details.
*
* You should have received a copy of the Eclipse Public License
* along with this program. If not, see <https://www.eclipse.org/legal/epl-2.0/>.
*
* @license EPL-2.0 <http://spdx.org/licenses/EPL-2.0>
*/
package org.omg.sysml.interactive.tests;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.xtext.EcoreUtil2;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import org.omg.sysml.interactive.SysMLInteractive;
import org.omg.sysml.lang.sysml.BindingConnector;
import org.omg.sysml.lang.sysml.Classifier;
import org.omg.sysml.lang.sysml.ConnectionDefinition;
import org.omg.sysml.lang.sysml.Element;
import org.omg.sysml.lang.sysml.Feature;
import org.omg.sysml.lang.sysml.FeatureChainExpression;
import org.omg.sysml.lang.sysml.FeatureMembership;
import org.omg.sysml.lang.sysml.ReferenceUsage;
import org.omg.sysml.lang.sysml.SuccessionAsUsage;
import org.omg.sysml.lang.sysml.SysMLFactory;
import org.omg.sysml.lang.sysml.TransitionUsage;
import org.omg.sysml.lang.sysml.Type;
import org.omg.sysml.util.ElementUtil;
import org.omg.sysml.util.FeatureUtil;
import org.omg.sysml.util.SysMLLibraryUtil;
import org.omg.sysml.util.TypeUtil;
import org.omg.sysml.util.UsageUtil;
import org.omg.sysml.util.VirtualContainer;
/**
* Tests that the elements the implementation creates outside the model for implied relationships
* (feature chains and binding connectors) are linked to the model element for which they are created,
* and that {@link ElementUtil#getEffectiveContainer(EObject)} reaches the model from them.
*/
public class VirtualContainerTest {
private static ResourceSet resourceSet;
private final List<Resource> models = new ArrayList<>();
/** Loads and resolves libraries once. */
@BeforeClass
public static void loadLibraries() {
SysMLInteractive interactive = SysMLInteractive.createInstance();
interactive.setVerbose(false);
interactive.getLibraryIndexCache().setIndexDisabled(true);
interactive.loadLibrary(Path.of(System.getProperty("libraryPath")).toAbsolutePath().toString());
resourceSet = interactive.getResourceSet();
for (int i = 0; i < resourceSet.getResources().size(); i++) {
EcoreUtil2.resolveLazyCrossReferences(resourceSet.getResources().get(i), null);
}
}
/** Removes each scenario without altering the shared library contents. */
@After
public void removeModels() {
for (Resource resource : models) {
resource.unload();
resourceSet.getResources().remove(resource);
}
}
/**
* The result of a {@code FeatureChainExpression} subsets a chain of the source parameter and the
* source target feature. The expression adds that chain to the implicit general types of its result
* when it is transformed; the chain is created detached and its virtual container, and therefore
* its effective container, must be the expression result.
*/
@Test
public void featureChainExpressionResultChainIsLinkedToTheResult() throws Exception {
// package Chains {
// feature a { feature b; }
// feature c = a.b;
// }
Resource resource = parse("chainExpression.kerml", """
package Chains {
feature a { feature b; }
feature c = a.b;
}
""");
Feature c = findByName(resource, "c", Feature.class);
FeatureChainExpression expression = (FeatureChainExpression)FeatureUtil.getValuationFor(c).getValue();
Feature result = expression.getResult();
// Transforming the expression alone records the chain "source.b" as an implicit general type of
// the result, without materializing it: the chain is still detached.
ElementUtil.transform(expression);
Feature chain = findDetachedChain(TypeUtil.getImplicitGeneralTypesFor(result));
assertSame(result, VirtualContainer.getVirtualContainer(chain));
assertSame(result, ElementUtil.getEffectiveContainer(chain));
}
/**
* A feature bound to a value without an explicit specialization subsets the chain of the value
* expression and its result. That chain is created detached and must be linked to the valued
* feature.
*/
@Test
public void boundValueChainIsLinkedToTheValuedFeature() throws Exception {
// package BoundValue {
// feature x;
// feature y = x;
// }
Resource resource = parse("boundValue.kerml", """
package BoundValue {
feature x;
feature y = x;
}
""");
Feature y = findByName(resource, "y", Feature.class);
// The implicit subsetting of y targets the detached chain "value.result".
Feature chain = findDetachedChain(TypeUtil.getImplicitGeneralTypesFor(y));
assertSame(y, VirtualContainer.getVirtualContainer(chain));
assertSame(y, ElementUtil.getEffectiveContainer(chain));
}
/**
* A succession whose source is a decision node, and a succession whose target is a merge node,
* specialize a detached chain through the control node. Each chain must be linked to its
* succession.
*/
@Test
public void decisionAndMergeChainsAreLinkedToTheSuccession() throws Exception {
// action def Control {
// action A1;
// action A2;
// decide D;
// if true then A1;
// else A2;
// action B1;
// then M;
// action B2;
// then M;
// merge M;
// }
Resource resource = parse("control.sysml", """
action def Control {
action A1;
action A2;
decide D;
if true then A1;
else A2;
action B1;
then M;
action B2;
then M;
merge M;
}
""");
// Outgoing succession of D: its chained general is "D.outgoingHBLink".
SuccessionAsUsage fromDecision = findSuccession(resource, "D", true);
Feature decisionChain = findDetachedChain(TypeUtil.getImplicitGeneralTypesFor(fromDecision));
assertSame(fromDecision, VirtualContainer.getVirtualContainer(decisionChain));
assertSame(fromDecision, ElementUtil.getEffectiveContainer(decisionChain));
// Incoming succession of M: its chained general is "M.incomingHBLink".
SuccessionAsUsage toMerge = findSuccession(resource, "M", false);
Feature mergeChain = findDetachedChain(TypeUtil.getImplicitGeneralTypesFor(toMerge));
assertSame(toMerge, VirtualContainer.getVirtualContainer(mergeChain));
assertSame(toMerge, ElementUtil.getEffectiveContainer(mergeChain));
}
/**
* The payload parameter of a transition with an accepter subsets the chain of the accepter and its
* payload parameter. That chain is created detached and must be linked to the payload parameter.
*/
@Test
public void transitionPayloadChainIsLinkedToThePayloadParameter() throws Exception {
// state def Machine {
// attribute def Signal;
// entry; then s1;
// state s1;
// state s2;
// transition t first s1 accept sig : Signal then s2;
// }
Resource resource = parse("transition.sysml", """
state def Machine {
attribute def Signal;
entry; then s1;
state s1;
state s2;
transition t first s1 accept sig : Signal then s2;
}
""");
TransitionUsage transition = findByName(resource, "t", TransitionUsage.class);
ReferenceUsage payload = (ReferenceUsage)UsageUtil.getPayloadParameterOf(transition);
assertNotNull("Missing transition payload parameter", payload);
// The implicit subsetting of the payload parameter targets the detached chain "accepter.sig".
Feature chain = findDetachedChain(TypeUtil.getImplicitGeneralTypesFor(payload));
assertSame(payload, VirtualContainer.getVirtualContainer(chain));
assertSame(payload, ElementUtil.getEffectiveContainer(chain));
}
/**
* The transformation of a valued feature creates a binding connector detached, linked to the
* feature, then inserts it into the model. Once inserted, the connector keeps its virtual
* container but its effective container is its real container.
*/
@Test
public void valueBindingConnectorKeepsItsVirtualContainerOnceContained() throws Exception {
// package Binding {
// feature x;
// feature y = x;
// }
Resource resource = parse("binding.kerml", """
package Binding {
feature x;
feature y = x;
}
""");
Feature y = findByName(resource, "y", Feature.class);
// Transformation creates the binding connector of y's value and adds it to the model. The value
// expression also owns a binding connector for its own result, linked to the expression, so the
// connector is selected by its virtual container.
ElementUtil.transformAll(resource, true);
BindingConnector connector = findBindingConnectorLinkedTo(y);
assertNotNull("Expected the value binding connector in the model", connector.eContainer());
assertSame(y, VirtualContainer.getVirtualContainer(connector));
assertSame(connector.eContainer(), ElementUtil.getEffectiveContainer(connector));
}
/**
* A detached chain resolves library types from the model through its virtual container, as the
* element it was created for does. The rules applied by the chain's own adapter then find its
* library general: without the link, the lookup returns nothing and the chain gets no general.
*/
@Test
public void detachedChainResolvesLibraryTypesFromItsModel() throws Exception {
// package Library {
// feature x;
// feature y = x;
// }
Resource resource = parse("library.kerml", """
package Library {
feature x;
feature y = x;
}
""");
Feature y = findByName(resource, "y", Feature.class);
Feature chain = findDetachedChain(TypeUtil.getImplicitGeneralTypesFor(y));
// The chain has no resource: the library is found through its virtual container, y.
Type things = SysMLLibraryUtil.getLibraryType(y, "Base::things");
assertNotNull(things);
assertSame(things, SysMLLibraryUtil.getLibraryType(chain, "Base::things"));
// The default rule of the chain's own adapter therefore finds its library general
// (checkFeatureSpecialization).
List<String> generals = TypeUtil.getImplicitGeneralTypesFor(chain).stream().map(Type::getQualifiedName).toList();
assertTrue("Expected Base::things in " + generals, generals.contains("Base::things"));
}
/**
* A binding connector created for a valued feature, before it is inserted into the model,
* resolves library types from the model through its virtual container.
*/
@Test
public void detachedBindingConnectorResolvesLibraryTypesFromItsModel() throws Exception {
// package Connector {
// feature x;
// feature y = x;
// }
Resource resource = parse("connector.kerml", """
package Connector {
feature x;
feature y = x;
}
""");
Feature y = findByName(resource, "y", Feature.class);
// Transformation without implicit elements creates the value binding connector of y but does
// not insert it: the connector stays detached, linked to y.
ElementUtil.transformAll(resource, false);
List<BindingConnector> connectors = new ArrayList<>();
TypeUtil.forEachImplicitBindingConnectorOf(y, (connector, membershipKind) -> connectors.add(connector));
BindingConnector connector = connectors.stream()
.filter(candidate -> VirtualContainer.getVirtualContainer(candidate) == y).findFirst().orElseThrow();
assertNull(connector.eResource());
// The library general of a binding connector is found from the connector itself.
assertNotNull(SysMLLibraryUtil.getLibraryType(connector, "Links::selfLinks"));
}
/**
* A Type that is the root of its resource and the featuring type of its ends stays the root of
* its resource after transformation: materializing the implied TypeFeaturing of an end must not
* move the root into that relationship, which would create a containment cycle and leave the
* resource.
*/
@Test
public void resourceRootStaysInItsResourceAfterTransformation() throws Exception {
// A Type cannot be the root of a parsed resource, whose root is a Namespace: the model is built
// programmatically, a ConnectionDefinition with two end Features as the only resource content.
Resource resource = resourceSet.createResource(URI.createURI("memory:/root.sysml"));
models.add(resource);
ConnectionDefinition connectionDefinition = SysMLFactory.eINSTANCE.createConnectionDefinition();
resource.getContents().add(connectionDefinition);
for (int i = 0; i < 2; i++) {
Feature end = SysMLFactory.eINSTANCE.createFeature();
end.setIsEnd(true);
FeatureMembership membership = SysMLFactory.eINSTANCE.createFeatureMembership();
membership.setOwnedMemberFeature(end);
connectionDefinition.getOwnedRelationship().add(membership);
}
// The ends are featured by the ConnectionDefinition; inserting that TypeFeaturing must leave
// the ConnectionDefinition where it is.
ElementUtil.transformAll(connectionDefinition, true);
assertNull(connectionDefinition.eContainer());
assertSame(resource, connectionDefinition.eResource());
}
/**
* The featuring type of a variable feature is a {@code <Owner>_snapshots} feature created
* outside the model and stored as an implicit featuring type of the feature. Storing it records
* the feature, which owns the implied TypeFeaturing, as its virtual container.
*/
@Test
public void snapshotsFeaturingTypeIsLinkedToTheVariableFeature() throws Exception {
Resource resource = parse("snapshots.kerml", """
package Snapshots {
class C {
var feature x;
}
}
""");
Feature x = findByName(resource, "x", Feature.class);
// Transforming x computes its featuring type (checkFeatureFeatureMembershipTypeFeaturing):
// a new C_snapshots feature redefining Occurrence::snapshots, which is not inserted.
ElementUtil.transform(x);
Feature snapshots = x.getFeaturingType().stream()
.filter(Feature.class::isInstance).map(Feature.class::cast)
.filter(featuring -> "C_snapshots".equals(featuring.getDeclaredName()))
.findFirst().orElseThrow();
assertNull(snapshots.eContainer());
// Expected: its virtual container is x, through which it reaches the model.
assertSame(x, VirtualContainer.getVirtualContainer(snapshots));
assertSame(x, ElementUtil.getClosestElementInResource(snapshots));
}
/**
* The binding connector of an initial value is featured by a {@code that.startShot} chain
* created outside the model. The chain is stored as an implicit featuring type of the connector,
* so the connector is its virtual container, and the chain reaches the model through the
* connector's own virtual container, the valued feature.
*/
@Test
public void initialValueFeaturingChainIsLinkedToTheBindingConnector() throws Exception {
// package Initial {
// class C {
// feature x;
// var feature y := x;
// }
// }
Resource resource = parse("initial.kerml", """
package Initial {
class C {
feature x;
var feature y := x;
}
}
""");
Feature y = findByName(resource, "y", Feature.class);
// Transforming y creates its value binding connector (checkFeatureValueBindingConnector),
// featured by the chain that.startShot because the value is initial.
ElementUtil.transform(y);
BindingConnector connector = findImplicitBindingConnectorOf(y);
Feature chain = connector.getFeaturingType().stream()
.filter(Feature.class::isInstance).map(Feature.class::cast)
.filter(featuring -> featuring.getChainingFeature().size() == 2)
.findFirst().orElseThrow();
// Expected: the chain is linked to the connector, and the connector to y.
assertSame(connector, VirtualContainer.getVirtualContainer(chain));
assertSame(y, VirtualContainer.getVirtualContainer(connector));
assertSame(y, ElementUtil.getClosestElementInResource(chain));
}
/**
* An unresolved proxy has no container or resource but is not a detached inferred element.
* Attaching it must leave it without a virtual container or access to the model's library,
* so its placeholder metaclass cannot acquire library specializations.
*/
@Test
public void unresolvedProxyHasNoVirtualContainer() throws Exception {
Resource resource = parse("proxyContext.kerml", """
package Context {
feature x;
}
""");
Feature x = findByName(resource, "x", Feature.class);
// A proxy's concrete class is a placeholder, not the type of the unresolved referent.
Feature proxy = SysMLFactory.eINSTANCE.createAcceptActionUsage();
((InternalEObject)proxy).eSetProxyURI(URI.createURI("memory:/unresolved.sysml#referent"));
VirtualContainer.attach(proxy, x);
// The proxy must not reach x's resource and infer Actions::acceptActions from its class.
assertTrue(proxy.eIsProxy());
assertNull(VirtualContainer.getVirtualContainer(proxy));
assertNull(ElementUtil.getClosestElementInResource(proxy));
assertNull(SysMLLibraryUtil.getLibraryType(proxy, "Actions::acceptActions"));
}
/**
* In a model built without a resource, a root can be stored as the target of an implied
* relationship owned by one of its own members, for example as the featuring type of a nested
* feature. Linking the root to that member would close a cycle of effective containers: the
* link is refused, and the walk to the model terminates.
*/
@Test
public void rootIsNotLinkedToOneOfItsMembers() {
// classifier Root { feature member; }, built without a resource.
Classifier root = SysMLFactory.eINSTANCE.createClassifier();
Feature member = SysMLFactory.eINSTANCE.createFeature();
TypeUtil.addOwnedFeatureTo(root, member);
// Storing root as an implied relationship target of member must not link them.
VirtualContainer.attach(root, member);
assertNull(VirtualContainer.getVirtualContainer(root));
// Expected: no element in a resource is found, instead of an endless walk.
assertNull(ElementUtil.getClosestElementInResource(member));
}
/**
* An element parsed from text is created in the model: it has no virtual container and its
* effective container is its real container.
*/
@Test
public void parsedElementHasNoVirtualContainer() throws Exception {
// package Parsed {
// feature x;
// }
Resource resource = parse("parsed.kerml", """
package Parsed {
feature x;
}
""");
Feature x = findByName(resource, "x", Feature.class);
assertNull(VirtualContainer.getVirtualContainer(x));
assertSame(x.eContainer(), ElementUtil.getEffectiveContainer(x));
}
/**
* Parses a model into a new in-memory resource of the shared resource set and registers it for
* removal after the test.
*
* @param name the resource name, whose extension selects the language
* @param text the textual model
* @return the loaded resource, checked to have no parsing errors
* @throws Exception when the text cannot be loaded
*/
private Resource parse(String name, String text) throws Exception {
Resource resource = resourceSet.createResource(URI.createURI("memory:/" + name));
models.add(resource);
resource.load(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)), Map.of());
assertTrue(resource.getErrors().toString(), resource.getErrors().isEmpty());
return resource;
}
/**
* Returns the first element of a resource with the given declared name and metaclass.
*
* @param resource the resource searched, in containment order
* @param name the declared name
* @param kind the expected metaclass
* @return the element found
* @throws AssertionError when no such element exists
*/
private static <T extends Element> T findByName(Resource resource, String name, Class<T> kind) {
for (var contents = resource.getAllContents(); contents.hasNext();) {
EObject object = contents.next();
if (kind.isInstance(object) && name.equals(((Element)object).getDeclaredName())) {
return kind.cast(object);
}
}
throw new AssertionError("Missing " + kind.getSimpleName() + " " + name);
}
/**
* Returns the first feature chain that is not contained in the model among the given general
* types.
*
* @param generals the general types searched, in order
* @return the detached feature chain
* @throws AssertionError when the list contains no detached feature chain
*/
private static Feature findDetachedChain(List<Type> generals) {
for (Type general : generals) {
if (general instanceof Feature feature && !feature.getOwnedFeatureChaining().isEmpty()
&& feature.eContainer() == null) {
return feature;
}
}
throw new AssertionError("Missing detached feature chain among " + generals);
}
/**
* Returns the first SuccessionAsUsage of a resource whose source or target end is the named node.
*
* @param resource the resource searched, in containment order
* @param nodeName the declared name of the end feature
* @param fromNode {@code true} to match the source end, {@code false} to match the target end
* @return the succession found
* @throws AssertionError when no such succession exists
*/
private static SuccessionAsUsage findSuccession(Resource resource, String nodeName, boolean fromNode) {
for (var contents = resource.getAllContents(); contents.hasNext();) {
if (contents.next() instanceof SuccessionAsUsage succession) {
Feature end;
if (fromNode) {
end = UsageUtil.getSourceOf(succession);
} else {
end = UsageUtil.getTargetOf(succession);
}
if (end != null && nodeName.equals(end.getDeclaredName())) {
return succession;
}
}
}
throw new AssertionError("Missing succession for " + nodeName);
}
/**
* Returns the first BindingConnector contained in a feature whose virtual container is that
* feature.
*
* @param feature the feature whose contents are searched
* @return the binding connector found
* @throws AssertionError when no such binding connector exists
*/
private static BindingConnector findBindingConnectorLinkedTo(Feature feature) {
for (var contents = feature.eAllContents(); contents.hasNext();) {
if (contents.next() instanceof BindingConnector connector
&& VirtualContainer.getVirtualContainer(connector) == feature) {
return connector;
}
}
throw new AssertionError("Missing binding connector linked to " + feature.getDeclaredName());
}
/**
* Returns the first implicit BindingConnector of a feature, not yet inserted into the model.
*
* @param feature the feature whose implicit binding connectors are searched
* @return the binding connector found
* @throws AssertionError when the feature has no implicit binding connector
*/
private static BindingConnector findImplicitBindingConnectorOf(Feature feature) {
List<BindingConnector> connectors = new ArrayList<>();
TypeUtil.forEachImplicitBindingConnectorOf(feature, (connector, membershipKind) -> connectors.add(connector));
if (connectors.isEmpty()) {
throw new AssertionError("Missing implicit binding connector of " + feature.getDeclaredName());
}
return connectors.get(0);
}
}