Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 421b9b21a264218adb9080ff9819d59565cb9e0e (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
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
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
/*******************************************************************************
 * Copyright (c) 2007, 2013 Borland Software Corporation and others
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *   
 * Contributors:
 *     Borland Software Corporation - initial API and implementation
 *     Christopher Gerking - bugs 302594, 309762, 310991, 325192, 377882, 388325, 392080, 392153, 394498, 397215, 397218, 269744, 415660, 415315, 414642
 *     Alex Paperno - bugs 294127, 416584, 419299, 267917, 420970
 *******************************************************************************/
package org.eclipse.m2m.internal.qvt.oml.evaluator;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EEnumLiteral;
import org.eclipse.emf.ecore.EFactory;
import org.eclipse.emf.ecore.EModelElement;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EOperation;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EParameter;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.m2m.internal.qvt.oml.NLS;
import org.eclipse.m2m.internal.qvt.oml.QvtPlugin;
import org.eclipse.m2m.internal.qvt.oml.ast.binding.ASTBindingHelper;
import org.eclipse.m2m.internal.qvt.oml.ast.binding.IModuleSourceInfo;
import org.eclipse.m2m.internal.qvt.oml.ast.env.IVirtualOperationTable;
import org.eclipse.m2m.internal.qvt.oml.ast.env.InternalEvaluationEnv;
import org.eclipse.m2m.internal.qvt.oml.ast.env.ModelParameterExtent;
import org.eclipse.m2m.internal.qvt.oml.ast.env.QvtEvaluationResult;
import org.eclipse.m2m.internal.qvt.oml.ast.env.QvtOperationalEnv;
import org.eclipse.m2m.internal.qvt.oml.ast.env.QvtOperationalEnvFactory;
import org.eclipse.m2m.internal.qvt.oml.ast.env.QvtOperationalEvaluationEnv;
import org.eclipse.m2m.internal.qvt.oml.ast.env.QvtOperationalModuleEnv;
import org.eclipse.m2m.internal.qvt.oml.ast.env.QvtOperationalStdLibrary;
import org.eclipse.m2m.internal.qvt.oml.ast.parser.ConstructorOperationAdapter;
import org.eclipse.m2m.internal.qvt.oml.ast.parser.IntermediateClassFactory;
import org.eclipse.m2m.internal.qvt.oml.ast.parser.IntermediateClassFactory.ExceptionClassInstance;
import org.eclipse.m2m.internal.qvt.oml.ast.parser.QvtOperationalParserUtil;
import org.eclipse.m2m.internal.qvt.oml.ast.parser.QvtOperationalUtil;
import org.eclipse.m2m.internal.qvt.oml.blackbox.BlackboxRegistry;
import org.eclipse.m2m.internal.qvt.oml.emf.util.EmfUtil;
import org.eclipse.m2m.internal.qvt.oml.evaluator.TransformationInstance.InternalTransformation;
import org.eclipse.m2m.internal.qvt.oml.evaluator.iterators.QvtIterationTemplateCollectSelect;
import org.eclipse.m2m.internal.qvt.oml.evaluator.iterators.QvtIterationTemplateForExp;
import org.eclipse.m2m.internal.qvt.oml.evaluator.iterators.QvtIterationTemplateXCollect;
import org.eclipse.m2m.internal.qvt.oml.evaluator.iterators.QvtIterationTemplateXSelect;
import org.eclipse.m2m.internal.qvt.oml.expressions.Constructor;
import org.eclipse.m2m.internal.qvt.oml.expressions.ConstructorBody;
import org.eclipse.m2m.internal.qvt.oml.expressions.ContextualProperty;
import org.eclipse.m2m.internal.qvt.oml.expressions.DirectionKind;
import org.eclipse.m2m.internal.qvt.oml.expressions.EntryOperation;
import org.eclipse.m2m.internal.qvt.oml.expressions.ExpressionsPackage;
import org.eclipse.m2m.internal.qvt.oml.expressions.Helper;
import org.eclipse.m2m.internal.qvt.oml.expressions.ImperativeCallExp;
import org.eclipse.m2m.internal.qvt.oml.expressions.ImperativeOperation;
import org.eclipse.m2m.internal.qvt.oml.expressions.Library;
import org.eclipse.m2m.internal.qvt.oml.expressions.MappingBody;
import org.eclipse.m2m.internal.qvt.oml.expressions.MappingCallExp;
import org.eclipse.m2m.internal.qvt.oml.expressions.MappingOperation;
import org.eclipse.m2m.internal.qvt.oml.expressions.MappingParameter;
import org.eclipse.m2m.internal.qvt.oml.expressions.ModelParameter;
import org.eclipse.m2m.internal.qvt.oml.expressions.ModelType;
import org.eclipse.m2m.internal.qvt.oml.expressions.Module;
import org.eclipse.m2m.internal.qvt.oml.expressions.ModuleImport;
import org.eclipse.m2m.internal.qvt.oml.expressions.ObjectExp;
import org.eclipse.m2m.internal.qvt.oml.expressions.OperationBody;
import org.eclipse.m2m.internal.qvt.oml.expressions.OperationalTransformation;
import org.eclipse.m2m.internal.qvt.oml.expressions.ResolveExp;
import org.eclipse.m2m.internal.qvt.oml.expressions.ResolveInExp;
import org.eclipse.m2m.internal.qvt.oml.expressions.VarParameter;
import org.eclipse.m2m.internal.qvt.oml.expressions.impl.ImperativeOperationImpl;
import org.eclipse.m2m.internal.qvt.oml.expressions.impl.OperationBodyImpl;
import org.eclipse.m2m.internal.qvt.oml.library.Context;
import org.eclipse.m2m.internal.qvt.oml.library.EObjectEStructuralFeaturePair;
import org.eclipse.m2m.internal.qvt.oml.library.LateResolveInTask;
import org.eclipse.m2m.internal.qvt.oml.library.LateResolveTask;
import org.eclipse.m2m.internal.qvt.oml.library.QvtResolveUtil;
import org.eclipse.m2m.internal.qvt.oml.stdlib.CallHandler;
import org.eclipse.m2m.internal.qvt.oml.stdlib.ConversionUtils;
import org.eclipse.m2m.internal.qvt.oml.stdlib.DictionaryImpl;
import org.eclipse.m2m.internal.qvt.oml.stdlib.MutableListImpl;
import org.eclipse.m2m.internal.qvt.oml.stdlib.model.ExceptionInstance;
import org.eclipse.m2m.internal.qvt.oml.trace.Trace;
import org.eclipse.m2m.internal.qvt.oml.trace.TraceRecord;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.AltExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.AssertExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.AssignExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.BlockExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.BreakExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.CatchExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.ComputeExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.ContinueExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.DictLiteralExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.DictLiteralPart;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.ForExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.ImperativeIterateExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.ImperativeLoopExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.ImperativeOCLPackage;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.InstantiationExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.ListType;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.LogExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.OrderedTupleLiteralExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.OrderedTupleLiteralPart;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.RaiseExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.ReturnExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.SeverityKind;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.SwitchExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.TryExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.UnlinkExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.UnpackExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.VariableInitExp;
import org.eclipse.m2m.qvt.oml.ecore.ImperativeOCL.WhileExp;
import org.eclipse.m2m.qvt.oml.util.Dictionary;
import org.eclipse.m2m.qvt.oml.util.EvaluationMonitor;
import org.eclipse.m2m.qvt.oml.util.IContext;
import org.eclipse.m2m.qvt.oml.util.Log;
import org.eclipse.m2m.qvt.oml.util.MutableList;
import org.eclipse.ocl.Environment;
import org.eclipse.ocl.EnvironmentFactory;
import org.eclipse.ocl.EvaluationEnvironment;
import org.eclipse.ocl.EvaluationVisitor;
import org.eclipse.ocl.EvaluationVisitorImpl;
import org.eclipse.ocl.ParserException;
import org.eclipse.ocl.ecore.CallOperationAction;
import org.eclipse.ocl.ecore.Constraint;
import org.eclipse.ocl.ecore.EcoreEnvironment;
import org.eclipse.ocl.ecore.EcoreFactory;
import org.eclipse.ocl.ecore.EcorePackage;
import org.eclipse.ocl.ecore.SendSignalAction;
import org.eclipse.ocl.expressions.CollectionItem;
import org.eclipse.ocl.expressions.CollectionKind;
import org.eclipse.ocl.expressions.CollectionLiteralExp;
import org.eclipse.ocl.expressions.CollectionLiteralPart;
import org.eclipse.ocl.expressions.CollectionRange;
import org.eclipse.ocl.expressions.EnumLiteralExp;
import org.eclipse.ocl.expressions.IfExp;
import org.eclipse.ocl.expressions.OCLExpression;
import org.eclipse.ocl.expressions.OperationCallExp;
import org.eclipse.ocl.expressions.PropertyCallExp;
import org.eclipse.ocl.expressions.Variable;
import org.eclipse.ocl.expressions.VariableExp;
import org.eclipse.ocl.types.BagType;
import org.eclipse.ocl.types.CollectionType;
import org.eclipse.ocl.types.SetType;
import org.eclipse.ocl.types.TupleType;
import org.eclipse.ocl.types.VoidType;
import org.eclipse.ocl.util.Bag;
import org.eclipse.ocl.util.CollectionUtil;
import org.eclipse.ocl.util.Tuple;
import org.eclipse.ocl.utilities.ASTNode;
import org.eclipse.ocl.utilities.PredefinedType;
import org.eclipse.ocl.utilities.UMLReflection;


public class QvtOperationalEvaluationVisitorImpl
	extends EvaluationVisitorImpl<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter,
EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject>
implements QvtOperationalEvaluationVisitor, InternalEvaluator, DeferredAssignmentListener {	

	private static int tempCounter = 0;
	
    private QvtOperationalEvaluationEnv myEvalEnv;
    // FIXME - move me to the root environment?
    private OCLAnnotationSupport oclAnnotationSupport;

    public QvtOperationalEvaluationVisitorImpl(QvtOperationalEnv env, QvtOperationalEvaluationEnv evalEnv) {
        super(env, evalEnv, evalEnv.createExtentMap(null));

        myEvalEnv = evalEnv;
    }
    
	protected QvtOperationalEvaluationVisitorImpl(QvtOperationalEvaluationVisitorImpl parent, QvtOperationalEvaluationEnv nestedEvalEnv) {
		this(parent.getOperationalEnv(), nestedEvalEnv);
		
		oclAnnotationSupport = parent.getOCLAnnotationSupport();
	}    
    
	protected QvtOperationalEvaluationVisitorImpl createNestedEvaluationVisitor(QvtOperationalEvaluationVisitorImpl parent, QvtOperationalEvaluationEnv nestedEvalEnv) {
		return new QvtOperationalEvaluationVisitorImpl(parent, nestedEvalEnv); 
	}
	
	public Object visitDictLiteralExp(DictLiteralExp dictLiteralExp) {
		Dictionary<Object, Object> result = new DictionaryImpl<Object, Object>();
		for (DictLiteralPart part : dictLiteralExp.getPart()) {
			Object key = visitExpression(part.getKey());
			Object value = visitExpression(part.getValue());
			if(key != getInvalid() && value != getInvalid())
			result.put(key, value);
		}
		
		return result;
	}
	
	@Override
    public Object visitVariableExp(VariableExp<EClassifier, EParameter> v) {
		QvtOperationalEvaluationEnv evalEnv = getOperationalEvaluationEnv();		
		Variable<EClassifier, EParameter> vd = v.getReferredVariable();
		String varName = vd.getName();		
		Object value = evalEnv.getValueOf(varName);
		
		if(QvtOperationalEnv.THIS.equals(varName)) {
			EClassifier varType = v.getType();
			if(varType instanceof Module) {
				Module referredThisModule = (Module)varType;
				ModuleInstance thisObj = evalEnv.getThisOfType(referredThisModule);
				// only if not null, the variables is part of the QVT type system.
				// otherwise, it may be a custom variable in non-QVT execution context, like ImperativeOCL 
				if(thisObj != null) {
					return thisObj;
				}
			}
		} else if(vd instanceof ModelParameter || value instanceof ModelParameter) {
			// Handling of 'self'->Param->ModelInstance in WHERE clauses
			if (value instanceof ModelParameter) {
				vd = (ModelParameter)value;
			}
			
			OperationalTransformation transformation = (OperationalTransformation) vd.eContainer();
			TransformationInstance transformationInstance = (TransformationInstance)evalEnv.getThisOfType(transformation);
			assert transformationInstance != null;
			
			ModelInstance model = transformationInstance.getModel((ModelParameter)vd);
			assert model != null;			
			return model;
		}
		
		return value;
	}
	
    /**
	 * Creates evaluation visitor for an non-transformation execution client.
	 * <p>
	 * No main entry operation is available, the execution flow is undefined and
	 * it is the responsibility of the executor client.
	 * </p>
	 * <code>Note:</code>Only helper operation can be executed on the resulting
	 * visitor by an external clients.
	 * 
	 * @see #executeHelperOperation(Helper, Object, List)
	 */
    public static QvtOperationalEvaluationVisitorImpl createNonTransformationExecutionContextVisitor(Context context, ImportToNonTransformCtxHelper importProvider) {    	
		QvtOperationalEnv env = (QvtOperationalEnv)QvtOperationalEnvFactory.INSTANCE.createEnvironment();
		QvtOperationalEvaluationEnv evalEnv = QvtOperationalEnvFactory.INSTANCE.createEvaluationEnvironment(context, null);
    	return createNonTransformationExecutionContextVisitor(env, evalEnv, importProvider);
    }
    
    public static QvtOperationalEvaluationVisitorImpl createNonTransformationExecutionContextVisitor(
    		QvtOperationalEnv env, QvtOperationalEvaluationEnv evalEnv, ImportToNonTransformCtxHelper importsProvider) {
    	
    	QvtOperationalEvaluationVisitorImpl visitor = new QvtOperationalEvaluationVisitorImpl(env, evalEnv);    	
    	InternalEvaluationEnv internalEvalEnv = evalEnv.getAdapter(InternalEvaluationEnv.class);
		
    	ThisInstanceResolver importsByAccess = importsProvider.createImportedInstanceResolver();
		internalEvalEnv.setThisResolver(importsByAccess);
		
		// initialize those module only	newly instantiated, therefore uninitialized yet
		for (ModuleInstance nextModuleToInit : importsProvider.getModuleInstances(false)) {
			// the call bellow makes sure that all of its imported modules gets initialized 
			// if not done already due to other dependent modules
			ModuleInstance.Internal internalModule = nextModuleToInit.getAdapter(ModuleInstance.Internal.class);
			// check if initialized as the module we iterate through might cross-refence, so 
			// get initialized in the meantime
			if(!internalModule.isInitialized()) {			
				visitor.initModule(nextModuleToInit, null);
			}
		}
		
		return visitor;
    }
        
    public static QvtOperationalEvaluationVisitor createVisitor(QvtOperationalEnv env, QvtOperationalEvaluationEnv evalEnv) {
    	return new QvtOperationalEvaluationVisitorImpl(env, evalEnv).createInterruptibleVisitor();
    }
            
	@Override
	public EvaluationEnvironment<EClassifier, EOperation, EStructuralFeature, EClass, EObject> getEvaluationEnvironment() {
		return myEvalEnv;
	}
	
	public void setOperationalEvaluationEnv(QvtOperationalEvaluationEnv evalEnv) {
		myEvalEnv = evalEnv;
    }
	
	protected void pushedStack(QvtOperationalEvaluationEnv env) {
	}	
	
	protected void poppedStack() {
	}
	

    public IContext getContext() {
        return getOperationalEvaluationEnv().getContext();
    }
    
    public void notifyAfterDeferredAssign(final AssignExp assignExp, Object leftValue) {
    	// do nothing special here, subclasses may customize
    }
    
	@Override
    public Object visitIfExp(IfExp<EClassifier> ie) {
		// get condition
		OCLExpression<EClassifier> condition = ie.getCondition();

		// evaluate condition
		Object condVal = visitExpression(condition);		
		if (isUndefined(condVal)) {
			return getInvalid();
		}
		
		Boolean condValBool = (Boolean) condVal;
		if (condValBool.booleanValue()) {
			return visitExpression(ie.getThenExpression());
        }
		if (ie.getElseExpression() != null) {
			return visitExpression(ie.getElseExpression());
		}
		return null;
	}

    @SuppressWarnings("unchecked")
	public Object visitAssignExp(final AssignExp assignExp) {
        QvtOperationalEvaluationEnv env = getOperationalEvaluationEnv();
		InternalEvaluationEnv internEnv = env.getAdapter(InternalEvaluationEnv.class);
        
    	boolean isDeferred = false;    	
        // TODO: modify the following code for more complex l-values
        OCLExpression<EClassifier> lValue = assignExp.getLeft();
        if (assignExp.getValue().size() == 1) {
        	isDeferred = QvtResolveUtil.hasDeferredRightSideValue(assignExp);
            if(isDeferred) {
                Object ownerObj = getAssignExpLValueOwner(lValue);
                if (ownerObj instanceof EObject) {
                    PropertyCallExp<EClassifier, EStructuralFeature> lvalueExp = (PropertyCallExp<EClassifier, EStructuralFeature>) assignExp.getLeft();
                    EStructuralFeature referredProperty = lvalueExp.getReferredProperty();
                    internEnv.setLastAssignmentLvalueEval(new EObjectEStructuralFeaturePair((EObject) ownerObj, referredProperty));
                }        	
            }        	
        }
                
        Object exprValue = null;
        for (OCLExpression<EClassifier> exp : assignExp.getValue()) {
        	exprValue = visitExpression(exp);
        }

        if(isDeferred) {
        	// the source of resolve calls has been evaluated above -> assignment of the left value is not executed now 
        	// but at deferred time in the end of the transformation
        	return null;
        }        
        
        if (lValue instanceof VariableExp<?, ?>) {
            VariableExp<EClassifier, EParameter> varExp = (VariableExp<EClassifier, EParameter>) lValue;
            Variable<EClassifier, EParameter> referredVariable = varExp.getReferredVariable();
            if (referredVariable != null) {
                String varName = referredVariable.getName();
                Object oldValue = getRuntimeValue(varName);
                EClassifier variableType = lValue.getType();
                if (variableType instanceof CollectionType && exprValue != getInvalid()) {
                    Collection<Object> leftOclCollection = null;
                	if (oldValue instanceof Collection) {
	                    Collection<Object> oldOclCollection = (Collection<Object>) oldValue;
	                    if (assignExp.isIsReset()) {
	                        leftOclCollection = EvaluationUtil.createNewCollectionOfSameKind(oldOclCollection);
	                    } else {
	                        leftOclCollection = oldOclCollection;
	                    }
                	}
                	else {
                		leftOclCollection = EvaluationUtil.createNewCollection((CollectionType<EClassifier, EOperation>) variableType);
                	}
                	
                    final CollectionKind leftCollectionKind = getCollectionKind(leftOclCollection);
					if (exprValue instanceof Collection) {
                        if(leftCollectionKind == CollectionKind.ORDERED_SET_LITERAL) {
                            // can't use CollectionUtil.union(), the result type is not OrderedSet              
                            LinkedHashSet<Object> values = new LinkedHashSet<Object>();
                            values.addAll(leftOclCollection);
                            values.addAll((Collection<?>)exprValue);
                            leftOclCollection = CollectionUtil.createNewCollection(((CollectionType<?, ?>)variableType).getKind(), values);
                        } else if(leftCollectionKind != null){
                        	leftOclCollection = CollectionUtil.union(leftOclCollection, (Collection<?>) exprValue);                        	
                        } else {
                        	// QVT mutable types
                        	leftOclCollection.addAll((Collection<?>)exprValue);
                        }
                    } else if (leftCollectionKind == CollectionKind.ORDERED_SET_LITERAL
                            || leftCollectionKind == CollectionKind.SEQUENCE_LITERAL) {
                        leftOclCollection = CollectionUtil.append(leftOclCollection, exprValue);
                    } else if(leftCollectionKind != null) {
                        leftOclCollection = CollectionUtil.including(leftOclCollection, exprValue);
                    } else {
                    	// QVT mutable types
                    	leftOclCollection.add(exprValue);
                    }

                    replaceInEnv(varName, leftOclCollection, variableType);
                } else {
                    replaceInEnv(varName, exprValue, variableType);
                }
            }
        } else if (lValue instanceof PropertyCallExp<?, ?>) {
            Object ownerObj = getAssignExpLValueOwner(lValue);
            if (ownerObj instanceof EObject) {
                EObject oldIP = setCurrentEnvInstructionPointer(assignExp);
                env.callSetter(
                        (EObject) ownerObj,
                        ((PropertyCallExp<EClassifier, EStructuralFeature>) lValue).getReferredProperty(),
                        exprValue, isUndefined(exprValue), assignExp.isIsReset());
                setCurrentEnvInstructionPointer(oldIP);
            }
        } else {
            throw new UnsupportedOperationException("Unsupported LValue type: " + ((lValue == null) ? null : lValue.getType())); //$NON-NLS-1$
        }

        return exprValue;
    }
    
    private Object getAssignExpLValueOwner(OCLExpression<EClassifier> lValue) {
        if (lValue instanceof PropertyCallExp<?, ?>) {
            @SuppressWarnings("unchecked")
            PropertyCallExp<EClassifier, EParameter> propertyCallExp = (PropertyCallExp<EClassifier, EParameter>) lValue;
            OCLExpression<EClassifier> sourceExp = propertyCallExp.getSource();
            Object owner = visitExpression(sourceExp);
                        
            // obtain correct owner for features of modules, which are possibly defined in an extended module that is not an explicit supertype (fixed by bug 302594/310991)
            if (owner instanceof ModuleInstance) {
            	
            	ModuleInstance moduleInstance = (ModuleInstance) owner;
            	
            	Object property = ((PropertyCallExp<?,?>) lValue).getReferredProperty();
            	
            	EClassifier containingClassifier = getUMLReflection().getOwningClassifier(property);
            	if (containingClassifier instanceof Module) {
            		owner = moduleInstance.getThisInstanceOf((Module) containingClassifier);
            	}	
            	
            }
           
            return owner;
        }
               
        return null;
    }

    private Object visitConfigProperty(EStructuralFeature configProperty) {
		setCurrentEnvInstructionPointer(configProperty);
		
    	IContext context = getOperationalEvaluationEnv().getContext();

        Object rawValue = context.getConfigProperty(configProperty.getName());
        EClassifier propertyType = configProperty.getEType();
        
        Object value = rawValue;
        if (!context.getConfigProperties().containsKey(configProperty.getName())) {
        	//leave non-specified configuration property as undefined
        	//value = EvaluationUtil.createInitialValue(propertyType, getEnvironment().getOCLStandardLibrary(), getEvaluationEnvironment());
        }
        else if(rawValue instanceof String && propertyType != getEnvironment().getOCLStandardLibrary().getString()) {
        	try {
        		value = ConversionUtils.createFromString(propertyType, (String) rawValue);
        	}
        	catch (IllegalArgumentException e) {
        		value = getInvalid();
        	}
        	
        }

        if(value == getInvalid()) {
        	// we failed to parse the value
        	throwQVTException(new QvtRuntimeException(NLS.bind(EvaluationMessages.QvtOperationalEvaluationVisitorImpl_invalidConfigPropertyValue, configProperty.getName(), rawValue)));
        }
        
        return value;
    }

    public Object visitEntryOperation(EntryOperation entryOperation) {    
        visitImperativeOperation(entryOperation);
        return new OperationCallResult(visitOperationBody(entryOperation.getBody()), getOperationalEvaluationEnv());
    }
    
    public Object visitHelper(Helper helper) {
        visitImperativeOperation(helper);
        
        if (helper.isIsBlackbox()) {
        	Object result = doVisitBlackboxOperation(helper);        	
        	return new OperationCallResult(result, getOperationalEvaluationEnv());
        }
        
        return new OperationCallResult(visitOperationBody(helper.getBody()), getOperationalEvaluationEnv());
    }

    public Object visitImperativeOperation(ImperativeOperation imperativeOperation) {

        List<Object> args = getOperationalEvaluationEnv().getOperationArgs();
        Iterator<Object> argIt = args.iterator();

        QvtOperationalEvaluationEnv env = getOperationalEvaluationEnv();
        for (EParameter nextParam : imperativeOperation.getEParameters()) {
            if (!argIt.hasNext()) {
                throw new IllegalArgumentException("arguments mismatch: got" + args + ", expected " + //$NON-NLS-1$ //$NON-NLS-2$
                        imperativeOperation.getEParameters());
            }

            VarParameter param = (VarParameter) nextParam;
            Object arg = argIt.next();

            addToEnv(param.getName(), arg, param.getEType());
        }

        EClassifier contextType = QvtOperationalParserUtil.getContextualType(imperativeOperation);
        if (contextType != null) {
            addToEnv(Environment.SELF_VARIABLE_NAME, env.getOperationSelf(), contextType);
        }

		pushedStack(getOperationalEvaluationEnv());
        return null;
    }
    
    private Object doVisitBlackboxOperation(ImperativeOperation operation) {
    	
    	assert operation.isIsBlackbox() : "Blackbox operation expected"; //$NON-NLS-1$
    	
    	EcoreEnvironment moduleEnv = ASTBindingHelper.resolveEnvironment((ASTNode) operation.eContainer());
    	if (false == moduleEnv instanceof QvtOperationalModuleEnv) {
    		moduleEnv = ASTBindingHelper.getEnvironment(operation.eContainer(), QvtOperationalModuleEnv.class);
    	}
    	
		Collection<CallHandler> handlers = BlackboxRegistry.INSTANCE.getBlackboxCallHandler(operation,
				//getOperationalEnv().getAdapter(QvtOperationalModuleEnv.class));
				(QvtOperationalModuleEnv) moduleEnv);
    	if (handlers.isEmpty()) {
        	throwQVTException(new QvtRuntimeException(NLS.bind(EvaluationMessages.NoBlackboxOperationFound,
        			QvtOperationalParserUtil.safeGetMappingQualifiedName(getOperationalEnv(), operation))));
    	}
    	if (handlers.size() > 1) {
        	throwQVTException(new QvtRuntimeException(NLS.bind(EvaluationMessages.AmbiguousBlackboxOperationFound,
        			QvtOperationalParserUtil.safeGetMappingQualifiedName(getOperationalEnv(), operation))));
    	}

    	QvtOperationalEvaluationEnv evalEnv = getOperationalEvaluationEnv();
		return handlers.iterator().next().invoke(evalEnv.getThisOfType(QvtOperationalParserUtil.getOwningModule(operation)), evalEnv.getOperationSelf(), evalEnv.getOperationArgs().toArray(), evalEnv);
    }

    public Object visitLibrary(Library library) {
        return null;
    }

    public Object visitLocalProperty(EStructuralFeature property) {
    	OCLExpression<EClassifier> initExp = QvtOperationalParserUtil.getInitExpression(property);
    	if(initExp != null) {
    		return visitExpression(initExp);
    	}
    	
    	return null;
    }
    
	public Object visitContextualProperty(ContextualProperty contextualProperty) {
		if(contextualProperty.getInitExpression() != null) {
			return visitExpression(contextualProperty.getInitExpression());
		}
		return null;
	}
    
    protected boolean isWhenPreconditionSatisfied(MappingOperation mappingOperation) {
    	for (OCLExpression<EClassifier> nextCond : mappingOperation.getWhen()) {
    		if(!Boolean.TRUE.equals(visitExpression(nextCond))) {
    			return false;
    		}
		}
    	return true;
    }
    
    private void setupInitialResultVariables(MappingBody mappingBody) {
    	ImperativeOperation operation = mappingBody.getOperation();
    	QvtOperationalEvaluationEnv evalEnv = getOperationalEvaluationEnv();
		// Note: the variables for result parameters may not be set or existing yet
		// define variables if not done already by the reusing mapping caller so
    	// avoid overriding values    	
    	for (VarParameter resultParam : operation.getResult()) {    		
    		if(evalEnv.getValueOf(resultParam.getName()) == null) {
    			replaceInEnv(resultParam.getName(), null, resultParam.getEType());    			
    		}
		}

    	if(operation.getResult().size() > 1) {
    		if(evalEnv.getValueOf(Environment.RESULT_VARIABLE_NAME) == null) {
    			replaceInEnv(Environment.RESULT_VARIABLE_NAME, null, operation.getEType());
    		}
    	}    	
    }
    
    public Object visitMappingBody(MappingBody mappingBody) {
		QvtOperationalEvaluationEnv evalEnv = getOperationalEvaluationEnv();
        MappingOperation currentMappingCalled = (MappingOperation) mappingBody.getOperation();
		
		setupInitialResultVariables(mappingBody);
    	
        for (OCLExpression<EClassifier> initExp : mappingBody.getInitSection()) {
        	visitExpression(initExp);
        }
                
        if(!mappingBody.getInitSection().isEmpty()) {
        	// setup a meaningful IP after init section to avoid pointing to the last expression of init 
        	// section, so in case of error a proper error location can be computed        	
        	setCurrentEnvInstructionPointer(currentMappingCalled);
        }
        
		Object result = createOrGetResult(currentMappingCalled);
		
		// call inherited mappings
		if(!currentMappingCalled.getInherited().isEmpty()) {
			for (MappingOperation extendedMapping : currentMappingCalled.getInherited()) {
				
				// consider overriding mapping
	    		ImperativeOperation overridingOper = EvaluationUtil.getOverridingOperation(getOperationalEvaluationEnv(), extendedMapping);
	    		if (overridingOper instanceof MappingOperation) {
	    			extendedMapping = (MappingOperation) overridingOper;
	    		}
				
				executeImperativeOperation(extendedMapping, evalEnv.getOperationSelf(), evalEnv.getOperationArgs(), true);				
			}
		}

        visitOperationBody(mappingBody);

        // TODO investigate possibility to modify result
        for (OCLExpression<EClassifier> endExp : mappingBody.getEndSection()) {
        	visitExpression(endExp);
        }
        
		// call merged mappings
		callMergedMappings(currentMappingCalled, evalEnv);
		
		// result may have changed in body, end section, or merged mappings, so retrieve it again (fixed by bug 388325)
		result = getRuntimeValue(Environment.RESULT_VARIABLE_NAME);

        return result;
    }
    
    private void callMergedMappings(MappingOperation mappingOperation, QvtOperationalEvaluationEnv evalEnv) {
		for (MappingOperation extendedMapping : mappingOperation.getMerged()) {
			// consider overriding mapping
    		ImperativeOperation overridingOper = EvaluationUtil.getOverridingOperation(getOperationalEvaluationEnv(), extendedMapping);
    		if (overridingOper instanceof MappingOperation) {
    			extendedMapping = (MappingOperation) overridingOper;
    		}
			
			executeImperativeOperation(extendedMapping, evalEnv.getOperationSelf(), evalEnv.getOperationArgs(), true);				
		}
    }

    public Object visitMappingCallExp(MappingCallExp mappingCallExp) {
        return visitOperationCallExp(mappingCallExp);
    }

    @Override
    public Object visitOperationCallExp(OperationCallExp<EClassifier, EOperation> operationCallExp) {
    	// TODO - review the note bellow
    	// set IP of the current stack (represented by the top operation fEnv)
    	// to the this operation call in order to refeflect this call position 
    	// in possible QVT stack, in case an exception is thrown 
        EObject oldIP = setCurrentEnvInstructionPointer(operationCallExp);
        Object result = doVisitOperationCallExp(operationCallExp);    	        
        setCurrentEnvInstructionPointer(oldIP);
        return result;
    }    
    
    protected Object doVisitOperationCallExp(OperationCallExp<EClassifier, EOperation> operationCallExp) {
        EOperation referredOperation = operationCallExp.getReferredOperation();
                
        boolean isImperative = QvtOperationalUtil.isImperativeOperation(referredOperation);
		if (isImperative && !CallHandler.Access.hasHandler(referredOperation)) {
			Object source = visitExpression(operationCallExp.getSource());
			if (((ImperativeOperation) referredOperation).getContext() != null) {
				source = doImplicitListCoercion(((ImperativeOperation) referredOperation).getContext().getEType(), source);
			}
            List<Object> args = makeArgs(operationCallExp);
            // does not make sense continue at all, call on null or invalid results in invalid 
        	if(isUndefined(source)) {
        		return getInvalid();
        	}

            ImperativeOperation method = null;
            if (QvtOperationalParserUtil.isOverloadableMapping(referredOperation, getOperationalEnv())) {                
        		EOperation actualOperation = findOperationByActualSourceType(source, referredOperation);
				if(actualOperation instanceof ImperativeOperation) { 
					method = (ImperativeOperation) actualOperation;
				}
            }
            
    		if((method == null) && referredOperation instanceof ImperativeOperation) {
    			// we can't dispatch non-imperative as we already evaluated the source 
    			method = (ImperativeOperation)referredOperation;
    		}

            if(method != null) {          
            	if(operationCallExp instanceof ImperativeCallExp) {
            		ImperativeCallExp imperativeCall = (ImperativeCallExp) operationCallExp;
            		if(imperativeCall.isIsVirtual()) {
            			ImperativeOperation overridingOper = EvaluationUtil.getOverridingOperation(getOperationalEvaluationEnv(), method);
            			if(overridingOper != null) {
            				method = overridingOper;
            			}
            		}
            	}

            	OperationCallResult opResult = executeImperativeOperation(method, source, args, false);
            	if (operationCallExp instanceof MappingCallExp && opResult instanceof MappingCallResult) {
            		if (((MappingCallExp) operationCallExp).isIsStrict()
            				&& ((MappingCallResult) opResult).isPreconditionFailed()) {
            			throwQVTException(new QvtAssertionFailed(NLS.bind(EvaluationMessages.MappingPreconditionFailed, method.getName())));
            		}
            	}
            	
            	return doImplicitListCoercion(referredOperation.getEType(), opResult.myResult);
            }
        }

        Object result = null;
        try {
        	result = super.visitOperationCallExp(operationCallExp);
        }
        catch (QvtRuntimeException e) {
        	throw e;
		}
        catch (RuntimeException ex) {
            //Logger.getLogger().log(Logger.WARNING, "QvtEvaluator: failed to evaluate oclOperationCall", ex);//$NON-NLS-1$
        	result = getInvalid();
        }
        
        return result;
    }

    /**
	 * Finds operation based on the actual type of the source object as per
	 * virtual call semantics.
	 * 
	 * @param source
	 *            the self instance of the contextual type
	 * @param referredOperation
	 *            the operation referred by the call expresion in the AST
	 * @return the actual operation to call, which is either the passed referred
	 *         operation or another one defined in the bottom-most class in the
	 *         type hierarchy of the source object
	 */
	private EOperation findOperationByActualSourceType(Object source, EOperation referredOperation) {
		EOperation actualOperation = referredOperation;
		IVirtualOperationTable vTable = getVirtualTable(referredOperation);
		if(vTable != null) {
			EClassifier sourceEClass = getEvaluationEnvironment().getType(source);
			if(sourceEClass != null) {
				InternalEvaluationEnv internEnv = getOperationalEvaluationEnv().getAdapter(InternalEvaluationEnv.class);
				EOperation oper = vTable.lookupActualOperation(sourceEClass, getEnvironment(), internEnv);
				if(oper != null) {
					actualOperation = oper;
				}
			}
		}
		return actualOperation;
	}
	
	/**
	 * Performs implicit coercion of instances of List type into Sequence type and vice versa.
	 * See: https://bugs.eclipse.org/bugs/show_bug.cgi?id=418961 
	 * @param declaredType Expected type of expression
	 * @param actualValue Actual value of expression
	 * @return In case coercion is needed then converted value is returned. Otherwise returns 'actualValue'.
	 */
	@SuppressWarnings("unchecked")
	private Object doImplicitListCoercion(EClassifier declaredType, Object actualValue) {
		if (declaredType instanceof CollectionType<?, ?> && actualValue instanceof Collection<?>) {
			if (declaredType.eClass() == ImperativeOCLPackage.eINSTANCE.getListType() && false == actualValue instanceof MutableList<?>) {
				Collection<Object> newCollection = EvaluationUtil.createNewCollection((CollectionType<EClassifier, EOperation>) declaredType);
				newCollection.addAll((Collection<Object>) actualValue);
				return newCollection;
			}
			if (declaredType.eClass() == EcorePackage.eINSTANCE.getSequenceType() && actualValue instanceof MutableList<?>) {
				Collection<Object> newCollection = EvaluationUtil.createNewCollection((CollectionType<EClassifier, EOperation>) declaredType);
				newCollection.addAll((Collection<Object>) actualValue);
				return newCollection;
			}
		}
		return actualValue;
	}
        
    @Override
    public Object visitEnumLiteralExp(EnumLiteralExp<EClassifier, EEnumLiteral> el) {
        return el.getReferredEnumLiteral().getInstance();
    }

    /**
	 * @return result object or <code>null</code> in case that no result
	 *         variable is declared and <code>OclInvalid</code> in case the
	 *         precondition failed and the body was not executed.
	 */
    public Object visitMappingOperation(MappingOperation mappingOperation) {
        visitImperativeOperation(mappingOperation);

        QvtOperationalEvaluationEnv evalEnv = getOperationalEvaluationEnv();
		if (!isWhenPreconditionSatisfied(mappingOperation)) {
        	// return Invalid, to indicate precondition failure to the caller. It is used instead of
        	// of 'null' as it is a legal value for no result inout mapping, even
        	// the precondition holds
 
        	return new MappingCallResult(null, evalEnv, MappingCallResult.PRECOND_FAILED);
        }
				
        // check the traces whether the relation already holds
        TraceRecord traceRecord = TraceUtil.getTraceRecord(evalEnv, mappingOperation);
        if (traceRecord != null) {
        	return new MappingCallResult(TraceUtil.fetchResultFromTrace(evalEnv, traceRecord), evalEnv, MappingCallResult.FETCHED_FROM_TRACE);
        }
        
        if(!mappingOperation.getDisjunct().isEmpty()) {
			return dispatchDisjunctMapping(mappingOperation);
		}
        
        if (mappingOperation.isIsBlackbox()) {        	
        	Object result = doVisitBlackboxOperation(mappingOperation);        	
        	if (isUndefined(result)) {
        		throwQVTException(new QvtRuntimeException(NLS.bind(EvaluationMessages.BlackboxMappingFailedToAssignResult,
        				QvtOperationalParserUtil.safeGetMappingQualifiedName(getOperationalEnv(), mappingOperation))));
        	}
        	
			replaceInEnv(Environment.RESULT_VARIABLE_NAME, result, mappingOperation.getEType());
	        TraceUtil.addTraceRecord(getOperationalEvaluationEnv(), mappingOperation);
	        
	        // call merged mappings
			callMergedMappings(mappingOperation, evalEnv);
	        
	        return new MappingCallResult(result, evalEnv, MappingCallResult.BODY_EXECUTED);        	
        }
                                        		
		return new MappingCallResult(((OperationBodyImpl) mappingOperation.getBody()).accept(getVisitor()), evalEnv,
				MappingCallResult.BODY_EXECUTED);
    }

    public Object execute(OperationalTransformation transformation) throws QvtRuntimeException {
    	try {
    		return doVisitTransformation(transformation);
    	} finally {
    		IntermediatePropertyModelAdapter.cleanup(transformation);
		}    		
    }
    
    public Object visitModule(Module module) {
        if (module instanceof OperationalTransformation == false) {
            throw new IllegalArgumentException(NLS.bind(EvaluationMessages.ExtendedOclEvaluatorVisitorImpl_ModuleNotExecutable, module.getName()));
        }
    	        
		try {
			return doVisitTransformation((OperationalTransformation) module);
		} 
		catch (QvtRuntimeException e) {
			StringWriter strWriter = new StringWriter();
			PrintWriter printWriter = new PrintWriter(strWriter);
			e.printQvtStackTrace(printWriter);

			Log logger = getContext().getLog();
			logger.log(EvaluationMessages.TerminatingExecution);
			logger.log(strWriter.getBuffer().toString());
			
			throw e;
		} finally {
			IntermediatePropertyModelAdapter.cleanup(module);
		}
    }        
        
    /**
	 * Executes the given helper operation with actual arguments passed.
	 * 
	 * @param method
	 *            the helper operation to execute
	 * @param self
	 *            the contextual instance in case of contextual operation,
	 *            otherwise the default instance of the module which defines the
	 *            called operation
	 * @param args
	 *            the actual parameter values
	 * @return return the value directly returned by the operation
	 */
	public Object executeHelperOperation(Helper method, Object self, List<Object> args) {
		Helper actualHelper = method;
		EOperation actualOperation = findOperationByActualSourceType(self, method);
		if(actualOperation instanceof Helper) { 
			actualHelper = (Helper) actualOperation;			
		} else {
			// Remark - the case when the actual operation is not imperative but 
			// a meta-model operation the virtual call will be dispatched by using 			
			// a normal operation call
			return getEvaluationEnvironment().callOperation(method, -1, self, args.toArray(new Object[args.size()]));
		}
		
		OperationCallResult result = executeImperativeOperation(actualHelper, self, args, false);
		return result.myResult;
	}
    
	@SuppressWarnings("unchecked")
	public Object visitInstantiationExp(InstantiationExp objectExp) { 
		// should instantiate the module transformation
		EClass _class = objectExp.getInstantiatedClass();
		if (_class instanceof OperationalTransformation) {
				
			EList<org.eclipse.ocl.ecore.OCLExpression> formalArguments = objectExp.getArgument();		
			List<ModelInstance> actualArguments = new ArrayList<ModelInstance>(formalArguments.size());
	
			for (OCLExpression<EClassifier> nextArg : formalArguments) {
				Object argVal = visitExpression(nextArg);	
				if(argVal instanceof ModelInstance == false) {
					throwQVTException(new QvtRuntimeException(EvaluationMessages.QvtOperationalEvaluationVisitorImpl_UndefModelParamInTransf));
				}
				ModelInstance modelInstance = (ModelInstance) argVal;
				actualArguments.add(modelInstance); 
			}
	
			OperationalTransformation targetTransf = (OperationalTransformation)_class;
			QvtOperationalEvaluationEnv currentEnv = getOperationalEvaluationEnv();		
			// create a nested environment for constructor invocation representing 
			// the root environment of explicitly called transformation		
			// Empty default context, no configuration property is available
			// Remark: Can we set configuration property in the concrete syntax on the explicit transf object.
			// bug 416584: Now we need to access configuration properties of non-entry modules
			Context nestedContext = EvaluationUtil.createAggregatedContext(currentEnv);
			Map<String,Object> configProps = getOperationalEvaluationEnv().getContext().getConfigProperties(); 
			for (String propName : configProps.keySet()) {
				nestedContext.setConfigProperty(propName, configProps.get(propName));
			}
			
			QvtOperationalEnvFactory envFactory = getOperationalEnv().getFactory();
			QvtOperationalEvaluationEnv nestedEvalEnv = envFactory.createEvaluationEnvironment(nestedContext, null);
			
			//bug 392153: reuse existing trace for nested environment
			Trace trace = currentEnv.getAdapter(InternalEvaluationEnv.class).getTraces();
			nestedEvalEnv.getAdapter(InternalEvaluationEnv.class).setTraces(trace);
			
			// send arguments into the entry operation
			nestedEvalEnv.getOperationArgs().addAll(actualArguments);
			// Use per transformation instance visitor 
			InternalEvaluator nestedVisitor = createNestedEvaluationVisitor(this, nestedEvalEnv).createInterruptibleVisitor();
			try {
				setOperationalEvaluationEnv(nestedEvalEnv);
				
				ModuleInstance moduleInstance = nestedVisitor.callTransformationImplicitConstructor(targetTransf, actualArguments);
				//nestedEvalEnv.add(QvtOperationalEnv.THIS, moduleInstance);
				moduleInstance.getAdapter(InternalTransformation.class).setEntryOperationHandler(createEntryOperationHandler(nestedVisitor));
				return moduleInstance;
			} finally {
				setOperationalEvaluationEnv(currentEnv);
			}
		}
		else {
	        Object owner = createInstance(objectExp.getType(), (ModelParameter) objectExp.getExtent());

			EList<org.eclipse.ocl.ecore.OCLExpression> formalArguments = objectExp.getArgument();		
			List<Object> actualArguments = new ArrayList<Object>(formalArguments.size());
	
			for (OCLExpression<EClassifier> nextArg : formalArguments) {
				Object argVal = visitExpression(nextArg);	
				actualArguments.add(argVal); 
			}

			Adapter adapter = EcoreUtil.getAdapter(objectExp.eAdapters(), ConstructorOperationAdapter.class);
			if (adapter != null) {
				Constructor constructorOp = ((ConstructorOperationAdapter) adapter).getReferredConstructor();
				
				for (int i = 0, in = constructorOp.getEParameters().size(); i < in; ++i) {
					actualArguments.set(i, doImplicitListCoercion(constructorOp.getEParameters().get(i).getEType(), actualArguments.get(i)));
				}

				executeImperativeOperation(constructorOp, owner, actualArguments, false);
			}
			else {
				if (objectExp.getArgument().isEmpty()) {
					// it's OK since default constructor is called
				}
				else if (objectExp.getEType() instanceof CollectionType<?,?> && owner instanceof Collection<?>) {
					((Collection<Object>) owner).addAll(actualArguments);
				}
				else {
					throwQVTException(new QvtRuntimeException("Undefined constructor is called")); //$NON-NLS-1$
				}
			}
			
	        return owner;
		}
	}
	
	public TransformationInstance callTransformationImplicitConstructor(OperationalTransformation transformation, List<ModelInstance> transfArgs) {
    	ModuleInstanceFactory eFactory = (ModuleInstanceFactory)transformation.getEFactoryInstance();
		assert eFactory != null : "Module class must have factory"; //$NON-NLS-1$
		
		TransformationInstance instance = (TransformationInstance) eFactory.create(transformation);
		// Note: need to make the main executed transf available via this
		// so all super module have access to env::getCurrentTransformation()
		getEvaluationEnvironment().add(QvtOperationalEnv.THIS, instance);
		
		ModelParameterHelper modelParameters = new ModelParameterHelper(transformation, transfArgs);
		initModule(instance, modelParameters);
		// we are initialized set back the pointer to the module 
		setCurrentEnvInstructionPointer(transformation);		
		return instance;
	}	
	
	// FIXME - review the strange case of having various return types
	private Object doVisitTransformation(OperationalTransformation transformation) {
        ImperativeOperation entryPoint = QvtOperationalParserUtil.getMainOperation(transformation);        
        if (entryPoint == null) {
            throw new IllegalArgumentException(NLS.bind(EvaluationMessages.ExtendedOclEvaluatorVisitorImpl_ModuleNotExecutable, transformation.getName()));
        }

        QvtOperationalEvaluationEnv evaluationEnv = getOperationalEvaluationEnv();        
		List<ModelInstance> modelArgs = EvaluationUtil.getTransfromationModelArguments(evaluationEnv, transformation);		

		TransformationInstance moduleInstance = callTransformationImplicitConstructor(transformation, modelArgs);    	
		CallHandler entryOperationHandler = createEntryOperationHandler(this);
		InternalTransformation internTransf = moduleInstance.getAdapter(InternalTransformation.class);		
		internTransf.setEntryOperationHandler(entryOperationHandler);
        			
        // call main entry operation
        OperationCallResult callResult = (OperationCallResult) entryOperationHandler.invoke(
        		null, moduleInstance,
        		makeEntryOperationArgs(entryPoint, 
        		transformation).toArray(), evaluationEnv);
        
        QvtEvaluationResult evalResult = EvaluationUtil.createEvaluationResult(callResult.myEvalEnv);
        
        if (evalResult.getModelExtents().isEmpty()) {
            if (callResult.myResult instanceof EObject) {
                // compatibility reason, make the main() operation return value available in an extent
            	ModelParameterExtent modelParameter = new ModelParameterExtent(
            			Collections.singletonList((EObject) callResult.myResult), null, null);
                evalResult.getModelExtents().add(modelParameter.getContents());
            } else {
                return callResult.myResult;
            }
        }
        
        return evalResult;
    }

	private static CallHandler createEntryOperationHandler(final InternalEvaluator evaluator) {
		return new CallHandler() {
			public Object invoke(ModuleInstance module, Object source, Object[] args, QvtOperationalEvaluationEnv evalEnv) {
				TransformationInstance transformation = (TransformationInstance) source;				
				try {
					return evaluator.runMainEntry(transformation.getTransformation(), Arrays.asList(args));
				} finally {
					transformation.getAdapter(InternalTransformation.class).dispose();
				}
			}
		};
	}

	protected void processDeferredTasks() {
		InternalEvaluationEnv internalEvalEnv = getOperationalEvaluationEnv().getAdapter(InternalEvaluationEnv.class);
		internalEvalEnv.processDeferredTasks();
	}

	public Object visitModuleImport(ModuleImport moduleImport) {
        return null;
    }

    public Object visitObjectExp(ObjectExp objectExp) {
        InternalEvaluationEnv internEnv = getOperationalEvaluationEnv().getAdapter(InternalEvaluationEnv.class);
        internEnv.setCurrentIP(objectExp);
    	
        Object owner = getOutOwner(objectExp);

    	if(objectExp.getBody() != null) {
    		EList<org.eclipse.ocl.ecore.OCLExpression> contents = objectExp.getBody().getContent();        
	        for (OCLExpression<EClassifier> exp : contents) {
	        	visitExpression(exp);    	
	        }
    	}
    	
    	// owner may have changed in body content, so retrieve it again (fixed by bug 388325)
    	owner = getOutOwner(objectExp);
    	
        if (getOperationalEnv().isTemporaryElement(objectExp.getName())) {
            getOperationalEvaluationEnv().remove(objectExp.getName());
        }

        return owner;
    }

    public Object visitReturnExp(ReturnExp returnExp) {
    	Object value = null;
    	OCLExpression<EClassifier> valueExp = returnExp.getValue();
    	if(valueExp != null) {
    		value = visitExpression(valueExp);
    	}
    	
		OperationBody body = QvtOperationalParserUtil.findParentElement(returnExp, OperationBody.class);
		if(body != null) {
			EList<org.eclipse.ocl.ecore.OCLExpression> content = body.getContent(); 
			if(!content.isEmpty() && content.get(content.size() - 1) == returnExp) {
				// return is the last expression in the body, simply return the value
				return value;
			}
		}    	

		// TODO - analyze more complex structured execution flow and
		// avoid the cost of exception throwing 
		throw new ReturnExpEvent(value, getOperationalEvaluationEnv());
    }
    
    public Object visitOperationBody(OperationBody operationBody) {
        Object result = null;
        for (OCLExpression<EClassifier> exp : operationBody.getContent()) {
        	result = visitExpression(exp);
        }
        
        ImperativeOperation operation = operationBody.getOperation();
        if(operation.getResult().size() > 1) {
        	return createTupleResult(operation);
        }
        return result;
    }

    public Object visitVarParameter(VarParameter varParameter) {
        return null;
    }

    public Object visitVariableInitExp(VariableInitExp variableInitExp) {
        org.eclipse.ocl.ecore.Variable referredVariable = variableInitExp.getReferredVariable();
        OCLExpression<EClassifier> initExpression = referredVariable.getInitExpression();
        Object value = null;
		if(initExpression != null) {
			value = visitExpression(initExpression);
			// check that collection is initialized to empty collection in case of 'null' 
			if(value == null && referredVariable.getType() instanceof CollectionType<?, ?>) {
				value = EvaluationUtil.createInitialValue(referredVariable.getType(), getQVTVisitor().getEnvironment().getOCLStandardLibrary(),
						getQVTVisitor().getEvaluationEnvironment());
			}
		} else { 
			value = EvaluationUtil.createInitialValue(referredVariable.getType(), getQVTVisitor().getEnvironment().getOCLStandardLibrary(),
					getQVTVisitor().getEvaluationEnvironment());
		}
		
        replaceInEnv(referredVariable.getName(), value, variableInitExp.getType());
        
        return variableInitExp.isWithResult() ? value : null;
    }

    public Object visitBlockExp(BlockExp blockExp) {
        return visitBlockExpImpl(blockExp.getBody(), blockExp.eContainer() instanceof ImperativeOperation);
    }

    private Object visitBlockExpImpl(EList<org.eclipse.ocl.ecore.OCLExpression> expList, boolean isInImperativeOper) {
    	List<String> scopeVars = null;
    	
        for (OCLExpression<EClassifier> exp : expList) {
        	if((exp instanceof VariableInitExp) && !isInImperativeOper) {
        		if(scopeVars == null) {
        			scopeVars = new LinkedList<String>();
        		}
        		VariableInitExp varInitExp = (VariableInitExp) exp;
        		scopeVars.add(varInitExp.getName());
        	}
        	
        	visitExpression(exp);
        }
        
        if(scopeVars != null) {
			EvaluationEnvironment<EClassifier, EOperation, EStructuralFeature, EClass, EObject> evalEnv = getEvaluationEnvironment();        	
        	for (String varName : scopeVars) {        		
				evalEnv.remove(varName);
			}
        }
        
        return null;
    }
    
    public Object visitComputeExp(ComputeExp computeExp) {
        Variable<EClassifier, EParameter> returnedElement = computeExp.getReturnedElement();
        Object initExpressionValue = null;
        OCLExpression<EClassifier> initExpression = returnedElement.getInitExpression();
        if (initExpression != null) {
        	initExpressionValue = visitExpression(initExpression);
        }
        replaceInEnv(returnedElement.getName(), initExpressionValue, returnedElement.getType());
        
        visitExpression(computeExp.getBody());

        return getEvaluationEnvironment().remove(returnedElement.getName());
    }

    public Object visitWhileExp(WhileExp whileExp) {
        while (true) {
        	Object condition = visitExpression(whileExp.getCondition());
        	if (Boolean.TRUE.equals(condition)) {
            	try {
            		visitExpression(whileExp.getBody());
            	}
            	catch (QvtTransitionReachedException ex) {
            		if (ex.getReason() == QvtTransitionReachedException.REASON_BREAK) {
            			break;
            		}
            		if (ex.getReason() == QvtTransitionReachedException.REASON_CONTINUE) {
            			continue;
            		}
            	}
            } else {
                break;
            }
        }
        
        return null;
    }
    
    private static class SwitchAltExpResult {
    	public Object myCondition;
    	public Object myResult;
    }
    
    public Object visitAltExp(AltExp switchAltExp) {
		SwitchAltExpResult result = new SwitchAltExpResult();
		result.myCondition = visitExpression(switchAltExp.getCondition());
		if (Boolean.TRUE.equals(result.myCondition)) {
			result.myResult = visitExpression(switchAltExp.getBody());
		}
		return result;
    }

    public Object visitSwitchExp(SwitchExp switchExp) {
        for (AltExp altExp : switchExp.getAlternativePart()) {
        	Object altResult = visitExpression(altExp);	
        	if (altResult instanceof SwitchAltExpResult) {
            	if (Boolean.TRUE.equals(((SwitchAltExpResult) altResult).myCondition)) {
                    return ((SwitchAltExpResult) altResult).myResult;
                }
        	}
        	else if (Boolean.TRUE.equals(altResult)) {
                return null;
            }
        }
        OCLExpression<EClassifier> elsePart = switchExp.getElsePart();
        if (elsePart != null) {
        	return visitExpression(elsePart);
        }
        return null;
    }

    /* resolve expressions family */

    public Object visitResolveExp(ResolveExp resolveExp) {
    	if (resolveExp.isIsDeferred()) {
    		InternalEvaluationEnv internalEvalEnv = getOperationalEvaluationEnv().getAdapter(InternalEvaluationEnv.class);
    		if(!internalEvalEnv.isDeferredExecution()) {	        	
	            LateResolveTask lateResolveTask = new LateResolveTask(resolveExp, internalEvalEnv.getLastAssignmentLvalueEval(), getQVTVisitor(), getOperationalEvaluationEnv(), this);
	            internalEvalEnv.addDeferredTask(lateResolveTask);
	            return null;
    		}
        }
        return QvtResolveUtil.resolveNow(resolveExp, this, getOperationalEvaluationEnv());
    }
    
    public Object visitResolveInExp(ResolveInExp resolveInExp) {
        if (resolveInExp.isIsDeferred()) {
        	InternalEvaluationEnv internalEvalEnv = getOperationalEvaluationEnv().getAdapter(InternalEvaluationEnv.class);        	
        	if(!internalEvalEnv.isDeferredExecution()) {
	            LateResolveInTask lateResolveInTask = new LateResolveInTask(resolveInExp, internalEvalEnv.getLastAssignmentLvalueEval(), getQVTVisitor(), getOperationalEvaluationEnv(), this);
	            internalEvalEnv.addDeferredTask(lateResolveInTask);            
	            return null;
        	}
        }        
        return QvtResolveUtil.resolveInNow(resolveInExp, this, getOperationalEvaluationEnv());
    }
    
	public Object visitModelType(ModelType modelType) {
		return null;
	}
    
	public Object visitLogExp(LogExp logExp) {
		doVisitLogExp(logExp, getContext().getLog(), null);
		return null;
	}
	
	private String doVisitLogExp(LogExp logExp, Log logger, String messagePrefix) {
		if(logExp.getCondition() != null && !Boolean.TRUE.equals(visitExpression(logExp.getCondition()))) {
			return null;
		}
		InternalEvaluationEnv internalEnv = getOperationalEvaluationEnv().getAdapter(InternalEvaluationEnv.class);		
		Object invalid = internalEnv.getInvalid();
		String invalidRepr = "<Invalid>"; //$NON-NLS-1$
		// process logging level
		Integer level = null;
		EList<OCLExpression<EClassifier>> args = logExp.getArgument();
		if(args.size() > 2) {
			Object levelObj = visitExpression(args.get(2));
			level = NumberConversions.strictConvertNumber(levelObj, Integer.class);
		}

		Object message = visitExpression(args.get(0));
		if(message == null) {
			message = "<null>"; //$NON-NLS-1$
		} else if(message == invalid) {
			message = invalidRepr;
		}
		
		Object logEntry = message;
		if(messagePrefix != null) {
			logEntry = messagePrefix + " : " + message; //$NON-NLS-1$
		}

		Object element = null;
		Object formatedElement = null;
		if(args.size() > 1) {
			element = visitExpression(args.get(1));
			if(element == invalid) {
				formatedElement = invalidRepr;
			} else {
				formatedElement = EvaluationUtil.formatLoggedElement(element);
			}
		}

		if(level == null) {
			if(element == null) {
				logger.log(String.valueOf(logEntry));
			} else {		
				logger.log(String.valueOf(logEntry), formatedElement);
			}
		} else {
			if(element == null) {
				logger.log(level, String.valueOf(logEntry));
			} else {		
				logger.log(level, String.valueOf(logEntry), formatedElement);
			}			
		}
		
		return message.toString();
	}
	
	public Object visitAssertExp(AssertExp assertExp) {		
		Object assertionValue = visitExpression(assertExp.getAssertion());
		
		if(!Boolean.TRUE.equals(assertionValue)) {	
			InternalEvaluationEnv internEvalEnv = getOperationalEvaluationEnv().getAdapter(InternalEvaluationEnv.class);
			Module currentModule = internEvalEnv.getCurrentModule().getModule();
			IModuleSourceInfo moduleSource = ASTBindingHelper.getModuleSourceBinding(currentModule);
			
			String source;
			if(moduleSource != null) {
				source = moduleSource.getSourceURI().lastSegment();
			} else {
				source = EvaluationMessages.UknownSourceLabel;				
			}

			StringBuilder locationBuf = new StringBuilder(source);
			if(assertExp.getStartPosition() >= 0 && moduleSource != null) {
				int lineNum = moduleSource.getLineNumberProvider().getLineNumber(assertExp.getStartPosition());
				locationBuf.append(':').append(lineNum);
			}
							
			String message = NLS.bind(EvaluationMessages.AssertFailedMessage, assertExp.getSeverity(), locationBuf.toString());				
			Log logger = getContext().getLog();
			
			String logMessage = null;
			if(assertExp.getLog() != null) {
				logMessage = doVisitLogExp(assertExp.getLog(), logger, message);
			} else {
				logger.log(message);				
			}
			
			if(SeverityKind.FATAL.equals(assertExp.getSeverity())) {
				String msg = (logMessage == null ? EvaluationMessages.FatalAssertionFailed : logMessage);
				throwQVTException(new QvtAssertionFailed(msg));
			}		
				
		}			
		
		return null;
	}
	
    public Object visitImperativeLoopExp(ImperativeLoopExp imperativeLoopExp) {
        throw new UnsupportedOperationException();
    }
    
    public Object visitForExp(ForExp forExp) {
    	Object sourceValue = visitExpression(forExp.getSource());
        
        if (!isUndefined(sourceValue)) {
            // generate a name for the result variable and add it to the environment
            String resultName = generateName();
            getEvaluationEnvironment().add(resultName, null);
            
            Collection<?> sourceCollection = (Collection<?>) sourceValue;
            // get the list of ocl iterators
            List<Variable<EClassifier, EParameter>> iterators = forExp.getIterator();
            // get the condition expression
            OCLExpression<EClassifier> condition = forExp.getCondition();
            // get the body expression
            OCLExpression<EClassifier> body = forExp.getBody();
            
            // evaluate
            QvtIterationTemplateForExp.getInstance(getVisitor()).evaluate(
                    sourceCollection, iterators, null, condition, body, resultName, "forOne".equals(forExp.getName())); //$NON-NLS-1$

            // remove result name from environment
            getEvaluationEnvironment().remove(resultName);
            
        }
        
        return null;
    }

    public Object visitImperativeIterateExp(ImperativeIterateExp imperativeIterateExp) {
        EClassifier sourceType = imperativeIterateExp.getSource().getType();
        
        if (sourceType instanceof PredefinedType<?>) {
        	Object sourceValue = visitExpression(imperativeIterateExp.getSource());
            
            // value of iteration expression is undefined if the source is
            //   null or OclInvalid
            if (isUndefined(sourceValue)) {
                return getInvalid();
            }
            
            // get initial result value based on the source type
            @SuppressWarnings("unchecked")
            CollectionType<EClassifier, EOperation> collType = (CollectionType<EClassifier, EOperation>) imperativeIterateExp.getSource().getType();
            
            
            Object initResultVal = null;
            if (imperativeIterateExp.getName().equals("xselect")) { //$NON-NLS-1$
                initResultVal = EvaluationUtil.createNewCollectionOfSameKind((Collection<?>) sourceValue);
            } else if (imperativeIterateExp.getName().equals("xcollect")  //$NON-NLS-1$
                    || imperativeIterateExp.getName().equals("collectselect")) { //$NON-NLS-1$
                initResultVal = ((collType instanceof SetType<?,?>) || (collType instanceof BagType<?,?>)) ?
                        CollectionUtil.createNewBag() : CollectionUtil.createNewSequence();
            }

            // generate a name for the result variable and add it to the environment
            String resultName = generateName();
            getEvaluationEnvironment().add(resultName, initResultVal);

            Collection<?> sourceCollection = (Collection<?>) sourceValue;
            // get the list of ocl iterators
            List<Variable<EClassifier, EParameter>> iterators = imperativeIterateExp.getIterator();
            // get the target expression
            Variable<EClassifier, EParameter> target = imperativeIterateExp.getTarget();
            // get the condition expression
            OCLExpression<EClassifier> condition = imperativeIterateExp.getCondition();
            // get the body expression
            OCLExpression<EClassifier> body = imperativeIterateExp.getBody();

            // evaluate
            Object result = null;
            if ("xcollect".equals(imperativeIterateExp.getName())) { //$NON-NLS-1$
                result = QvtIterationTemplateXCollect.getInstance(getVisitor()).evaluate(
                        sourceCollection, iterators, target, condition, body, resultName, false);
            } else if ("xselect".equals(imperativeIterateExp.getName())) { //$NON-NLS-1$
                result = QvtIterationTemplateXSelect.getInstance(getVisitor()).evaluate(
                        sourceCollection, iterators, target, condition, body, resultName, false);
            } else if ("collectselect".equals(imperativeIterateExp.getName())) { //$NON-NLS-1$
                result = QvtIterationTemplateCollectSelect.getInstance(getVisitor()).evaluate(
                        sourceCollection, iterators, target, condition, body, resultName, false);
            } else if ("collectOne".equals(imperativeIterateExp.getName())) { //$NON-NLS-1$
                result = QvtIterationTemplateXCollect.getInstance(getVisitor()).evaluate(
                        sourceCollection, iterators, target, condition, body, resultName, true);
            } else if ("selectOne".equals(imperativeIterateExp.getName())) { //$NON-NLS-1$
                result = QvtIterationTemplateXSelect.getInstance(getVisitor()).evaluate(
                        sourceCollection, iterators, target, condition, body, resultName, true);
            } else if ("collectselectOne".equals(imperativeIterateExp.getName())) { //$NON-NLS-1$
                result = QvtIterationTemplateCollectSelect.getInstance(getVisitor()).evaluate(
                        sourceCollection, iterators, target, condition, body, resultName, true);
            }

            // remove result name from environment
            getEvaluationEnvironment().remove(resultName);

            return result;
        }
        
        String message = NLS.bind(EvaluationMessages.IteratorNotImpl, imperativeIterateExp.getName());
        throw new UnsupportedOperationException(message);
    }
    
	public Object visitConstructor(Constructor constructor) {
        visitImperativeOperation(constructor);
        
        QvtOperationalEvaluationEnv env = getOperationalEvaluationEnv();
        
        if (constructor.isIsBlackbox()) {
        	Object result = doVisitBlackboxOperation(constructor);        	        	
        	return new OperationCallResult(result, env);
        }
        
        env.add(Environment.RESULT_VARIABLE_NAME, env.remove(Environment.SELF_VARIABLE_NAME));
        return new OperationCallResult(visitOperationBody(constructor.getBody()), env);
	}

	public Object visitConstructorBody(ConstructorBody constructorBody) {
		return visitOperationBody(constructorBody);
	}

	public Object visitBreakExp(BreakExp astNode) {
		throw new QvtTransitionReachedException(QvtTransitionReachedException.REASON_BREAK);
	}

	public Object visitCatchtExp(CatchExp astNode) {
		// TODO Auto-generated method stub
		return null;
	}

	public Object visitContinueExp(ContinueExp astNode) {
		throw new QvtTransitionReachedException(QvtTransitionReachedException.REASON_CONTINUE);
	}

	public Object visitDictLiteralPart(DictLiteralPart astNode) {
		// TODO Auto-generated method stub
		return null;
	}

	public Object visitOrderedTupleLiteralExp(OrderedTupleLiteralExp astNode) {
		// TODO Auto-generated method stub
		return null;
	}

	public Object visitOrderedTupleLiteralPart(OrderedTupleLiteralPart astNode) {
		// TODO Auto-generated method stub
		return null;
	}

	public Object visitRaiseExp(RaiseExp raiseExp) {
    	Object value = null;
    	if(raiseExp.getArgument() != null) {
    		value = visitExpression(raiseExp.getArgument());
    	}
    	String argument = (value instanceof String) ? (String)value : null;
		QvtException exception = new QvtException(argument, (EClass)raiseExp.getException());
		exception.setStackQvtTrace(new QvtStackTraceBuilder(getOperationalEvaluationEnv()).buildStackTrace());
		throw exception;
	}

	public Object visitTryExp(TryExp tryExp) {
		try {
            return visitBlockExpImpl(tryExp.getTryBody(), tryExp.eContainer() instanceof ImperativeOperation);
		}
		catch (QvtException exception) {
			boolean processed = false;
			
			OUTERMOST: for (CatchExp catchExp : tryExp.getExceptClause()) {
				for (EClassifier excType : catchExp.getException()) {
					if (EmfUtil.isAssignableFrom(excType, exception.getExceptionType())) { 
						processed = processCatch(catchExp, exception);
						break OUTERMOST;
					}
				}
				if (catchExp.getException().isEmpty()) { // catch all
					processed = processCatch(catchExp, exception);
					break OUTERMOST;
				}
			}
			
			if (!processed) {
				throw exception;
			}
		}
		
		return null;
	}
	
	private boolean processCatch(CatchExp catchExp, QvtException exception) {
		QvtOperationalEvaluationEnv evalEnv = getOperationalEvaluationEnv();
		String varName = null;

		org.eclipse.ocl.ecore.Variable catchVariable = ASTBindingHelper.getCatchVariable(catchExp);
		if (catchVariable != null) {
			ExceptionInstance excObject = null;
			if (exception.getExceptionType().getEPackage() == QvtOperationalStdLibrary.INSTANCE.getStdLibModule()) {
				excObject = QvtOperationalStdLibrary.INSTANCE.getStdlibFactory().createException(exception.getExceptionType(),
						exception.getMessage(), exception.getQvtStackTrace());
			}
			else {
				ExceptionClassInstance exceptionImpl = (ExceptionClassInstance) createInstance(exception.getExceptionType(), null);
				exceptionImpl.setArgument(exception.getMessage());
				exceptionImpl.setStackElements(exception.getQvtStackTrace());
				excObject = exceptionImpl;
			}

			varName = catchVariable.getName();
			evalEnv.add(varName, excObject);
		}
		
		visitBlockExpImpl(catchExp.getBody(), catchExp.eContainer() instanceof ImperativeOperation);
		
		if (varName != null) {
			evalEnv.remove(varName);
		}
		return true;
	}

	public Object visitUnlinkExp(UnlinkExp astNode) {
		// TODO Auto-generated method stub
		return null;
	}

	public Object visitUnpackExp(UnpackExp astNode) {
		// TODO Auto-generated method stub
		return null;
	}
    
    private static synchronized String generateName() {
        return "__qvtresult__" + tempCounter++;//$NON-NLS-1$
    }

	/**
	 * Initializes the model parameters and properties of the given module
	 * instance and all instances associated via import.
	 * 
	 * @param moduleInstance
	 *            the instance to initialize
	 * @param modelParameters
	 *            helper for binding transformation parameters
	 */
    private void initModule(ModuleInstance moduleInstance, ModelParameterHelper modelParameters) {
    	Module type = moduleInstance.getModule();
		QvtOperationalEnv env = (QvtOperationalEnv) getEnvironment();
		QvtOperationalEvaluationEnv currentEvalEnv = getOperationalEvaluationEnv();	

		QvtOperationalEvaluationEnv nestedEvalEnv = (QvtOperationalEvaluationEnv) env.getFactory().createEvaluationEnvironment(getOperationalEvaluationEnv());
		// ensure 'this' instance available in the initialization code
		nestedEvalEnv.add(QvtOperationalEnv.THIS, moduleInstance);
		// propagate arguments, provided it is a transformation module
		nestedEvalEnv.getOperationArgs().addAll(currentEvalEnv.getOperationArgs());
		// point to the module we are initializing
		nestedEvalEnv.getAdapter(InternalEvaluationEnv.class).setCurrentIP(type);
		try {
			setOperationalEvaluationEnv(nestedEvalEnv);
			// push stack before a chance for exception, to have push/pop in balance 
			pushedStack(nestedEvalEnv);
	        // eventually cause STO exception
	        EvaluationUtil.checkCurrentStackDepth(currentEvalEnv);			
	       
	        // do initialization of model params here to ensure existing out extent for objects created during initialization of imported modules (fixed by bug 392080)
	        doInitModelParams(moduleInstance, modelParameters);
	        
	    	for (ModuleImport moduleImport : type.getModuleImport()) {
	    		Module importedModule = moduleImport.getImportedModule();	    		
				ModuleInstance importedInstance = moduleInstance.getThisInstanceOf(importedModule);
		    	if(importedInstance != null) { 
					ModuleInstance.Internal importedInternal = importedInstance.getAdapter(ModuleInstance.Internal.class);
					if(!importedInternal.isInitialized()) {
						initModule(importedInstance, modelParameters);
					}
	    		}
			}
	    	
	        doInitModule(moduleInstance);
	    		    	
	    	moduleInstance.getAdapter(ModuleInstance.Internal.class).setInitialized();   				
	    	
		} finally {
			setOperationalEvaluationEnv(getOperationalEvaluationEnv().getParent());
			poppedStack();
		}
    }
    
    private void doInitModelParams(ModuleInstance moduleInstance, ModelParameterHelper modelParameters) {
    	
    	if(modelParameters != null && moduleInstance.getModule().eClass() == ExpressionsPackage.eINSTANCE.getOperationalTransformation()) {
			modelParameters.initModelParameters((TransformationInstance) moduleInstance);
		}
    	
    }
    
    private void doInitModule(ModuleInstance moduleInstance) {
    	Module module = moduleInstance.getModule();
    	
        QvtOperationalEvaluationEnv env = getOperationalEvaluationEnv();
                
		for (EStructuralFeature feature : module.getConfigProperty()) {			
			Object propValue = visitConfigProperty(feature);
			env.callSetter(moduleInstance, feature, propValue, isUndefined(propValue), true);			
		}
		
        for (EStructuralFeature feature : module.getEStructuralFeatures()) {
        	if(feature instanceof ContextualProperty || module.getConfigProperty().contains(feature)) {
        		continue;
        	}

        	setCurrentEnvInstructionPointer(feature);
        	
        	OCLExpression<EClassifier> initExp = QvtOperationalParserUtil.getInitExpression(feature);
			Object propValue = null;
            if(initExp != null) {
            	propValue = visitExpression(initExp);                
            }
            else {
            	propValue = EvaluationUtil.createInitialValue(feature.getEType(), getEnvironment().getOCLStandardLibrary(), getEvaluationEnvironment());
            }
			env.callSetter(moduleInstance, feature, propValue, isUndefined(propValue), true);        
        }
        
//        for (Rename rename : module.getOwnedRenaming()) {
//            ((RenameImpl) rename).accept(getVisitor());
//        }
    }
            
	private IVirtualOperationTable getVirtualTable(EOperation operation) {
		return IVirtualOperationTable.Access.INSTANCE.getVirtualTable(operation);
	}
    
    private Object createOrGetResult(MappingOperation mappingOperation) {
        Object result = null;
        
        if (!mappingOperation.getResult().isEmpty()) {
        	result = getRuntimeValue(Environment.RESULT_VARIABLE_NAME);
            if (isUndefined(result)) { // if nothing was assigned to the result in the init section
                EList<VarParameter> resultParams = mappingOperation.getResult();
                if(resultParams.size() > 1) {
                	result = createTupleResult(mappingOperation);
                } 
                else {
        			VarParameter type = (resultParams.isEmpty() ? null : resultParams.get(0));
                    if (type != null && false == type.getEType() instanceof VoidType<?>) {
                        result = createInstance(type.getEType(), ((MappingParameter) type).getExtent());
                    }    			
                }
                
                replaceInEnv(Environment.RESULT_VARIABLE_NAME, result, mappingOperation.getEType());
            }
        }
        
        TraceUtil.addTraceRecord(getOperationalEvaluationEnv(), mappingOperation);
        return result;
    }

    protected static class OperationCallResult {
    	public Object myResult;
    	public QvtOperationalEvaluationEnv myEvalEnv;
    	
		OperationCallResult(Object myResult, QvtOperationalEvaluationEnv myEvalEnv) {
			this.myResult = myResult;
			this.myEvalEnv = myEvalEnv;
		}
    }
    
    private static class MappingCallResult extends OperationCallResult {
		static final int BODY_EXECUTED = 0;
		static final int PRECOND_FAILED = 2;
		static final int FETCHED_FROM_TRACE = 4;
		static final int NO_DISJUNCT_SELECTED = 8;		
		
		int myStatus;
    	
    	private MappingCallResult(Object myResult, QvtOperationalEvaluationEnv myEvalEnv, int status) {
			super(myResult, myEvalEnv);
			myStatus = status;
		}
    	boolean isBodyExecuted() { return myStatus == BODY_EXECUTED; }
    	boolean isPreconditionFailed() { return (myStatus & PRECOND_FAILED) != 0; };
    	//boolean isFetchedFromTrace() { return (myStatus & FETCHED_FROM_TRACE) != 0; };
    	//boolean isNoDisjunctSelected() { return (myStatus & NO_DISJUCT_SELECTED) != 0; };    	
    }
    
    private OperationCallResult executeImperativeOperation(ImperativeOperation method, Object source, List<Object> args, boolean isReusingMappingCall) {    	
        QvtOperationalEvaluationEnv oldEvalEnv = getOperationalEvaluationEnv();
        
    	boolean isMapping = method instanceof MappingOperation;    	
        // eventually cause STO exception
        EvaluationUtil.checkCurrentStackDepth(oldEvalEnv);
        
        // create a nested evaluation environment for this operation call
        QvtOperationalEvaluationEnv nestedEnv = getOperationalEnv().getFactory().createEvaluationEnvironment(
        		oldEvalEnv.getContext(), oldEvalEnv);
        nestedEnv.setOperation(method);
        
        nestedEnv.getOperationArgs().addAll(args);
        if (!isUndefined(source)) {
            nestedEnv.setOperationSelf(source);
        }
        
        if(isReusingMappingCall) {
        	// let the reused mapping see the reusing caller's out/result parameters
        	EvaluationUtil.mapOperationOutAndResultParams(oldEvalEnv, nestedEnv);
        }
                        
        // setup 'this' module variable  
        Module targetModule = QvtOperationalParserUtil.getOwningModule(method);
        assert targetModule != null;
        // Resolves the target module instance to call from the currently executed module 'this'
        ModuleInstance calledThisInstance = oldEvalEnv.getThisOfType(targetModule);        
        assert calledThisInstance != null;
        
        setOperationalEvaluationEnv(nestedEnv);
        // add 'this' to the nested environment
        addToEnv(QvtOperationalEnv.THIS, calledThisInstance, targetModule);        
        
        // set IP initially to the method header
        setCurrentEnvInstructionPointer(method); 

        OperationCallResult callResult = null;
        try {
        	Object result = ((ImperativeOperationImpl) method).accept(getVisitor());    	
        	assert result instanceof OperationCallResult;
        	assert !isMapping || result instanceof MappingCallResult;        	
        	
        	callResult = (OperationCallResult)result;
        }
        catch (ReturnExpEvent e) {
        	callResult = e.getResult();
        }
        catch (StackOverflowError e) {
        	throwQVTException(new QvtStackOverFlowError(e));
        }
        catch (QvtRuntimeException e) {
       		throw e;
        }
        catch (RuntimeException e) {
        	String errorMessage = EvaluationMessages.QvtOperationalEvaluationVisitorImpl_unexpectedRuntimeExc;
			QvtPlugin.error(errorMessage, e);
			
        	throwQVTException(new QvtRuntimeException(errorMessage, e));
        }
        finally {
            if(isMapping && isReusingMappingCall && callResult != null) {
            	// reflect our output in the reusing mapping caller
            	if(((MappingCallResult)callResult).isBodyExecuted()) {
            		EvaluationUtil.mapOperationOutAndResultParams(nestedEnv, oldEvalEnv);
            	}
            }        	

        	setOperationalEvaluationEnv(oldEvalEnv);
        	poppedStack();
        }
        
    	return callResult;
    }
                
    private MappingCallResult dispatchDisjunctMapping(MappingOperation method) {
    	QvtOperationalEvaluationEnv evalEnv = getOperationalEvaluationEnv();
    	Object source = evalEnv.getOperationSelf();
    	List<Object> args = evalEnv.getOperationArgs();
    	
    	for (MappingOperation nextDisjunct : method.getDisjunct()) {
    		
    		// consider overriding mapping (fixed by bug 309762)
    		ImperativeOperation overridingOper = EvaluationUtil.getOverridingOperation(getOperationalEvaluationEnv(), nextDisjunct);
    		if (overridingOper instanceof MappingOperation) {
    			nextDisjunct = (MappingOperation) overridingOper;
    		}
    		
    		EClassifier ctxType = QvtOperationalParserUtil.getContextualType(nextDisjunct);
    		if(ctxType != null) {
    			if(!evalEnv.isKindOf(source, nextDisjunct.getContext().getEType())) {
    				continue;
    			}
    		}
    		
    		if(!dispatchDisjunctMappingArgumentsMatch(nextDisjunct)) {
    			continue;
    		}

    		MappingCallResult result = (MappingCallResult)executeImperativeOperation(nextDisjunct, source, args, false);
    		if(!result.isPreconditionFailed()) {
    			// precondition holds, mapping either executed, fetched from trace, or disjuncted
    			result.myStatus = MappingCallResult.BODY_EXECUTED; // from disjuncting mapping consider as executed
    			
    			// add trace record for disjuncting mapping (fixed by bug 377882) 
    			replaceInEnv(Environment.RESULT_VARIABLE_NAME, result.myResult, method.getEType());
    			TraceUtil.addTraceRecord(evalEnv, method);
    			
    			return result;
    		}
		}
    	
    	return new MappingCallResult(null, myEvalEnv, MappingCallResult.NO_DISJUNCT_SELECTED);
    }
    
    private boolean dispatchDisjunctMappingArgumentsMatch(MappingOperation disjunct) {
    	
    	List<EParameter> params = disjunct.getEParameters();
    	QvtOperationalEvaluationEnv evalEnv = getOperationalEvaluationEnv();
    	List<Object> args = evalEnv.getOperationArgs();
    	    	
    	if(params.size() != args.size()) {
    		return false;
    	}
    	
    	for (int i = 0; i < args.size(); i++) {
			Object nextArg = args.get(i);
			EClassifier nextParamType = params.get(i).getEType();    			
			if(nextArg != null && !evalEnv.isKindOf(nextArg, nextParamType)) {
				return false;
			}
		}
    	
    	return true;
    	
    }
    
    protected final void throwQVTException(QvtRuntimeException exception) throws QvtRuntimeException {
		getOperationalEvaluationEnv().getAdapter(InternalEvaluationEnv.class)
				.throwQVTException(exception);
    }
    
	@Override
    protected Object call(EOperation operation, OCLExpression<EClassifier> body, Object target, Object[] args) {
    	if(target instanceof EObject) {
    		EObject eTarget = (EObject) target;
    		if(OCLAnnotationSupport.isDynamicInstance(eTarget)) {
    			if(operation.eClass() != eTarget.eClass()) {
    				// check if not overridden for a sub-class 
	    			EOperation actualOperation = getOCLAnnotationSupport().resolveDynamic(operation, eTarget);
	    			if(actualOperation != null && actualOperation != operation) {
	    				OCLExpression<EClassifier> actualOperBody = getOperationBody(actualOperation);
	    				
	    				if(actualOperBody != null) {
							Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> myEnv = getEnvironment();
							EnvironmentFactory<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> factory = myEnv
									.getFactory();
							// create a nested evaluation environment for this
							// operation call
							EvaluationEnvironment<EClassifier, EOperation, EStructuralFeature, EClass, EObject> nested = factory
									.createEvaluationEnvironment(getEvaluationEnvironment());
	    			    	// bind "self"
	    			    	nested.add(Environment.SELF_VARIABLE_NAME, target);	    			    	
	    			    	// add the parameter bindings to the local variables
	    			    	if (args.length > 0) {
	    			    		int i = 0;
	    			    		UMLReflection<?, ?, EOperation, ?, ?, EParameter, ?, ?, ?, ?> uml = myEnv.getUMLReflection();
	    			    		for (EParameter param : uml.getParameters(operation)) { 
	    			    			nested.add(uml.getName(param), args[i]);
	    			    		}
	    			    	}
	    			    	
							EvaluationVisitor<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> visitor = factory
									.createEvaluationVisitor(myEnv, nested, getExtentMap());
	    			    	if(visitor instanceof QvtOperationalEvaluationVisitorImpl) {
	    			    		// ensure shared instance of oclAnnotationSupport to avoid repeated OCL parsing	    			    		
	    			    		((QvtOperationalEvaluationVisitorImpl)visitor).oclAnnotationSupport = getOCLAnnotationSupport();
	    			    	}

	    			    	return visitor.visitExpression(actualOperBody);
	    				}
	    			}
    			}
    		}
    	}
    	
    	return super.call(operation, body, target, args);
    }
    
    @Override
	public Object visitCollectionLiteralExp(CollectionLiteralExp<EClassifier> cl) {
		if (cl.getType() instanceof ListType) {
			Collection<Object> result = new MutableListImpl<Object>();
			for (CollectionLiteralPart<EClassifier> part : cl.getPart()) {
				if (part instanceof CollectionItem<?>) {
					// CollectionItem part
					CollectionItem<EClassifier> item = (CollectionItem<EClassifier>) part;
					OCLExpression<EClassifier> itemExp = item.getItem();
					Object itemVal = visitExpression(itemExp);
					if (itemVal == getInvalid()) {
						return getInvalid(); // can't have an invalid element in a collection
					}
					result.add(itemVal);
				} else {
					// Collection range
					CollectionRange<EClassifier> range = (CollectionRange<EClassifier>) part;
					OCLExpression<EClassifier> first = range.getFirst();
					OCLExpression<EClassifier> last = range.getLast();

					// evaluate first value
					Object firstVal = visitExpression(first);
					Object lastVal = visitExpression(last);
					if (firstVal == getInvalid() || lastVal == getInvalid()) {
						return getInvalid(); // can't have an invalid element in a collection
					}
					if (firstVal instanceof Integer && lastVal instanceof Integer) {
						// TODO: enhance IntegerRangeList to support multiple ranges
						// add values between first and last inclusive
						int firstInt = ((Integer) firstVal).intValue();
						int lastInt = ((Integer) lastVal).intValue();
						for (int i = firstInt; i <= lastInt; i++) {
                            result.add(new Integer(i));
                        }
					}
				} // end of collection range
			} // end of parts iterator
			return result;
		}
		return super.visitCollectionLiteralExp(cl);
	}

	@Override
	protected Object navigate(EStructuralFeature property, OCLExpression<EClassifier> derivation, Object target) {
		Environment<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> myEnv = getEnvironment();
		EnvironmentFactory<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> factory = myEnv
				.getFactory();
		// create a nested evaluation environment for this property call
		EvaluationEnvironment<EClassifier, EOperation, EStructuralFeature, EClass, EObject> nested = factory
				.createEvaluationEnvironment(getEvaluationEnvironment());
    	// bind "self"
    	nested.add(Environment.SELF_VARIABLE_NAME, target);
    	
		EvaluationVisitor<EPackage, EClassifier, EOperation, EStructuralFeature, EEnumLiteral, EParameter, EObject, CallOperationAction, SendSignalAction, Constraint, EClass, EObject> visitor = factory
				.createEvaluationVisitor(myEnv, nested, getExtentMap());
    	if(visitor instanceof QvtOperationalEvaluationVisitorImpl) {
    		// ensure shared instance of oclAnnotationSupport to avoid repeated OCL parsing
    		((QvtOperationalEvaluationVisitorImpl)visitor).oclAnnotationSupport = getOCLAnnotationSupport();
    	}

    	return visitor.visitExpression(derivation);
    }    

    @Override
    protected OCLExpression<EClassifier> getPropertyBody(EStructuralFeature property) {    	
    	if(OCLAnnotationSupport.isDynamicClassFeature(property)) {
    		return getOCLAnnotationSupport().getDerivedProperty(property);
    	}
    	
    	return super.getPropertyBody(property);
    }
        
	@Override
	protected OCLExpression<EClassifier> getOperationBody(EOperation operation) {
		if(operation == null) {
			return null;
		}
		
		if(OCLAnnotationSupport.isDynamicClassOperation(operation)) {			
			return getOCLAnnotationSupport().getBody(operation);
		}		
		return super.getOperationBody(operation);
	}
    
	private OCLAnnotationSupport getOCLAnnotationSupport() {
		if(oclAnnotationSupport == null) {
			oclAnnotationSupport = new OCLAnnotationSupport();		
			
			oclAnnotationSupport.setErrorHandler(new OCLAnnotationSupport.ParseErrorHandler() {
				org.eclipse.ocl.ecore.OCLExpression invalidBodyExpr = EcoreFactory.eINSTANCE.createInvalidLiteralExp();
				
				public org.eclipse.ocl.ecore.OCLExpression handleError(ParserException parserException, EModelElement contextElement) {
					QvtPlugin.error("Failed to parse OCL annotation :" +  //$NON-NLS-1$
							getUMLReflection().getQualifiedName(contextElement) , parserException);

					return invalidBodyExpr;
				}
			});
		}
		return oclAnnotationSupport;
	}
	
    protected QvtOperationalEnv getOperationalEnv() {
        return (QvtOperationalEnv) getEnvironment();
    }

    public QvtOperationalEvaluationEnv getOperationalEvaluationEnv() {
        return (QvtOperationalEvaluationEnv) getEvaluationEnvironment();
    }
    
    
	/**
	 * Adds the given variable value into evaluation environment.
	 * 
	 * @param varName
	 *            the name of the variable
	 * @param value
	 *            the value of the variable
	 * @param declaredType
	 *            the type of the variable (optional) or <code>null</code>
	 */    
	protected void addToEnv(String varName, Object value, EClassifier declaredType) {
		getOperationalEvaluationEnv().add(varName, value);
	}
	
	/**
	 * Replaces the given variable value in evaluation environment.
	 * 
	 * @param varName
	 *            the name of the variable to replace
	 * @param value
	 *            the new value of the variable
	 * @param declaredType
	 *            the type of the variable (optional) or <code>null</code>
	 */
	protected void replaceInEnv(String varName, Object value, EClassifier declaredType) {
		getOperationalEvaluationEnv().replace(varName, value);
	}
	
    private Object getRuntimeValue(final String name) {
        return getEvaluationEnvironment().getValueOf(name);
    }

    private Object getOutOwner(final ObjectExp objectExp) {
        Object owner = getRuntimeValue(objectExp.getName()); 
        if (owner != null) {
        	if (objectExp.getType() instanceof CollectionType<?, ?> == false) {
	            if (!oclIsKindOf(owner, objectExp.getType())) {
	                throw new RuntimeException(MessageFormat.format(
	                        EvaluationMessages.ExtendedOclEvaluatorVisitorImpl_InvalidObjectExpType, new Object[] {
	                                objectExp.getName(), owner, objectExp.getType() }));
	            }
        	}
        } else {
        	owner = createInstance(objectExp.getType(), (ModelParameter) objectExp.getExtent());
        	if(objectExp.getName() != null) {
        		getOperationalEvaluationEnv().replace(objectExp.getName(), owner);
        	}
        }

        return owner;
    }
    
    /**
	 * Creates tuple value representing the result of the given operation.
	 * 
	 * @param operation
	 *          the operation currently executed by this environment
	 *          
	 * @return the tuple value collecting all result parameters, never <code>null</code>
	 */
    private Tuple<EOperation, EStructuralFeature> createTupleResult(ImperativeOperation operation) {
    	boolean isMapping = operation.eClass() == ExpressionsPackage.eINSTANCE.getMappingOperation();
    	QvtOperationalEvaluationEnv evalEnv = getOperationalEvaluationEnv();
    	EList<VarParameter> resultParams = operation.getResult();
    	
    	HashMap<EStructuralFeature, Object> values = new HashMap<EStructuralFeature, Object>(2);
    	@SuppressWarnings("unchecked")
    	TupleType<EClassifier, EStructuralFeature> tupleType = (TupleType<EClassifier, EStructuralFeature>)operation.getEType();
		
    	for (EStructuralFeature tupleProp : tupleType.oclProperties()) {
			Object propVal = evalEnv.getValueOf(tupleProp.getName());
			if(propVal == null && isMapping) {
				ModelParameter extent = null;
				for (VarParameter resultParam : resultParams) {
					if(tupleProp.getName().equals(resultParam.getName())) {
						MappingParameter mappingParameter = (MappingParameter) resultParam;
						extent = mappingParameter.getExtent();
						break;
					}
				}
				
				propVal = createInstance(tupleProp.getEType(), extent);
			}
			values.put(tupleProp, propVal);
			evalEnv.replace(tupleProp.getName(), propVal, tupleProp.getEType());
		}
    	
    	return evalEnv.createTuple(operation.getEType(), values);
    }
    
    private static CollectionKind getCollectionKind(Collection<?> collection) {
    	if (collection instanceof MutableList<?>) {
    		return null;
    	}
    	if (collection instanceof Dictionary<?,?>) {
    		return null;
    	}
        if (collection instanceof ArrayList<?>) {
            return CollectionKind.SEQUENCE_LITERAL;
        }
        if (collection instanceof LinkedHashSet<?>) {
            return CollectionKind.ORDERED_SET_LITERAL;
        }
        // Remark: check Set after Ordered set
        if (collection instanceof HashSet<?>) {
            return CollectionKind.SET_LITERAL;
        }        
        if (collection instanceof Bag<?>) {
            return CollectionKind.BAG_LITERAL;
        }
        return null;
    }

	private List<Object> makeArgs(OperationCallExp<EClassifier, EOperation> operationCallExp) {
    	EOperation referredOperation = operationCallExp.getReferredOperation();
    	Iterator<EParameter> iterParam = referredOperation.getEParameters().iterator();
        List<Object> argValues = new ArrayList<Object>();
        for (OCLExpression<EClassifier> arg : operationCallExp.getArgument()) {
        	Object value = visitExpression(arg);
        	EParameter param = iterParam.next();
            argValues.add(doImplicitListCoercion(param.getEType(), value));
        }

        return argValues;
    }
    
	private List<Object> makeEntryOperationArgs(ImperativeOperation entryPoint, OperationalTransformation module) {
		List<Object> args = new ArrayList<Object>(entryPoint.getEParameters().size());
		
		int paramIndex = 0;
		for (EParameter param : entryPoint.getEParameters()) {
			int matchedIndex = paramIndex;

			MappingParameter mappingParam = (MappingParameter) param;
			if (mappingParam.getKind() == DirectionKind.OUT) {
				args.add(null);
				continue;
			}
			
			if (mappingParam.getExtent() != null) {
				int modelParamIndex = 0;
		        for (ModelParameter modelParam : module.getModelParameter()) {
		        	if (modelParam == mappingParam.getExtent()) {
		        		matchedIndex = modelParamIndex;
		        		break;
		        	}
		        	modelParamIndex++;
		        }
			}

	        if (matchedIndex < getOperationalEvaluationEnv().getOperationArgs().size()) {
	        	Object envArg = getOperationalEvaluationEnv().getOperationArgs().get(matchedIndex);
	        	ModelInstance argModel = (ModelInstance) envArg;
	        	ModelParameterExtent argExtent = argModel.getExtent();
				List<EObject> initialObjects = argExtent.getInitialObjects();
				if(!initialObjects.isEmpty()) {
					args.add(initialObjects.get(0));
				}
	        }
			else {
                throw new IllegalArgumentException("entry operation arguments mismatch: no argument for " + mappingParam + " parameter"); //$NON-NLS-1$ //$NON-NLS-2$
			}

	        paramIndex++;
		}
		return args;
	}

//    private EStructuralFeature getRenamedProperty(EStructuralFeature property) {
//    	EAnnotation annotation = property.getEAnnotation(Environment.OCL_NAMESPACE_URI);
//    	if (annotation != null) {
//    		for (EObject nextAnn : annotation.getContents()) {
//    			if (false == nextAnn instanceof Constraint) {
//    				continue;
//    			}
//    			Constraint cnt = (Constraint) nextAnn;
//    			if (QvtOperationalEnv.RENAMED_PROPERTY_STEREOTYPE.equals(cnt.getStereotype())
//    					&& !cnt.getConstrainedElements().isEmpty()
//    					&& cnt.getConstrainedElements().get(0) instanceof EStructuralFeature) {
//    				return (EStructuralFeature) cnt.getConstrainedElements().get(0);
//    			}
//    		}
//    	}
//    	return property;
//    }
    
    /**
	* Wraps the environment's creatInstance() and transforms failures to QVT exception
	*/    
	protected Object createInstance(EClassifier type, ModelParameter extent) throws QvtRuntimeException {
		Object newInstance = null;
		try {			
			if(type instanceof CollectionType<?, ?>) {
				@SuppressWarnings("unchecked")
				CollectionType<EClassifier, EOperation> collectionType = (CollectionType<EClassifier, EOperation>)type;
				newInstance = EvaluationUtil.createNewCollection(collectionType);
			} else {
				newInstance = getOperationalEvaluationEnv().createInstance(type, extent);

				EFactory eFactory = type.getEPackage().getEFactoryInstance();
				if(eFactory instanceof IntermediateClassFactory) {
					IntermediateClassFactory intermFactory = (IntermediateClassFactory) eFactory;
					intermFactory.doInstancePropertyInit(newInstance, getQVTVisitor());
				}
			}

		} catch (IllegalArgumentException e) {
			throwQVTException(new QvtRuntimeException(e));
		}
		
		return newInstance;
	}
   
    protected EObject setCurrentEnvInstructionPointer(EObject node) {
    	InternalEvaluationEnv internEnv = getOperationalEvaluationEnv().getAdapter(InternalEvaluationEnv.class);
    	if(node != null) {
    		return internEnv.setCurrentIP(node);
    	}
    	return internEnv.getCurrentIP();
    }
    
    protected InternalEvaluator createInterruptibleVisitor() {
    	final EvaluationMonitor monitor = getContext().getMonitor();
    	    
    	class InterruptVisitor extends QvtGenericEvaluationVisitor.Any implements InternalEvaluator {
    		public InterruptVisitor() {
    			super(QvtOperationalEvaluationVisitorImpl.this);
			}
    		
    		public Object execute(OperationalTransformation transformation) throws QvtRuntimeException {
    			return QvtOperationalEvaluationVisitorImpl.this.execute(transformation);
    		}
    		
    		public QvtOperationalEvaluationEnv getOperationalEvaluationEnv() {
    			return QvtOperationalEvaluationVisitorImpl.this.getOperationalEvaluationEnv();
    		}
    		
    		public void setOperationalEvaluationEnv(QvtOperationalEvaluationEnv evalEnv) {
    			QvtOperationalEvaluationVisitorImpl.this.setOperationalEvaluationEnv(evalEnv);
    		}
    		
    		public IContext getContext() {
    			return QvtOperationalEvaluationVisitorImpl.this.getContext();
    		}

    		public ModuleInstance callTransformationImplicitConstructor(OperationalTransformation transformation, List<ModelInstance> args) {
    			return QvtOperationalEvaluationVisitorImpl.this.callTransformationImplicitConstructor(transformation, args);
    		}
    		
    		public OperationCallResult runMainEntry(OperationalTransformation transformation, List<Object> args) {
				return QvtOperationalEvaluationVisitorImpl.this.runMainEntry(transformation, args);
			}
    		
    		@Override
    		protected Object genericVisitAny(Object object) {
    			if(monitor != null && monitor.isCanceled()) {    				
    				throwQVTException(new QvtInterruptedExecutionException());    				
    			}
    			
    			// set the current instruction pointer
    			if(object instanceof EObject) {
    				InternalEvaluationEnv evalEnv = getOperationalEvaluationEnv().getAdapter(InternalEvaluationEnv.class);
    				evalEnv.setCurrentIP((EObject)object);
    			}
    			
    			return null;
    		}    		
    	};
    	
    	return new InterruptVisitor();
    }

	public OperationCallResult runMainEntry(OperationalTransformation transformation, List<Object> args) {
		ImperativeOperation entryOperation = QvtOperationalParserUtil.getMainOperation(transformation);				
		
		for (ModelParameter parameter : transformation.getModelParameter()) {
			if (parameter.getEType() instanceof ModelType && parameter.getKind() != DirectionKind.OUT) {
				ModelType parameterType = (ModelType) parameter.getEType();
				for (OCLExpression<EClassifier> whereExpression : parameterType.getAdditionalCondition()) {
					myEvalEnv.add(Environment.SELF_VARIABLE_NAME, parameter);
					boolean isConditionMet = Boolean.TRUE.equals(visitExpression(whereExpression));
					myEvalEnv.remove(Environment.SELF_VARIABLE_NAME);
		    		if(!isConditionMet) {
		    			throwQVTException(new QvtAssertionFailed(NLS.bind(EvaluationMessages.ModelTypeConstraintFailed, 
		    					parameter.getName(), transformation.getName())));
		    		}
		    		
				}
			}
		}
		
		OperationCallResult result = executeImperativeOperation(entryOperation, null, args, false);        	        					
		processDeferredTasks();
		return result;
	}    
    
    /**
     * Performs cast on the result of {@link #getVisitor()}; 
     * @see #getVisitor()
     */
    protected QvtOperationalEvaluationVisitor getQVTVisitor() {
    	return (QvtOperationalEvaluationVisitor)getVisitor();
    }
    
    
	/**
	 * TODO - Avoid using this exception return expression to interrupt execution flow for 
	 * immediate return from an operation.
	 * Though, if the last statement in a body is return expression, no exception is thrown, we
	 * should try to avoid this cost to be paid in general
	 */
	private static class ReturnExpEvent extends QvtRuntimeException {
		private static final long serialVersionUID = 2971434369853642555L;		
		private final OperationCallResult fResult;
		
		ReturnExpEvent(Object returnValue, QvtOperationalEvaluationEnv evalEnv) {
			fResult = new OperationCallResult(returnValue, evalEnv);
		}
		
		public OperationCallResult getResult() {
			return fResult;
		}
	}

}

Back to the top