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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
|
/*******************************************************************************
* Copyright (c) 2004 INRIA and other.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* Contributors:
* Frederic Jouault (INRIA) - initial API and implementation
* Freddy Allilaire (INRIA)
* Dennis Wagelaar (Vrije Universiteit Brussel)
*******************************************************************************/
package org.eclipse.m2m.atl.drivers.emf4atl;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.logging.Level;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EEnum;
import org.eclipse.emf.ecore.EEnumLiteral;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.util.FeatureMapUtil;
import org.eclipse.emf.ecore.xmi.XMIResource;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.m2m.atl.common.ATLLogger;
import org.eclipse.m2m.atl.engine.vm.ASMExecEnv;
import org.eclipse.m2m.atl.engine.vm.ClassNativeOperation;
import org.eclipse.m2m.atl.engine.vm.Operation;
import org.eclipse.m2m.atl.engine.vm.StackFrame;
import org.eclipse.m2m.atl.engine.vm.VMException;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMBag;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMBoolean;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMCollection;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMEnumLiteral;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMInteger;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMModel;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMModelElement;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMOclAny;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMOclType;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMOclUndefined;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMOrderedSet;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMReal;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMSequence;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMSet;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMString;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMTuple;
/**
* The EMF implementation for ASMModelElement.
*
* @author <a href="mailto:frederic.jouault@univ-nantes.fr">Frederic Jouault</a>
* @author <a href="mailto:dennis.wagelaar@vub.ac.be">Dennis Wagelaar</a>
*/
public class ASMEMFModelElement extends ASMModelElement {
private static WeakHashMap methodCache = new WeakHashMap();
// instance counter for memory leak testing
private static int instanceCount;
protected EObject object;
/**
* Creates a new {@link ASMEMFModelElement} with the given parameters.
*
* @param modelElements
* the model elements map
* @param model
* the model element
* @param object
* the object
*/
protected ASMEMFModelElement(Map modelElements, ASMModel model, EObject object) {
super(model, getMetaobject(model, object));
this.object = object;
// must be done here and not in getASMModelElement because EClass extends EClassifier whose type is
// EClass
modelElements.put(object, this);
final EStructuralFeature sfName = object.eClass().getEStructuralFeature("name");
if (sfName != null) {
String name = null;
try {
name = (String)object.eGet(sfName);
if (name == null) {
name = "<notnamedyet>";
}
} catch (Exception e) {
name = "<nonstringname>";
}
setName(name);
} else {
setName("<unnamed>");
}
if (getMetaobject() == null) {
setMetaobject(this);
}
setType(getMetaobject());
// Supertypes
if (object instanceof EClass) {
addSupertype(ASMOclType.myType);
final EClass cl = (EClass)object;
for (Iterator i = cl.getESuperTypes().iterator(); i.hasNext();) {
EClass s = (EClass)i.next();
addSupertype(((ASMEMFModel)model).getASMModelElement(s));
}
}
instanceCount++;
ATLLogger.fine(this + " created (" + instanceCount + ")");
}
// only for metamodels...?
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.engine.vm.nativelib.ASMModelElement#conformsTo(org.eclipse.m2m.atl.engine.vm.nativelib.ASMOclType)
*/
public ASMBoolean conformsTo(ASMOclType other) {
boolean ret = false;
if (other instanceof ASMEMFModelElement) {
final EObject o = ((ASMEMFModelElement)other).object;
final EObject t = object;
if ((o instanceof EClass) && (t instanceof EClass)) {
try {
ret = o.equals(t) || ((EClass)o).isSuperTypeOf((EClass)t);
} catch (Exception e) {
ATLLogger.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
}
}
return new ASMBoolean(ret);
}
// only for metamodels...?
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.engine.vm.nativelib.ASMModelElement#getPropertyType(java.lang.String)
*/
public ASMModelElement getPropertyType(String name) {
ASMModelElement ret = null;
ASMModelElement p = getProperty(name);
if (p != null) {
ret = (ASMModelElement)p.get(null, "eType");
}
return ret;
}
// only for metamodels...?
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.engine.vm.nativelib.ASMModelElement#getProperty(java.lang.String)
*/
public ASMModelElement getProperty(String name) {
ASMModelElement ret = null;
EObject t = object;
if (t instanceof EClass) {
try {
ret = ((ASMEMFModel)getModel()).getASMModelElement(((EClass)t).getEStructuralFeature(name));
} catch (Exception e) {
ATLLogger.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
}
return ret;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.engine.vm.nativelib.ASMOclAny#refImmediateComposite()
*/
public ASMOclAny refImmediateComposite() {
ASMOclAny ret = null;
EObject ic = object.eContainer();
if (ic == null) {
ret = super.refImmediateComposite();
} else {
ret = ((ASMEMFModel)getModel()).getASMModelElement(ic);
}
return ret;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.engine.vm.nativelib.ASMModelElement#get(org.eclipse.m2m.atl.engine.vm.StackFrame,
* java.lang.String)
*/
public ASMOclAny get(StackFrame frame, String name) {
ASMOclAny ret = null;
if ((frame != null) && isHelper(frame, name)) {
ret = getHelper(frame, name);
} else if ("__xmiID__".equals(name)) {
String id = ((XMIResource)((ASMEMFModel)getModel()).getExtent()).getURIFragment(object);
ret = emf2ASM(frame, id);
} else {
EStructuralFeature sf = object.eClass().getEStructuralFeature(name);
if (sf == null) {
throw new VMException(frame, "Feature " + name + " does not exist on " + getType(), null);
}
if (sf.equals(EcorePackage.eINSTANCE.getEEnum_ELiterals())) {
// treat meta-description of enum literals as ASMModelElements:
final Object value = object.eGet(sf);
ASMCollection col;
if (value instanceof List) {
col = new ASMSequence();
} else if (value instanceof Set) {
col = new ASMSet();
} else {
col = new ASMBag();
}
for (Iterator i = ((Collection)value).iterator(); i.hasNext();) {
col.add(eObjectToASM(frame, (EObject)i.next()));
}
ret = col;
} else {
ret = emf2ASM(frame, object.eGet(sf));
}
}
return ret;
}
/**
* Converts an ASM element to its EMF equivalent.
*
* @param frame
* the frame context
* @param value
* the element to convert
* @param propName
* the property name
* @param feature
* the feature which refers to the element
* @return the converted element
*/
protected Object asm2EMF(StackFrame frame, ASMOclAny value, String propName, EStructuralFeature feature) {
Object ret = null;
if (value instanceof ASMString) {
ret = ((ASMString)value).getSymbol();
if (feature != null && feature.getEType() instanceof EEnum) {
ret = getEENumLiteral((EEnum)feature.getEType(), ((ASMString)value).getSymbol())
.getInstance();
}
} else if (value instanceof ASMBoolean) {
ret = new Boolean(((ASMBoolean)value).getSymbol());
} else if (value instanceof ASMReal) {
ret = new Double(((ASMReal)value).getSymbol());
} else if (value instanceof ASMInteger) {
int val = ((ASMInteger)value).getSymbol();
if (feature != null) {
String targetType = feature.getEType().getInstanceClassName();
if (targetType.equals("java.lang.Double") || targetType.equals("java.lang.Float")) {
ret = new Double(val);
} else {
ret = new Integer(val);
}
} else {
ret = new Integer(val);
}
} else if (value instanceof ASMEMFModelElement) {
ret = ((ASMEMFModelElement)value).object;
} else if (value instanceof ASMOclUndefined) {
ret = null;
} else if (value instanceof ASMEnumLiteral) {
String name = ((ASMEnumLiteral)value).getName();
EClassifier type = ((EClass)((ASMEMFModelElement)getMetaobject()).object).getEStructuralFeature(
propName).getEType();
ret = getEENumLiteral((EEnum)type, name).getInstance();
} else if (value instanceof ASMTuple) {
Object f = asm2EMF(frame, ((ASMTuple)value).get(frame, "eStructuralFeature"), propName, feature);
if (f instanceof EStructuralFeature) {
Object v = asm2EMF(frame, ((ASMTuple)value).get(frame, "value"), propName, feature);
ret = FeatureMapUtil.createEntry((EStructuralFeature)f, v);
} else {
throw new VMException(frame, "Cannot convert " + value + " : " + value.getClass()
+ " to EMF.", null);
}
} else if (value instanceof ASMCollection) {
ret = new ArrayList();
for (Iterator i = ((ASMCollection)value).iterator(); i.hasNext();) {
Object v = asm2EMF(frame, (ASMOclAny)i.next(), propName, feature);
if (v != null) {
((List)ret).add(v);
}
}
} else {
throw new VMException(frame, "Cannot convert " + value + " : " + value.getClass() + " to EMF.",
null);
}
return ret;
}
/**
* Converts an EMF element to its ASM equivalent.
*
* @param frame
* the frame context
* @param value
* the element to convert
* @return the converted element
*/
protected ASMOclAny emf2ASM(StackFrame frame, Object value) {
ASMOclAny ret = null;
if (value instanceof String) {
ret = new ASMString((String)value);
} else if (value instanceof Boolean) {
ret = new ASMBoolean(((Boolean)value).booleanValue());
} else if (value instanceof Double) {
ret = new ASMReal(((Double)value).doubleValue());
} else if (value instanceof Float) {
ret = new ASMReal(((Float)value).doubleValue());
} else if (value instanceof Integer) {
ret = new ASMInteger(((Integer)value).intValue());
} else if (value instanceof Long) {
ret = new ASMInteger(((Long)value).intValue());
} else if (value instanceof Byte) {
ret = new ASMInteger(((Byte)value).intValue());
} else if (value instanceof Short) {
ret = new ASMInteger(((Short)value).intValue());
} else if (value instanceof Character) {
ret = new ASMInteger(((Character)value).charValue());
} else if (value instanceof Enumerator) {
ret = new ASMEnumLiteral(((Enumerator)value).getName());
} else if (value instanceof FeatureMap.Entry) {
ret = new ASMTuple();
ret.set(frame, "eStructuralFeature", emf2ASM(frame, ((FeatureMap.Entry)value)
.getEStructuralFeature()));
ret.set(frame, "value", emf2ASM(frame, ((FeatureMap.Entry)value).getValue()));
} else if (value instanceof EObject) {
ret = eObjectToASM(frame, (EObject)value);
} else if (value == null) {
ret = new ASMOclUndefined();
} else if (value instanceof Collection) {
ASMCollection col;
if (value instanceof List) {
col = new ASMSequence();
} else if (value instanceof Set) {
col = new ASMSet();
} else {
col = new ASMBag();
}
for (Iterator i = ((Collection)value).iterator(); i.hasNext();) {
col.add(emf2ASM(frame, i.next()));
}
ret = col;
} else {
throw new VMException(frame, "Cannot convert " + value + " : " + value.getClass() + " from EMF.",
null);
}
return ret;
}
/**
* Returns the corresponding ASMModelElement, taking into account the model in which the element should
* reside. Uses this model as a proxy if no other model contains the given value.
*
* @author <a href="mailto:dennis.wagelaar@vub.ac.be">Dennis Wagelaar</a>
* @param frame
* The ATL VM stackframe
* @param value
* The EMF value to convert
* @return The corresponding ASMModelElement, taking into account the model in which the element should
* reside
*/
private ASMOclAny eObjectToASM(StackFrame frame, EObject value) {
ASMEMFModel model = (ASMEMFModel)getModel();
Resource valueExtent = value.eResource();
if (model.getExtent().equals(valueExtent)) {
return model.getASMModelElement(value);
} else {
Iterator models = frame.getModels().values().iterator();
while (models.hasNext()) {
Object m = models.next();
if ((m instanceof ASMEMFModel) && (!model.equals(m))) {
if (((ASMEMFModel)m).getExtent().equals(valueExtent)) {
return ((ASMEMFModel)m).getASMModelElement(value);
}
}
}
}
// Use this model as proxy
return model.getASMModelElement(value);
}
/**
* Returns the literal matching the given name or literal.
*
* @param eEnum
* the enumeration
* @param id
* the name or the literal
* @return the literal
*/
public static EEnumLiteral getEENumLiteral(EEnum eEnum, String id) {
EEnumLiteral ret = eEnum.getEEnumLiteralByLiteral(id);
if (ret == null) {
ret = eEnum.getEEnumLiteral(id);
}
return ret;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.engine.vm.nativelib.ASMModelElement#set(org.eclipse.m2m.atl.engine.vm.StackFrame,
* java.lang.String, org.eclipse.m2m.atl.engine.vm.nativelib.ASMOclAny)
*/
public void set(StackFrame frame, String name, ASMOclAny value) {
final boolean debug = false;
if (debug) {
ATLLogger.info("Setting: " + this + " : " + getType() + "." + name + " to " + value);
}
super.set(frame, name, value);
EStructuralFeature feature = object.eClass().getEStructuralFeature(name);
if ("__xmiID__".equals(name)) {
// WARNING: Allowed manual setting of XMI ID for the current model element
// This operation is advised against but seems necessary of some special case
Resource r = ((ASMEMFModel)getModel()).getExtent();
ATLLogger.warning("Manual setting of " + this + ":" + getType() + " XMI ID.");
((XMLResource)r).setID(object, ((ASMString)value).cString());
return;
}
if (frame != null) {
ASMExecEnv execEnv = (ASMExecEnv)frame.getExecEnv();
if (execEnv.isWeavingHelper(getMetaobject(), name)) {
execEnv.setHelperValue(frame, this, name, value);
return;
}
}
if (feature == null) {
throw new VMException(frame, "Feature " + name + " does not exist on " + getType(), null);
} else {
if (!feature.isChangeable()) {
throw new VMException(frame, "Feature " + name + " is not changeable", null);
}
if (feature.isMany()) {
EList l = (EList)object.eGet(feature);
if (value instanceof ASMCollection) {
for (Iterator i = ((ASMCollection)value).iterator(); i.hasNext();) {
ASMOclAny sv = (ASMOclAny)i.next();
if (isNotAssignable(feature, sv)) {
continue;
}
Object val = asm2EMF(frame, sv, name, feature);
if (val != null) {
try {
l.add(val);
checkContainment(feature, val);
} catch (Exception e) {
throw new VMException(frame, "Cannot set feature " + getType() + "." + name
+ " to value " + val, e);
}
}
}
} else {
if (!isNotAssignable(feature, value)) {
Object val = asm2EMF(frame, value, name, feature);
l.add(val);
checkContainment(feature, val);
}
}
} else {
if (isNotAssignable(feature, value)) {
// should not happen but the ATL compiler does not add checks for this in resolveTemp yet
} else {
Object val = asm2EMF(frame, value, name, feature);
if (val != null) {
try {
object.eSet(feature, val);
checkContainment(feature, val);
} catch (Exception e) {
throw new VMException(frame, "Cannot set feature " + getType() + "." + name
+ " to value " + val, e);
}
}
}
}
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.engine.vm.nativelib.ASMOclAny#unset(org.eclipse.m2m.atl.engine.vm.StackFrame,
* java.lang.String)
*/
public void unset(StackFrame frame, String name) {
final boolean debug = false;
if (debug) {
ATLLogger.info("Unsetting: " + this + " : " + getType() + "." + name);
}
EStructuralFeature feature = object.eClass().getEStructuralFeature(name);
if ("__xmiID__".equals(name)) {
// WARNING: Allowed manual setting of XMI ID for the current model element
// This operation is advised against but seems necessary of some special case
Resource r = ((ASMEMFModel)getModel()).getExtent();
ATLLogger.warning("Manual unsetting of " + this + ":" + getType() + " XMI ID.");
((XMLResource)r).setID(object, null);
return;
}
if (frame != null) {
ASMExecEnv execEnv = (ASMExecEnv)frame.getExecEnv();
if (execEnv.isWeavingHelper(getMetaobject(), name)) {
// TODO unset helper value
return;
}
}
if (feature == null) {
throw new VMException(frame, "Feature " + name + " does not exist on " + getType(), null);
} else {
if (!feature.isChangeable()) {
throw new VMException(frame, "Feature " + name + " is not changeable", null);
}
try {
object.eUnset(feature);
} catch (Exception e) {
throw new VMException(frame, "Cannot unset feature " + getType() + "." + name, e);
}
}
}
/**
* Returns <code>true</code> if the value cannot be assigned to the feature.
*
* @author <a href="mailto:dennis.wagelaar@vub.ac.be">Dennis Wagelaar</a>
* @param feature
* The feature to assign to
* @param value
* The value to assign
* @return <code>true</code> if the value cannot be assigned to the feature
*/
private boolean isNotAssignable(EStructuralFeature feature, ASMOclAny value) {
if ((value instanceof ASMModelElement) && (((ASMModelElement)value).getModel() != getModel())) {
// assigning a model element that resides in a different model isn't always allowed
if (getModel().isCheckSameModel()) {
// cross-model references are explicitly disallowed
return true;
} else if (feature instanceof EReference) {
// containment references cannot span across models
EReference ref = (EReference)feature;
return ref.isContainer() || ref.isContainment();
}
}
return false;
}
private void checkContainment(EStructuralFeature feature, Object val) {
if ((val != null) && (feature instanceof EReference)) {
EReference ref = (EReference)feature;
if (ref.isContainment()) {
ASMEMFModel model = (ASMEMFModel)getModel();
/*
* TODO add a plugin dependency to an assertion API (e.g., org.eclipse.jface.text.Assert in
* 3.1.2 or org.eclipse.core.runtime.Assert in 3.2) Assert.isNotNull(model);
*/
EList toplevelElements = model.getExtent().getContents();
// Check if 'val' is a toplevel element
// in the content list of the model resource extent.
if (toplevelElements.contains(val)) {
// 'val' is about to become a contained element.
// therefore, we need to remove it from the list of toplevel elements
toplevelElements.remove(val);
}
} else if (ref.isContainer()) {
ASMEMFModel model = (ASMEMFModel)getModel();
/*
* TODO add a plugin dependency to an assertion API (e.g., org.eclipse.jface.text.Assert in
* 3.1.2 or org.eclipse.core.runtime.Assert in 3.2) Assert.isNotNull(model);
*/
EList toplevelElements = model.getExtent().getContents();
// Check if 'val' is a toplevel element
// in the content list of the model resource extent.
if (toplevelElements.contains(object)) {
// 'val' is about to become a contained element.
// therefore, we need to remove it from the list of toplevel elements
toplevelElements.remove(object);
}
}
}
}
private static ASMModelElement getMetaobject(ASMModel model, EObject object) {
ASMModelElement ret = null;
EObject metaobject = object.eClass();
if (metaobject != object) {
ret = ((ASMEMFModel)model.getMetamodel()).getASMModelElement(metaobject);
}
return ret;
}
private static void registerMOFOperation(String modelelementName, String methodName, Class[] args)
throws Exception {
List realArgs = new ArrayList(Arrays.asList(args));
realArgs.add(0, ASMEMFModelElement.class);
realArgs.add(0, StackFrame.class);
ClassNativeOperation no = new ClassNativeOperation(ASMEMFModelElement.class.getMethod(methodName,
(Class[])realArgs.toArray(args)));
ASMModelElement amme = ASMEMFModel.getMOF().findModelElement(modelelementName);
amme.registerVMOperation(no);
}
static {
try {
// Force creation of MOF!EClass before any other (otherwise MOF!Classifier gets created twice)
ASMEMFModel.getMOF().findModelElement("EClass");
// Operations on MOF!Classifier
// TODO on EClassifier after having added supertypes
registerMOFOperation("EClass", "allInstances", new Class[] {});
registerMOFOperation("EClass", "allInstancesFrom", new Class[] {ASMString.class});
registerMOFOperation("EClassifier", "newInstance", new Class[] {});
registerMOFOperation("EClassifier", "newInstanceIn", new Class[] {ASMString.class});
registerMOFOperation("EClassifier", "getInstanceById", new Class[] {ASMString.class,
ASMString.class,});
} catch (Exception e) {
ATLLogger.log(Level.SEVERE, e.getLocalizedMessage(), e);
}
}
/**
* Returns the instance with the given id. For testing purpose.
*
* @param frame
* the frame context
* @param self
* the current element
* @param modelName
* the model name
* @param id
* the instance id
* @return the instance
*/
public static ASMOclAny getInstanceById(StackFrame frame, ASMEMFModelElement self, ASMString modelName,
ASMString id) {
ASMOclAny ret = null;
ASMModel model = (ASMModel)frame.getModels().get(modelName.getSymbol());
if (model instanceof ASMEMFModel) {
// TODO: test new version, was: getIDToEObjectMap().get(id.getSymbol());
EObject eo = ((XMIResource)((ASMEMFModel)model).getExtent()).getEObject(id.getSymbol());
if (eo != null) {
ret = ((ASMEMFModel)model).getASMModelElement(eo);
}
}
return (ret == null) ? new ASMOclUndefined() : ret;
}
/**
* Returns all instances of a type.
*
* @param frame
* the frame context
* @param self
* the caller type
* @return all instances of a type
*/
public static ASMOrderedSet allInstances(StackFrame frame, ASMEMFModelElement self) {
return allInstancesFrom(frame, self, null);
}
/**
* Returns all instances of a type from a given model. TODO: return type could be a Set because there is
* no order, in theory However, keeping resource (i.e., XMI) order is sometimes less confusing
*
* @param frame
* the frame context
* @param self
* the caller type
* @param sourceModelName
* the model name
* @return all instances of a type from a given model
*/
public static ASMOrderedSet allInstancesFrom(StackFrame frame, ASMEMFModelElement self,
ASMString sourceModelName) {
final boolean debug = false;
ASMOrderedSet aret = new ASMOrderedSet();
Collection ret = aret.collection();
if (debug) {
ATLLogger.info(self + ".allInstancesFrom("
+ ((sourceModelName == null) ? "null" : "\"" + sourceModelName + "\"") + ")");
}
for (Iterator i = frame.getModels().keySet().iterator(); i.hasNext();) {
String mname = (String)i.next();
if (mname == null) {
continue;
}
if (debug) {
ATLLogger.info("\ttrying: " + mname);
}
if ((sourceModelName != null) && !mname.equals(sourceModelName.getSymbol())) {
continue;
}
ASMModel am = (ASMModel)frame.getModels().get(mname);
if (debug) {
ATLLogger.info("\t\tfound: " + am.getName());
ATLLogger.info("\t\tam.getMetamodel() = " + am.getMetamodel().hashCode());
ATLLogger.info("\t\tself.getModel() = " + self.getModel().hashCode());
ATLLogger.info("\t\tam.getMetamodel().equals(self.getModel()) = "
+ am.getMetamodel().equals(self.getModel()));
}
if (!am.getMetamodel().equals(self.getModel())) {
continue;
}
if (debug) {
ATLLogger.info("\t\t\tsearching on: " + am.getName());
}
Set elems = am.getElementsByType(self);
ret.addAll(elems);
if (debug) {
ATLLogger.info("\t\t\t\tfound: " + elems);
}
}
// }
return aret;
}
/**
* Creates a new instance of a given type.
*
* @param frame
* the frame context
* @param self
* the given type
* @return the new element
*/
public static ASMModelElement newInstance(StackFrame frame, ASMEMFModelElement self) {
ASMModelElement ret = null;
if (self.object.eClass().getName().equals("EClass")) {
ret = createNewInstance(frame, self);
}
return ret;
}
/**
* Creates a new instance of a given type.
*
* @param frame
* the frame context
* @param self
* the given type
* @param modelName
* the model where to create the element
* @return the new element
*/
public static ASMModelElement newInstanceIn(StackFrame frame, ASMEMFModelElement self, ASMString modelName) {
ASMModelElement ret = null;
if (self.object.eClass().getName().equals("EClass")) {
for (Iterator j = frame.getExecEnv().getModels().values().iterator(); j.hasNext();) {
ASMModel model = (ASMModel)j.next();
if (model.isTarget() && model.getName().equals(modelName.cString())) {
return model.newModelElement(self);
}
}
}
return ret;
}
/**
* Returns the method which match the given parameters.
*
* @param cls
* the class which contains the method
* @param name
* the method name
* @param argumentTypes
* th method parameters
* @return the method
*/
protected Method findMethod(Class cls, String name, Class[] argumentTypes) {
String sig = getMethodSignature(name, argumentTypes);
Method ret = findCachedMethod(sig);
if (ret != null) {
return ret;
}
Method[] methods = cls.getDeclaredMethods();
for (int i = 0; i < (methods.length) && (ret == null); i++) {
Method method = methods[i];
if (method.getName().equals(name)) {
Class[] pts = method.getParameterTypes();
if (pts.length == argumentTypes.length) {
boolean ok = true;
for (int j = 0; (j < pts.length) && ok; j++) {
if (!pts[j].isAssignableFrom(argumentTypes[j])) {
if (!(pts[j] == boolean.class && argumentTypes[j] == Boolean.class
|| pts[j] == int.class && argumentTypes[j] == Integer.class
|| pts[j] == char.class && argumentTypes[j] == Character.class
|| pts[j] == long.class && argumentTypes[j] == Long.class
|| pts[j] == float.class && argumentTypes[j] == Float.class || pts[j] == double.class
&& argumentTypes[j] == Double.class)) {
ok = false;
}
}
}
if (ok) {
ret = method;
}
}
}
}
if ((ret == null) && (cls.getSuperclass() != null)) {
ret = findMethod(cls.getSuperclass(), name, argumentTypes);
}
cacheMethod(sig, ret);
return ret;
}
private Method findCachedMethod(String signature) {
Method ret = null;
Map sigMap = (Map)methodCache.get(getMetaobject());
if (sigMap != null) {
ret = (Method)sigMap.get(signature);
}
return ret;
}
private void cacheMethod(String signature, Method method) {
ASMModelElement mo = getMetaobject();
synchronized (methodCache) {
Map sigMap = (Map)methodCache.get(mo);
if (sigMap == null) {
sigMap = new HashMap();
methodCache.put(mo, sigMap);
}
sigMap.put(signature, method);
}
}
/**
* Returns the method signature.
*
* @param name
* the method name
* @param argumentTypes
* the arguments type of the method
* @return The method signature
*/
private String getMethodSignature(String name, Class[] argumentTypes) {
StringBuffer sig = new StringBuffer();
sig.append(name);
sig.append('(');
for (int i = 0; i < argumentTypes.length; i++) {
if (i > 0) {
sig.append(',');
}
sig.append(argumentTypes[i].getName());
}
sig.append(')');
return sig.toString();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.engine.vm.nativelib.ASMOclAny#invoke(org.eclipse.m2m.atl.engine.vm.StackFrame,
* java.lang.String, java.util.List)
*/
public ASMOclAny invoke(StackFrame frame, String opName, List arguments) {
ASMOclAny ret = null;
Operation oper = findOperation(frame, opName, arguments, getType());
if (oper != null) {
ret = invoke(frame, oper, arguments);
} else {
Object[] args = new Object[arguments.size()];
Class[] argumentTypes = new Class[arguments.size()];
int k = 0;
for (Iterator i = arguments.iterator(); i.hasNext();) {
// warning: ASMEnumLiterals will not be converted!
args[k] = asm2EMF(frame, (ASMOclAny)i.next(), null, null);
argumentTypes[k] = args[k].getClass();
k++;
}
Method method = findMethod(object.getClass(), opName, argumentTypes);
try {
if (method != null) {
ret = emf2ASM(frame, method.invoke(object, args));
} else {
throw new VMException(frame, "Could not find operation " + opName + " on " + getType()
+ " having supertypes: " + getType().getSupertypes()
+ " (including Java operations)", null);
}
} catch (IllegalAccessException e) {
throw new VMException(frame,
"Could not invoke operation " + opName + " on " + getType() + " having supertypes: "
+ getType().getSupertypes() + " (including Java operations)", e);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
Exception toReport = (cause instanceof Exception) ? (Exception)cause : e;
throw new VMException(frame, "Exception during invocation of operation " + opName + " on "
+ getType() + " (java method: " + method + ")", toReport);
}
}
return ret;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.engine.vm.nativelib.ASMOclAny#invokeSuper(org.eclipse.m2m.atl.engine.vm.StackFrame,
* java.lang.String, java.util.List)
*/
public ASMOclAny invokeSuper(StackFrame frame, String opName, List arguments) {
ASMOclAny ret = null;
Operation oper = null;
for (Iterator i = getType().getSupertypes().iterator(); i.hasNext() && oper == null;) {
oper = findOperation(frame, opName, arguments, (ASMOclType)i.next());
}
if (oper != null) {
ret = invoke(frame, oper, arguments);
} else {
Object[] args = new Object[arguments.size()];
Class[] argumentTypes = new Class[arguments.size()];
int k = 0;
for (Iterator i = arguments.iterator(); i.hasNext();) {
// warning: ASMEnumLiterals will not be converted!
args[k] = asm2EMF(frame, (ASMOclAny)i.next(), null, null);
argumentTypes[k] = args[k].getClass();
k++;
}
Method method = findMethod(object.getClass().getSuperclass(), opName, argumentTypes);
try {
if (method != null) {
ret = emf2ASM(frame, method.invoke(object, args));
} else {
throw new VMException(frame, "Could not find operation " + opName + " on " + getType()
+ " having supertypes: " + getType().getSupertypes()
+ " (including Java operations)", null);
}
} catch (IllegalAccessException e) {
throw new VMException(frame,
"Could not invoke operation " + opName + " on " + getType() + " having supertypes: "
+ getType().getSupertypes() + " (including Java operations)", e);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
Exception toReport = (cause instanceof Exception) ? (Exception)cause : e;
throw new VMException(frame, "Exception during invocation of operation " + opName + " on "
+ getType() + " (java method: " + method + ")", toReport);
}
}
return ret;
}
/**
* Returns the internal EObject.
*
* @return The internal EObject.
*/
public EObject getObject() {
return object;
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#finalize()
*/
protected void finalize() throws Throwable {
instanceCount--;
ATLLogger.fine(this + " is being collected (" + instanceCount + ")");
super.finalize();
}
}
|