summaryrefslogtreecommitdiff
path: root/org.genivi.commonapi.core/src/org/genivi/commonapi/core/generator/FrancaGeneratorExtensions.xtend
blob: e567e3986eb08f4342d9a60db6ea3d3c50da659e (plain)
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
/* Copyright (C) 2013 BMW Group
 * Author: Manfred Bathelt (manfred.bathelt@bmw.de)
 * Author: Juergen Gehring (juergen.gehring@bmw.de)
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.genivi.commonapi.core.generator

import com.google.common.base.Charsets
import com.google.common.hash.Hasher
import com.google.common.hash.Hashing
import com.google.common.primitives.Ints
import java.math.BigInteger
import java.util.ArrayList
import java.util.Collection
import java.util.HashMap
import java.util.HashSet
import java.util.LinkedList
import java.util.List
import java.util.Map
import java.util.Set
import org.eclipse.core.resources.IResource
import org.eclipse.core.resources.ResourcesPlugin
import org.eclipse.core.runtime.Path
import org.eclipse.core.runtime.preferences.DefaultScope
import org.eclipse.core.runtime.preferences.InstanceScope
import org.eclipse.emf.ecore.EObject
import org.eclipse.emf.ecore.resource.Resource
import org.eclipse.emf.ecore.util.EcoreUtil
import org.franca.core.franca.FArrayType
import org.franca.core.franca.FAttribute
import org.franca.core.franca.FBasicTypeId
import org.franca.core.franca.FBroadcast
import org.franca.core.franca.FConstantDef
import org.franca.core.franca.FEnumerationType
import org.franca.core.franca.FEnumerator
import org.franca.core.franca.FExpression
import org.franca.core.franca.FField
import org.franca.core.franca.FInitializerExpression
import org.franca.core.franca.FIntegerConstant
import org.franca.core.franca.FInterface
import org.franca.core.franca.FMapType
import org.franca.core.franca.FMethod
import org.franca.core.franca.FModel
import org.franca.core.franca.FModelElement
import org.franca.core.franca.FQualifiedElementRef
import org.franca.core.franca.FStringConstant
import org.franca.core.franca.FStructType
import org.franca.core.franca.FType
import org.franca.core.franca.FTypeCollection
import org.franca.core.franca.FTypeDef
import org.franca.core.franca.FTypeRef
import org.franca.core.franca.FTypedElement
import org.franca.core.franca.FUnionType
import org.franca.core.franca.FVersion
import org.franca.core.franca.FrancaFactory
import org.franca.deploymodel.dsl.fDeploy.FDInterface
import org.franca.deploymodel.dsl.fDeploy.FDModel
import org.franca.deploymodel.dsl.fDeploy.FDTypes
import org.franca.deploymodel.dsl.fDeploy.FDProvider
import org.genivi.commonapi.core.deployment.PropertyAccessor
import org.genivi.commonapi.core.deployment.PropertyAccessor.DefaultEnumBackingType
import org.genivi.commonapi.core.deployment.PropertyAccessor.EnumBackingType
import org.genivi.commonapi.core.preferences.FPreferences
import org.genivi.commonapi.core.preferences.PreferenceConstants
import org.osgi.framework.FrameworkUtil

import static com.google.common.base.Preconditions.*

import static extension java.lang.Integer.*


class FrancaGeneratorExtensions {
	
	def boolean isComplex(String _typeName) {
        if (_typeName == "bool" || 
            _typeName == "int8" ||
            _typeName == "int16" ||
            _typeName == "int32" ||
            _typeName == "int64" ||
            _typeName == "uint8" ||
            _typeName == "uint16" ||
            _typeName == "uint32" ||
            _typeName == "uint64") {
            return false
        }
        return true
    }

    def String generateIndent(int _indent) {
        var String  empty = ""
        var int i = 0
        while (i < _indent) {
            empty = empty + "    "
            i = i + 1
        }
        return empty
    }
    
    def String getRelativeName(FModelElement _element) {
        if (_element instanceof FTypeCollection)
            return ""
        val String next = (_element.eContainer as FModelElement).relativeName
        if (next != "")
            return next + "_" + _element.name
        return _element.name
    }

    def String getFullyQualifiedName(FModelElement fModelElement) {
        if (fModelElement.eContainer instanceof FModel)
            return (fModelElement.eContainer as FModel).name + '.' + fModelElement.elementName
        return (fModelElement.eContainer as FModelElement).fullyQualifiedName + '.' + fModelElement.elementName
    }
    
     def String getFullyQualifiedCppName(FModelElement fModelElement) {
        if (fModelElement.eContainer instanceof FModel) {
        	var name = (fModelElement.eContainer as FModel).name
        	if (fModelElement instanceof FTypeCollection) {
        		val FVersion itsVersion = fModelElement.version
        		if (itsVersion != null) {
        			name = fModelElement.versionPrefix + name
        		}
        	}
            return "::" + (name + "::" + fModelElement.elementName).replace(".", "::")
        }
        return "::" + ((fModelElement.eContainer as FModelElement).fullyQualifiedName + "::" + fModelElement.elementName).replace(".", "::")
    }
    
    def splitCamelCase(String string) {
        string.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")
    }

    def FModel getModel(FModelElement fModelElement) {
        if (fModelElement.eContainer instanceof FModel)
            return (fModelElement.eContainer as FModel)
        return (fModelElement.eContainer as FModelElement).model
    }

    def FInterface getContainingInterface(FModelElement fModelElement) {
        if (fModelElement.eContainer == null || fModelElement.eContainer instanceof FModel) {
            return null
        }
        if (fModelElement.eContainer instanceof FInterface) {
            return (fModelElement.eContainer as FInterface)
        }

        return (fModelElement.eContainer as FModelElement).containingInterface
    }

    def FTypeCollection getContainingTypeCollection(FModelElement fModelElement) {
        if (fModelElement.eContainer != null && fModelElement.eContainer instanceof FModel) {
            return null
        }
        if (fModelElement.eContainer instanceof FTypeCollection) {
            return (fModelElement.eContainer as FTypeCollection)
        }

        return (fModelElement.eContainer as FModelElement).containingTypeCollection
    }

    def getDirectoryPath(FModel fModel) {
        fModel.name.replace('.', '/')
    }

    def String getDefineName(FModelElement fModelElement) {
        val defineSuffix = '_' + fModelElement.elementName.splitCamelCase.join('_')

        if (fModelElement.eContainer instanceof FModelElement)
            return (fModelElement.eContainer as FModelElement).defineName + defineSuffix

        return (fModelElement.eContainer as FModel).defineName + defineSuffix
    }

    def getDefineName(FModel fModel) {
        fModel.name.toUpperCase.replace('.', '_')
    }

    def getElementName(FModelElement fModelElement) {
        if ((fModelElement.name == null || fModelElement.name == "") && fModelElement instanceof FTypeCollection) {
            return "__Anonymous__"
        }
        else {
            return fModelElement.name
        }
    }

    def private dispatch List<String> getNamespaceAsList(FModel fModel) {
        newArrayList(fModel.name.split("\\."))
    }

    def private dispatch List<String> getNamespaceAsList(FModelElement fModelElement) {
        val namespaceList = fModelElement.eContainer.namespaceAsList
        val isRootElement = fModelElement.eContainer instanceof FModel

        if (!isRootElement)
            namespaceList.add((fModelElement.eContainer as FModelElement).elementName)

        return namespaceList
    }

    def private getSubnamespaceList(FModelElement destination, EObject source) {
        val sourceNamespaceList = source.namespaceAsList
        val destinationNamespaceList = destination.namespaceAsList
        val maxCount = Ints::min(sourceNamespaceList.size, destinationNamespaceList.size)
        var dropCount = 0

        while (dropCount < maxCount &&
            sourceNamespaceList.get(dropCount).equals(destinationNamespaceList.get(dropCount)))
            dropCount = dropCount + 1

        return destinationNamespaceList.drop(dropCount)
    }

    def getRelativeNameReference(FModelElement destination, EObject source) {
        var nameReference = destination.elementName

        if (destination.eContainer != null && !destination.eContainer.equals(source)) {
            val subnamespaceList = destination.getSubnamespaceList(source)
            if (!subnamespaceList.empty)
                nameReference = subnamespaceList.join('::') + '::' + nameReference
        }

        return nameReference
    }

    def getHeaderFile(FTypeCollection fTypeCollection) {
        fTypeCollection.elementName + ".hpp"
    }

    def getHeaderPath(FTypeCollection fTypeCollection) {
        fTypeCollection.versionPathPrefix + fTypeCollection.model.directoryPath + '/' + fTypeCollection.headerFile
    }

    def getSourceFile(FTypeCollection fTypeCollection) {
        fTypeCollection.elementName + ".cpp"
    }

    def getSourcePath(FTypeCollection fTypeCollection) {
        fTypeCollection.versionPathPrefix + fTypeCollection.model.directoryPath + '/' + fTypeCollection.sourceFile
    }

    def getProxyBaseHeaderFile(FInterface fInterface) {
        fInterface.elementName + "ProxyBase.hpp"
    }

    def getProxyBaseHeaderPath(FInterface fInterface) {
        fInterface.versionPathPrefix + fInterface.model.directoryPath + '/' + fInterface.proxyBaseHeaderFile
    }

    def getProxyBaseClassName(FInterface fInterface) {
        fInterface.elementName + 'ProxyBase'
    }

    def getProxyHeaderFile(FInterface fInterface) {
        fInterface.elementName + "Proxy.hpp"
    }

    def getProxyHeaderPath(FInterface fInterface) {
        fInterface.versionPathPrefix + fInterface.model.directoryPath + '/' + fInterface.proxyHeaderFile
    }

    def getStubDefaultHeaderFile(FInterface fInterface) {
        fInterface.elementName + "Stub" + skeletonNamePostfix + ".hpp"
    }

	def getSkeletonNamePostfix() {
		FPreferences::instance.getPreference(PreferenceConstants::P_SKELETONPOSTFIX, "Default")
	}
	
	def getHeaderDefineName(FInterface fInterface) {
		fInterface.defineName + "_STUB_" + skeletonNamePostfix.toUpperCase()
	}

    def getStubDefaultHeaderPath(FInterface fInterface) {
        fInterface.versionPathPrefix + fInterface.model.directoryPath + '/' + fInterface.stubDefaultHeaderFile
    }

	def getStubDefaultClassName(FInterface fInterface) {
        fInterface.elementName + "Stub" + skeletonNamePostfix
    }

    def getStubDefaultSourceFile(FInterface fInterface) {
        fInterface.elementName + "Stub" + skeletonNamePostfix + ".cpp"
    }

    def getStubDefaultSourcePath(FInterface fInterface) {
        fInterface.versionPathPrefix + fInterface.model.directoryPath + '/' + fInterface.getStubDefaultSourceFile
    }

    def getStubRemoteEventClassName(FInterface fInterface) {
        fInterface.elementName + 'StubRemoteEvent'
    }

    def getStubAdapterClassName(FInterface fInterface) {
        fInterface.elementName + 'StubAdapter'
    }
    
    def getStubCommonAPIClassName(FInterface fInterface) {
        'CommonAPI::Stub<' + fInterface.stubAdapterClassName + ', ' + fInterface.stubRemoteEventClassName + '>'
    }

    def getStubHeaderFile(FInterface fInterface) {
        fInterface.elementName + "Stub.hpp"
    }

    def getStubHeaderPath(FInterface fInterface) {
        fInterface.versionPathPrefix + fInterface.model.directoryPath + '/' + fInterface.stubHeaderFile
    }

    def generateSelectiveBroadcastStubIncludes(FInterface fInterface, Collection<String> generatedHeaders,
        Collection<String> libraryHeaders) {
        if (!fInterface.broadcasts.filter[!selective].empty) {
            libraryHeaders.add("unordered_set")
        }

        return null
    }

    def generateSelectiveBroadcastProxyIncludes(FInterface fInterface, Collection<String> generatedHeaders,
        Collection<String> libraryHeaders) {
        if (!fInterface.broadcasts.filter[!selective].empty) {
            libraryHeaders.add("CommonAPI/Types.hpp")
        }

        return null
    }

    def getStubClassName(FInterface fInterface) {
        fInterface.elementName + 'Stub'
    }
    
    def getStubFullClassName(FInterface fInterface) {
    	fInterface.getFullName + 'Stub'
    }

    def hasAttributes(FInterface fInterface) {
        !fInterface.attributes.empty
    }

    def hasBroadcasts(FInterface fInterface) {
        !fInterface.broadcasts.empty
    }

    def hasSelectiveBroadcasts(FInterface fInterface) {
        !fInterface.broadcasts.filter[selective].empty
    }

	def Collection<FMethod> getMethodsWithError(FInterface _interface) {
		val Map<String, FMethod> itsMethods = new HashMap<String, FMethod>()
		for (method : _interface.methods.filter[errors != null]) {
			var existing = itsMethods.get(method.name)
			if (existing == null) {
				itsMethods.put(method.name, method)
			} else {
				val List<FEnumerator> itsAdditionals = new ArrayList<FEnumerator>()
				for (e : method.errors.enumerators) {
					var found = false
					for (f : existing.errors.enumerators) {
						if (f.name == e.name) {
							found = true
						}
					}
					if (!found)
						itsAdditionals.add(e)
				}
				existing.errors.enumerators.addAll(itsAdditionals)
			}
		}
		return itsMethods.values
	}

    def generateDefinition(FMethod fMethod, boolean _isDefault) {
        fMethod.generateDefinitionWithin(null, _isDefault)
    }

    def generateDefinitionWithin(FMethod fMethod, String parentClassName, boolean _isDefault) {
        var definition = 'void '
        if (FTypeGenerator::isdeprecated(fMethod.comment))
            definition = "COMMONAPI_DEPRECATED " + definition
        if (!parentClassName.nullOrEmpty)
            definition = definition + parentClassName + '::'

        definition = definition + fMethod.elementName + '(' + fMethod.generateDefinitionSignature(_isDefault) + ')'

        return definition
    }

    def generateDefinitionSignature(FMethod fMethod, boolean _isDefault) {
        var signature = fMethod.inArgs.map['const ' + getTypeName(fMethod, true) + ' &_' + elementName].join(', ')

        if (!fMethod.inArgs.empty)
            signature = signature + ', '

        signature = signature + 'CommonAPI::CallStatus &_internalCallStatus'

        if (fMethod.hasError)
            signature = signature + ', ' + fMethod.getErrorNameReference(fMethod.eContainer) + ' &_error'

        if (!fMethod.outArgs.empty)
            signature = signature + ', ' + fMethod.outArgs.map[getTypeName(fMethod, true) + ' &_' + elementName].join(', ')

        if (!fMethod.fireAndForget) {
            signature += ", const CommonAPI::CallInfo *_info"
            if (_isDefault)
                signature += " = nullptr"
        }
        return signature
    }

    def generateStubSignature(FMethod fMethod) {
        var signature = 'const std::shared_ptr<CommonAPI::ClientId> _client'

        if (!fMethod.inArgs.empty)
            signature = signature + ', '

        signature = signature + fMethod.inArgs.map[getTypeName(fMethod, true) + ' _' + elementName].join(', ')
        
        if (!fMethod.isFireAndForget) {
        	if (signature != "")
        		signature = signature + ", ";
        	signature = signature + fMethod.elementName + "Reply_t _reply";
        }
        
        return signature
    }

    def generateOverloadedStubSignature(FMethod fMethod, String methodName) {
        var signature = 'const std::shared_ptr<CommonAPI::ClientId> _client'

        if (!fMethod.inArgs.empty)
            signature = signature + ', '

        signature = signature + fMethod.inArgs.map[getTypeName(fMethod, true) + ' _' + elementName].join(', ')
        
        if (!fMethod.isFireAndForget) {
        	if (signature != "")
        		signature = signature + ", ";
        	signature = signature + methodName + "Reply_t _reply";
        }
        
        return signature
    }
    
    def generateStubReplySignature(FMethod fMethod) {
        var signature = ''

        if (fMethod.hasError)
            signature = signature + fMethod.getErrorNameReference(fMethod.eContainer) + ' _error'
        if (fMethod.hasError && !fMethod.outArgs.empty)
            signature = signature + ', '

        if (!fMethod.outArgs.empty)
            signature = signature + fMethod.outArgs.map[getTypeName(fMethod, true) + ' _' + elementName].join(', ')

        return signature
    }
    
    def String generateDummyArgumentInitializations(FMethod fMethod) {
       var String retval = ""
       for(list_element : fMethod.outArgs) {
          retval += getTypeName(list_element, fMethod, true)  + ' ' + list_element.elementName
          if (((list_element.type.derived instanceof FStructType
             && (list_element.type.derived as FStructType).hasPolymorphicBase))
             || list_element.array){
                retval += " = {}"
          } else if(list_element.type.predefined != null) {
             // primitive types
             switch list_element.type.predefined {
               case FBasicTypeId::BOOLEAN: retval+= " = false"
               case FBasicTypeId::INT8: retval += " = 0"
               case FBasicTypeId::UINT8: retval += " = 0"
               case FBasicTypeId::INT16: retval += " = 0"
               case FBasicTypeId::UINT16: retval += " = 0"
               case FBasicTypeId::INT32: retval += " = 0"
               case FBasicTypeId::UINT32: retval += " = 0"
               case FBasicTypeId::INT64: retval += " = 0"
               case FBasicTypeId::UINT64: retval += " = 0"
               case FBasicTypeId::FLOAT: retval += " = 0.0f"
               case FBasicTypeId::DOUBLE: retval += " = 0.0"
               case FBasicTypeId::STRING: retval += " = \"\""
               case FBasicTypeId::BYTE_BUFFER: retval += " = {}"
               default: {}//System.out.println("No initialization generated for" +
                   //" non-basic type: " + list_element.getName)
             }
          }
          retval += ";\n"
       }
       return retval
    }

    def generateDummyArgumentDefinitions(FMethod fMethod) {
      var definition = ''
      if (fMethod.hasError)
         definition = fMethod.getErrorNameReference(fMethod.eContainer) + ' error;\n'
      if (!fMethod.outArgs.empty)
         definition = definition + generateDummyArgumentInitializations(fMethod)
      return definition
    }

	def generateDummyArgumentList(FMethod fMethod) {
        var arguments = ''
        if (fMethod.hasError)
            arguments = "error"
	    if (!fMethod.outArgs.empty) {
	        if (arguments != '')
	            arguments = arguments + ', '
            arguments = arguments + fMethod.outArgs.map[elementName].join(', ')
    	}
        return arguments
    }

    def generateFireSelectiveSignatur(FBroadcast fBroadcast, FInterface fInterface) {
        var signature = 'const std::shared_ptr<CommonAPI::ClientId> _client'

        if (!fBroadcast.outArgs.empty)
            signature = signature + ', '

        signature = signature +
            fBroadcast.outArgs.map['const ' + getTypeName(fInterface, true) + ' &_' + elementName].join(', ')

        return signature
    }

    def generateSendSelectiveSignatur(FBroadcast fBroadcast, FInterface fInterface, Boolean withDefault) {
        var signature = fBroadcast.outArgs.map['const ' + getTypeName(fInterface, true) + ' &_' + elementName].join(', ')

        if (!fBroadcast.outArgs.empty)
            signature = signature + ', '

        signature = signature + 'const std::shared_ptr<CommonAPI::ClientIdList> _receivers'

        if (withDefault)
            signature = signature + ' = nullptr'

        return signature
    }

    def generateStubSignatureErrorsAndOutArgs(FMethod fMethod) {
        var signature = ''

        if (fMethod.hasError)
            signature = signature + fMethod.getErrorNameReference(fMethod.eContainer) + ' &_error'
        if (fMethod.hasError && !fMethod.outArgs.empty)
            signature = signature + ', '

        if (!fMethod.outArgs.empty)
            signature = signature + fMethod.outArgs.map[getTypeName(fMethod, true) + ' &_' + elementName].join(', ')

        return signature
    }

    def generateArgumentsToStub(FMethod fMethod) {
        var arguments = ' _client'
        
        if (!fMethod.inArgs.empty)
        	arguments = arguments + ', ' + fMethod.inArgs.map[elementName].join(', ')

        if ((fMethod.hasError || !fMethod.outArgs.empty))
            arguments = arguments + ', '

        if (fMethod.hasError)
            arguments = arguments + '_error'
            
        if (fMethod.hasError && !fMethod.outArgs.empty)
            arguments = arguments + ', '

        if (!fMethod.outArgs.empty)
            arguments = arguments + fMethod.outArgs.map[elementName].join(', ')

        return arguments
    }

    def generateArgumentsToStubOldStyle(FMethod fMethod) {
        var arguments = fMethod.inArgs.map[elementName].join(', ')

        if ((fMethod.hasError || !fMethod.outArgs.empty) && !fMethod.inArgs.empty)
            arguments = arguments + ', '

        if (fMethod.hasError)
            arguments = arguments + '_error'
        if (fMethod.hasError && !fMethod.outArgs.empty)
            arguments = arguments + ', '

        if (!fMethod.outArgs.empty)
            arguments = arguments + fMethod.outArgs.map[elementName].join(', ')

        return arguments
    }

    def generateAsyncDefinition(FMethod fMethod, boolean _isDefault) {
        fMethod.generateAsyncDefinitionWithin(null, _isDefault)
    }

    def generateAsyncDefinitionWithin(FMethod fMethod, String parentClassName, boolean _isDefault) {
        var definition = 'std::future<CommonAPI::CallStatus> '

        if (!parentClassName.nullOrEmpty) {
            definition = definition + parentClassName + '::'
        }

        definition = definition + fMethod.elementName + 'Async(' + fMethod.generateAsyncDefinitionSignature(_isDefault) + ')'

        return definition
    }

    def generateAsyncDefinitionSignature(FMethod fMethod, boolean _isDefault) {
        var signature = fMethod.inArgs.map['const ' + getTypeName(fMethod, true) + ' &_' + elementName].join(', ')
        if (!fMethod.inArgs.empty) {
            signature = signature + ', '
        }
        
        signature += fMethod.asyncCallbackClassName + ' _callback'
        signature += ", const CommonAPI::CallInfo *_info"
        if (_isDefault)
            signature += " = nullptr"
          
        return signature
    }
    
    def getErrorType(FMethod _method) {
    	var errorType = ""
    	if (_method.hasError) {
    		errorType = _method.getErrorNameReference(_method.eContainer)
    	}
    	return errorType
    }

	def getInTypeList(FMethod _method) {
		return _method.inArgs.map[getTypeName(_method, true)].join(', ')
	}
    
	def getOutTypeList(FMethod _method) {
		return _method.outArgs.map[getTypeName(_method, true)].join(', ')
	}
	
	def getErrorAndOutTypeList(FMethod _method) {
		val errorType = _method.errorType
		val outTypes = _method.outTypeList
		
		var errorAndOutTypes = errorType
		if (errorType != "" && outTypes != "") 
			errorAndOutTypes = errorAndOutTypes + ", "
		errorAndOutTypes = errorAndOutTypes + outTypes	
			
		return errorAndOutTypes	
	}

    def private String getBasicMangledName(FBasicTypeId basicType) {
        switch (basicType) {
            case FBasicTypeId::BOOLEAN:
                return "b"
            case FBasicTypeId::INT8:
                return "i8"
            case FBasicTypeId::UINT8:
                return "u8"
            case FBasicTypeId::INT16:
                return "i16"
            case FBasicTypeId::UINT16:
                return "u16"
            case FBasicTypeId::INT32:
                return "i32"
            case FBasicTypeId::UINT32:
                return "u32"
            case FBasicTypeId::INT64:
                return "i64"
            case FBasicTypeId::UINT64:
                return "u64"
            case FBasicTypeId::FLOAT:
                return "f"
            case FBasicTypeId::DOUBLE:
                return "d"
            case FBasicTypeId::STRING:
                return "s"
            case FBasicTypeId::BYTE_BUFFER:
                return "au8"
			default: {
				return null
			}
        }
    }

    def private dispatch String getDerivedMangledName(FEnumerationType fType) {
        "Ce" + fType.fullyQualifiedName
    }

    def private dispatch String getDerivedMangledName(FMapType fType) {
        "Cm" + fType.fullyQualifiedName
    }

    def private dispatch String getDerivedMangledName(FStructType fType) {
        "Cs" + fType.fullyQualifiedName
    }

    def private dispatch String getDerivedMangledName(FUnionType fType) {
        "Cv" + fType.fullyQualifiedName
    }

    def private dispatch String getDerivedMangledName(FArrayType fType) {
        "Ca" + fType.elementType.mangledName
    }

    def private dispatch String getDerivedMangledName(FTypeDef fType) {
        fType.actualType.mangledName
    }

    def private String getMangledName(FTypeRef fTypeRef) {
        if (fTypeRef.derived != null) {
            return fTypeRef.derived.derivedMangledName
        } else {
            return fTypeRef.predefined.basicMangledName
        }
    }

    def private getBasicAsyncCallbackClassName(FMethod fMethod) {
        fMethod.elementName.toFirstUpper + 'AsyncCallback'
    }

    def private int16Hash(String originalString) {
        val hash32bit = originalString.hashCode

        var hash16bit = hash32bit.bitwiseAnd(0xFFFF)
        hash16bit = hash16bit.bitwiseXor((hash32bit >> 16).bitwiseAnd(0xFFFF))

        return hash16bit
    }

    def private getMangledAsyncCallbackClassName(FMethod fMethod) {
        val baseName = fMethod.basicAsyncCallbackClassName + '_'
        var mangledName = ''
        for (outArg : fMethod.outArgs) {
            mangledName = mangledName + outArg.type.mangledName
        }
		mangledName = mangledName + fMethod.errorEnum?.name

        return baseName + mangledName.int16Hash
    }

    def String getAsyncCallbackClassName(FMethod fMethod) {
        if (fMethod.needsMangling) {
            return fMethod.mangledAsyncCallbackClassName
        } else {
            return fMethod.basicAsyncCallbackClassName
        }
    }

    def hasError(FMethod fMethod) {
        fMethod.errorEnum != null || fMethod.errors != null
    }

    def generateASyncTypedefSignature(FMethod fMethod) {
        var signature = 'const CommonAPI::CallStatus&'

        if (fMethod.hasError)
            signature = signature + ', const ' + fMethod.getErrorNameReference(fMethod.eContainer) + '&'

        if (!fMethod.outArgs.empty)
            signature = signature + ', ' + fMethod.outArgs.map['const ' + getTypeName(fMethod, true) + '&'].join(', ')

        return signature
    }

    def needsMangling(FMethod fMethod) {
        for (otherMethod : fMethod.containingInterface.methods) {
            if (otherMethod != fMethod && otherMethod.basicAsyncCallbackClassName == fMethod.basicAsyncCallbackClassName &&
                otherMethod.generateASyncTypedefSignature != fMethod.generateASyncTypedefSignature) {
                return true
            }
        }
        return false
    }

    def getErrorNameReference(FMethod fMethod, EObject source) {
        checkArgument(fMethod.hasError, 'FMethod has no error: ' + fMethod)
        if (fMethod.errorEnum != null) {
            return fMethod.errorEnum.getElementName(fMethod, true)
        }

        var errorNameReference = fMethod.errors.errorName
        errorNameReference = (fMethod.eContainer as FInterface).getRelativeNameReference(source) + '::' +
            errorNameReference
        return errorNameReference
    }

    def getClassName(FAttribute fAttribute) {
        fAttribute.elementName.toFirstUpper + 'Attribute'
    }

    def generateGetMethodDefinition(FAttribute fAttribute) {
        fAttribute.generateGetMethodDefinitionWithin(null)
    }

    def generateGetMethodDefinitionWithin(FAttribute fAttribute, String parentClassName) {
        var definition = fAttribute.className + '& '

        if (!parentClassName.nullOrEmpty)
            definition = parentClassName + '::' + definition + parentClassName + '::'

        definition = definition + 'get' + fAttribute.className + '()'

        return definition
    }

    def isReadonly(FAttribute fAttribute) {
        fAttribute.readonly
    }

    def isObservable(FAttribute fAttribute) {
        fAttribute.noSubscriptions == false
    }

    def getStubAdapterClassFireChangedMethodName(FAttribute fAttribute) {
        'fire' + fAttribute.elementName.toFirstUpper + 'AttributeChanged'
    }

    def getStubRemoteEventClassSetMethodName(FAttribute fAttribute) {
        'onRemoteSet' + fAttribute.elementName.toFirstUpper + 'Attribute'
    }

    def getStubRemoteEventClassChangedMethodName(FAttribute fAttribute) {
        'onRemote' + fAttribute.elementName.toFirstUpper + 'AttributeChanged'
    }

    def getStubClassGetMethodName(FAttribute fAttribute) {
        'get' + fAttribute.elementName.toFirstUpper + 'Attribute'
    }

    def getClassName(FBroadcast fBroadcast) {
        var className = fBroadcast.elementName.toFirstUpper

        if (fBroadcast.selective)
            className = className + 'Selective'

        className = className + 'Event'

        return className
    }

    def generateGetMethodDefinition(FBroadcast fBroadcast) {
        fBroadcast.generateGetMethodDefinitionWithin(null)
    }
    
    def String getTypes(FBroadcast _broadcast) {
    	return _broadcast.outArgs.map[getTypeName(_broadcast, true)].join(', ')
    }

    def generateGetMethodDefinitionWithin(FBroadcast fBroadcast, String parentClassName) {
        var definition = fBroadcast.className + '& '

        if (!parentClassName.nullOrEmpty)
            definition = parentClassName + '::' + definition + parentClassName + '::'

        definition = definition + 'get' + fBroadcast.className + '()'

        return definition
    }

    def getStubAdapterClassFireEventMethodName(FBroadcast fBroadcast) {
        'fire' + fBroadcast.elementName.toFirstUpper + 'Event'
    }

    def getStubAdapterClassFireSelectiveMethodName(FBroadcast fBroadcast) {
        'fire' + fBroadcast.elementName.toFirstUpper + 'Selective';
    }

    def getStubAdapterClassSendSelectiveMethodName(FBroadcast fBroadcast) {
        'send' + fBroadcast.elementName.toFirstUpper + 'Selective';
    }

    def getSubscribeSelectiveMethodName(FBroadcast fBroadcast) {
        'subscribeFor' + fBroadcast.elementName + 'Selective';
    }

    def getUnsubscribeSelectiveMethodName(FBroadcast fBroadcast) {
        'unsubscribeFrom' + fBroadcast.elementName + 'Selective';
    }

    def getSubscriptionChangedMethodName(FBroadcast fBroadcast) {
        'on' + fBroadcast.elementName.toFirstUpper + 'SelectiveSubscriptionChanged';
    }

    def getSubscriptionRequestedMethodName(FBroadcast fBroadcast) {
        'on' + fBroadcast.elementName.toFirstUpper + 'SelectiveSubscriptionRequested';
    }

    def getStubAdapterClassSubscribersMethodName(FBroadcast fBroadcast) {
        'getSubscribersFor' + fBroadcast.elementName.toFirstUpper + 'Selective';
    }

    def getStubAdapterClassSubscriberListPropertyName(FBroadcast fBroadcast) {
        'subscribersFor' + fBroadcast.elementName.toFirstUpper + 'Selective_';
    }

    def getStubSubscribeSignature(FBroadcast fBroadcast) {
        'const std::shared_ptr<CommonAPI::ClientId> clientId, bool& success'
    }

    def String getTypeName(FTypedElement _element, FModelElement _source, boolean _isOther) {
    	var String typeName = _element.type.getElementType(_source, _isOther)
    	
        if (_element.type.derived instanceof FStructType && (_element.type.derived as FStructType).hasPolymorphicBase)
            typeName = 'std::shared_ptr<' + typeName + '>'

        if (_element.array) {
            typeName = 'std::vector<' + typeName + '>'
        }

        return typeName
    }
    
    def String getElementType(FTypeRef _typeRef, FModelElement _container, boolean _isOther) {
    	var String typeName
    	if (_typeRef.derived != null) {
	   		typeName = _typeRef.derived.getElementName(_container, _isOther)
    	} else if (_typeRef.predefined != null) {
    		typeName = _typeRef.predefined.primitiveTypeName
    	}
    	return typeName
    }

    def boolean isPolymorphic(FTypeRef typeRef) {
        return (typeRef.derived != null && typeRef.derived instanceof FStructType && (typeRef.derived as FStructType).polymorphic)
    }

    def getNameReference(FTypeRef destination, EObject source) {
        if (destination.derived != null)
            return destination.derived.getRelativeNameReference(source)
        return destination.predefined.primitiveTypeName
    }

    def getErrorName(FEnumerationType fMethodErrors) {
        checkArgument(fMethodErrors.eContainer instanceof FMethod, 'Not FMethod errors')
        (fMethodErrors.eContainer as FMethod).elementName + 'Error'
    }

    def getBackingType(FEnumerationType fEnumerationType, PropertyAccessor deploymentAccessor) {
        if (deploymentAccessor.getEnumBackingType(fEnumerationType) == EnumBackingType::UseDefault) {
            if (fEnumerationType.containingInterface != null) {
                switch (deploymentAccessor.getDefaultEnumBackingType(fEnumerationType.containingInterface)) {
                    case DefaultEnumBackingType::UInt8:
                        return FBasicTypeId::UINT8
                    case DefaultEnumBackingType::UInt16:
                        return FBasicTypeId::UINT16
                    case DefaultEnumBackingType::UInt32:
                        return FBasicTypeId::UINT32
                    case DefaultEnumBackingType::UInt64:
                        return FBasicTypeId::UINT64
                    case DefaultEnumBackingType::Int8:
                        return FBasicTypeId::INT8
                    case DefaultEnumBackingType::Int16:
                        return FBasicTypeId::INT16
                    case DefaultEnumBackingType::Int32:
                        return FBasicTypeId::INT32
                    case DefaultEnumBackingType::Int64:
                        return FBasicTypeId::INT64
                }
            }
        }
        switch (deploymentAccessor.getEnumBackingType(fEnumerationType)) {
            case EnumBackingType::UInt8:
                return FBasicTypeId::UINT8
            case EnumBackingType::UInt16:
                return FBasicTypeId::UINT16
            case EnumBackingType::UInt32:
                return FBasicTypeId::UINT32
            case EnumBackingType::UInt64:
                return FBasicTypeId::UINT64
            case EnumBackingType::Int8:
                return FBasicTypeId::INT8
            case EnumBackingType::Int16:
                return FBasicTypeId::INT16
            case EnumBackingType::Int32:
                return FBasicTypeId::INT32
            case EnumBackingType::Int64:
                return FBasicTypeId::INT64
			default: {
				return FBasicTypeId::INT32
			}
        }
    }

    def String getBaseType(FEnumerationType _enumeration, String _backingType) {
        var String baseType
        if (_enumeration.base != null) {
            baseType = _enumeration.base.getElementName(_enumeration, false)
        } else {
            baseType = "CommonAPI::Enumeration<" + _backingType + ">"
        }
        return baseType
    }

	def private getMaximumEnumerationValue(FEnumerationType _enumeration) {
		var int maximum = 0;
		for (literal : _enumeration.enumerators) {
			if (literal.value != null && literal.value != "") {
				val int literalValue = Integer.parseInt(literal.value.enumeratorValue) 
				if (maximum < literalValue)
					maximum = literalValue
			}
		}
		return maximum
	} 

	def void setEnumerationValues(FEnumerationType _enumeration) {
		var int currentValue = 0
		val predefineEnumValues = new ArrayList<String>()

		// collect all predefined enum values
		for (literal : _enumeration.enumerators) {
			if (literal.value != null) {
				predefineEnumValues.add(literal.value.enumeratorValue)
			}
		}
		if (_enumeration.base != null) {
			setEnumerationValues(_enumeration.base)
			currentValue = getMaximumEnumerationValue(_enumeration.base) + 1
		}

		for (literal : _enumeration.enumerators) {
			if (literal.value == null || literal.value == "") {
				// not predefined
				while (predefineEnumValues.contains(String.valueOf(currentValue))) {
					// increment it, if this was found in the list of predefined values
					currentValue += 1
				}
				literal.setValue(toExpression(Integer.toString(currentValue)))
			} else {
				var enumValue = literal.value.enumeratorValue
				if (enumValue != null) {
					try {
						val int literalValue = Integer.parseInt(enumValue)
						literal.setValue(toExpression(Integer.toString(literalValue)))
					} catch (NumberFormatException e) {
						literal.setValue(toExpression(Integer.toString(currentValue)))
					}
				} else {
					literal.setValue(toExpression(Integer.toString(currentValue)))
				}
			}
			currentValue += 1
		}
	}

   def getPrimitiveTypeName(FBasicTypeId fBasicTypeId) {
        switch fBasicTypeId {
            case FBasicTypeId::BOOLEAN: "bool"
            case FBasicTypeId::INT8: "int8_t"
            case FBasicTypeId::UINT8: "uint8_t"
            case FBasicTypeId::INT16: "int16_t"
            case FBasicTypeId::UINT16: "uint16_t"
            case FBasicTypeId::INT32: "int32_t"
            case FBasicTypeId::UINT32: "uint32_t"
            case FBasicTypeId::INT64: "int64_t"
            case FBasicTypeId::UINT64: "uint64_t"
            case FBasicTypeId::FLOAT: "float"
            case FBasicTypeId::DOUBLE: "double"
            case FBasicTypeId::STRING: "std::string"
            case FBasicTypeId::BYTE_BUFFER: "CommonAPI::ByteBuffer"
            default: throw new IllegalArgumentException("Unsupported basic type: " + fBasicTypeId.getName)
        }
    }

    def String typeStreamSignature(FTypeRef fTypeRef, PropertyAccessor deploymentAccessor, FField forThisElement) {
        if (forThisElement.array) {
            var String ret = ""
            ret = ret + "typeOutputStream.beginWriteVectorType();\n"
            ret = ret + fTypeRef.actualTypeStreamSignature(deploymentAccessor)
            ret = ret + "typeOutputStream.endWriteVectorType();\n"
            return ret
        }
        return fTypeRef.actualTypeStreamSignature(deploymentAccessor)
    }

    def String actualTypeStreamSignature(FTypeRef fTypeRef, PropertyAccessor deploymentAccessor) {
        if (fTypeRef.derived != null) {
            return fTypeRef.derived.typeStreamFTypeSignature(deploymentAccessor)
        }

        return fTypeRef.predefined.basicTypeStreamSignature
    }

	def String createSerials(FStructType fStructType) {
		var String serials;
		serials = "static const CommonAPI::Serial " 
				  + fStructType.elementName.toUpperCase() + "_SERIAL = 0x"
				  + getSerialId(fStructType).toHexString.toUpperCase() + ";\n";
		for (derived : fStructType.derivedFStructTypes)
			serials = serials + createSerials(derived)
		return serials
	}
	
	def String generateCases(FStructType fStructType, FModelElement parent, boolean qualified) {
		var String itsCases = "case ";
			
		//if (parent != null)
		//	itsCases = itsCases + parent.elementName + "::"
					
		if (qualified) {
			 itsCases = itsCases 
			 if (fStructType.containingInterface != null)
			     itsCases = itsCases + fStructType.containingInterface.elementName  + "::";
		}
		
		itsCases = itsCases + fStructType.elementName.toUpperCase() + "_SERIAL:\n";

		for (derived : fStructType.derivedFStructTypes)
			itsCases = itsCases + derived.generateCases(parent, qualified);

		return itsCases;
	}

    def private String getBasicTypeStreamSignature(FBasicTypeId fBasicTypeId) {
        switch fBasicTypeId {
            case FBasicTypeId::BOOLEAN: return "typeOutputStream.writeBoolType();"
            case FBasicTypeId::INT8: return "typeOutputStream.writeInt8Type();"
            case FBasicTypeId::UINT8: return "typeOutputStream.writeUInt8Type();"
            case FBasicTypeId::INT16: return "typeOutputStream.writeInt16Type();"
            case FBasicTypeId::UINT16: return "typeOutputStream.writeUInt16Type();"
            case FBasicTypeId::INT32: return "typeOutputStream.writeInt32Type();"
            case FBasicTypeId::UINT32: return "typeOutputStream.writeUInt32Type();"
            case FBasicTypeId::INT64: return "typeOutputStream.writeInt64Type();"
            case FBasicTypeId::UINT64: return "typeOutputStream.writeUInt64Type();"
            case FBasicTypeId::FLOAT: return "typeOutputStream.writeFloatType();"
            case FBasicTypeId::DOUBLE: return "typeOutputStream.writeDoubleType();"
            case FBasicTypeId::STRING: return "typeOutputStream.writeStringType();"
            case FBasicTypeId::BYTE_BUFFER: return "typeOutputStream.writeByteBufferType();"
			default: return "UNDEFINED"
        }
    }

    def private dispatch String typeStreamFTypeSignature(FTypeDef fTypeDef,
        PropertyAccessor deploymentAccessor) {
        return fTypeDef.actualType.actualTypeStreamSignature(deploymentAccessor)
    }

    def private dispatch String typeStreamFTypeSignature(FArrayType fArrayType,
        PropertyAccessor deploymentAccessor) {
        return 'typeOutputStream.beginWriteVectorType();\n' +
            fArrayType.elementType.actualTypeStreamSignature(deploymentAccessor) + '\n' +
            'typeOutputStream.endWriteVectorType();'
    }

    def private dispatch String typeStreamFTypeSignature(FMapType fMap,
        PropertyAccessor deploymentAccessor) {
        return 'typeOutputStream.beginWriteMapType();\n' + fMap.keyType.actualTypeStreamSignature(deploymentAccessor) + '\n' +
            fMap.valueType.actualTypeStreamSignature(deploymentAccessor) + '\n' + 'typeOutputStream.endWriteMapType();'
    }

    def private dispatch String typeStreamFTypeSignature(FStructType fStructType,
        PropertyAccessor deploymentAccessor) {
        return 'typeOutputStream.beginWriteStructType();\n' +
            fStructType.getElementsTypeStreamSignature(deploymentAccessor) + '\n' +
            'typeOutputStream.endWriteStructType();'
    }

    def private dispatch String typeStreamFTypeSignature(FEnumerationType fEnumerationType,
        PropertyAccessor deploymentAccessor) {
        val backingType = fEnumerationType.getBackingType(deploymentAccessor)
        if (backingType != FBasicTypeId.UNDEFINED)
            return backingType.basicTypeStreamSignature
    
        return FBasicTypeId.INT32.basicTypeStreamSignature
    }

    def private dispatch String typeStreamFTypeSignature(FUnionType fUnionType,
        PropertyAccessor deploymentAccessor) {
        return 'typeOutputStream.writeVariantType();'
    }

    def private String getElementsTypeStreamSignature(FStructType fStructType,
        PropertyAccessor deploymentAccessor) {
        var signature = fStructType.elements.map[type.typeStreamSignature(deploymentAccessor, it)].join

        if (fStructType.base != null)
            signature = fStructType.base.getElementsTypeStreamSignature(deploymentAccessor) + signature

        return signature
    }

    def List<FType> getDirectlyReferencedTypes(FType type) {
        val directlyReferencedTypes = newLinkedList

        directlyReferencedTypes.addFTypeDirectlyReferencedTypes(type)

        return directlyReferencedTypes
    }

    def private dispatch addFTypeDirectlyReferencedTypes(List<FType> list, FStructType fType) {
        list.addAll(fType.elements.filter[type.derived != null].map[type.derived])

        if (fType.base != null)
            list.add(fType.base)
    }

    def private dispatch addFTypeDirectlyReferencedTypes(List<FType> list, FEnumerationType fType) {
        if (fType.base != null)
            list.add(fType.base)
    }

    def private dispatch addFTypeDirectlyReferencedTypes(List<FType> list, FArrayType fType) {
        if (fType.elementType.derived != null)
            list.add(fType.elementType.derived)
    }

    def private dispatch addFTypeDirectlyReferencedTypes(List<FType> list, FUnionType fType) {
        list.addAll(fType.elements.filter[type.derived != null].map[type.derived])

        if (fType.base != null)
            list.add(fType.base)
    }

    def private dispatch addFTypeDirectlyReferencedTypes(List<FType> list, FMapType fType) {
        if (fType.keyType.derived != null)
            list.add(fType.keyType.derived)

        if (fType.valueType.derived != null)
            list.add(fType.valueType.derived)
    }

    def private dispatch addFTypeDirectlyReferencedTypes(List<FType> list, FTypeDef fType) {
        if (fType.actualType.derived != null)
            list.add(fType.actualType.derived)
    }

    def boolean hasPolymorphicBase(FStructType fStructType) {
        if (fStructType.isPolymorphic)
            return true;

        return fStructType.base != null && fStructType.base.hasPolymorphicBase
    }
    
    def boolean hasDerivedTypes(FStructType fStructType) {
    	return !fStructType.derivedFStructTypes.empty
    }

    def getSerialId(FStructType fStructType) {
        val hasher = Hashing::murmur3_32.newHasher
        hasher.putFTypeObject(fStructType);
        return hasher.hash.asInt
    }

    def private dispatch void putFTypeObject(Hasher hasher, FStructType fStructType) {
        if (fStructType.base != null)
            hasher.putFTypeObject(fStructType.base)

        hasher.putString('FStructType', Charsets::UTF_8)
        fStructType.elements.forEach [
            hasher.putFTypeRef(type)
            // avoid cases where the positions of 2 consecutive elements of the same type are switched
            hasher.putString(elementName, Charsets::UTF_8)
        ]
    }

    def private dispatch void putFTypeObject(Hasher hasher, FEnumerationType fEnumerationType) {
        if (fEnumerationType.base != null)
            hasher.putFTypeObject(fEnumerationType.base)

        hasher.putString('FEnumerationType', Charsets::UTF_8)
        hasher.putInt(fEnumerationType.enumerators.size)
    }

    def private dispatch void putFTypeObject(Hasher hasher, FArrayType fArrayType) {
        hasher.putString('FArrayType', Charsets::UTF_8)
        hasher.putFTypeRef(fArrayType.elementType)
    }

    def private dispatch void putFTypeObject(Hasher hasher, FUnionType fUnionType) {
        if (fUnionType.base != null)
            hasher.putFTypeObject(fUnionType.base)

        hasher.putString('FUnionType', Charsets::UTF_8)
        fUnionType.elements.forEach[hasher.putFTypeRef(type)]
    }

    def private dispatch void putFTypeObject(Hasher hasher, FMapType fMapType) {
        hasher.putString('FMapType', Charsets::UTF_8)
        hasher.putFTypeRef(fMapType.keyType)
        hasher.putFTypeRef(fMapType.valueType)
    }

    def private dispatch void putFTypeObject(Hasher hasher, FTypeDef fTypeDef) {
        hasher.putFTypeRef(fTypeDef.actualType)
    }

    def private void putFTypeRef(Hasher hasher, FTypeRef fTypeRef) {
        if (fTypeRef.derived != null)
            hasher.putFTypeObject(fTypeRef.derived)
        else
            hasher.putString(fTypeRef.predefined.getName, Charsets::UTF_8);
    }

    def boolean hasDerivedFStructTypes(FStructType fStructType) {
        return EcoreUtil.UsageCrossReferencer::find(fStructType, fStructType.model.eResource.resourceSet).exists [
            EObject instanceof FStructType && (EObject as FStructType).base == fStructType
        ]
    }

    def getDerivedFStructTypes(FStructType fStructType) {
        return EcoreUtil.UsageCrossReferencer::find(fStructType, fStructType.model.eResource.resourceSet).map[EObject].
            filter[it instanceof FStructType].map[it as FStructType].filter[base == fStructType]
    }
    
    def generateCppNamespace(FModel fModel) '''
    «fModel.namespaceAsList.map[toString].join("::")»::'''

    def generateNamespaceBeginDeclaration(FModel fModel) '''
        «FOR subnamespace : fModel.namespaceAsList»
            namespace «subnamespace» {
        «ENDFOR»
    '''

    def generateNamespaceEndDeclaration(FModel fModel) '''
        «FOR subnamespace : fModel.namespaceAsList.reverse»
            } // namespace «subnamespace»
        «ENDFOR»
    '''

    def generateVersionNamespaceBegin(FTypeCollection _tc) '''
        «var FVersion itsVersion = _tc.version»
        «IF itsVersion != null && (itsVersion.major != 0 || itsVersion.minor != 0)»
            namespace v«itsVersion.major.toString»_«itsVersion.minor.toString» {
        «ENDIF»  
    '''

    def generateVersionNamespaceEnd(FTypeCollection _tc) '''
        «var FVersion itsVersion = _tc.version»
        «IF itsVersion != null && (itsVersion.major != 0 || itsVersion.minor != 0)»
            } // namespace v«itsVersion.major.toString»_«itsVersion.minor.toString»
        «ENDIF»
    '''

	def generateDeploymentNamespaceBegin(FTypeCollection _tc) '''
        namespace «_tc.elementName»_ {
    '''

    def generateDeploymentNamespaceEnd(FTypeCollection _tc) '''
        } // namespace «_tc.elementName»_
    '''
    
    def getVersionPrefix(FTypeCollection _tc) {
        var String prefix = "::"
        var FVersion itsVersion = _tc.version
        if (itsVersion != null && (itsVersion.major != 0 || itsVersion.minor != 0)) {
            prefix += "v" + itsVersion.major.toString + "_" + itsVersion.minor.toString + "::"
        }
        return prefix
    }

    def getVersionPathPrefix(FTypeCollection _tc) {
    	var String prefix = ""
        var FVersion itsVersion = _tc.version
        if (itsVersion != null && (itsVersion.major != 0 || itsVersion.minor != 0)) {
            prefix = "v" + itsVersion.major.toString + "_" + itsVersion.minor.toString + "/"
        }
        return prefix
    }
    
	// TODO: Remove the following method
    def isFireAndForget(FMethod fMethod) {
        return fMethod.fireAndForget
    }

    def getFilePath(Resource resource) {
        if (resource.URI.file)
            return resource.URI.toFileString

        val platformPath = new Path(resource.URI.toPlatformString(true))
        val file = ResourcesPlugin::getWorkspace().getRoot().getFile(platformPath);

        return file.location.toString
    }

    def getHeader(FModel model, IResource res) {
        if (FrameworkUtil::getBundle(this.getClass()) != null) {
            var returnValue = DefaultScope::INSTANCE.getNode(PreferenceConstants::SCOPE).get(PreferenceConstants::P_LICENSE, "")
            returnValue = InstanceScope::INSTANCE.getNode(PreferenceConstants::SCOPE).get(PreferenceConstants::P_LICENSE, returnValue)
            returnValue = FPreferences::instance.getPreference(PreferenceConstants::P_LICENSE, returnValue)
            return returnValue
        }
        return ""
    }

    def getFrancaVersion() {
        val bundle = FrameworkUtil::getBundle(FrancaGeneratorExtensions)
        val bundleContext = bundle.getBundleContext();
        for (b : bundleContext.bundles) {
            if (b.symbolicName.equals("org.franca.core")) {
                return b.version.toString
            }
        }
    }

    def static getCoreVersion() {
        val bundle = FrameworkUtil::getBundle(FrancaGeneratorExtensions)
        val bundleContext = bundle.getBundleContext();
        for (b : bundleContext.bundles) {
            if (b.symbolicName.equals("org.genivi.commonapi.core")) {
                return b.version.toString
            }
        }
    }

    def generateCommonApiLicenseHeader(FModelElement model, IResource modelid) '''
        /*
        * This file was generated by the CommonAPI Generators.
        * Used org.genivi.commonapi.core «FrancaGeneratorExtensions::getCoreVersion()».
        * Used org.franca.core «getFrancaVersion()».
        *
        «getCommentedString(getHeader(model.model, modelid))»
        */
    '''

    def getCommentedString(String string) {
        val lines = string.split("\n");
        var builder = new StringBuilder();
        for (String line : lines) {
            builder.append("* " + line + "\n");
        }
        return builder.toString()
    }

    def stubManagedSetName(FInterface fInterface) {
        'registered' + fInterface.elementName + 'Instances'
    }

    def stubManagedSetGetterName(FInterface fInterface) {
        'get' + fInterface.elementName + 'Instances'
    }

    def stubRegisterManagedName(FInterface fInterface) {
        'registerManagedStub' + fInterface.elementName
    }

    def stubRegisterManagedAutoName(FInterface fInterface) {
        'registerManagedStub' + fInterface.elementName + 'AutoInstance'
    }

    def stubRegisterManagedMethod(FInterface fInterface) {
        'bool ' + fInterface.stubRegisterManagedName + '(std::shared_ptr<' + fInterface.getStubFullClassName + '>, const std::string&)'
    }

    def stubRegisterManagedMethodImpl(FInterface fInterface) {
        fInterface.stubRegisterManagedName + '(std::shared_ptr<' + fInterface.getStubFullClassName + '> _stub, const std::string &_instance)'
    }    

    def stubDeregisterManagedName(FInterface fInterface) {
        'deregisterManagedStub' + fInterface.elementName
    }

    def proxyManagerGetterName(FInterface fInterface) {
        'getProxyManager' + fInterface.elementName
    }

    def proxyManagerMemberName(FInterface fInterface) {
        'proxyManager' + fInterface.elementName + '_'
    }
    
    def Set<FInterface> getBaseInterfaces(FInterface _interface) {
    	val Set<FInterface> baseInterfaces = new HashSet<FInterface>()
    	if (_interface.base != null) {
    		baseInterfaces.add(_interface.base)
    		baseInterfaces.addAll(getBaseInterfaces(_interface.base))
    	}
    	return baseInterfaces
    }
    
    def generateBaseInstantiations(FInterface _interface) {
		val Set<FInterface> baseInterfaces = getBaseInterfaces(_interface)
		return baseInterfaces.map[getTypeCollectionName(_interface) + "(_address, _connection)"].join(',\n')
	}
	
    def generateDBusBaseInstantiations(FInterface _interface) {
		val Set<FInterface> baseInterfaces = getBaseInterfaces(_interface)
		return baseInterfaces.map[
					getTypeCollectionName(_interface) +
					"DBusProxy(_address, _connection)"		
		].join(',\n')
	}
	
    def generateSomeIPBaseInstantiations(FInterface _interface) {
		val Set<FInterface> baseInterfaces = getBaseInterfaces(_interface)
		return baseInterfaces.map[
					getTypeCollectionName(_interface) +
					"SomeIPProxy(_address, _connection)"		
		].join(',\n')
	}	
	
	def String generateBaseRemoteHandlerConstructorsCalls(FInterface _interface) {
		val Set<FInterface> baseInterfaces = getBaseInterfaces(_interface)
		var String itsCalls = ""
		itsCalls = baseInterfaces.map[getTypeCollectionName(_interface) + "StubDefault::RemoteEventHandler(_defaultStub)"].join(', ')
		if (itsCalls != "")
			itsCalls = itsCalls + ','
		return itsCalls
	}
	
    def List<FMethod> getInheritedMethods(FInterface fInterface) {
    	val List<FMethod> result = new ArrayList<FMethod>()
    	
        if(fInterface.base == null) {
        	return result
        }

        result.addAll(fInterface.base.methods)
        result.addAll(fInterface.base.inheritedMethods)

        return result
    }

    def List<FAttribute> getInheritedAttributes(FInterface fInterface) {
        val List<FAttribute> result = new ArrayList<FAttribute>()
        if(fInterface.base == null) {
            return result
        }

        result.addAll(fInterface.base.attributes)
        result.addAll(fInterface.base.inheritedAttributes)

        return result
    }

    def List<FBroadcast> getInheritedBroadcasts(FInterface fInterface) {
        val List<FBroadcast> result = new ArrayList<FBroadcast>()
        
        if(fInterface.base == null) {
            return result
        }

        result.addAll(fInterface.base.broadcasts)
        result.addAll(fInterface.base.inheritedBroadcasts)

        return result
    }
    
    def static FExpression toExpression(String value)
    {
        return switch trimmedValue : if(value != null) value.trim else ""
        {
            case trimmedValue.length > 0:
            {
                try
                {
                    FrancaFactory.eINSTANCE.createFIntegerConstant => [
                        ^val = new BigInteger(trimmedValue)
                    ]
                }
                catch(NumberFormatException e)
                {
                    FrancaFactory.eINSTANCE.createFStringConstant => [
                        ^val = trimmedValue
                    ]
                }
            }
            default:
            {
                null
            }
        }
    }

    def static String getEnumeratorValue(FExpression expression)
    {
        return switch (expression)
        {
            FIntegerConstant: expression.^val.toString
            FStringConstant: expression.^val
            FQualifiedElementRef: expression.element.constantValue
            default: null
        }
    }

    def static String getConstantValue(FModelElement  expression)
    {
        return switch (expression)
        {
            FConstantDef: expression.rhs.constantType
            default: null
        }
    }

    def static String getConstantType(FInitializerExpression  expression)
    {
        return switch (expression)
        {
            FIntegerConstant: expression.^val.toString
            default: null
        }
    }

    def Integer getTimeout(FMethod _method, PropertyAccessor _accessor) {
    	var timeout = 0;
    	try {
    		timeout = _accessor.getTimeout(_method)
    	}
    	catch (NullPointerException e) {
    		// intentionally empty
    	}
    	return timeout
    }
    
    def boolean isTheSameVersion(FVersion _mine, FVersion _other) {
        return ((_mine == null && _other == null) ||
                (_mine != null && _other != null &&
                 _mine.major == _other.major &&
                 _mine.minor == _other.minor));
        
    }

    def EObject getCommonContainer(EObject _me, EObject _other) {
        if (_other == null)
            return null

        if (_me == _other)
            return _me

        if (_me instanceof FTypeCollection && _other instanceof FTypeCollection) {
            val FTypeCollection me = _me as FTypeCollection
            val FTypeCollection other = _other as FTypeCollection
            
            if (me.eContainer == other.eContainer &&
            	((me.version == null && other.version == null) ||
                 (me.version != null && other.version != null &&
                  me.version.major == other.version.major &&
                  me.version.minor == other.version.minor))) {
                return _me;
           	}
		}

      	return getCommonContainer(_me, _other.eContainer)
    }

    def String getContainerName(EObject _container) {
        var String name = ""
        if (_container instanceof FTypeCollection) {
            name = _container.name
            if (name == null) name = "__Anonymous__"
        } else if (_container instanceof FModelElement) {
            name = _container.name
        } else if (_container instanceof FModel) {
            name = _container.name
        }
        return name
    }

    def String getPartialName(FModelElement _me, EObject _until) {
        var String name = _me.containerName
        var EObject container = _me.eContainer
        while (container != null && container != _until) {
            if (container instanceof FModel) {
                name = container.containerName + "::" + name
            }
            if (container instanceof FModelElement) {
                name = container.containerName + "::" + name
            }
            container = container.eContainer
        }
        return name.replace(".", "::")
    }

    def String getFullName(EObject _me) {
        var String name = ""
        if (_me instanceof FModelElement) {
            var String prefix = ""
            var EObject container = _me
            while (container != null) {
                if (container instanceof FTypeCollection) {
                    prefix = container.versionPrefix
                }
                val containerName = getContainerName(container)
                if (containerName != null && containerName != "") {
                    if (name != "") { 
                        name = containerName + "::" + name
                    } else {
                        name = containerName
                    }
                }
                
                container = container.eContainer
            }
            name = prefix + name
        }
        return name.replace(".", "::")
    }

    def String getElementName(FModelElement _me, FModelElement _other, boolean _isOther) {
        if (_other == null)
            return _me.containerName

        var FVersion myVersion = null
        if (_me instanceof FTypeCollection)
            myVersion = _me.version
            
        var FVersion otherVersion = null
        if (_other instanceof FTypeCollection)
            otherVersion = _other.version

        if (isTheSameVersion(myVersion, otherVersion)) {
            val EObject myContainer = _me.eContainer
            val EObject otherContainer = _other.eContainer

            if (myContainer == otherContainer) {
                var String name = _me.containerName
                if (_isOther) {
                    name = getContainerName(myContainer) + "::" + _me.containerName
                }
                return name
            }

	        if (myContainer.getCommonContainer(otherContainer) != null) {
                return _me.getPartialName(myContainer.eContainer)
            }

            if (otherContainer.getCommonContainer(myContainer) != null) {
                var String name = _me.containerName
                if (_isOther) {
                    name = getContainerName(myContainer) + "::" + name
                }
                return name
            }
        }

        return _me.getFullName()
    }

    def String getTypeCollectionName(FTypeCollection _me, FTypeCollection _other) {
        if (_other == null ||
            _me.eContainer() != _other.eContainer() ||
             !isTheSameVersion(_me.version, _other.version)) {
            return _me.getFullName()
        }
        return _me.getContainerName()
    }
    
    def String getEnumPrefix(){
  			FPreferences::instance.getPreference(PreferenceConstants::P_ENUMPREFIX, "")
    }
    
    def List<FField> getAllElements(FStructType _struct) {
        if (_struct.base == null)
            return new LinkedList(_struct.elements)

        val elements = _struct.base.allElements
        elements.addAll(_struct.elements)
        return elements
    }
    
    def List<FField> getAllElements(FUnionType _union) {
        if (_union.base == null)
            return new LinkedList(_union.elements)

        val elements = _union.base.allElements
        elements.addAll(_union.elements)
        return elements
    }
    
	/**
	 * Get all interfaces from the deployment model that have a specification that contains 
	 * the given selector string (e.g.: "dbus" for commonapi.dbus specification)
	 * @return the list of FDInterfaces
	 */
	def List<FDInterface> getFDInterfaces(FDModel fdmodel, String selector) {
		var List<FDInterface> fdinterfaces = new ArrayList<FDInterface>() 
		
		for(depl : fdmodel.getDeployments()) {
			if (depl instanceof FDInterface) {
				var specname = depl.spec.name
				if(specname != null && specname.contains(selector)) {
				fdinterfaces.add(depl);
				}
			}
		}
		return fdinterfaces;
	}	  
	
  	/**
	 * Get all type collections from the deployment model that have a specification that contains 
	 * the given selector string (e.g.: "dbus" for commonapi.dbus specification)
	 * @return the list of FDTypes
	 */
	def List<FDTypes> getFDTypesList(FDModel fdmodel, String selector) {
		var List<FDTypes> fdTypes = new ArrayList<FDTypes>() 
		
		for(depl : fdmodel.getDeployments()) {
			if (depl instanceof FDTypes) {
				var specname = depl.spec?.name
				if(specname != null && specname.contains(selector)) {
				fdTypes.add(depl);
				}
			}
		}
		return fdTypes;
	}	
	
  	/**
	 * Get all providers from the deployment model that have a specification that contains 
	 * the given selector string (e.g.: "dbus" for commonapi.dbus specification)
	 * @return the list of FDTypes
	 */
	def List<FDProvider> getFDProviders(FDModel fdmodel, String selector) {
		var List<FDProvider> fdProviders = new ArrayList<FDProvider>() 
		
		for(depl : fdmodel.getDeployments()) {
			if (depl instanceof FDProvider) {
				var specname = depl.spec?.name
				if(specname != null && specname.contains(selector)) {
				fdProviders.add(depl);
				}
			}
		}
		return fdProviders;
	}	
	
	/**
	 * Copy deployment attributes into the destination deployment 
	 */
	def mergeDeployments(FDInterface source, FDInterface destination) {
		
		if(source.target.equals(destination.target)) {
			if(source.attributes.size > 0) {
				if( destination.attributes.size == 0) {
					// e.g: attribute timeout
				destination.attributes.addAll(source.attributes)
				}
			}			
			if(source.methods.size > 0) { 
				destination.methods.addAll(source.methods)
			}			
			// e.g: EnumBackingType
			if(source.types.size > 0) {
				destination.types.addAll(source.types)
			}
//    		Not used so far:
//			if(source.broadcasts != null) {
//				destination.broadcasts.addAll(source.broadcasts)
//			}
		} else {
			throw new IllegalArgumentException("Cannot merge deployments for different interfaces \n(" + source.target + " != " + destination.target + ")!");
		}
	}	

    def public getAllReferencedFInterfaces(FModel fModel)
    {
        val referencedFInterfaces = fModel.interfaces.toSet
        fModel.interfaces.forEach[base?.addFInterfaceTree(referencedFInterfaces)]
        fModel.interfaces.forEach[managedInterfaces.forEach[addFInterfaceTree(referencedFInterfaces)]]
        return referencedFInterfaces
    }

    def public void addFInterfaceTree(FInterface fInterface, Collection<FInterface> fInterfaceReferences)
    {
        if(!fInterfaceReferences.contains(fInterface))
        {
            fInterfaceReferences.add(fInterface)
            fInterface.base?.addFInterfaceTree(fInterfaceReferences)
        }
    }

    def public getAllReferencedFTypes(FModel fModel)
    {
        val referencedFTypes = new HashSet<FType>

        fModel.typeCollections.forEach[types.forEach[addFTypeDerivedTree(referencedFTypes)]]

        fModel.interfaces.forEach [
            attributes.forEach[type.addDerivedFTypeTree(referencedFTypes)]
            types.forEach[addFTypeDerivedTree(referencedFTypes)]
            methods.forEach [
                inArgs.forEach[type.addDerivedFTypeTree(referencedFTypes)]
                outArgs.forEach[type.addDerivedFTypeTree(referencedFTypes)]
            ]
            broadcasts.forEach [
                outArgs.forEach[type.addDerivedFTypeTree(referencedFTypes)]
            ]
        ]

        return referencedFTypes
    }

    def public void addDerivedFTypeTree(FTypeRef fTypeRef, Collection<FType> fTypeReferences)
    {
        fTypeRef.derived?.addFTypeDerivedTree(fTypeReferences)
    }

    def public dispatch void addFTypeDerivedTree(FTypeDef fTypeDef, Collection<FType> fTypeReferences)
    {
        if(!fTypeReferences.contains(fTypeDef))
        {
            fTypeReferences.add(fTypeDef)
            fTypeDef.actualType.addDerivedFTypeTree(fTypeReferences)
        }
    }

    def public dispatch void addFTypeDerivedTree(FArrayType fArrayType, Collection<FType> fTypeReferences)
    {
        if(!fTypeReferences.contains(fArrayType))
        {
            fTypeReferences.add(fArrayType)
            fArrayType.elementType?.addDerivedFTypeTree(fTypeReferences)
        }
    }

    def public dispatch void addFTypeDerivedTree(FMapType fMapType, Collection<FType> fTypeReferences)
    {
        if(!fTypeReferences.contains(fMapType))
        {
            fTypeReferences.add(fMapType)
            fMapType.keyType.addDerivedFTypeTree(fTypeReferences)
            fMapType.valueType.addDerivedFTypeTree(fTypeReferences)
        }
    }

    def public dispatch void addFTypeDerivedTree(FStructType fStructType, Collection<FType> fTypeReferences)
    {
        if(!fTypeReferences.contains(fStructType))
        {
            fTypeReferences.add(fStructType)
            fStructType.base?.addFTypeDerivedTree(fTypeReferences)
            fStructType.elements.forEach[type.addDerivedFTypeTree(fTypeReferences)]
        }
    }

    def public dispatch void addFTypeDerivedTree(FEnumerationType fEnumerationType, Collection<FType> fTypeReferences)
    {
        if(!fTypeReferences.contains(fEnumerationType))
        {
            fTypeReferences.add(fEnumerationType)
            fEnumerationType.base?.addFTypeDerivedTree(fTypeReferences)
        }
    }

    def public dispatch void addFTypeDerivedTree(FUnionType fUnionType, Collection<FType> fTypeReferences)
    {
        if(!fTypeReferences.contains(fUnionType))
        {
            fTypeReferences.add(fUnionType)
            fUnionType.base?.addFTypeDerivedTree(fTypeReferences)
            fUnionType.elements.forEach[type.addDerivedFTypeTree(fTypeReferences)]
        }
    }
}