File: 4-ttcn3_language_extensions.adoc

package info (click to toggle)
eclipse-titan 6.5.0-1
  • links: PTS
  • area: main
  • in suites: buster
  • size: 101,128 kB
  • sloc: cpp: 259,139; ansic: 47,560; yacc: 22,554; makefile: 14,074; sh: 12,630; lex: 9,101; xml: 5,362; java: 4,849; perl: 3,784; awk: 48; php: 32; python: 13
file content (8850 lines) | stat: -rw-r--r-- 373,208 bytes parent folder | download
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
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
[[ttcn-3-language-extensions]]
= TTCN–3 Language Extensions
:toc:
:table-number: 3

The Test Executor supports the following non-standard additions to TTCN–3 Core Language in order to improve its usability or provide backward compatibility with older versions.

== Syntax Extensions

The compiler does not report an error or warning if the semi-colon is missing at the end of a TTCN–3 definition although the definition does not end with a closing bracket.

The statement block is optional after the guard operations of `altsteps`, `alt` and `interleave` constructs and in the response and exception handling part of `call` statements. A missing statement block has the same meaning as an empty statement block. If the statement block is omitted, a terminating semi-colon must be present after the guard statement.

The standard escape sequences of C/{cpp} programming languages are recognized and accepted in TTCN–3 character string values, that is, in literal values of `charstring` and `universal` `charstring` types, as well as in the arguments of built-in operations `log()` and `action()`.

NOTE: As a consequence of the extended escape sequences and in contrast with the TTCN–3 standard, the backslash character itself has to be always duplicated within character string values.

The following table summarizes all supported escape sequences of TTCN–3 character string values:

.Character string escape sequences
[cols=",,",options="header",]
|===
|*Escape sequence* |*Character code (decimal)* |*Meaning*
| |7 |bell
| |8 |backspace
| |12 |new page
| |10 |line feed
| |13 |carriage return
| |9 |horizontal tabulator
| 11 |vertical tabulator |
|\ |92 |backslash
|" |34 |quotation mark
|’ |39 |apostrophe
|? |63 |question mark
| <newline> |nothing |line continuation
| |NNN |octal notation (NNN is the character code in at most 3 octal digits)
| |NN |hexadecimal notation (NN is the character code in at most 2 hexadecimal digits)
|"" |34 |quotation mark (standard notation of TTCN–3 )
|===

NOTE: Only the standardized escape sequences are recognized in matching patterns of character string templates because they have special meaning there. For example, inside string patterns `\n` denotes a set of characters rather than a single character.

Although the standard requires that characters of TTCN–3 `charstring` values must be between 0 and 127, TITAN allows characters between 0 and 255. The printable representation of characters with code 128 to 255 is undefined.

The compiler implements an ASN.1-like scoping for TTCN–3 enumerated types, which means it allows the re-use of the enumerated values as identifiers of other definitions. The enumerated values are recognized only in contexts where enumerated values are expected; otherwise the identifiers are treated as simple references. However, using identifiers this way may cause misleading error messages and complicated debugging.

The compiler allows the local definitions (constants, variables, timers) to be placed in the middle of statement blocks, that is, after other behavior statements. The scope of such definitions extends from the statement following the definition to the end of the statement block. Forward-referencing of local definitions and jumping forward across them using `goto` statements are not allowed.

The compiler accepts in-line compound values in the operands of TTCN–3 expressions although the BNF of the standard allows only single values. The only meaningful use of the compound operands is with the comparison operators, that is, == and !=. Two in-line compound values cannot be compared with each other because their types are unknown; at least one operand of the comparison must be a referenced value. This feature has a limitation: In the places where in-line compound templates are otherwise accepted by the syntax (e.g. in the right-hand side of a variable assignment or in the actual parameter of a function call) the referenced value shall be used as the left operand of the comparison. Otherwise the parser gets confused when seeing the comparison operator after the compound value.

Examples:
[source]
----
// invalid since neither of the operands is of known type
if ({ 1, 2 } == { 2, 1 }) { }

// both are valid
while (v_myRecord == { 1, omit }) { }
if ({ f1 :=1, f2 := omit } != v_mySet) {}

// rejected because cannot be parsed
v_myBooleanFlag := { 1, 2, 3 } == v_myRecordOf;
f_myFunctionTakingBoolean({ 1, 2, 3 } != v_mySetOf);

// in reverse order these are allowed
v_myBooleanFlag := v_myRecordOf == { 1, 2, 3 };
f_myFunctionTakingBoolean(v_mySetOf != { 1, 2, 3 });
----

[[visibility-modifiers]]
== Visibility Modifiers

TITAN defines 3 visibility modifiers for module level definitions, and component member definitions: public, private, friend (8.2.5 in <<13-references.adoc#_1, [1]>>).

On module level definitions they mean the following:

* The public modifier means that the definition is visible in every module importing its module.
* The private modifier means that the definition is only visible within the same module.
* The friend modifier means that the definition is only visible within modules that the actual module declared as a friend module.

If no visibility modifier is provided, the default is the public modifier.

In component member definitions they mean the followings:

* The public modifier means that any function/testcase/altstep running on that component can access the member definition directly.
* The private modifier means that only those functions/testcases/altsteps can access the definition which runs on the component type directly. If they run on a component type extending the one containing the definition, it will not be directly visible.

The friend modifier is not available within component types.

Example:
[source]
----
module module1
{
import from module2 all;
import from module3 all;
import from module4 all;

const module2Type akarmi1 := 1; //OK, type is implicitly public
const module2TypePublic akarmi2 := 2; //OK, type is explicitly public
const module2TypeFriend akarmi3 := 3; //OK, module1 is friend of module2
const module2TypePrivate akarmi4 := 4; //NOK, module2TypePrivate is private to module2

const module3Type akarmi5 := 5; //OK, type is implicitly public
const module3TypePublic akarmi6 := 6; //OK, type is explicitly public
const module3TypeFriend akarmi7 := 7; //NOK, module1 is NOT a friend of module3
const module3TypePrivate akarmi8 := 8; //NOK, module2TypePrivate is private to module2

type component User_CT extends Lib4_CT {};
function f_set3_Lib4_1() runs on User_CT { v_Lib4_1 := 0 } //OK
function f_set3_Lib4_2() runs on User_CT { v_Lib4_2 := 0 } //OK
function f_set3_Lib4_3() runs on User_CT { v_Lib4_3 := 0 } //NOK, v_Lib4_3 is private
}

module module2
{

friend module module1;

type integer module2Type;
public type integer module2TypePublic;
friend type integer module2TypeFriend;
private type integer module2TypePrivate;
} // end of module

module module3
{
type integer module3Type;
public type integer module3TypePublic;
friend type integer module3TypeFriend;
private type integer module3TypePrivate;
} // end of module

module module4 {
type component Lib4_CT {
var integer v_Lib4_1;
public var integer v_Lib4_2;
private var integer v_Lib4_3;
}
----

== The `anytype`

The special TTCN-3 type `anytype` is defined as shorthand for the union of all known data types and the address type (if defined) in a TTCN-3 module. This would result in a large amount of code having to be generated for the `anytype`, even if it is not actually used. For performance reasons, Titan only generates this code if a variable of `anytype` is declared or used, and does not create fields in the `anytype` for all data types. Instead, the user has to specify which types are needed as `anytype` fields with an extension attribute at module scope.

Examples:

[source]
----
module elsewhere {
  type float money;
  type charstring greeting;
  }
  module local {
    import from elsewhere all;
    type integer money;
type record MyRec {
  integer i,
  float f
}

control {
  var anytype v_any;
  v_any.integer := 3;
  // ischosen(v_any.integer) == true

 v_any.charstring := "three";
 // ischosen(v_any.charstring) == true

 v_any.greeting := "hello";
 // ischosen(v_any.charstring) == false
 // ischosen(v_any.greeting) == true

 v_any.MyRec := { i := 42, f := 0.5 }
 // ischosen(v_any.MyRec) == true

 v_any.integer := v_any.MyRec.i – 2;
 // back to ischosen(v_any.integer) == true v_any.money := 0;
 // local money i.e. integer
 // not elsewhere.money (float)
 // ischosen(v_any.integer) == false
 // ischosen(v_any.money) == true

 // error: no such field (not added explicitly)
 // v_any.float := 3.1;

 // error: v_any.elsewhere.money
 }
}

with {

extension "anytype integer, charstring" // adds two fields
extension "anytype MyRec" // adds a third field
extension "anytype money" // adds the local money type
//not allowed: extension "anytype elsewhere.money"
extension "anytype greeting" // adds the imported type}
----

In the above example, the `anytype` behaves as a union with five fields named "integer", "charstring", "MyRec", "money" and "greeting". The anytype extension attributes are cumulative; the effect is the same as if a single extension attribute contained all five types.

NOTE: Field "greeting" of type charstring is distinct from the field "charstring" even though they have the same type (same for "integer" and "money").

Types imported from another module (elsewhere) can be added to the anytype of the importing module (local) if the type can be accessed with its unqualified name, which requires that it does not clash with any local type. In the example, the imported type "greeting" can be added to the anytype of module local, but "money" (a float) clashes with the local type "money" (an integer). To use the imported "money", it has to be qualified with its module name, for example a variable of type elsewhere.money can be declared, but elsewhere.money can not be used as an anytype field.

== Ports and Test Configurations

If all instances of a TTCN–3 port type are intended to be used for internal communication only (i.e. between two TTCN–3 test components) the generation and linking of an empty Test Port skeleton can be avoided. If the attribute `with { extension "internal" }` is appended to the port type definition, all {cpp} code that is needed for this port will be included in the output modules.<<13-references.adoc#_9, [9]>>

If the user wants to use `address` values in `to` and `from` clause and sender redirect of TTCN–3 port operations the `with { extension "address" }` attribute shall be used in the corresponding port type definition(s) to generate proper {cpp} code.

NOTE: When address is used in port operations the corresponding port must have an active mapping to a port of the test system interface, otherwise the operation will fail at runtime. Using of address values in to and from clauses implicitly means system as component reference. (See section "Support of address type" in <<13-references.adoc#_16, [16]>> for more details).<<13-references.adoc#_10, [10]>>

Unlike the latest TTCN–3 standard, our run time environment allows to connect a TTCN–3 port to more than one ports of the same remote test component. When these connections persist (usually in transient states), only receiving is allowed from that remote test component, because the destination cannot be specified unambiguously in the `to` clause of the `send` operation. Similarly, it is allowed to map a TTCN–3 port to more than one ports of the system, although it is not possible to send messages to the SUT.

[[parameters-of-create-operation]]
== Parameters of create Operation

The built-in TTCN–3 `create` operation can take a second, optional argument in the parentheses. The first argument, which is the part of the standard, can assign a name to the newly created test component. The optional, non-standard second argument specifies the location of the component. Also the second argument is a value or expression of type `charstring`.

According to the standard the component name is a user-defined attribute for a test component, which can be an arbitrary string value containing any kind of characters including whitespace. It is not necessary to assign a unique name for each test component; several active test components can have the same name at the same time. The component name is not an identifier; it cannot be used to address test components in configuration operations as component references can. The name can be assigned only at component creation and it cannot be changed later.

Component name is useful for the following purposes:

* it appears in the printout when logging the corresponding component reference;
* it can be incorporated in the name of the log file (see the metacharacter `%n`);
* it can be used to identify the test component in the configuration file (when specifying test port parameters (see section <<7-the_run-time_configuration_file.adoc#logging, `[LOGGING]`>>), component location constraints (see section <<7-the_run-time_configuration_file.adoc#components-parallel-mode, [COMPONENTS] (Parallel mode)>>) and logging options (see sections <<7-the_run-time_configuration_file.adoc#filemask, `FileMask`>> and <<7-the_run-time_configuration_file.adoc#consolemask, `ConsoleMask`>>).

Specifying the component location is useful when performing distributed test execution. The value used as location must be a host name, a fully qualified domain name, an IP address or the name of a host group defined in the configuration file (see section <<7-the_run-time_configuration_file.adoc#groups-parallel-mode, [GROUPS] (Parallel mode)>>). The explicit specification of the location overrides the location constraints given in the configuration file (see section <<7-the_run-time_configuration_file.adoc#components-parallel-mode, [COMPONENTS] (Parallel mode)>> for detailed description). If no suitable and available host is found the `create` operation fails with a dynamic test case error.

If only the component name is to be specified, the second argument may be omitted. If only the component location is specified a `NotUsedSymbol` shall be given in the place of the component name.

Examples:

[source]
----
//create operation without arguments
var MyCompType v_myCompRef := MyCompType.create;

// component name is assigned
v_myCompRef := MyCompType.create("myCompName");

// component name is calculated dynamically
v_myCompArray[i] := MyCompType.create("myName" & int2str(i));

// both name and location are specified (non-standard notation)
v_myCompRef := MyCompType.create("myName", "heintel");

// only the location is specified (non-standard notation)
v_myCompRef := MyCompType.create(-, "159.107.198.97") alive;
----

== Altsteps and Defaults

According to the TTCN–3 standard an `altstep` can be activated as `default` only if all of its value parameters are `in` parameters. However, our compiler and run-time environment allows the activation of altsteps with `out` or `inout` value or template parameters as well. In this case the actual parameters of the activated `default` shall be the references of variables or template variables that are defined in the respective component type. This restriction is in accordance with the rules of the standard about timer parameters of activated defaults.

NOTE: Passing local variables or timers to defaults is forbidden because the lifespan of local definitions might be shorter than the `default` itself, which might lead to unpredictable behavior if the `default` is called after leaving the statement block that the local variable is defined in. Since ports can be defined only in component types, there is no restriction about the `port` parameters of `altsteps`. These restrictions are not applicable to direct invocations of `altsteps` (e.g. in `alt` constructs).

The compiler allows using a statement block after `altstep` instances within `alt` statements. The statement block is executed if the corresponding `altstep` instance was chosen during the evaluation of the alt statement and the `altstep` has finished without reaching a `repeat` or `stop` statement. This language feature makes the conversion of TTCN–2 test suites easier.

NOTE: This construct is valid according to the TTCN–3 BNF syntax, but its semantics are not mentioned anywhere in the standard text.

The compiler accepts `altsteps` containing only an `[else]` branch. This is not allowed by the BNF as every `altstep` must have at least one regular branch (which can be either a guard statement or an `altstep` instance). This construct is practically useful if the corresponding `altstep` is instantiated as the last branch of the alternative.

== Interleave Statements

The compiler realizes TTCN–3 `interleave` statements using a different approach than it is described in section 7.5 of <<13-references.adoc#_1, [1]>>. The externally visible behavior of the generated code is equivalent to that of the canonical mapping, but our algorithm has the following advantages:

* Loop constructs `for`, `while` and `do-while` loops are accepted and supported without any restriction in `interleave` statements. The transformation of statements is done in a lower level than the TTCN–3 language, which does not restrict the embedded loops.
* Statements `activate`, `deactivate` and `stop` can also be used within `interleave`. The execution of these statements is atomic so we did not see the reason why the standard forbids them.
* The size of our generated code is linear in contrast to the exponential code growth of the canonical algorithm. In other words, the {cpp} equivalent of every embedded statement appears exactly once in the output.
* The run-time realization does not require any extra operating system resources, such as multi-threading.

== Logging Disambiguation

The TTCN–3 log statement provides the means to write logging information to a file or display on console (standard error). Options <<7-the_run-time_configuration_file.adoc#filemask, `FileMask`>> and <<7-the_run-time_configuration_file.adoc#consolemask, `ConsoleMask`>> determine which events will appear in the file and on the console, respectively. The generated logging messages are of type `USER_UNQUALIFIED`.

The `log` statement accepts among others fixed character strings TTCN–3 constants, variables, timers, functions, templates and expressions; for a complete list please refer to the table 18 in <<13-references.adoc#_1, [1]>>. It is allowed to pass multiple arguments to a single `log` statement, separated by commas.

The TTCN-3 standard does not specify how logging information should be presented. The following sections describe how TITAN implemented logging.

The arguments of the TTCN-3 statement `action` are handled according to the same rules as `log`.

=== Literal Free Text String

Strings entered between quotation marks (") <<13-references.adoc#_11, [11]>> and the results of special macros given in section <<ttcn3-macros, TTCN-3 Macros>> in the argument of the `log` statement are verbatim copied to the log. The escape sequences given in Table 4 are interpreted and the resulting non-printable characters (such as newlines, tabulators, etc.) will influence the printout.

Example:

[source]
----
log("foo");//The log printout will look like this:
 12:34:56.123456 foo
 bar
----

=== TTCN-3 Values and Templates

Literal values, referenced values or templates, wildcards, compound values, in-line (modified) templates, etc. (as long as the type of the expression is unambiguous) are discussed in this section.

These values are printed into the log using TTCN-3 Core Language syntax so that the printout can be simply copied into a TTCN-3 module to initialize an appropriate constant/variable/template, etc.

In case of (`universal`) `charstring` values the delimiter quotation marks ("") are printed and the embedded non-printable characters are substituted with the escape sequences in the first 9 rows of Table 4. All other non-printable characters are displayed in the TTCN-3 quadruple notation.

If the argument refers to a constant of type `charstring`, the actual value is not substituted to yield a literal string.

Example:

[source]
----
const charstring c_string := "foo\000";
log(c_string);
//The log printout will look like this:
12:34:56.123456 "foo" & char(0, 0, 0, 0)
----

=== Built-in Function match()

For the built-in `match()` function the printout will contain the detailed matching process field-by-field (similarly to the failed `receive` statements) instead of the Boolean result.

This rule is applied only if the` match()` operation is the top-level expression to be logged, see the example below:

[source]
----
 // this will print the detailed matching process
log(match(v_myvalue, t_template));
 // this will print only a Boolean value (true or false)
log(not not match(v_myvalue, t_template));
----
All the other predefined and user-defined functions with actual arguments will print the return value of the function into the log according to the TTCN-3 standard.

=== Special TTCN-3 Objects

If the argument refers to a TTCN-3 `port`, `timer` or array (slice) of the above, then the actual properties of the TTCN-3 object is printed into the log.

For ports the name and the state of the port is printed.

In case of timers the name of the timer, the default duration, the current state (`inactive`, `started` or `expired`), the actual duration and the elapsed time (if applicable) is printed in a structured form.

== Value Returning done

The compiler allows starting TTCN–3 functions having return type on PTCs. Those functions must have the appropriate `runs on` clause. If such a function terminates normally on the PTC, the returned value can be matched and retrieved in a `done` operation.

According to the TTCN-3 standard, the value redirect in a `done` operation can only be used to store the local verdict on the PTC that executed the behavior function. In TITAN the value redirect can also be used to store the behavior function’s return value with the help of an optional template argument.

If this template argument is present, then the compiler treats it as a value returning done operation, otherwise it is treated as a verdict returning `done`.

The following rules apply to the optional template argument and the value redirect:

* The syntax of the template and value redirect is identical with that of the `receive` operation.
* If the template is present, then the type of the template and the variable used in the value redirect shall be identical. If the template is not present, then the type of the value redirect must be `verdicttype`.
* In case of a value returning done the return type shall be a TTCN–3 type marked with the following attribute: `with { extension "done" }`. It is allowed to mark and use several types in done statements within one test suite. If the type to be used is defined in ASN.1 then a type alias shall be added to one of the TTCN–3 modules with the above attribute.
* In case of a value returning done the type of the template or variable must be visible from the module where the `done` statement is used.
* Only those done statements can have a template or a value redirect that refer to a specific PTC component reference. That is, it is not allowed to use this construct with `any component.done` or `all component.done`.

A value returning `done` statement is successful if all the conditions below are fulfilled:

* The corresponding PTC has terminated.
* The function that was started on the PTC has terminated normally. That is, the PTC was stopped neither by itself nor by other component and no dynamic test case error occurred.
* The return type of the function that was started on the PTC is identical to the type of the template used in the `done` statement.
* The value returned by the function on the PTC matches the given template.

If the `done` operation was successful and the value redirect is present the value returned by the PTC (if there was a matching template), or the local verdict on the PTC (if there was no matching template) is stored in the given variable or variable field.

The returned value can be retrieved from `alive` PTCs, too. In this case the `done` operation always refers to the return value of the lastly started behavior function of the PTC. Starting a new function on the PTC discards the return value of the previous function automatically (i.e. it cannot be retrieved or matched after the start component operation anymore).

Example:

[source]
----
type integer MyReturnType with { extension "done" };

function ptcBehavior() runs on MyCompType return MyReturnType
{
  setverdict(inconc);
  return 123;
}

// value returning ‘done’
testcase myTestCase() runs on AnotherCompType
{
  var MyReturnType myVar;
  var MyCompType ptc := MyCompType.create;
  ptc.start(ptcBehavior());
  ptc.done(MyReturnType : ?) -> value myVar;
  // myVar will contain 123
}

// verdict returning ‘done’
testcase myTestCase2() runs on AnotherCompType
{
  var verdicttype myVar;
  var MyCompType ptc := MyCompType.create;
  ptc.start(ptcBehavior());
  ptc.done -> value myVar;
  // myVar will contain inconc
}
----

== Dynamic Templates

Dynamic templates (template variables, functions returning templates and passing template variables by reference) are now parts of the TTCN–3 Core Language standard (<<13-references.adoc#_1, [1]>>). These constructs have been added to the standard with the same syntax and semantics as they were supported in this Test Executor. Thus dynamic templates are not considered language extensions anymore.

However, there is one extension compared to the supported version of Core Language. Unlike the standard, the compiler and the run-time environment allow the external functions to return templates.

Example:

[source]
----
// this is not valid according to the standard
external function MyExtFunction() return template octetstring;
----

== Template Module Parameters

The compiler accepts template module parameters by inserting an optional "template" keyword into the standard modulepar syntax construct between the modulepar keyword and the type reference. The extended BNF rule:

[source,subs="+quotes"]
ModuleParDef ::= "modulepar" (ModulePar | (“{“MultiTypedModuleParList "}"))ModulePar ::= *["template"]* Type ModuleParList

Example:

[source]
----
modulepar template charstring mp_tstr1 := ( "a" .. "f") ifpresent
modulepar template integer mp_tint := complement (1,2,3)
----

== Predefined Functions

The built-in predefined functions `ispresent`, `ischosen`, `lengthof` and `sizeof` are applicable not only to value-like language elements (constants, variables, etc.), but template-like entities (templates, template variables, template parameters) as well. If the function is allowed to be called on a value of a given type it is also allowed to be called on a template of that type with the meaning described in the following subchapters.

NOTE: "dynamic test case error" does not necessarily denote here an error situation: it may well be a regular outcome of the function.

=== `sizeof`

The function `sizeof` is applicable to templates of `record`, `set`, `record` of, `set` `of` and `objid` types. The function is applicable only if the `sizeof` function gives the same result on all values that match the template.<<13-references.adoc#_12, [12]>> In case of `record of` and `set of` types the length restrictions are also considered. Dynamic test case error occurs if the template can match values with different sizes or the length restriction contradicts the number of elements in the template body.

Examples:

[source]
----
type record of integer R;
type set S { integer f1, bitstring f2 optional, charstring f3 optional }
template R tr_1 := { 1, permutation(2, 3), ? }
template R tr_2 := {1, *, (2, 3) }
template R tr_3 := { 1, *, 10 } length(5)
template R tr_4 := { 1, 2, 3, * } length(1..2)
template S tr_5 := { f1 := (0..99), f2 := omit, f3 := ? }
template S tr_6 := { f3 := *, f1 := 1, f2 := ’00’B ifpresent }
template S tr_7 := ({ f1 := 1, f2 := omit, f3 := "ABC" },
                  { f1 := 2, f3 := omit, f2 := ’1’B })
template S tr_8 := ?

//sizeof(tr_1) → 4
//sizeof(tr_2) → error
//sizeof(tr_3) → 5
//sizeof(tr_4) → error
//sizeof(tr_5) → 2
//sizeof(tr_6) → error
//sizeof(tr_7) → 2
//sizeof(tr_8) → error
----

=== `ispresent`

The predefined function `ispresent` has been extended; its parameter can now be any valid TemplateInstance. It is working according to the following ETSI CRs: http://forge.etsi.org/mantis/view.php?id=5934 and http://forge.etsi.org/mantis/view.php?id=5936.

=== `oct2unichar`

The function `oct2unichar` (`in octetstring invalue`, `in charstring string_encoding := "UTF-8"`) `return universal charstring` converts an octetstring `invalue` to a universal charstring by use of the given `string_encoding`. The octets are interpreted as mandated by the standardized mapping associated with the given `string_encoding` and the resulting characters are appended to the returned value. If the optional `string_encoding` parameter is omitted, the default value "UTF-8".

The following values are allowed as `string_encoding` actual parameters: `UTF8`, `UTF-16`, `UTF-16BE`, `UTF-16LE`, `UTF-32`, `UTF-32BE`, `UTF-32LE`.

DTE occurs if the `invalue` does not conform to UTF standards. The `oct2unichar` checks if the Byte Order Mark (BOM) is present. If not a warning will be appended to the log file. `oct2unichar` will `decode` the invalue even in absence of the BOM.

Any code unit greater than 0x10FFFF is ill-formed.

UTF-32 code units in the range of 0x0000D800 – 0x0000DFFF are ill-formed.

UTF-16 code units in the range of 0xD800 – 0xDFFF are ill-formed.

UTF-8 code units in the range of 0xD800 – 0xDFFF are ill-formed.

Example:
----
oct2unichar('C384C396C39CC3A4C3B6C3BC'O)="ÄÖÜäöü";oct2unichar('00C400D600DC00E400F600FC'O,"UTF-16LE") = "ÄÖÜäöü";
----

=== `unichar2oct`

The function `unichar2oct` (`in universal charstring invalue, in charstring string_encoding := "UTF-8"`) `return octetstring` converts a universal charstring `invalue` to an octetstring. Each octet of the octetstring will contain the octets mandated by mapping the characters of `invalue` using the standardized mapping associated with the given `string_encoding` in the same order as the characters appear in inpar. If the optional `string_encoding` parameter is omitted, the default encoding is "UTF-8".

The following values are allowed as `string_encoding` actual parameters: UTF-8, UTF-8 BOM, UTF-16, UTF-16BE, UTF-16LE, UTF-32, UTF-32BE, UTF-32LE.

The function `unichar2oct` adds the Byte Order Mark (BOM) to the beginning of the `octetstring` in case of `UTF-16` and `UTF-32` encodings. The `remove_bom` function helps to remove it, if it is not needed. The presence of the BOM is expected at the inverse function `oct2unichar` because the coding type (without the BOM) can be detected only in case of `UTF-8` encoded `octetstring`. By default UTF-8 encoding does not add the BOM to the `octetstring`, however `UTF-8` `BOM` encoding can be used to add it.

DTE occurs if the `invalue` does not conform to UTF standards.

Any code unit greater than 0x10FFFF is ill-formed.

Example:

[source]
----
unichar2oct("ÄÖÜäöü") = 'EFBBBFC384C396C39CC3A4C3B6C3BC'O;
unichar2oct("ÄÖÜäöü","UTF-16LE") = 'FFFE00C400D600DC00E400F600FC'O;
----

[[get-stringencoding]]
=== `get_stringencoding`

The function `get_stringencoding (in octetstring encoded_value) return charstring` identifies the encoding of the `encoded_value`. The following return values are allowed as charstring: ASCII, UTF-8, UTF-16BE, UTF-16LE, UTF-32BE, UTF-32LE.

If the type of encoding could not been identified, it returns the value: <unknown>

Example:

[source]
----
var octetstring invalue := 'EFBBBFC384C396C39CC3A4C3B6C3BC'O;
var charstring codingtype := get_stringencoding(invalue);
the resulting codingtype is "UTF-8"
----

[[remove-bom]]
=== `remove_bom`

The function `remove_bom (in octetstring encoded_value) return octetstring` strips the BOM if it is present and returns the original octetstring otherwise.

Example:

[source]
----
var octetstring invalue := 'EFBBBFC384C396C39CC3A4C3B6C3BC'O;
var octetstring nobom := remove_bom(invalue);
the resulting nobom contains: 'C384C396C39CC3A4C3B6C3BC'O;
----

== Additional Predefined Functions

In addition to standardized TTCN–3 predefined functions given in Annex C of <<13-references.adoc#_1, [1]>> and Annex B of <<13-references.adoc#_3, [3]>> the following built-in conversion functions are supported by our compiler and run-time environment:

=== `str2bit`

The function `str2bit (charstring value) return bitstring` converts a `charstring` value to a `bitstring`, where each character represents the value of one bit in the resulting bitstring. Its argument may contain the characters "0" or "1" only, otherwise the result is a dynamic test case error.

NOTE: This function is the reverse of the standardized `bit2str`.

Example:

[source]
str2bit ("1011011100") = ’1011011100’B

=== `str2hex`

The function `str2hex (charstring value)` `return hexstring` converts a `charstring` value to a `hexstring`, where each character in the character string represents the value of one hexadecimal digit in the resulting `hexstring`. The incoming character string may contain any number of characters. A dynamic test case error occurs if one or more characters of the charstring are outside the ranges "0" .. "9", "A" .. "F" and "a" .. "f".

NOTE: This function is the reverse of the standardized `hex2str`.

Example:

[source]
----
str2hex ("1D7") = ’1D7’H
----

=== float2str

The function `float2str (float value) return charstring` converts a `float` value to a `charstring`. If the input is zero or its absolute value is between 10^-4^ and 10^10^, the decimal dot notation is used in the output with 6 digits in the fraction part. Otherwise the exponential notation is used with automatic (at most 6) digits precision in the mantissa.

Example:

[source]
----
float2str (3.14) = "3.140000"
----

=== unichar2char

The function `unichar2char (universal charstring value) return charstring` converts a` universal charstring` value to a `charstring`. The elements of the input string are converted one by one. The function only converts universal characters when the conversion result lies between 0 end 127 (that is, the result is an ISO 646 character).

NOTE: The inverse conversion is implicit, that is, the `charstring` values are converted to `universal charstring` values automatically, without the need for a conversion function.

Example:

[source]
----
unichar2char(char(0,0,0,64)) = "@"
----

=== `log2str`

The function `log2str` can be used to log into `charstring` instead of the log file.

Syntax:

[source]
log2str (…) return charstring

This function can be parameterized in the same way as the `log` function, it returns a charstring value which contains the log string for all the provided parameters, but it does not contain the timestamp, severity and call stack information, thus the output does not depend on the runtime configuration file. The parameters are interpreted the same way as they are in the log function: their string values are identical to what the log statement writes to the log file. The extra information (timestamp, severity, call stack) not included in the output can be obtained by writing external functions which use the runtime’s Logger class to obtain the required data.

=== `testcasename`

The function `testcasename` returns the unqualified name of the actually executing test case. When it is called from the control part and no test case is being executed, it returns the empty string.

Syntax:

[source]
testcasename () return charstring

=== `isbound`

The function `isbound` behaves identically to the `isvalue` function with the following exception: it returns true for a record-of value which contains both initialized and uninitialized elements.

[source]
----
type record of integer rint;
var rint r_u; // uninitialized
isvalue(r_u); // returns false
isbound(r_u); // returns false also
//lengthof(r_u) would cause a dynamic testcase error

var rint r_0 := {} // zero length
isvalue(r_3); // returns true
isbound(r_3); // returns true
lengthof(r_3); // returns 0

var rint r_3 := { 0, -, 2 } // has a "hole"
isvalue(r_3); // returns false
isbound(r_3); // returns true
lengthof(r_3); // returns 3

var rint r_3full := { 0, 1, 2 }
isvalue(r_3full); // returns true
isbound(r_3full); // returns true
lengthof(r_3full); // returns 3
----

The introduction of `isbound` permits TTCN-3 code to distinguish between r_u and r_3; `isvalue` alone cannot do this (it returns false for both).

Syntax:
[source]
isbound (in template any_type i) return boolean;

=== `ttcn2string`

Syntax:
[source]
ttcn2string(in <TemplateInstance> ti) return charstring

This predefined function returns its parameter’s value in a string which is in TTCN-3 syntax. The returned string has legal ttcn-3 with a few exceptions such as unbound values. Unbound values are returned as “-“, which can be used only as fields of assignment or value list notations, but not as top level assignments (e.g. `x:=- is illegal`). Differences between the output format of `ttcn2string()` and `log2str()`:

[cols=",,",options="header",]
|===
|Value/template |`log2str()` |`ttcn2string()`
|Unbound value |`"<unbound>"` |“-“
|Uninitialized template |`"<uninitialized template>"` |“-“
|Enumerated value |`name (number)` |name
|===

=== `string2ttcn`

Syntax:

[source]
string2ttcn(in charstring ttcn_str, inout <reference> ref)

This predefined function does not have a return value, thus it is a statement. Any error in the input string will cause an exception that can be caught using @try - @catch blocks. The message string of the exception contains the exact cause of the error. There might be syntax and semantic errors. This function uses the module parameter parser of the TITAN runtime, it accepts the same syntax as the module parameters of the configuration file. Check the documentation chapters for the module parameters section. There are differences between the ttcn-3 syntax and the configuration file module parameters syntax, these are described in the documentation chapter of the module parameters. The second parameter must be a reference to a value or template variable.

Example code:

[source]
----
type record MyRecord { integer a, boolean b }
var template MyRecord my_rec
@try {
  string2ttcn("complement ({1,?},{(1,2,3),false}) ifpresent", my_rec)
  log(my_rec)
  }
  @catch (err_str) {
    log(“string2ttcn() failed: “, err_str)
  }

The log output will look like this:
complement ({ a := 1, b := ? }, { a := (1, 2, 3), b := false }) ifpresent
----

[[encode-base64]]
=== `encode_base64`

Syntax:

[source]
----
encode_base64(in octetstring ostr, in boolean
  use_linebreaks := false) return charstring
----

The function `encode_base64 (in octetstring ostr, in boolean use_linebreaks := false) return charstring `converts an octetstring `ostr` to a charstring. The charstring will contain the Base64 representation of `ostr`. The `use_linebreaks` parameter adds newlines after every 76 output characters, according to the MIME specs, if it is omitted, the default value is false.

Example:

[source]
----
encode_base64('42617365363420656E636F64696E6720736368656D65'O) ==
"QmFzZTY0IGVuY29kaW5nIHNjaGVtZQ=="
----

[[decode-base64]]
=== `decode_base64`

Syntax:

[source]
----
decode_base64(in charstring str) return octetstring
----

The function `decode_base64 (in charstring str) return octetstring` converts a charstring `str` encoded in Base64 to an octetstring. The octetstring will contain the decoded Base64 string of `str`.

Example:

[source]
----
decode_base64("QmFzZTY0IGVuY29kaW5nIHNjaGVtZQ==") ==
'42617365363420656E636F64696E6720736368656D65'O
----

=== `json2cbor`

Syntax:

[source]
----
json2cbor(in universal charstring us) return octetstring
----

The function `json2cbor(in universal charstring us) return octetstring` converts a TITAN encoded json document into the binary representation of that json document using a binary coding called CBOR. The encoding follows the recommendations written in the CBOR standard <<13-references.adoc#_22, [22]>> section 4.2.

Example:

[source]
----
json2cbor("{"a":1,"b":2}") == ‘A2616101616202’O
----

=== `cbor2json`

Syntax:
[source]
----
cbor2json(in octetstring os) return universal charstring
----

The function `cbor2json(in octetstring os) return universal charstring` converts a CBOR encoded bytestream into a json document which can be decoded using the built in JSON decoder. The decoding follows the recommendations written in the CBOR standard <<13-references.adoc#_22, [22]>> section 4.1 except that the indefinite-length items are not made definite before conversion and the decoding of indefinite-length items is not supported.

Example:
[source]
----
cbor2json(‘A2616101616202’O) == "{"a":1,"b":2}"
----

=== `json2bson`

Syntax:
[source]
----
json2bson(in universal charstring us) return octetstring
----

The function `json2bson(in universal charstring us) return octetstring` converts a TITAN encoded json document into the binary representation of that json document using a binary coding called BSON. Only top level json objects and arrays can be encoded. (Note that an encoded top level json array will be decoded as a json object) The encoding follows the rules written in the BSON standard <<13-references.adoc#_23, [23]>>. The encoding handles the extension rules written in the MongoDB Extended JSON document <<13-references.adoc#_24, [24]>>. The encoding of 128-bit float values is not supported.

Example:
[source]
----
json2bson("{"a":1,"b":2}") == ‘13000000106100010000001062000200000000’O
----

=== `bson2json`

Syntax:
[source]
----
bson2json(in octetstring os) return universal charstring
----

The function `bson2json(in octetstring os) return universal charstring` converts a BSON encoded bytestream into a json document which can be decoded using the built in JSON decoder. The decoding follows the extension rules written in the BSON standard <<13-references.adoc#_23, [23]>>. The decoding handles the rules written in the MongoDB Extended JSON document <<13-references.adoc#_24, [24]>>. The decoding of 128-bit float values is not supported.

Example:
[source]
----
bson2json(‘13000000106100010000001062000200000000’O) == "{"a":1,"b":2}"
----

== Exclusive Boundaries in Range Subtypes

The boundary values used to specify range subtypes can be preceded by an exclamation mark. By using the exclamation mark the boundary value itself can be excluded from the specified range. For example integer range (!0..!10) is equivalent to range (1..9). In case of float type open intervals can be specified by using excluded boundaries, for example (0.0..!1.0) is an interval which contains 0.0 but does not contain 1.0.

[[special-float-values-infinity-and-not-a-number]]
== Special Float Values Infinity and not_a_number

The keyword infinity (which is also used to specify value range and size limits) can be used to specify the special float values –infinity and +infinity, these are equivalent to MINUS-INFINITY and PLUS-INFINITY used in ASN.1. A new keyword not_a_number has been introduced which is equivalent to NOT-A-NUMBER used in ASN.1. The -infinity and +infinity and not_a_number special values can be used in arithmetic operations. If an arithmetic operation’s operand is not_a_number then the result of the operation will also be not_a_number. The special value not_a_number cannot be used in a float range subtype because it’s an unordered value, but can be added as a single value, for example subtype (0.0 .. infinity, not_a_number) contains all positive float values and the not_a_number value.

[[ttcn-3-preprocessing]]
== TTCN–3 Preprocessing

Preprocessing of the TTCN-3 files with a C preprocessor is supported by the compiler. External preprocessing is used: the Makefile Generator generates a `Makefile` which will invoke the C preprocessor to preprocess the TTCN-3 files with the suffix `."ttcnpp`. The output of the C preprocessor will be generated to an intermediate file with the suffix `."ttcn`. The intermediate files contain the TTCN-3 source code and line markers. The compiler can process these line markers along with TTCN-3. If the preprocessing is done with the `-P` option <<13-references.adoc#_13, [13]>>, the resulting code will not contain line markers; it will be compatible with any standard TTCN-3 compiler. The compiler will use the line markers to give almost <<13-references.adoc#_14, [14]>> correct error or warning messages, which will point to the original locations in the `.ttcnpp` file. The C preprocessor directive `#"include` can be used in .ttcnpp files; the Makefile Generator will treat all files with suffix `."ttcnin` as TTCN-3 include files. The `."ttcnin` files will be added to the Makefile as special TTCN-3 include files which will not be translated by the compiler, but will be checked for modification when building the test suite.

Extract from the file:
[source]
----
Example.ttcnpp:
module Example {
function func()
{
#ifdef DEBUG
log("Example: DEBUG");
#else
log("Example: RELEASE");
#endif

}

----

The output is a preprocessed intermediate file `Example.ttcn`. The resulting output from the above code:
[source]
----
# 1 "Example.ttcnpp"
module Example {
function func()
{
log("Example: RELEASE");
}
----

The line marker (`# 1 "Example.ttcnpp"`) tells the compiler what the origin of the succeeding code is.

== Parameter List Extensions

In addition to standardized TTCN-3 parameter handling described in 5.4.2 of <<13-references.adoc#_1, [1]>> TITAN also supports the mixing of list notation and assignment notation in an actual parameter list.

=== Missing Named and Unnamed Actual Parameters

To facilitate handling of long actual parameter lists in the TITAN implementation, the actual parameter list consists of two optional parts: an unnamed part followed by a named part, in this order. In the actual parameter list a value must be assigned to every mandatory formal parameter either in the named part or in the unnamed part. (Mandatory parameter is one without default value assigned in the formal parameter list.) Consequently, the unnamed part, the named part or both may be omitted from the actual parameter list. Omitting the named part from the actual parameter lists provides backward compatibility with the standard notation.

The named and unnamed parts are separated by a comma as are the elements within both lists. It is not allowed to assign value to a given formal parameter in both the named and the unnamed part of the actual parameter list.

There can be at most one unnamed part, followed by at most one named part. Consequently, an unnamed actual parameter may not follow a named parameter.

Named actual parameters must follow the same relative order as the formal parameters. It is not allowed to specify named actual parameters in an arbitrary order.

Examples

The resulting parameter values are indicated in brackets in the comments:

[source]
----
function myFunction(integer p_par1, boolean p_par2 := true) { … }
control {
*// the actual parameter list is syntactically correct below:*
myFunction(1, p_par2 := false); // (1, false)
myFunction(2); // (2, true)
myFunction(p_par1 := 3, p_par2 := false); // (3, false)
*// the actual parameter list is syntactically erroneous below:*
myFunction(0, true, -); // too many parameters
myFunction(1, p_par1 := 1); // p_par1 is given twice
myFunction(); // no value is assigned to mandatory p_par1
myFunction(p_par2 := false, p_par1 := 3); // out of order
myFunction(p_par2 := false, 1); // unnamed part cannot follow
// named part
}
----

== `function`, `altstep` and `testcase` References

Although TITAN supports the behaviour type package (<<13-references.adoc#_5, [5]>>) of the TTCN-3 standard, but this feature was included in the standard with a different syntax.

It is allowed to create TTCN–3 types of `functions`, `altsteps` and `testcases`. Values, for example variables, of such types can carry references to the respective TTCN–3 definitions. To facilitate reference using, three new operations (`refers`, `derefers` and `apply`) were introduced. This new language feature allows to create generic algorithms in TTCN–3 with late binding, (i.e. code in which the function to be executed is specified only at runtime).

[[function-types-with-a-runson-self-clause]]
== Function Types with a RunsOn_self Clause

A function type or an altstep type, defined with a standard `runs on` clause, can use all constants, variables, timers and ports given in the component type definition referenced by the `runs on` clause (see chapter 16 of <<13-references.adoc#_1, [1]>>).

A function type or an altstep type, defined with the TITAN-introduced `runs on self` clause, similarly, makes use of the resources of a component type; however, the component type in question is not given in advance. When an altstep or a function is called via a function variable, that is, a reference, using the `apply` operation, it can use the resources defined by the component type indicated in the `runs on` clause of the actually referenced function or altstep.

The "runs on self" construct is permitted only for `function` and `altstep` types. Any actual function or altstep must refer to a given component type name in their `runs on` clause.

A variable with type of function type is called a *function variable*. Such variables can contain references to functions or altsteps. At function variable assignment, component type compatibility checking is performed with respect to the component context of the assignment statement and the "runs on" clause of the assigned function or altstep. When the `apply()` operator is applied to a function variable, no compatibility checking is performed.

The rationale for this distinction is the following: due to type compatibility checking at the time of value assignment to the function variable, the TTCN-3 environment can be sure that any non-`null` value of the variable is a function reference that is component-type-compatible with that component that is actually executing the code using the `apply()` operator.

As a consequence of this, it is forbidden to use values of function variables as arguments to the TTCN-3 operators `start()` or `send()`.

Example of using the clause `runs on self` in a library

A component type may be defined as an extension of another component type (using the standard `extends` keyword mentioned in chapter 6.2.10.2 of <<13-references.adoc#_1, [1]>>). The effect of this definition is that the extended component type will implicitly contain all constant, variable, port and timer definitions from the parent type as well. In the example below, the component type `User_CT` aggregates its own constant, variable, port and timer definitions (resources) with those defined in the component type `Library_CT` (see line a).

The library developer writes a set of library functions that have a `runs on Library_CT` clause (see line h). Such library functions may offer optional references to other functions that are supposed to be specified by the user of the library (see line e). We say in this case that the library function may call user-provided *callback functions* via function variables. These function variables must have a type specified; optionally with a runs on clause. If this `runs on` clause refers to an actual component type name, then this actual type name must be known at the time of writing the library.

Library functions that runs on `Library_CT` can run on other component types as well, provided that the actual component type is compatible with `Library_CT` (see chapter 6.3.3 of <<13-references.adoc#_1, [1]>>). An obvious design goal for the library writer is to permit references to any callback function that has a component-type-compatible `runs on` clause. However, the cardinality of compatible component types is infinitely large; therefore, they *cannot* be explicitly referenced by the function type definitions of the library.

The "runs on self" concept provides a remedy for this contradiction and allows conceiving library components prepared to take up user-written "plug-ins".

In the code excerpt below, function `f_LibraryFunction` (which has the clause `runs on Library_CT`) uses the function reference variable `v_callBackRef_self` (defined in `Library_CT`).The function `f_MyCallbackFunction` (see line b) has a `runs on User_CT` clause. `User_CT` (see line a) extends `Library_CT`, therefore it is suitable for running library function with runs on `Library_CT` clause, for example.

When the assignment to the function variable `v_CallbackRef_self` is performed (see line c) inside `f_MyUserFunction` (that is, inside the context `User_CT`), then compatibility checking is performed. Since `User_CT` is compatible with `Library_CT`, the assignment is allowed.

Direct call to `f_MyCallbackFunction()` with `runs on User_CT` from a `runs on Library_CT` context (see line g) would cause semantic error according to the TTCN3 language. However, calling the function via `v_CallBackRef_self` is allowed (see line d).

[source]
----
module RunsOn_Self
{
//=========================================================================
// Function Types
//=========================================================================

//---- line f)
type function CallbackFunctionRefRunsonSelf_FT () runs on self;

//=========================================================================
//Component Types
//=========================================================================
type component Library_CT
{
//---- line e)
  var CallbackFunctionRefRunsonSelf_FT v_CallbackRef_self := null;
  var integer v_Lib;
}
//---- line a)
type component User_CT extends Library_CT
{
  var integer v_User;
}

//---- line h)
function f_LibraryFunction () runs on Library_CT
{
//---- line g)
  // Direct call of the callback function would cause semantic ERROR
//f_MyCallbackFunction();

  if (v_CallbackRef_self != null)
  {
    // Calling a function via reference that has a "runs on self" in its header
    // is always allowed with the exception of functions/altsteps without runs
    // on clause
//---- line d)
    v_CallbackRef_self.apply();
  }
}// end f_LibraryFunction

function f_MyUserFunction () runs on User_CT
{
  // This is allowed as f_MyCallbackFunction has runs on clause compatible
  // with the runs on clause of this function (f_MyUserFunction)
  // The use of function/altstep references with "runs on self" in their
  // headers is limited to call them on the given component instance; i.e.
  // allowed: assignments, parameterization and activate (the actual function's
  //          runs on is compared to the runs on of the function in which
  //          the operation is executed)
  // not allowed: start, sending and receiving
  // no check is needed for apply!
//---- line c)
  v_CallbackRef_self := refers (f_MyCallbackFunction);

  // This is allowed as Library_CT is a parent of User_CT
  // Pls. note, as the function is executing on a User_CT
  // instance, it shall never cause a problem of calling
  // a callback function with "runs on User_CT" from it.
  f_LibraryFunction();

}//end f_MyUserFunction

//---- line b)
function f_MyCallbackFunction () runs on User_CT
{/*application/dependent behaviour*/}

} // end of module RunsOn_Self
----

[[ttcn3-macros]]
== TTCN–3 Macros

The compiler and the run-time environment support the following non-standard macro notation in TTCN–3 modules. All TTCN–3 macros consist of a percent (%) character followed by the macro identifier. Macro identifiers are case sensitive. The table below summarizes the available macros and their meaning. Macro identifiers not listed here are reserved for future extension.

.TTCN-3 macros
[cols=",",options="header",]
|===
|Macro |Meaning
|`%moduleId` |name of the TTCN–3 module
|`%definitionId` |name of the top-level TTCN–3 definition
|`%testcaseId` |name of the test case that is currently being executed
|`%fileName` |name of the TTCN–3 source file
|`%lineNumber` |number of line in the source file
|===

The following rules apply to macros:

* All macros are substituted with a value of type `charstring`. They can be used as operands of complex expressions (concatenation, comparison, etc.).
* All macros except `%testcaseId` are evaluated during compilation and they can be used anywhere in the TTCN–3 module.
* Macro `%testcaseId` is evaluated at runtime. It can be used only within functions and altsteps that are being run on test components (on the MTC or PTCs) and within testcases. It is not allowed to use macro `%testcaseId` in the module control part. If a function or altstep that contains macro `%testcaseId` is called directly from the control part the evaluation of the macro results in a dynamic test case error.
* The result of macro `%testcaseId` is not a constant thus it cannot be used in the value of TTCN–3 constants. It is allowed only in those contexts where TTCN–3 variable references are permitted.
* Macro `%definitionId` is always substituted with the name of the top-level module definition that it is used in. <<13-references.adoc#_15, [15]>> For instance, if the macro appears in a constant that is defined within a function then the macro will be substituted with the function’s name rather than the one of the constant. When used within the control part macro `%definitionId` is substituted with the word "`control`".
* Macro `%fileName` is substituted with the name of the source file in the same form as it was passed to the compiler. This can be a simple file name, a relative or an absolute path name.
* The result of macro `%lineNumber` is always a string that contains the current line number as a decimal number. Numbering of lines starts from 1. All lines of the input file (including comments and empty lines) are counted. When it needs to be used in an integer expression a conversion is necessary: `str2int(%lineNumber)`. The above expression is evaluated during compilation without any runtime performance penalty.
* Source line markers are considered when evaluating macros `%fileName` and `%lineNumber`. In preprocessed TTCN–3 modules the macros are substituted with the original file name and line number that the macro comes from provided that the preprocessor supports it.
* When macros are used in `log()` statements, they are treated like literal strings rather than charstring value references. That is, quotation marks around the strings are not used and special characters within them are not escaped in the log file.
* For compatibility with the C preprocessor the compiler also recognizes the following C style macros: \\__FILE__ is identical to `%fileName` and \\__LINE__ is identical to `str2int(%lineNumber)`.
* Macros are not substituted within quotation marks (i.e. within string literals and attributes).
* The full power of TTCN–3 macros can be exploited in combination with the C preprocessor.

Example:
[source]
----
module M {
// the value of c_MyConst will be "M"
const charstring c_MyConst := %moduleId;
// MyTemplate will contain 28
template integer t_MyTemplateWithVeryLongName := lengthof(%definitionId);
function f_MyFunction() {
// the value of c_MyLocalConst1 will be "f_MyFunction"
const charstring c_MyLocalConst1 := %definitionId;
// the value of c_MyLocalConst2 will be "%definitionId"
const charstring c_MyLocalConst2 := "%definitionId";
// the value of c_MyLocalConst3 will be "12"
const charstring c_MyLocalConst3 := %lineNumber; //This is line 12
// the value of c_MyLocalConst4 will be 14
const integer c_MyLocalConst4 := str2int(%lineNumber);//This is line 14
// the line below is invalid because %testcaseId is not a constant
const charstring c_MyInvalidConst := %testcaseId;
// this is valid, of course
var charstring v_MyLocalVar := %testcaseId;
// the two log commands below give different output in the log file
log("function:", %definitionId, " testcase: “, %testcaseId);
// printout: function: f_MyFunction testcase: tc_MyTestcase
log("function:", c_MyLocalConst1, " testcase: “, v_MyLocalVar);
// printout: function: "f_MyFunction" testcase: "tc_MyTestcase"
}
}
----

== Component Type Compatibility

The ETSI standard defines type compatibility of component types for component reference values and for functions with "`runs on`" clause. In order to be compatible, both component types are required to have identical definitions (cf. <<13-references.adoc#_1, [1]>>, chapter 6.3.3).

NOTE: Compatibility is an asymmetric relation, if component type B is compatible with component type A, the opposite is not necessarily true. (E.g., component type B may contain definitions absent in component type A.)

All definitions from the parent type are implicitly contained when the keyword `extends` appears in the type definition (cf. <<13-references.adoc#_1, [1]>>, chapter 6.2.10.2) and so the required identity of the type definitions is ensured. The compiler considers component type B to be compatible with A if B has an `extends` clause, which contains A or a component type that is compatible with A.

Example:
[source]
----
type component A { var integer i; }
type component B extends A {
// extra definitions may be added here
}
----

In order to provide support for existing TTCN–3 code (e.g. standardized test suites) it is allowed to explicitly signal the compatibility relation between component types using a special `extension` attribute. Using such attributes shall be avoided in newly written TTCN–3 modules. Combining component type inheritance and the attribute `extension` is possible, but not recommended.

Thus, the compiler considers component type B to be compatible with A if B has an `extension` attribute that points to A as base component type and all definitions of A are present and identical in B.

[source]
----
type component A { var integer i; }
type component B {
var integer i; // definitions of A must be repeated
var octetstring o; // new definitions may be added
} with {
extension "extends A"
}
----

=== Implementation Restrictions

The list of definitions shared with different compatible component types shall be distinct. If component type Z is compatible with both X and Y and neither X is compatible with Y nor Y is compatible with X then X and Y shall not have definitions with identical names but different origin. If both X and Y are compatible with component type C then all definitions in X and Y which are originated from C are inherited by Z on two paths.

Example: According to the standard component type Z should be compatible with both X and Y, but the compatibility relation cannot be established because X and Y have a definition with the same name.

[source]
----
type component X { timer T1, T2; }
type component Y { timer T1, T3; }
type component Z { timer T1, T2, T3; }
with { extension "extends X, Y" }
// invalid because the origin of T1 is ambiguous
----

The situation can be resolved by introducing common ancestor C for X and Y, which holds the shared definition.

[source]
----
type component C { timer T1; }
type component X { timer T1, T2; } with { extension "extends C" }
type component Y { timer T1, T3; } with { extension "extends C" }
type component Z {
timer T1, // origin is C
T2, // origin is X
T3; // origin is Y
} with { extension "extends X, Y" }
----

Circular compatibility chains between component types are not allowed. If two component types need to be defined as identical, type aliasing must be used instead of compatibility.

The following code is invalid:

[source]
----
type component A {
// the same definitions as in B
} with { extension "extends B" }
type component B {
// the same definitions as in A
} with { extension "extends A" }
----

When using the non-standard extension attribute the initial values of the corresponding definitions of compatible components should be identical. The compiler does not enforce this for all cases; however, in the case of different initial values the resulting run-time behavior is undefined. If the initial values cannot be determined at compile time (module parameters) the compiler will remain silent. In other situations the compiler may report an error or a warning.

All component types are compatible with each empty component type. Empty components are components which have neither own nor inherited definitions.

== Implicit Message Encoding

The TTCN–3 standard <<13-references.adoc#_1, [1]>> does not specify a standard way of data encoding/decoding. TITAN has a common {cpp} API for encoding/decoding; to use this API external functions are usually needed. The common solution is to define a TTCN–3 external function and write the {cpp} code containing the API calls. In most cases the {cpp} code explicitly written to an auxiliary {cpp} file contains only simple code patterns which call the encoding/decoding API functions on the specified data. In TITAN there is a TTCN–3 language extension which automatically generates such external functions.

Based on this automatic encoding/decoding mechanism, dual-faced ports are introduced. Dual-faced ports have an external and an internal interface and can automatically transform messages passed through them based on mapping rules defined in TTCN–3 source files. These dual-faced ports eliminate the need for simple port mapping components and thus simplify the test configuration.

[[dual-faced-ports]]
=== Dual-faced Ports

In the TTCN–3 standard (<<13-references.adoc#_1, [1]>>), a port type is defined by listing the allowed incoming and outgoing message types. Dual-faced ports have on the other hand two different message lists: one for the external and one for the internal interface. External and internal interfaces are given in two distinct port type definitions. The dual-faced concept is applicable to message based ports and the message based part of mixed ports.

Dual-faced port types must have `user` attribute to designate its external interface. The internal interface is given by the port type itself. A port type can be the external interface of several different dual-faced port types.

The internal interface is involved in communication operations (`send`, `receive`, etc.) and the external interface is used when transferring messages to/from other test components or the system under test. The operations `connect` and `map` applied on dual-faced ports will consider the external port type when checking the consistency of the connection or mapping.<<13-references.adoc#_16, [16]>>

==== Dual-faced Ports between Test Components

Dual-faced ports used for internal communication must have the attributes `internal` in addition to `user` (see section <<visibility-modifiers, Visibility Modifiers>>). The referenced port type describing the external interface may have any attributes.

==== Dual-faced Ports between Test Components and the SUT

The port type used as external interface must have the attribute `provider`. These dual-faced port types do not have their own test port; instead, they use the test port belonging to the external interface when communicating to SUT. Using the attribute `provider` implies changes in the Test Port API of the external interface. For details see the section "Provider port types" in <<13-references.adoc#_16, [16]>>.

If there are several entities within the SUT to be addressed, the dual-faced port type must have the attribute `address` in addition to `user`. In this case the external interface must have the attribute `address` too. For more details see section <<visibility-modifiers, Visibility Modifiers>>.

=== Type Mapping

Mapping is required between the internal and external interfaces of the dual-faced ports because the two faces are specified in different port type definitions, thus, enabling different sets of messages.

Messages passing through dual-faced ports will be transformed based on the mapping rules. Mapping rules must be specified for the outgoing and incoming directions separately. These rules are defined in the attribute `user` of the dual-faced port type.

An outgoing mapping is applied when a `send` operation is performed on the dual-faced port. The outcome of the mapping will be transmitted to the destination test component or SUT. The outgoing mappings transform each outgoing message of the internal interface to the outgoing messages of the external interface.

An incoming mapping is applied when a message arrives on a dual-faced port from a test component or the SUT. The outcome of the mapping will be inserted into the port queue and it will be extracted by the `receive` operation. The incoming mappings transform each incoming messages of the external interface to the incoming message of the internal interface.

==== Mapping Rules

A mapping rule is an elementary transformation step applied on a message type (source type) resulting in another message type (target type). Source type and target type are not necessarily different.

Mapping rules are applied locally in both directions, thus, an error caused by a mapping rule affects the test component owning the dual-faced port, not its communication partner.

Mappings are given for each source type separately. Several mapping targets may belong to the same source type; if this is the case, all targets must be listed immediately after each other (without repeating the source type).

The following transformation rules may apply to the automatic conversion between the messages of the external and internal interfaces of a dual-faced port:

* No conversion. Applicable to any message type, this is a type preserving mapping, no value conversion is performed. Source and target types must be identical. This mapping does not have any options. For example, control or status indication massages may transparently be conveyed between the external and the internal interfaces. Keyword used in attribute `user` of port type definition: `simple`.
* Message discarding. This rule means that messages of the given source type will not be forwarded to the opposite interface. Thus, there is no destination type, which must be indicated by the not used symbol (-). This mapping does not have any options. For example, incoming status indication massages of the external interface may be omitted on the internal interface. Keyword used in attribute `user` of port type definition: `discard`.
* Conversion using the built-in codecs. Here, a corresponding encoding or decoding subroutine of the built-in codecs (for example RAW, TEXT or BER) is invoked. The conversion and error handling options are specified with the same syntax as used for the encoding/decoding functions, see section <<attribute-syntax, Attribute Syntax>>. Here, source type corresponds to input type and target type corresponds to output type of the encoding. Keyword used in attribute `user` of port type definition: `encode` or `decode`; either followed by an optional `errorbehavior`.
* Function or external function. The transformation rule may be described by an (external) function referenced by the mapping. The function must have the attribute `extension` specifying one of the prototypes given in section <<encoder-decoder-function-prototypes, Encoder/decoder Function Prototypes>>. The incoming and the outgoing type of the function must be equal to the source and target type of the mapping, respectively. The function may be written in TTCN-3, {cpp} or generated automatically by the compiler. This mapping does not have any options. Keyword used in attribute `user` of port type definition: `function`.

==== Mapping with One Target

Generally speaking, a source type may have one or more targets. Every mapping target can be used alone. However, only one target can be designated with the following rules if

* no conversion takes place (keyword `simple`);
* encoding a structured message (keyword `encode`) <<13-references.adoc#_17, [17]>>;
* an (external) function with prototype `convert` or `fast` is invoked

==== Mapping with More Targets

On the other hand, more than one target is needed, when the type of an encoded message must be reconstructed. An octetstring, for example, can be decoded to a value of more than one structured PDU type. It is not necessary to specify mutually exclusive decoder rules. It is possible and useful to define a catch-all rule at the end to handle invalid messages.

The following rules may be used with more than one target if

* an (external) function with prototype `backtrack` is invoked;
* decoding a structured message (keyword `decode`);
* (as a last alternative) the source message is `discarded`

The conversion rules are tried in the same order as given in the attribute until one of them succeeds, that is, the function returns `0 OK` or decoding is completed without any error. The outcome of the successful conversion will be the mapped result of the source message. If all conversion rules fail and the last alternative is `discard`, then the source message is discarded. Otherwise dynamic test case error occurs.

==== Mapping from Sliding Buffer

Using sliding buffers is necessary for example, if a stream-based transport, like TCP, is carrying the messages. A stream-based transport is destroying message boundaries: a message may be torn apart or subsequent messages may stick together.

The following rules may be used with more than one target when there is a sliding buffer on the source side if

* an (external) function with prototype `sliding` is invoked;
* decoding a structured message (keyword `decode`)

Above rules imply that the source type of this mapping be either `octetstring` or `charstring`. The run-time environment maintains a separate buffer for each connection of the dual-faced port. Whenever data arrives to the buffer, the conversion rules are applied on the buffer in the same order as given in the attribute. If one of the rules succeeds (that is, the function returns `0` or decoding is completed without any error) the outcome of the conversion will appear on the destination side. If the buffer still contains data after successful decoding, the conversion is attempted again to get the next message. If one of the rules indicates that the data in the buffer is insufficient to get an entire message (the function returns `2 INCOMPLETE_MESSAGE` or decoding fails with error code `ET_INCOMPL_MSG`), then the decoding is interrupted until the next fragment arrives in the buffer. If all conversion rules fail (the function returns `1 NOT_MY_TYPE` or decoding fails with any other error code than `ET_INCOMPL_MSG`), dynamic test case error occurs.

NOTE: Decoding with sliding should be the last decoding option in the list of decoding options and there should be only one decoding with sliding buffer. In other cases the first decoding with sliding buffer might disable reaching later decoding options.

[[encoder-decoder-function-prototypes]]
=== Encoder/decoder Function Prototypes

Encoder/decoder functions are used to convert between different data (message) structures. We can consider e.g. an octet string received from the remote system that should be passed to the upper layer as a TCP message.

Prototypes are attributes governing data input/output rules and conversion result indication. In other words, prototypes are setting the data interface types. The compiler will verify that the parameters and return value correspond to the given prototype. Any TTCN–3 function (even external ones) may be defined with a prototype. There are four prototypes defined as follows:

* prototype `convert`
+
Functions of this prototype have one parameter (i.e. the data to be converted), which shall be an `in` value parameter, and the result is obtained in the return value of the function.
+
Example:
[source]
----
external function f_convert(in A param_ex) return B
with { extension "prototype(convert)" }
----
+
The input data received in the parameter `param_ex` of type A is converted. The result returned is of type B.

* prototype `fast`
+
Functions of this prototype have one input parameter (the same as above) but the result is obtained in an `out` value parameter rather than in return value. Hence, a faster operation is possible as there is no need to copy the result if the target variable is passed to the function. The order of the parameters is fixed: the first one is always the input parameter and the last one is the output parameter.
+
Example:
[source]
----
external function f_fast(in A param_1, out B param_2)
with { extension "prototype(fast)" }
----
+
The input data received in the parameter `param_1` of type A is converted. The resulting data of type B is contained in the output parameter `param_2` of type B.

* prototype `backtrack`
+
Functions of this prototype have the same data input/output structure as of prototype `fast`, but there is an additional integer value returned to indicate success or failure of the conversion process. In case of conversion failure the contents of the output parameter is undefined. These functions can only be used for decoding. The following return values are defined to indicate the outcome of the decoding operation:
+
--
** 0 (`OK`). Decoding was successful; the result is stored in the out parameter.

** 1 (`NOT_MY_TYPE`). Decoding was unsuccessful because the input parameter does not contain a valid message of type `B`. The content of the out parameter is undefined.
--
+
Example:
[source]
----
external function f_backtrack(in A param_1, out B param_2) return integer
with { extension "prototype(backtrack)" }
----

The input data received in the parameter `param_1` of type A is converted. The resulting data of type B is contained in the output parameter `param_2` of type B. The function return value (an integer) indicates success or failure of the conversion process.

* prototype `sliding`
+
Functions of this prototype have the same behavior as the one of prototype backtrack, consequently, these functions can only be used for decoding. The difference is that there is no need for the input parameter to contain exactly one message: it may contain a fragment of a message or several concatenated messages stored in a FIFO buffer. The first parameter of the function is an `inout` value parameter, which is a reference to a buffer of type `octetstring` or `charstring`. The function attempts to recognize an entire message. It if succeeds, the message is removed from the beginning of the FIFO buffer, hence the name of this prototype: sliding (buffer). In case of failure the contents of the buffer remains unchanged. The return value indicates success or failure of the conversion process or insufficiency of input data as follows:
+
--
** 0 (`OK`). Decoding was successful; the result is stored in the out parameter. The decoded message was removed from the beginning of the inout parameter which is used as a sliding buffer.

** 1 (`NOT_MY_TYPE`). Decoding was unsuccessful because the input parameter does not contain or start with a valid message of type B. The buffer (`inout` parameter) remains unchanged. The content of out parameter is undefined.

** 2 (`INCOMPLETE_MESSAGE`). Decoding was unsuccessful because the input stream does not contain a complete message (i.e. the end of the message is missing). The input buffer (inout parameter) remains unchanged. The content of out parameter is undefined.
--
+
Example:
[source]
----
external function f_sliding(inout A param_1, out B param_2) return integer
with { extension "prototype(sliding)" }
----
+
The first portion of the input data received in the parameter `param_1` of type `A` is converted. The resulting data of type B is contained in the output parameter `param_2` of type `B`. The return value indicates the outcome of the conversion process.

[[automatic-generation-of-encoder-decoder-functions]]
=== Automatic Generation of Encoder/decoder Functions

Encoding and decoding is performed by {cpp} external functions using the built-in codecs. These functions can be generated automatically by the complier. The present section deals with attributes governing the function generation.

==== Input and Output Types

Automatically generated encoder/decoder functions must have an attribute `prototype` assigned. If the encoder/decoder function has been written manually, only the attribute `prototype` may be given. Automatically generated encoder/decoder functions must have either the attribute `encode` or the attribute `decode`. In the case of encoding, the input type of the function must be the (structured) type to be encoded, which in turn must have the appropriate encoding attributes needed for the specified encoding method. The output type of the encoding procedure must be `octetstring` (BER, RAW, XER and JSON coding) or `charstring` (TEXT coding). In case of decoding the functions work the other way around: the input type is `octetstring` or `charstring` and the output type can be any (structured) type with appropriate encoding attributes.

[[attribute-syntax]]
==== Attribute Syntax

The syntax of the `encode` and `decode` attributes is the following:

[source]
----
("encode"|"decode") "("("RAW"|"BER"|"TEXT"|"XER"|"JSON") [":" <codec_options>] ")"
----

BER encoding can be applied only for ASN.1 types.

The <`codec_options`> part specifies extra options for the particular codec. Currently it is applicable only in case of BER and XML encoding/decoding. The `codec_options` are copied transparently to the parameter list of the {cpp} encoder/decoder function call in the generated function body without checking the existence or correctness of the referenced symbols.

Example of prototype `convert`, BER encoding and decoding (the PDU is an ASN.1 type):
[source]
----
external function encode_PDU(in PDU pdu) return octetstring
with { extension "prototype(convert) encode(BER:BER_ENCODE_DER)" }
external function decode_PDU(in octetstring os) return PDU
with { extension "prototype(convert) decode(BER:BER_ACCEPT_ALL)" }
----

Example of prototype `convert`, XML encoding and decoding (the PDU is a TTCN-3 type):
[source]
----
external function encode_PDU(in PDU pdu) return octetstring
with { extension "prototype(convert) encode(XER:XER_EXTENDED)" }
external function decode_PDU(in octetstring os) return PDU
with { extension "prototype(convert) decode(XER:XER_EXTENDED)" }
----

[[codec-error-handling]]
==== Codec Error Handling

The TITAN codec API has some well defined function calls that control the behavior of the codecs in various error situations during encoding and decoding. An error handling method is set for each possible error type. The default error handling method can be overridden by specifying the `errorbehavior` attribute:

[source]
----
"errorbehavior" "(" <error_type> ":" <error_handling>
{ "," <error_type> ":" <error_handling> } ")"
----

Possible error types and error handlings are defined in <<13-references.adoc#\_16, [16]>>, section "The common API". The value of `<error_type>` shall be a value of type `error_type_t` without the prefix `ET_`. The value of `<error_handling>` shall be a value of type `error_behavior_t` without the prefix `EB_`.

The TTCN–3 attribute `errorbehavior(INCOMPL_ANY:ERROR)`, for example, will be mapped to the following {cpp} statement:
[source]
----
TTCN_EncDec::set_error_behavior(TTCN_EncDec::ET_INCOMPL_ANY,
  TTCN_EncDec::EB_ERROR);
----

When using the `backtrack` or `sliding` decoding functions, the default error behavior has to be changed in order to avoid a runtime error if the `in` or `inout` parameter does not contain a type we could decode. With this change an integer value is returned carrying the fault code. Without this change a dynamic test case error is generated. Example:

[source]
----
external function decode_PDU(in octetstring os, out PDU pdu) return integer
with {
extension "prototype(backtrack)"
extension "decode(BER:BER_ACCEPT_LONG|BER_ACCEPT_INDEFINITE)"
extension "errorbehavior(ALL:WARNING)"
}
----

=== Handling of encode and variant attributes

The TITAN compiler offers two different ways of handling encoding-related attributes:

* the new (standard compliant) handling method, and
* the legacy handling method, for backward compatibility.

==== New codec handling

This method of handling `encode` and `variant` attributes is active by default. It supports many of the newer encoding-related features added to the TTCN-3 standard.

Differences from the legacy method:

* `encode` and `variant` attributes can be defined for types as described in the TTCN-3 standard (although the type restrictions for built-in codecs still apply);
* a type can have multiple `encode` attributes (this provides the option to choose from multiple codecs, even user-defined ones, when encoding values of that type);
* ASN.1 types automatically have `BER`, `JSON`, `PER` (see section <<PER-encoding, PER encoding and decoding through user defined functions>>), and XML (if the compiler option `-a` is set) encoding (they are treated as if they had the corresponding `encode` attributes);
* encoding-specific `variant` attributes are supported(e.g.: `variant "XML"."untagged"`);
* the parameters `encoding_info/decoding_info` and `dynamic_encoding` of predefined functions `encvalue`, `decvalue`, `encvalue_unichar` and `decvalue_unichar` are supported (the `dynamic_encoding` parameter can be used for choosing the codec to use for values of types with multiple encodings; the `encoding_info`/`decoding_info` parameters are currently ignored);
* the `self.setencode` version of the `setencode` operation is supported (it can be used for choosing the codec to use for types with multiple encodings within the scope of the current component);
* the `@local` modifier is supported for `encode` attributes;
* a type’s the default codec (used by `decmatch` templates, the @decoded modifier, and the predefined functions `encvalue`, `decvalue`, `encvalue_unichar` and `decvalue_unichar` when no dynamic encoding parameter is given) is:
* its one defined codec, if it has exactly one codec defined; or
* unspecified, if it has multiple codecs defined (the mentioned methods of encoding/decoding can only be used in this case, if a codec was selected for the type using `self.setencode`).

Differences from the TTCN-3 standard:

* switching codecs during the encoding or decoding of a structure is currently not supported (the entire structure will be encoded or decoded using the codec used at top level);
* the port-specific versions of the `setencode` operation are not supported (since messages sent through ports are not automatically encoded; see also dual-faced ports in section <<dual-faced-ports, Dual-faced Ports>>);
* the `@local` modifier only affects encode attributes, it does not affect the other attribute types;
* `encode` and `variant` attributes do not affect `constants`, `templates`, `variables`, `template` `variables` or `import` statements (these are accepted, but ignored by the compiler);
* references to multiple definitions in attribute qualifiers is not supported(e.g.: `encode` (`template all except` (`t1`)) "`RAW`");
* retrieving attribute values is not supported (e.g.: `var universal charstring x := MyType.encode`).

[[legacy-codec-handling]]
==== Legacy codec handling

This is the method of handling encode and variant attributes that was used before version 6.3.0 (/6 R3A). It can be activated through the compiler command line option `-e`.

Differences from the new method:

* each codec has its own rules for defining `encode` and `variant` attributes;
* a type can only have one `encode` attribute (if more than one is defined, then only the last one is considered), however, it can have `variant` attributes that belong to other codecs (this can make determining the default codec tricky);
* ASN.1 types automatically have `BER`, `JSON`, `PER` (see section <<PER-encoding, PER encoding and decoding through user defined functions>>), and `XML` (if the compiler option -a is set) encoding, however the method of setting a default codec (for the predefined functions `encvalue`, `decvalue`, `encvalue_unichar`, `decvalue_unichar`, for `decmatch` templates, and for the `@decoded` modifier) is different (see section <<setting-the-default-codec-for-asn-1-types, Setting the default codec for ASN.1 types>>);
* encoding-specific `variant` attributes are not supported(e.g.: `variant "XML"."untagged"`);
* the parameters `encoding_info/decoding_info` and `dynamic_encoding` of predefined functions `encvalue`, `decvalue`, `encvalue_unichar` and `decvalue_unichar` are ignored;
* the `setencode` operation is not supported;
* the  @local` modifier is not supported.

The differences from the TTCN-3 standard listed in the previous section also apply to the legacy method.

[[setting-the-default-codec-for-asn-1-types]]
===== Setting the default codec for ASN.1 types

Since ASN.1 types cannot have `encode` or `variant` attributes, the compiler determines their encoding type by checking external encoder or decoder functions (of built-in encoding types) declared for the type.

The TITAN runtime does not directly call these external functions, they simply indicate which encoding type to use when encoding or decoding the ASN.1 type in question through predefined functions `encvalue` and `decvalue`, decoded content matching (`decmatch` templates) and in value and parameter redirects with the `@decoded` modifier.

These external functions can be declared with any prototype, and with the regular stream type of either `octetstring` or `charstring` (even though `encvalue` and `decvalue` have `bitstring` streams).

The ASN.1 type cannot have several external encoder or decoded functions of different (built-in or PER) encoding types, as this way the compiler won’t know which encoding to use. Multiple encoder or decoder functions of the same encoding type can be declared for one type.

NOTE: These requirements are only checked if there is at least one `encvalue`, `decvalue`, `decmatch` template or decoded parameter or value redirect in the compiled modules. They are also checked separately for encoding and decoding (meaning that, for example, multiple encoder functions do not cause an error if only `decvalues` are used in the modules and no `encvalues`). +
The compiler searches all modules when attempting to find the coder functions needed for a type (including those that are not imported to the module where the encvalue, decvalue, decmatch or @decoded is located).

Example:
[source]
----
external function f_enc_seq(in MyAsnSequenceType x) return octetstring
with { extension "prototype(convert) encode(JSON)" }

external function f_dec_seq(in octetstring x, out MyAsnSequenceType y)
with { extension "prototype(fast) decode(JSON)" }


var MyAsnSequenceType v_seq := { num := 10, str := "abc" };
var bitstring v_enc := encvalue(v_seq); // uses the JSON encoder

var MyAsnSequenceType v_seq2;
var integer v_result := decvalue(v_enc, v_seq2); // uses the JSON decoder
----

[[calling-user-defined-encoding-functions-with-encvalue-and-decvalue]]
=== Calling user defined encoding functions with encvalue and decvalue

The predefined functions `encvalue` and `decvalue` can be used to encode and decode values with user defined external functions (custom encoding and decoding functions).

These functions must have the `encode`/`decode` and `prototype` extension attributes, similarly to built-in encoder and decoder functions, except the name of the encoding (the string specified in the `encode` or `decode` extension attribute) must not be equal to any of the built-in encoding names (e.g. BER, TEXT, XER, etc.).

The compiler generates calls to these functions whenever `encvalue` or `decvalue` is called, or whenever a matching operation is performed on a `decmatch` template, or whenever a redirected value or parameter is decoded (with the `@decoded` modifier), if the value’s type has the same encoding as the encoder or decoder function (the string specified in the type’s `encode` attribute is equivalent to the string in the external function’s `encode` or `decode` extension attribute).

Restrictions:

* only one custom encoding and one custom decoding function can be declared per user-defined codec (only checked if `encvalue`, `decvalue`, `decmatch` or `@decoded` are used at least once on the type)
* the prototype of custom encoding functions must be `convert`
* the prototype of custom decoding functions must be `sliding`
* the stream type of custom encoding and decoding functions is `bitstring`

NOTE: Although theoretically variant attributes can be added for custom encoding types, their coding functions would not receive any information about them, so they would essentially be regarded as comments. If custom variant attributes are used, the variant attribute parser’s error level must be lowered to warnings with the compiler option `-E`. +
The compiler searches all modules when attempting to find the coder functions needed for a type (including those that are not imported to the module where the `encvalue`, `decvalue`, `decmatch` or `@decoded` is located; if this is the case, then an extra include statement is added in the generated {cpp} code to the header generated for the coder function’s module).

Example:
[source]
----
type union Value {
  integer intVal,
  octetstring byteVal,
  charstring strVal
  }
with {
  encode "abc";
}

external function f_enc_value(in Value x) return bitstring
 with { extension "prototype(convert) encode(abc)" }

external function f_dec_value(inout bitstring b, out Value x) return integer
with { extension "prototype(sliding) decode(abc)" }


var Value x := { intVal := 3 };
var bitstring bs := encvalue(x); // equivalent to f_enc_value(x)

var integer res := decvalue(bs, x); // equivalent to f_dec_value(bs, x)
----

[[PER-encoding]]
=== PER encoding and decoding through user defined functions

TITAN does not have a built-in PER codec, but it does provide the means to call user defined PER encoder and decoder external functions when using `encvalue`, `decvalue`, `decmatch` templates, and value and parameter redirects with the `@decoded` modifier.

This can be achieved the same way as the custom encoder and decoder functions described in section <<calling-user-defined-encoding-functions-with-encvalue-and-decvalue, Calling user defined encoding functions with encvalue and decvalue>>, except the name of the encoding (the string specified in the encode or decode extension attribute) must be PER.

This can only be done for ASN.1 types, and has the same restrictions as the custom encoder and decoder functions. There is one extra restriction when using legacy codec handling (see section <<setting-the-default-codec-for-asn-1-types, Setting the default codec for ASN.1 types>>): an ASN.1 type cannot have both a PER encoder/decoder function and an encoder/decoder function of a built-in type set (this is checked separately for encoding and decoding).

NOTE: The compiler searches all modules when attempting to find the coder functions needed for a type (including those that are not imported to the module where the `encvalue`, `decvalue`, `decmatch` or `@decoded` is located; if this is the case, then an extra include statement is added in the generated {cpp} code to the header generated for the coder function’s module).

Example:
[source]
----
external function f_enc_per(in MyAsnSequenceType x) return bitstring
with { extension "prototype(convert) encode(PER)" }

external function f_dec_per(in bitstring x, out MyAsnSequenceType y)
with { extension "prototype(fast) decode(PER)" }


var MyAsnSequenceType x := { num := 10, str := "abc" };
var bitstring bs := encvalue(x); // equivalent to f_enc_per(x)

var MyAsnSequenceType y;
var integer res := decvalue(bs, y); // equivalent to f_dec_per(bs, y);
----

=== Common Syntax of Attributes

All information related to implicit message encoding shall be given as `extension` attributes of the relevant TTCN–3 definitions. The attributes have a common basic syntax, which is applicable to all attributes given in this section:

* Whitespace characters (spaces, tabulators, newlines, etc.) and TTCN–3 comments are allowed anywhere in the attribute text. Attributes containing only comments, whitespace or both are simply ignored +
Example: +
`with { extension “/* this is a comment */" }`
* When a definition has multiple attributes, the attributes can be given either in one attribute text separated by whitespace or in separate TTCN–3 attributes. +
Example: +
`with { extension "address provider" }` means exactly the same as +
`with { extension "address"; extension "provider" }`
* Settings for a single attribute, however, cannot be split in several TTCN–3 attributes. +
Example of an invalid attribute: +
`with { extension "prototype("; extension "convert)" }`
* Each kind of attribute can be given at most once for a definition. +
Example of an invalid attribute: +
`with { extension "internal internal" }`
* The order of attributes is not relevant. +
Example: +
`with { extension "prototype(fast) encode(RAW)" }` means exactly the same as +
`with { extension "encode(RAW) prototype(fast)" }`
* The keywords introduced in this section, which are not TTCN–3 keywords, are not reserved words. The compiler will recognize the word properly if it has a different meaning (e.g. the name of a type) in the given context. +
Example: the attribute +
`with { extension "user provider in(internal -> simple: function(prototype))" }` can be a valid if there is a port type named `provider`; `internal` and `simple` are message types and `prototype` is the name of a function.

=== API describing External Interfaces

Since the default class hierarchy of test ports does not allow sharing of {cpp} code with other port types, an alternate internal API is introduced for port types describing external interfaces. This alternate internal API is selected by giving the appropriate TTCN–3 extension attribute to the port. The following extension attributes or attribute combinations can be used:

.Port extension attributes
[cols=",,,,,",options="header",]
|===
|*Attribute(s)* |*Test Port* |*Communication with SUT allowed* |*Using of SUT addresses allowed* |*External interface* |*Notes*
|nothing |normal |yes |no |own |
|internal |none |no |no |own |
|address |see <<13-references.adoc#_16, [16]>> "Support of address type" |yes |yes |own |
|provider |see <<13-references.adoc#_16, [16]>> "Provider port types" |yes |no |own |
|internal provider |none |no |no |own |means the same as internal
|address provider |see <<13-references.adoc#_16, [16]>> "Support of address type" and "Provider port types" |yes |yes |own |
|user PT … |none |yes |depends on PT |PT |PT must have attribute provider
|internal user PT … |none |no |no |PT |PT can have any attributes
|address user PT … |none |yes |yes |PT |PT must have attributes address and provider
|===

=== BNF Syntax of Attributes

[source]
----
FunctionAttributes ::= {FunctionAttribute}
FunctionAttribute ::= PrototypeAttribute | TransparentAttribute

ExternalFunctionAttributes ::= {ExternalFunctionAttribute}
ExternalFunctionAttribute ::= PrototypeAttribute | EncodeAttribute | DecodeAttribute | ErrorBehaviorAttribute

PortTypeAttributes ::= {PortTypeAttribute}
PortTypeAttribute ::= InternalAttribute | AddressAttribute | ProviderAttribute | UserAttribute

PrototypeAttribute ::= "prototype" "(" PrototypeSetting ")"
PrototypeSetting ::= "convert" | "fast" | "backtrack" | "sliding"

TransparentAttribute ::= "transparent"

EncodeAttribute ::= "encode" "(" EncodingType [":" EncodingOptions] ")"
EncodingType ::= "BER" | "RAW" | "TEXT"| "XER" | "JSON"
EncodingOptions ::= {ExtendedAlphaNum}

DecodeAttribute ::= "decode" "(" EncodingType [":" EncodingOptions] ")"

ErrorBehaviorAttribute ::= "errorbehavior" "(" ErrorBehaviorSetting {"," ErrorBehaviorSetting} ")"
ErrorBehaviorSetting ::= ErrorType ":" ErrorHandling
ErrorType ::= ErrorTypeIdentifier | "ALL"
ErrorHandling ::= "DEFAULT" | "ERROR" | "WARNING" | "IGNORE"

InternalAttribute ::= "internal"

AddressAttribute ::= "address"

ProviderAttribute ::= "provider"

UserAttribute ::= "user" PortTypeReference {InOutTypeMapping}
PortTypeReference ::= [ModuleIdentifier "."] PortTypeIdentifier
InOutTypeMapping ::= ("in" | "out") "(" TypeMapping {";" TypeMapping} ")"
TypeMapping ::= MessageType "->" TypeMappingTarget {"," TypeMappingTarget}
TypeMappingTarget ::= (MessageType ":" (SimpleMapping | FunctionMapping | EncodeMapping | DecodeMapping)) | ("-" ":" DiscardMapping)

MessageType ::= PredefinedType | ReferencedMessageType
ReferencedMessageType ::= [ModuleIdentifier "."] (StructTypeIdentifier | EnumTypeIdentifier | SubTypeIdentifier | ComponentTypeIdentifier)

SimpleMapping ::= "simple"

FunctionMapping ::= "function" "(" FunctionReference ")"
FunctionReference ::= [ModuleIdentifier "."] (FunctionIdentifier | ExtFunctionIdentifier)

EncodeMapping ::= EncodeAttribute [ErrorBehaviorAttribute]

DecodeMapping ::= DecodeAttribute [ErrorBehaviorAttribute]

DiscardMapping ::= "discard"
----

Non-terminal symbols in bold are references to the BNF of the TTCN-3 Core Language (Annex A, <<13-references.adoc#_1, [1]>>)

Example:
[source]
----
type record ControlRequest { }
type record ControlResponse { }
type record PDUType1 { }
type record PDUType2 { }
// the encoder/decoder functions are written in {cpp}
external function enc_PDUType1(in PDUType1 par) return octetstring
with { extension "prototype(convert)" }
external function dec_PDUType1(in octetstring stream,
out PDUType1 result) return integer
with { extension "prototype(backtrack)" }

// port type PT1 is the external interface of the dual-faced port
// with its own Test Port. See section "The purpose of Test Ports" in the API guide.

type port PT1 message {
out ControlRequest;
in ControlResponse;
inout octetstring;
} with { extension "provider" }

// port type PT2 is the internal interface of the dual-faced port
// This port is communicating directly with the SUT using the Test Port of PT1.

type port PT2 message {
out ControlRequest;
inout PDUType1, PDUType2;
} with { extension “user PT1

out(ControlRequest -> ControlRequest: simple;
PDUType1 -> octetstring: function(enc_PDUType1);
PDUType2 -> octetstring: encode(RAW))
in(ControlResponse -> - : discard;
octetstring -> PDUType1: function(dec_PDUType1),

PDUType2: decode(RAW),
* : discard)"
}

type component MTC_CT {
port PT2 MTC_PORT;
}

type component SYSTEM_SCT {
port PT1 SYSTEM_PORT;
}
testcase tc_DUALFACED () runs on MTC_CT system SYSTEM_SCT

{
map(mtc:MTC_PORT, system:SYSTEM_PORT);
MTC_PORT.send(PDUType1:{…});
MTC_PORT.receive(PDUType1:?);
}
----

The external face of the dual-faced port (defined by `PT1`) sends and receives the protocol massages as octetstrings. On the internal face of the same dual-faced port (defined by `PT2`) the octetstring is converted to two message types (`PDUType1`, `PDUType2`). The conversion happens both when sending and when receiving messages.

When sending messages, messages of type `PDUType1` will be converted as defined by the function `enc_PDUType1`; whereas messages of type `PDUType2` will be converted using the built-in conversion rules RAW.

When a piece of octetstring is received, decoding will first be attempted using the function `dec_PDUType1`; in successful case the resulting structured type has `PDUType1`. When decoding using the function `dec_PDUType1` is unsuccessful, the octetstring is decoded using the built-in conversion rules RAW; the resulting message is of type `PDUType2`. When none of the above conversion succeeds, the octetstring will be discarded.

`ControlRequest` and `ControlResponse` will not be affected by a conversion in either direction.

image::images/dualfaced.png[Dual-faced port]

== RAW Encoder and Decoder

The RAW encoder and decoder are general purpose functionalities developed originally for handling legacy protocols.

The encoder converts abstract TTCN-3 structures (or types) into a bitstream suitable for serial transmission.

The decoder, on the contrary, converts the received bitstream into values of abstract TTCN-3 structures.

This section covers the <<general-rules-and-restrictions, coding rules in general>>, the <<attributes, attributes controlling them>> and the <<ttcn-3-types-and-their-attributes, attributes allowed for a particular type>>.

You can use the encoding rules defined in this section to encode and decode the following TTCN–3 types:

* bitstring
* boolean
* charstring
* enumerated
* float
* hexstring
* integer
* octetstring
* record
* record of, set of
* set
* union
* universal charstring

The compiler will produce code capable of RAW encoding/decoding if

. The module has attribute 'encode "RAW", in other words at the end of the module there is a text +
`with { encode "RAW" }`

. Compound types have at least one `variant` attribute. When a compound type is only used internally or it is never RAW encoded/decoded then the attribute `variant` has to be omitted.

[NOTE]
====
When a type can be RAW encoded/decoded but with default specification then the empty variant specification can be used: variant "". +
In order to reduce the code size the TITAN compiler only add the RAW encoding if

a. Either the type has a RAW variant attribute OR +
b. The type is used by an upper level type definition with RAW variant attribute.
====

Example: In this minimal introductory example there are two types to be RAW encoded: OCT2 and CX_Frame but only the one of them has RAW variant attribute.
[source]
----
module Frame {
external function enc_CX_frame( in CX_Frame cx_message ) return octetstring
with { extension "prototype(convert) encode(RAW)" }

external function dec_CX_frame( in octetstring stream ) return CX_Frame
with { extension "prototype(convert) decode(RAW)" }

type octetstring OCT2 length(2);
type record CX_Frame

{
OCT2 data_length,
octetstring data_stream
} with { variant "" }
} with { encode "RAW" }
----

[[general-rules-and-restrictions]]
=== General Rules and Restrictions

The TTCN-3 standard defines a mechanism using `attributes` to define, among others, encoding variants (see <<13-references.adoc#_1, [1]>>, chapter 27 "Specifying attributes"). However, the `attributes` to be defined are implementation specific. This and the following chapters describe each `attribute` available in TITAN.

==== General Rules

If an `attribute` can be assigned to a given type, it can also almost always be assigned to the same type of fields in a `record`, set or `union`. Attributes belonging to a `record` or `set` field overwrites the effect of the same attributes specified for the type of the field.

The location of an attribute is evaluated before the attribute itself. This means that if an attribute is overwritten thanks to its qualification or the overwriting rules, or both, its validity at the given location will not be checked.

It is not recommended to use the attributes `LENGTHTO`, `LENGTHINDEX`, `TAG`, `CROSSTAG`, `PRESENCE`, `UNIT`, `POINTERTO`, `PTROFFSET` with dotted qualifiers as it may lead to confusion.

Octetstrings and records with extension bit shall be octet aligned. That is, they should start and end in octet boundary.

Error encountered during the encoding or decoding process are handled as defined in section "Setting error behavior" in <<13-references.adoc#_16, [16]>>.

=== Rules Concerning the Encoder

The encoder doesn’t modify the data to be encoded; instead, it substitutes the value of calculated fields (`length`, `pointer`, `tag`, `crosstag` and `presence` fields) with the calculated value in the encoded bitfield if necessary.

The value of the `pointer` and `length` fields are calculated during encoding and the resulting value will be used in sending operations. During decoding, the decoder uses the received length and pointer information to determine the length and the place of the fields.

During encoding, the encoder sets the value of the `presence`, `tag` and `crosstag` fields according to the presence of the `optional` and `union` fields.

=== Rule Concerning the Decoder

The decoder determines the presence of the optional fields on the basis of the value of the `tag`, `crosstag` and `presence` fields.

[[attributes]]
=== Attributes

An `attribute` determines coding and encoding rules. In this section the `attributes` are grouped according to their function.

==== Attributes Governing Conversion of TTCN-3 Types into Bitfields

This section defines the attributes describing how a TTCN-3 type is converted to a bitfield.

*BITORDERINFIELD*

Attribute syntax: `BITORDERINFIELD(<parameter>)`

Parameters allowed: `msb`, `lsb`

Default value: `lsb`

Can be used with: stand-alone types, or a field of a `record` or `set`.

Description: This attribute specifies the order of the bits within a field. When set to `msb`, the first bit sent will be the most significant bit of the original field. When set to `lsb`, the first bit sent will be the least significant bit of the original field.

Comment: The effect of `BITORDERINFIELD(msb)` is equal to the effect of `BITORDER(msb) BYTORDER(last)`.

Example:
[source]
----
type bitstring BITn
with {
variant "BITORDERINFIELD(lsb)"
}

const BITn c_bits := ’10010110’B
//Encoding of c_bits gives the following result: 10010110

type bitstring BITnreverse
with {
variant "BITORDERINFIELD(msb)"
}

const BITnreverse c_bitsrev := ’10010110’B
//Encoding of c_bitsrev gives the following result: 01101001
----

*COMP*

Attribute syntax: `COMP(<parameter>)`

Parameters allowed: `nosign`, `2scompl`, `signbit`

Default value: `nosign`

Can be used with: stand-alone types or the field of a `record` or `set`.

Description: This attribute specifies the type of encoding of negative integer numbers as follows: +
`nosign`: negative numbers are not allowed; +
`2scompl`: 2’s complement encoding; +
`signbit`: sign bit and the absolute value is coded. (Only with integer and enumerated types.)

Examples:
[source]
----
//Example number 1): coding with sign bit
type integer INT1
with {
variant "COMP(signbit)";
variant "FIELDLENGTH(8)"
}

const INT1 c_i := -1
//Encoded c_i: 10000001 ’81’O
// sign bitˆ
//Example number 2): two's complement coding
type integer INT2 with {variant "COMP(2scompl)";
variant "FIELDLENGTH(8)"
}

const INT2 c_i2 := -1
//Encoded c_i2: 11111111 ’FF’O
----

*FIELDLENGTH*

Attribute syntax: `FIELDLENGTH(<parameter>)`

Parameters allowed: `variable`, `null_terminated` (for `charstrin` and universal `charstring` types only) positive integer

Default value: `variable`, 8 (for `integer` type only)

Can be used with:

* `integer`;
* `enumerated`;
* `octetstring`;
* `charstring`;
* `bitstring`;
* `hexstring`;
* `universal charstring`;
* `record` fields;
* `set` fields;
* `record of` types;
* `set of` types.

Description: `FIELDLENGTH` specifies the length of the encoded type. The units of the parameter value for specific types are the following:

* `integer, enumerated, bitstring:` bits;
* `octetstring, universal charstring:` octets;
* `charstring:` characters;
* `hexstring:` hex digits;
* `set of/record of:` elements.

The value 0 means variable length or, in case of the enumerated type, the minimum number of bits required to display the maximum `enumerated` value. `Integer` cannot be coded with variable length.

NOTE: If `FIELDLENGTH` is not specified, but a TTCN–3 length restriction with a fixed length is, then the restricted length will be used as `FIELDLENGTH`.

Examples:
[source]
----
//Example number 1): variable length octetstring
type octetstring OCTn
with {
variant "FIELDLENGTH(variable)"
}

//Example number 2): 22 bit length bitstrings
type bitstring BIT22
with {
variant "FIELDLENGTH(22)"
}

type record SomeRecord {
bitstring field
}

with {
variant (field) "FIELDLENGTH(22)"
}

// Null terminated strings
type charstring null_str with {variant "FIELDLENGTH(null_terminated)"}
type universal charstring null_ustr with { variant "FIELDLENGTH(null_terminated)"}
----

*N bit / unsigned N bit*

Attribute syntax: `[unsigned] <parameter> bit`

Parameters allowed: positive integer

Default value: -

Can be used with:

* `integer`;
* `enumerated`;
* `octetstring`;
* `charstring`;
* `bitstring`;
* `hexstring`;
* `record` fields;
* `set` fields.

Description: This attribute sets the `FIELDLENGTH`, `BYTEORDER` and `COMP` attributes to the following values:

* `BYTEORDER` is set to `last`.
* `N bit` sets `COMP` to `signbit`, while `unsigned` `N` `bit` sets `COMP` to `nosign` (its default value).
* Depending on the encoded value’s type `FIELDLENGTH` is set to: +
`integer, enumerated, bitstring, boolean:` N; +
`octetstring, charstring:` N / 8; +
`hexstring:` N / 4.

NOTE: If `FIELDLENGTH` is not specified, but a TTCN–3 length restriction with a fixed length is, then the restricted length will be used as `FIELDLENGTH`.

The `[unsigned] <parameter> bits` syntax is also supported but the usage of `bit` keyword is preferred.

Examples:
[source]
----
//Example number 1): integer types
type integer Short (-32768 .. 32767)
with { variant "16 bit" };

// is equal to:
type integer ShortEq (-32768 .. 32767)
with { variant "FIELDLENGTH(16), COMP(signbit), BYTEORDER(last)" };

type integer UnsignedLong (0 .. 4294967295)
with { variant "unsigned 32 bit" };

// is equal to:
type integer UnsignedLongEq (0 .. 4294967295)
with { variant "FIELDLENGTH(32), COMP(nosign), BYTEORDER(last)" };

//Example number 2): string types
type hexstring HStr20
with { variant "unsigned 20 bit" };

// 20 bits = 5 hex nibbles, `unsigned' is ignored
type hexstring HStr20Eq
with { variant "FIELDLENGTH(5), BYTEORDER(last)" };

type octetstring OStr32
with { variant "32 bit" };

// 32 bits = 4 octets
type octetstring OStr32Eq
with { variant "FIELDLENGTH(4), BYTEORDER(last)" };

type charstring CStr64 with
{ variant "64 bit" };

// 64 bits = 8 characters
type charstring CStr64Eq
with { variant "FIELDLENGTH(8), BYTEORDER(last)" };
----

*FORMAT*

Attribute syntax: `FORMAT(<parameter>)`

Parameters allowed: `IEEE754 double`, `IEEE754 float`

Default value: `IEEE754 double`

Can be used with: `float` type.

Description: `FORMAT` specifies the encoding format of `float` values. +
`IEEE754 double:` The `float` value is encoded as specified in standard IEEE754 using 1 sign bit, 11 exponent bits and 52 bits for mantissa. +
`IEEE754 float:` The `float` value is encoded as specified in standard IEEE754 using 1 sign bit, 8 exponent bits and 23 bits for mantissa.

Examples:
[source]
----
//Example number 1): single precision float
type float Single_float
with {
variant "FORMAT(IEEE754 float)"
}

//Example number 2): double precision float
type float Double_float
with {
variant "FORMAT(IEEE754 double)"
}
----

==== Attributes Controlling Conversion of Bitfields into a Bitstream

This section defines the attributes describing how bits and octets are put into the buffer.

*BITORDER*

Attribute syntax: `BITORDER(<parameter>)`

Parameters allowed: `msb`, `lsb`

Default value: `lsb`

Can be used with: stand-alone types or the field of a `record` or `set`.

Description: This attribute specifies the order of the bits within an octet. When set to `lsb`, the first bit sent will be the least significant bit of the original byte. When set to `msb`, the first bit sent will be the most significant bit of the original byte. When applied to an `octetstring` using the extension bit mechanism, only the least significant 7 bits are reversed, the 8th bit is reserved for the extension bit.

Examples:
[source]
----
// Example number 1)
type octetstring OCT
with {
variant "BITORDER(lsb)"
}

const OCT c_oct := ’123456’O

//The encoded bitfield: 01010110 00110100 00010010
// last octet^ ^first octet
// The buffer will have the following content:
// 00010010
// 00110100
// 01010110

//The encoding result in the octetstring ’123456’O

//Example number 2)
type octetstring OCTrev
with {
variant "BITORDER(msb)"
}

const OCTrev c_octr := ’123456’O

//The encoded bitfield: 01010110 00110100 00010010

// last octet^ ^first octet

//The buffer will have the following content:
// 01001000
// 00101100
// 01101010

//The encoding results in the octetstring ’482C6A’O

//Example number 3)

type bitstring BIT12 with {
variant "BITORDER(lsb), FIELDLENGTH(12)"
}

const BIT12 c_bits:=’101101101010’B
//The encoded bitfield: 1011 01101010

// last octet^ ^first octet

The buffer will have the following content:
// 01101010
// ….1011
// ^ next field

//The encoding will result in the octetstring ’6A.9’O

//Example number 4)
type bitstring BIT12rev with {
variant "BITORDER(msb), FIELDLENGTH(12)"
}

const BIT12 c_BIT12rev:=’101101101010’B
//The encoded bitfield: 1011 01101010
// last octet^ ^first octet
//The buffer will have the following content:
// 01010110
// ….1101
// ^ next field
//The encoding will result in the octetstring ’56.D’O
----

*BYTEORDER*

Attribute syntax: `BYTEORDER(<parameter>)`

Parameters allowed: `first`, `last`

Default value: `first`

Can be used with: stand-alone types or the field of a `record` or `set`.

Description: The attribute determines the order of the bytes in the encoded data.

* `first`: The first octet placed first into the buffer.
* `last`: The last octet placed first into the buffer.

Comment: The attribute has no effect on a single octet field.

NOTE: The attribute works differently for `octetstring` and `integer` types. The ordering of bytes is counted from left-to-right (starting from the MSB) in an `octetstring` but right-to-left (starting from the LSB) in an `integer`. Thus, the attribute `BYTEORDER(first)` for an `octetstring` results the same encoded value than `BYTEORDER(last)` for an `integer` having the same value.

Examples:
[source]
----
//Example number 1)
type octetstring OCT
with {
variant "BYTEORDER(first)"
}

const OCT c_oct := ’123456’O
//The encoded bitfield: 01010110 00110100 00010010
// last octet^ ^first octet

The buffer will have the following content:
// 00010010
// 00110100
// 01010110

//The encoding will result in the octetstring ’123456’O

//Example number 2)
type octetstring OCTrev
with {variant "BYTEORDER(last)"
}

const OCTrev c_octr := ’123456’O
//The encoded bitfield: 01010110 00110100 00010010
// last octet^ ^first octet

//The buffer will have the following content:

// 01010110

// 00110100

// 00010010

The encoding will result in the octetstring ’563412’O
//Example number 3)
type bitstring BIT12 with {
variant "BYTEORDER(first), FIELDLENGTH(12)"
}

const BIT12 c_bits:=’100101101010’B
//The encoded bitfield: 1001 01101010
// last octet^ ^first octet
The buffer will have the following content:
// 01101010
// ….1001
// ^ next field

//The encoding will result in the octetstring ’6A.9’O
//Example number 4)
type bitstring BIT12rev with {
variant "BYTEORDER(last), FIELDLENGTH(12)"
}

const BIT12rev c_bits:=’100101101010’B
//The encoded bitfield: 1001 01101010
// last octet^ ^first octet
//The buffer will have the following content:
// 10010110
// ….1010
// ^ next field
//The encoding will result in the octetstring ’96.A’O

----

*FIELDORDER*

Attribute syntax: `FIELDORDER(<parameter>)`

Parameters allowed: `msb`, `lsb`

Default value: `lsb`

Can be used with: `record` or `set` types. It can also be assigned to a group of fields of a `record`.

Description: The attribute specifies the order in which consecutive fields of a structured type are placed into octets.
* `msb:` coded bitfields are concatenated within an octet starting from MSB, when a field stretches the octet boundary, it continues at the MSB of next the octet.
* `lsb:` coded bitfields are concatenated within an octet starting from LSB, when a field stretches the octet boundary, it continues at the LSB of next the octet.

Comment: Fields within an octet must be coded with the same `FIELDORDER`. +
Fields are always concatenated in increasing octet number direction. +
`FIELDORDER` has a slightly different effect than order attributes. While the `FIELDORDER` shifts the location of coded bitfields inside octets, the order attributes describes the order of the bits within a bitfield. +
There is NO connection between the effect of the `FIELDORDER` and the effects of the other order attributes.

NOTE: The attribute does not extend to lower level structures. If the same field order is desired for the fields of a lower level `record`/`set`, then that `record`/`set` also needs a `FIELDORDER` attribute.

Examples:
[source]
----
//Example number 1)
type record MyRec_lsb {
BIT1 field1,
BIT2 field2,
BIT3 field3,
BIT4 field4,
BIT6 field5
}

with { variant "FIELDORDER(lsb)" }
const MyRec_lsb c_pdu := {
field1:=’1’B // bits of field1: a
field2:=’00’B // bits of field2: b
field3:=’111’B // bits of field3: c
field4:=’0000’B // bits of field4: d
field5:=’111111’B // bits of field5: e
}

//Encoding of c_pdu will result in:
// 00111001 ddcccbba
// 11111100 eeeeeedd
//Example number 2)

type record MyRec_msb {
BIT1 field1,
BIT2 field2,
BIT3 field3,
BIT4 field4,
BIT6 field5
}

with { variant "FIELDORDER(msb)" }
const MyRec_msb c_pdu2 := {
field1:=’1’B // bits of field1: a
field2:=’00’B // bits of field2: b
field3:=’111’B // bits of field3: c
field4:=’0000’B // bits of field4: d
field5:=’111111’B // bits of field5: e
}

//Encoding of c_pdu2 will result in:
// 10011100 abbcccdd
// 00111111 ddeeeeee
----

*HEXORDER*

Attribute syntax: `HEXORDER(<parameter>)`

Parameters allowed: `low`, `high`

Default value: `low`

Can be used with: `hexstring` or `octetstring` type.

Description: Order of the hexs in the encoded data.
* `low:` The hex digit in the lower nibble of the octet is put in the lower nibble of the octet in the buffer.
* `high:` The hex digit in the higher nibble of the octet is put in the lower nibble of the octet in the buffer. (The value is swapped)

NOTE: Only the whole octet is swapped if necessary. For more details see the example.

Examples:
[source]
----
//Example number 1)
type hexstring HEX_high
with {variant "HEXORDER(high)"}

const HEX_high c_hexs := ’12345’H
//The encoded bitfield: 0101 00110100 00010010
// last octet^ ^first octet

//The buffer will have the following content:
// 00010010 12
// 00110100 34
// ….0101 .5
// ^ next field
//The encoding will result in the octetstring ’1234.5’O

//Example number 2)
type hexstring HEX_low
with {variant "HEXORDER(low)"}
const HEX_low c_hexl := ’12345’H

//The encoded bitfield: 0101 00110100 00010010
// last octet^ ^first octet
//The buffer will have the following content:
// 00100001 21
// 01000011 43
// ….0101 .5 ←not twisted!
// ^ next field
//The encoding will result in the octetstring ’2143.5’O

//Example number 3)
type octetstring OCT
with {variant "HEXORDER(high)"}

const OCT c_hocts := ’1234’O
//The encoded bitfield: 00110100 00010010
// last octet^ ^first octet
//The buffer will have the following content:
// 00100001 21
// 01000011 43
//The encoding will result in the octetstring ’2143’O
----

==== Extension Bit Setting Attributes

This section defines the attributes describing the extension bit mechanism.

The extension bit mechanism allows the size of an Information Element (IE) to be increased by using the most significant bit (MSB, bit 7) of an octet as an extension bit. When an octet within an IE has bit 7 defined as an extension bit, then the value `0' in that bit position indicates that the following octet is an extension of the current octet. When the value is `1', the octet is not continued.

*EXTENSION_BIT*

Attribute syntax: `EXTENSION_BIT(<parameter>)`

Parameters allowed: `no`, `yes`, `reverse`

Default value: none

Can be used with:

* `octetstring`,
* (fields of a) `record`,
* `set`,
* `record of`,
* `set of`.

Description: When `EXTENSION_BIT` is set to `yes`, then each MSB is set to 0 except the last one which is set to 1. When `EXTENSION_BIT` is set to `reverse`, then each MSB is set to 1 and the MSB of the last octet is set to 0 to indicate the end of the Information Element. When `EXTENSION_BIT` is set to `no`, then no changes are made to the MSBs.

NOTE: In case of the types `record` of and `set of` the last bit of the element of the structured type will be used as `EXTENSION_BIT`. The data in the MSBs will be overwritten during the encoding. When `EXTENSION_BIT` belongs to a record, the field containing the `EXTENSION_BIT` must explicitly be declared in the type definition. Also the last bit of the element of `record of` and `set of` type shall be reserved for `EXTENSION_BIT` in the type definition.

Examples:
[source]
----
//Example number 1)
octetstring OCTn
with {variant "EXTENSION_BIT(reverse)"}
const OCTn c_octs:=’586211’O

//The encoding will have the following result:
// 11011000
// 11100010
// 00010001
// ˆ the overwritten EXTENSION_BITs

//The encoding will result in the octetstring ’D8E211’O
//Example number 2)

type record Rec3 {
BIT7 field1,
BIT1 extbit1,
BIT7 field2 optional,
BIT1 extbit2 optional
}

with { variant "EXTENSION_BIT(yes)" }
const Rec3 c_MyRec{
field1:=’1000001’B,
extbit1:=’1’B,
field2:=’1011101’B,
extbit2:=’0’B
}

//The encoding will have the following result:
// 01000001
// 11011101
// ˆ the overwritten EXTENSION_BITs

The encoding will result in the octetstring ’41DD’O

//Example number 3)
type record Rec4{
BIT11 field1,
BIT1 extbit
}

type record of Rec4 RecList
with { variant "EXTENSION_BIT(yes)"}
const RecList c_recs{
{ field1:=’10010011011’B, extbit:=’1’B}
{ field1:=’11010111010’B, extbit:=’0’B}
}

//The encoding will have the following result:
// 10011011
// 10100100
// 11101011
// ˆ the overwritten EXTENSION_BITs

//The encoding will result in the octetstring ’9BA4EB’O
----

*EXTENSION_BIT_GROUP*

Attribute syntax: `EXTENSION_BIT_GROUP(<param1, param2, param3>)`

Parameters allowed: `param1: no, yes, reverse` +
                    `param2: first_field_name`, +
                    `param3: last_field_name`

Default value: none

Can be used with: a group of `record` fields

Description: The `EXTENSION_BIT_GROUP` limits the extension bit mechanism to a group of the fields of a `record` instead of the whole `record`. +
`first_field_name`: the name of the first field in the +
`grouplast_field_name`: the name of the last field in the group

NOTE: Multiple group definition is allowed to define more groups within one `record`. Every group must be octet aligned and the groups must not overlap.

Example:
[source]
----
type record MyPDU{
OCT1 header,
BIT7 octet2info,
BIT1 extbit1,
BIT7 octet2ainfo optional,
BIT1 extbit2 optional,
OCT1 octet3,
BIT7 octet4info,
BIT1 extbit3,
BIT7 octet4ainfo optional,
BIT1 extbit4 optional,
} with {
variant "EXTENSION_BIT_GROUP(yes,octet2info,extbit2)";
variant "EXTENSION_BIT_GROUP(yes,octet4info,extbit4)"
}

const MyPDU c_pdu:={
header:=’0F’O,
octet2info:=’1011011’B,
extbit1:= ’0’B,
octet2ainfo:= omit,
extbit2:= omit,
octet3:=’00’O,
octet4info:=’0110001’B,
extbit3:=’1’B,
octet4ainfo:=’0011100’B,
extbit4:=’0’B,
}

//The encoding will have the following result:
// 00001111
// **1**1011011
// 00000000
// **0**0110001
// **1**0011100
// ˆ the overwritten extension bits
//The encoding will result in the octetstring: ’0FDB00319C’O
----

==== Attributes Controlling Padding

This section defines the attributes that describe the padding of fields.

*ALIGN*

Attribute syntax: `ALIGN(<parameter>)`

Parameters allowed: `left`, `right`

Default value: `right`

Can be used with: stand-alone types or the field of a `record` or `set`.

Description: This attribute has meaning when the length of the actual value can be determined and is less than the specified `FIELDLENGTH`. In such cases the remaining bits/bytes will be padded with zeros. The attribute `ALIGN` specifies the sequence of the actual value and the padding within the encoded bitfield. +
`right`: The LSB of the actual value is aligned to the LSB of coded bitfield +
`left`: The MSB of the actual value is aligned to the MSB of coded bitfield

NOTE: It has no meaning during decoding except if the length of the actual value can be determined from the length restriction of the type. In this case the `ALIGN` also specifies the order of the actual value and the padding within the encoded bitfield.

Examples:
[source]
----
//Example number 1)
type octetstring OCT10
with {
variant "ALIGN(left)";
variant "FIELDLENGTH(10)"
}

const OCT10 c_oct := ’0102030405’O
//Encoded value: ’01020304050000000000’O
//The decoded value: ’01020304050000000000’O
//Example number 2)
type octetstring OCT10length5 length(5)
with {
variant "ALIGN(left)";
variant "FIELDLENGTH(10)"
}

const OCT10length5 c_oct5 := ’0102030405’O
//Encoded value: ’01020304050000000000’O
//The decoded value: ’0102030405’O
----

*PADDING*

Attribute syntax: `PADDING(<parameter>)`

Parameters allowed:

* `no`
* `yes`
* `octet`
* `nibble`
* `word16`
* `dword32`
* integer to specify the padding unit and allow padding.

Default value: none

Can be used with: This attribute can belong to any types.

Description: This attribute specifies that an encoded type shall *end* at a boundary fixed by a multiple of `padding` unit bits counted from the beginning of the message. The default padding unit is 8 bits. If `PADDING` is set to `yes`, then unused bits of the last octets of the encoded type will be filled with padding pattern. If `PADDING` is set to `no`, the next field will use the remaining bits of the last octet. If padding unit is specified, then the unused bits between the end of the field and the next padding position will be filled with padding pattern.

NOTE: It is possible to use different padding for every field of structured types. The padding unit defined by `PADDING` and `PREPADDING` attributes can be different for the same type.

Examples:
[source]
----
//Example number 1)
type BIT5 Bit5padded with { variant "PADDING(yes)"}

const Bit5padded c_bits:=’10011’B

//The encoding will have the following result:
// 00010011
// ˆ the padding bits
//The encoding will result in the octetstring ’13’O

//Example number 2)
type record Paddedrec{
BIT3 field1,
BIT7 field2
} with { variant "PADDING(yes)"}

const Paddedrec c_myrec:={
field1:=’101’B,
field2:=’0110100’B
}

//The encoding will have the following result:
// 10100101
// 00000001
// ˆ the padding bits

//The encoding will result in the octetstring ’A501’O

//Example number 3): padding to 32 bits
type BIT5 Bit5padded_dw with { variant "PADDING(dword32)"}
const Bit5padded_dw c_dword:=’10011’B
//The encoding will have the following result:
// 00010011
// 00000000
// 00000000
// 00000000
// ˆ the padding bits

The encoding will result in the octetstring ’13000000’O

//Example number 4)
type record Paddedrec_dw{
BIT3 field1,
BIT7 field2
} with { variant "PADDING(dword32)"}
const Paddedrec_dw c_dwords:={
field1:=’101’B,
field2:=’0110100’B
}

//The encoding will have the following result:
// 10100101
// 00000001
// 00000000
// 00000000
// ˆ the padding bits
The encoding will result in the octetstring ’A5010000’O
----

*PADDING_PATTERN*

Attribute syntax: `PADDING_PATTERN(<parameter>)`

Parameters allowed: bitstring

Default value: `’0’B`

Can be used with: any type with attributes `PADDING` or `PREPADDING`.

Description: This attribute specifies padding pattern used by padding mechanism. The default padding pattern is ’0’B.If the specified padding pattern is shorter than the padding space, then the padding pattern is repeated.

Comment: For a particular field or type only one padding pattern can be specified for `PADDING` and `PREPADDING`.

Examples:
[source]
----
//Example number 1)
type BIT8 Bit8padded with {
variant "PREPADDING(yes), PADDING_PATTERN(’1’B)"
}

type record PDU {
BIT3 field1,
Bit8padded field2
} with {variant ""}

const PDU c_myPDU:={
field1:=’101’B,
field2:=’10010011’B
}

//The encoding will have the following result:
// 11111101
// 10010011
//the padding bits are indicated in bold
//The encoding will result in the octetstring ’FD93’O
//Example number 2): padding to 32 bits

type BIT8 Bit8pdd with {
variant "PREPADDING(dword32), PADDING_PATTERN(’10’B)"
}

type record PDU{
BIT3 field1,
Bit8pdd field2
} with {variant ""}
const PDU c_myPDUplus:={
field1:=’101’B,
field2:=’10010011’B
}

//The encoding will have the following result:
// 01010101
// 01010101
// 01010101
// 01010101
// 10010011
//The padding bits are indicated in bold

//The encoding will result in the octetstring ’5555555593’O
----

*PADDALL*

Attribute syntax: PADDALL(<parameter>)

Can be used with: `record` or `set`.

Description: If `PADDALL` is specified, the padding parameter specified for a whole `record` or `set` will be valid for every field of the structured type in question.

NOTE: If a different padding parameter is specified for any fields it won’t be overridden by the padding parameter specified for the record.

Examples:
[source]
----
//Example number 1)
type record Paddedrec{
BIT3 field1,
BIT7 field2
} with { variant "PADDING(yes)"}
const Paddedrec c_myrec:={
field1:=’101’B,
field2:=’0110100’B
}

//The encoding will have the following result:
// 10100101
// 00000001
// ˆ the padding bits
//The encoding will result in the octetstring ’A501’O

//Example number 2)

type record Padddd{
BIT3 field1,
BIT7 field2
} with { variant "PADDING(yes), PADDALL"}

const Padddd c_myrec:={
field1:=’101’B,
field2:=’0110100’B
}

//The encoding will have the following result:
// 00000101
// 00110100
// ˆ the padding bits

//The encoding will result in the octetstring ’0534’O

//Example number 3)

type record Padded{
BIT3 field1,
BIT5 field2,
BIT7 field3
} with { variant "PADDING(yes), PADDALL"}

const Padded c_ourrec:={
field1:=’101’B,
field2:=’10011’B,
field3:=’0110100’B
}

//The encoding will have the following result:
// 00000101
// 00010011
// 00110100
// ˆ the padding bits

//The encoding will result in the octetstring ’051334’O

//Example number 4): field1 shouldn’t be padded

type record Paddd{
BIT3 field1,
BIT5 field2,
BIT7 field3
} with { variant "PADDING(yes), PADDALL";
variant (field1) "PADDING(no)" }
const Paddd c_myrec:={
field1:=’101’B,
field2:=’10011’B,
field3:=’0110100’B
}

//The encoding will have the following result:
// 10011101 < field1 is not padded!!!
// 00110100
// ˆ the padding bit
//The encoding will result in the octetstring ’9D34’O
----

*PREPADDING*

Attribute syntax: `PREPADDING(<parameter>)`

Parameters allowed:

* `no`
* `yes`
* `octet`
* `nibble`
* `word16`
* `dword32`
* integer to specify the padding unit and allow padding.

Default value: none

Can be used with: any type.

Description: This attribute specifies that an encoded type shall *start* at a boundary fixed by a multiple of padding unit bits counted from the beginning of the message. The default padding unit is 8 bits. If `PREPADDING` is set to `yes`, then unused bits of the last octets of the previous encoded type will be filled with padding pattern and the actual field starts at octet boundary. If `PREPADDING` is set to `no`, the remaining bits of the last octet will be used by the field. If padding unit specified, then the unused bits between the end of the last field and the next padding position will be filled with padding pattern and the actual field starts at from this point.

NOTE: It is possible to use different padding for every field of structured types. The padding unit defined by `PADDING` and `PREPADDING` attributes can be different for the same type.

Examples:
[source]
----
//Example number 1)

type BIT8 bit8padded with { variant "PREPADDING(yes)"}
type record PDU{
BIT3 field1,
bit8padded field2
} with {variant ""}
const PDU c_myPDU:={
field1:=’101’B,
field2:=’10010011’B
}

//The encoding will have the following result:
// 00000101
// 10010011
//The padding bits are indicated in bold
//The encoding will result in the octetstring ’0593’O
//Example number 2): padding to 32 bits

type BIT8 bit8padded_dw with { variant "PREPADDING(dword32)"}
type record PDU{
BIT3 field1,
bit8padded_dw field2
} with {variant ""}
const PDU myPDU:={
field1:=’101’B,
field2:=’10010011’B
}

//The encoding will have the following result:
// 00000101
// 00000000
// 00000000
// 00000000
// 10010011

//The padding bits are indicated in bold

//The encoding will result in the octetstring ’0500000093’O
----

==== Attributes of Length and Pointer Field

This section describes the coding attributes of fields containing length information or serving as pointer within a `record`.

The length and pointer fields must be of TTCN–3 `integer` type and must have fixed length.

The attributes described in this section are applicable to fields of a `record`.

*LENGTHTO*

Attribute syntax: `LENGTHTO(<parameter>) [ (`+' | `-') <offset> ]`

Parameters allowed: list of TTCN–3 field identifiers

Parameter value: any field name

Offset value: positive integer

Default value: none

Can be used with: fields of a `record`.

Description: The encoder is able to calculate the encoded length of one or several fields and put the result in another field of the same record. Consider a record with the fields `lengthField`, `field1`, `field2` and `field3`. Here `lengthField` may contain the encoded length of either one field (for example, `field2`), or sum of the lengths of multiple fields ((for example, that of `field2` + `field3`). The parameter is the field identifier (or list of field identifiers) of the `record` to be encoded.

If the offset is present, it is added to or subtracted from (the operation specified in the attribute is performed) the calculated length during encoding. During decoding, the offset is subtracted from or added to (the opposite operation to the one specified in the attribute is performed) the decoded value of the length field.

NOTE: The length is expressed in units defined by the attribute UNIT The default unit is octet. The length field should be a TTCN–3 `integer` or `union` type. Special union containing only integer fields can be used for variable length field. It must not be used with `LENGTHINDEX`. The length field can be included in to the sum of the lengths of multiple fields (e.g. `lengthField` + `field2` + `field3`). The `union` field is NOT selected by the encoder. So the suitable field must be selected before encoding! The fields included in the length computing need not be continuous.

Examples:
[source]
----
//Example number 1)
type record Rec {
INT1 len,
OCT3 field1,
octetstring field2
}

with {
variant (len) “LENGTHTO(field1);
variant (len) "UNIT(bits)"
}

//Example number 2)

type record Rec2 {
INT1 len,
OCT3 field1,
octetstring field2
}

with {
variant (len) “LENGTHTO(len, field1, field2)
}

//Example number 3)

type record Rec3 {
INT1 len,
OCT3 field1,
OCT1 field2
octetstring field3
}

with {
variant (len) “LENGTHTO(field1, field3)
// field2 is excluded!
}

//Example number 4): using union as length field
type union length_union{
integer short_length_field,
integer long_length_field
} with {
variant (short_length_field) "FIELDLENGTH(7)";
variant (long_length_field) "FIELDLENGTH(15)";
}

type record Rec4{
BIT1 flag,
length_union length_field,
octetstring data
} with {
variant (length_field)
“CROSSTAG(short_length_field, flag = ’0’B
long_length_field, flag = ’1’B)“;
variant (length_field) "LENGTHTO(data)"
}

//Const for short data. Data is shorter than 127 octets:

const Rec4(octetstring oc):={
flag :=’0’B,
length_field:={short_length_field:=0},
data := oc
}

//Const for long data. Data is longer than 126 octets:

const Rec4(octetstring oc):={
flag :=’1’B,
length_field:={long_length_field:=0},
data := oc
}

//Example number 5): with offset
type record Rec5 {
integer len,
octetstring field
}

with {
variant (len) "LENGTHTO(field) + 1"
}

// { len := 0, field := '12345678'O } would be encoded into '0512345678'O
// (1 is added to the length of `field')
// and '0512345678'O would be decoded into { len := 4, field := '12345678'O }
// (1 is subtracted from the decoded value of `len')

//Example number 6): with offset

type record Rec6 {
integer len,
octetstring field
}

with {
variant (len) "LENGTHTO(field) - 2"
}

// { len := 0, field := '12345678'O } would be encoded into '0212345678'O
// (1 is added to the length of `field')
// and '0212345678'O would be decoded into { len := 4, field := '12345678'O }
// (1 is subtracted from the decoded value of `len')
----

*LENGTHINDEX*

Attribute syntax: `LENGTHINDEX(<parameter>)`

Parameters allowed: TTCN–3 field identifier

Allowed values: any nested field name

Default value: none

Can be used with: fields of a `record`.

Description: This attribute extends the `LENGTHTO` attribute with the identification of the nested field containing the length value within the field of the corresponding `LENGTHTO` attribute.

Comment: See also the description of the `LENGTHTO` attribute.
NOTE: The field named by `LENGTHINDEX` attribute should be a TTCN–3 integer type.

Example (see also example of `LENGTHTO` attribute).
[source]
----
type integer INT1
with {
variant "FIELDLENGTH(8)"
}

type record InnerRec {
INT1 length
}

with { variant "" }
type record OuterRec {
InnerRec lengthRec,
octetstring field
}

with {
variant (lengthRec) "LENGTHTO(field)";
variant (lengthRec) "LENGTHINDEX(length)"
}
----

*POINTERTO*

Attribute syntax: `POINTERTO(<parameter>)`

Parameters allowed: TTCN–3 field identifier

Default value: none

Can be used with: fields of a `record`.

Description: Some record fields contain the distance to another encoded field. Records can be encoded in the form of: `ptr1`, `ptr2`, `ptr3`, `field1`, `field2`, `field3`, where the position of fieldN within the encoded stream can be determined from the value and position of field ptrN. The distance of the pointed field from the base field will be `ptrN` * `UNIT` + `PTROFFSET`. The default base field is the pointer itself. The base field can be set by the PTROFFSET attribute. When the pointed field is optional, the pointer value 0 indicates the absence of the pointed field.

Comment: See also the description of `UNIT` (0) and `PTROFFSET` (0) attributes.
NOTE: Pointer fields should be TTCN–3 `integer` type.

Examples:
[source]
----
type record Rec {
INT1 ptr1,
INT1 ptr2,
INT1 ptr3,
OCT3 field1,
OCT3 field2,
OCT3 field3
}

with {
variant (ptr1) "POINTERTO(field1)";
variant (ptr2) "POINTERTO(field2)";
variant (ptr3) "POINTERTO(field3)"
}

const Rec c_rec := {
ptr1 := <any value>,
ptr2 := <any value>,
ptr3 := <any value>,
field1 := ’010203’O,
field2 := ’040506’O,
field3 := ’070809’O
}

//Encoded c_rec: ’030507010203040506070809’O//The value of ptr1: 03
//PTROFFSET and UNIT are not set, so the default (0) is being //using.
//The starting position of ptr1: 0th bit
//The starting position of field1= 3 * 8 + 0 = 24th bit.
----

*PTROFFSET*

Attribute syntax: `PTROFFSET(<parameter>)`

Parameters allowed: `integer`, TTCN–3 field identifier

Default value: 0

Can be used with: fields of a `record`.

Description: This attribute specifies where the pointed field area starts and the base field of pointer calculating. The distance of the pointed field from the base field will equal `ptr_field * UNIT + PTROFFSET`.

Comment: It can be specified a base field and pointer offset for one field. See also the description of the attributes `POINTERTO` (0) and `UNIT` (0).

Examples:
[source]
----
type record Rec {
INT2 ptr1,
INT2 ptr2
OCT3 field1,
OCT3 field2
}

with {
variant (ptr1) "POINTERTO(field1)";
variant (ptr1) "PTROFFSET(ptr2)";
variant (ptr2) "POINTERTO(field2)";
variant (ptr2) "PTROFFSET(field1)"
}

//In the example above the distance will not include//the pointer itself.
----

*UNIT*

Attribute syntax: `UNIT(<parameter>)`

Parameters allowed:

* bits
* octets
* nibble
* word16
* dword32
* elements
* integer

Default value: octets

Can be used with: fields of a `record`.

Description: `UNIT` attribute is used in conjunction with the `LENGTHTO` (0) or `POINTERTO` (0) attributes. Length indicator fields may contain length expressed in indicated number of bits.

Comment: See also description of the `LENGTHTO` and `POINTERTO` attributes. The elements can be used with `LENGTHTO` only if the length field counts the number of elements in a `record`/`set` of field.

Examples:
[source]
----
//Example number 1): measuring length in 32 bit long units
type record Rec {
INT1 length,
octetstring field
}

with {
variant (length) "LENGTHTO(field)";
variant (length) "UNIT(dword32)"
}

//Example number 2): measuring length in 2 bit long units
type record Rec {
INT1 length,
octetstring field
}

with {
variant (length) "LENGTHTO(field)";
variant (length) "UNIT(2)"
}

//Example number 3): counting the number of elements of record of field
type record of BIT8 Bitrec
type record Rec{
integer length,
Bitrec data
}

with{
variant (length) "LENGTHTO(data)";
variant (length) "UNIT(elements)"
}
----

==== Attributes to Identify Fields in Structured Data Types

This section describes the coding attributes which during decoding identifies the fields within structured data types such as record, set or union.

*PRESENCE*

Attribute syntax: `PRESENCE(<parameter>)`

Parameters allowed: a `presence_indicator` expression (see Description)

Default value: none

Can be used with: `optional` fields of a `record` or `set`.

Description: Within records some fields may indicate the presence of another optional field. The attribute `PRESENCE` is used to describe these cases. Each optional field can have a `PRESENCE` definition. The syntax of the `PRESENCE` attribute is the following: a `PRESENCE` definition is a presence_indicator expression. `Presence_indicators` are of form `<key> = <constant> or {<key1> = <constant1>, <key2> = <constant2>, … <keyN> = <constantN>}` where each key is a field(.nestedField) of the `record`, `set` or `union` and each constant is a TTCN–3 constant expression (for example, `22`, `’25’O` or `’1001101’B`).

NOTE: The PRESENCE attribute can identify the presence of the whole record. In that case the field reference must be omitted.

Examples:
[source]
----
type record Rec {
BIT1 presence,
OCT3 field optional
}

with {
variant (field) "PRESENCE(presence = ’1’B)"
}

type record R2{
OCT1 header,
OCT1 data
} with {variant "PRESENCE(header=’11’O)"}
----

*TAG*

Attribute syntax: `TAG(<parameter>)`

Parameters allowed: list of `field_identifications` (see Description)

Default value: none

Can be used with: `record` or `set`.

Description: The purpose of the attribute `TAG` is to identify specific values in certain fields of the `set`, `record` elements or `union` choices. When the `TAG` is specified to a `record` or a `set`, the presence of the given element can be identified at decoding. When the `TAG` belongs to a `union`, the union member can be identified at decoding. The attribute is a list of `field_identifications`. Each `field_identification` consists of a record, set or union field name and a `presence_indicator` expression separated by a comma (,). `Presence_indicators` are of form `<key> = <constant>` or `{ <key1> = <constant1>, <key2> = <constant2>, … <keyN> = <constantN> }` where each key is a field(.nestedField) of the `record`, `set` or `union` and each constant is a TTCN–3 constant expression (e.g.` 22`, `’25’O` or `’1001101’B`).There is a special presence_indicator: `OTHERWISE`. This indicates the default union member in a union when the TAG belongs to union.

NOTE: `TAG` works on non-optional fields of a record as well. It is recommended to use the attributes `CROSSTAG` or `PRESENCE` leading to more effective decoding.

Examples:
[source]
----
//Example number 1): set
type record InnerRec {
INT1 tag,
OCT3 field
}

with { variant "" }
type set SomeSet {
InnerRec field1 optional,
InnerRec field2 optional,
InnerRec field3 optional
}

with {
variant “TAG(field1, tag = 1;
field2, tag = 2;
field3, tag = 3)"
}

//Example number 2): union
type union SomeUnion {
InnerRec field1,
InnerRec field2,
InnerRec field3
}

with {
variant “TAG(field1, tag = 1;
field2, tag = 2;
field3, OTHERWISE)"
}

If neither tag=1 in field1 nor tag=2 in field2 are matched, field3 is selected.

//Example number 3): record
type record MyRec{
OCT1 header,
InnerRec field1 optional
}

with{
variant (field1) "TAG(field1, tag = 1)"
}

//field1 is present when in field1 tag equals 1.
----

*CROSSTAG*

Attribute syntax: `CROSSTAG(<parameter>)`

Parameters allowed: list of union "field_identifications" (see Description)

Default value: none

Can be used with: `union` fields of `records`.

Description: When one field of a `record` specifies the union member of another field of a record, CROSSTAG definition is used. The syntax of the CROSSTAG attribute is the following. Each union field can have a `CROSSTAG` definition. A `CROSSTAG` definition is a list of union `field_identifications`. Each `field_identification` consists of a union field name and a `presence_indicator` expression separated by a comma (,). `Presence_indicators` are of form `<key> = <constant>` or `{<key1> = <constant1>`, `<key2> = <constant2>`, `… <keyN> = <constantN>}` where each key is a field(.nestedField) of the `record`, `set` or `union` and each constant is a TTCN–3 constant expression (for example, `22`, `’25’O` or `’1001101’B`).There is a special `presence_indicator`: `OTHERWISE`. This indicates the default union member in union.

NOTE: The difference between the `TAG` and `CROSSTAG` concept is that in case of `TAG` the field identifier is inside the field to be identified. In case of `CROSSTAG` the field identifier can either precede or succeed the union field it refers to. If the field identifier succeeds the union, they must be in the same record, the union field must be mandatory and all of its embedded types must have the same fixed size.

Examples:
[source]
----
type union AnyPdu {
PduType1 type1,
PduType2 type2,
PduType3 type3
}

with { variant "" }
type record PduWithId {
INT1 protocolId,
AnyPdu pdu
}

with {
variant (pdu) “CROSSTAG( type1, { protocolId = 1,
protocolId = 11 };
type2, protocolId = 2;
type3, protocolId = 3)"
}
----

*REPEATABLE*

Attribute syntax: `REPEATABLE(<parameter>)`

Parameters allowed: `yes`, `no`

Default value: none

Can be used with: `record/set` of type fields of a `set`.

Description: The element of the set can be in any order. The `REPEATABLE` attribute controls whether the element of the `record` or `set` `of` can be mixed with other elements of the `set` or they are grouped together.

NOTE: It has no effect during encoding.

Examples:
[source]
----
// Three records and a set are defined as follows:

type record R1{
OCT1 header,
OCT1 data
} with {variant "PRESENCE(header=’AA’O)"}

type record of R1 R1list;

type record R2{
OCT1 header,
OCT1 data
} with {variant "PRESENCE(header=’11’O)"}

type record R3{
OCT1 header,
OCT1 data
} with {variant "PRESENCE(header=’22’O)"}

type set S1 {
R2 field1,
R3 field2,
R1list field3
}

with {variant (field3) "REPEATABLE(yes)"}

//The following encoded values have equal meaning:
// (The value of R1 is indicated in bold.)
//example1: 1145**AA01AA02AA03**2267
//example2: 114**5AA01**2267**AA02AA03**
//example3: **AA01**2267**AA02**1145*AA03*

The decoded value of S1 type:

{
field1:={
header:=’11’O,
data:=’45’O
},

field2:={
header:=’22’O,
data:=’67’O
},

field3:={
{header:=’AA’O,data:=’01’O},
{header:=’AA’O,data:=’02’O},
{header:=’AA’O,data:=’03’O}
}
}

type set S2 {
R2 field1,
R3 field2,
R1list field3
}

with {variant (field3) "REPEATABLE(no)"}

//Only the example1 is a valid encoded value for S2, because
//the elements of the field3 must be groupped together.
----

*FORCEOMIT*

Attribute syntax: `FORCEOMIT(<parameter>)`

Parameters allowed: list of TTCN-3 field identifiers (can also be nested)

Default value: none

Can be used with: fields of a `record`/`set`.

Description: Forces the lower-level optional field(s) specified by the parameters to always be omitted.

NOTE: It has no effect during encoding. It only affects the specified fields (which are probably in a different type definition) if they are decoded as part of the type this instruction is applied to.

Examples:
[source]
----
type record InnerRec {
  integer opt1 optional,
  integer opt2 optional,
  integer opt3 optional,
  integer mand
}

// Note: decoding a value of type InnerRec alone does not force any of the
// fields mentioned in the variants below to be omitted

type record OuterRec1 {
  integer f1,
  InnerRec f2,
  integer f3
}
with {
  variant (f2) "FORCEOMIT(opt1)"
}

// Decoding ‘0102030405’O into a value of type OuterRec1 results in:
// {
//   f1 := 1,
//   f2 := { opt1 := omit, opt2 := 2, opt3 := 3, mand := 4 },
//   f3 := 5
// }

type record OuterRec2 {
  OuterRec1 f
}
with {
  variant (f) "FORCEOMIT(f2.opt2)"
}

// Decoding ‘01020304’O into a value of type OuterRec2 results in:
// {
//   f := {
//     f1 := 1,
//     f2 := { opt1 := omit, opt2 := omit, opt3 := 2, mand := 3 },
//     f3 := 4
//   }
// }

type record OuterRec3 {
  OuterRec1 f1,
  OuterRec1 f2
}
with {
  variant (f1) "FORCEOMIT(f2.opt2, f2.opt3)"
  variant (f2) "FORCEOMIT(f2.opt2), FORCEOMIT(f2.opt3)"
}

// Decoding ‘010203040506’O into a value of type OuterRec3 results in:
// {
//   f1 := {
//     f1 := 1,
//     f2 := { opt1 := omit, opt2 := omit, opt3 := omit, mand := 2 },
//     f3 := 3
//   },
//   f2 := {
//     f1 := 4,
//     f2 := { opt1 := omit, opt2 := omit, opt3 := omit, mand := 5 },
//     f3 := 6
//   }
// }
----

==== Type-specific attributes

*IntX*

Attribute syntax: `IntX`

Default value: none

Can be used with: `integer` types

Description: Encodes an integer value as the IntX type in the ETSI Common Library (defined in ETSI TS 103 097).

This is a variable length encoding for integers. Its length depends on the encoded value (but is always a multiple of 8 bits).

The data starts with a series of ones followed by a zero. This represents the length of the encoded value: the number of ones is equal to the number of additional octets needed to encode the value besides those used (partially) to encode the length. The following bits contain the encoding of the integer value (as it would otherwise be encoded).

Comment: Since the length of the encoding is variable, attribute `FIELDLENGTH` is ignored. Furthermore, `IntX` also sets `BITORDER` and `BITORDERINFIELD` to `msb`, and `BYTEORDER` to first, overwriting any manual settings of these attributes.

Only attribute `COMP` can be used together with `IntX` (if it’s set to `signbit`, then the sign bit will be the first bit after the length).

Restrictions: Using `IntX` in a `record` or `set` with `FIELDORDER` set to `lsb` is only supported if the `IntX` field starts at the beginning of a new octet. A compiler error is displayed otherwise. The `IntX` field may start anywhere if the parent `record`/`set’s` `FIELDORDER` is set to `msb`.

Examples:
[source]
----
// Example 1: Standalone IntX integer type with no sign bit:
type integer IntX_unsigned with { variant "IntX" }

// Encoding integer 10:
// 00001010
// ^ length bit (there are no ones as no additional octets are needed)

// Encoding integer 2184:
// 10001000 10001000
// ^^ length bits (one extra octet is needed after the partial length octet)

// Example 2: Standalone IntX integer type with sign bit:
type integer IntX_signed with { variant "IntX, COMP(signbit)" }
// Encoding integer -2184:
// 10101000 10001000
// length bits ^^
// ^ sign bit

// Example 3: Standalone IntX integer type with 2’s complement:
type integer IntX_compl with { variant "IntX, COMP(2scompl)" }
// Encoding integer -2184:
// 10110111 01111000
// ^^ length bits

// Example 4: IntX integer record field (starting in a partial octet):
type record RecIntXPartial {
integer i,
integer ix,
bitstring bs
}

with {
variant "FIELDORDER(msb)";
variant (i) "FIELDLENGTH(12), BITORDER(msb)";
variant (i) "BYTEORDER(first), BITORDERINFIELD(msb)";
variant (ix) "IntX";
variant (bs) "FIELDLENGTH(8)";
}

// Encoding record value { i := 716, ix := 716, bs := ‘10101010’B }:
// 00101100 11001000 00101100 11001010 10100000
// ^^^^^^^^ ^^^^ field `i' (same encoding as `ix', but with no length bits)
// field `ix' ^^^^ ^^^^^^^^ ^^^^ (the first 2 bits are the length bits)
// field `bs' ^^^^ ^^^^
// Note: setting the record’s FIELDORDER to `lsb' in this case is not supported
// and would cause the mentioned compiler error.
----

==== Obsolete Attributes

This section describes the obsolete attributes. These attributes are kept for compatibility reason. The usage of the obsolete attributes is not recommended in new developments.

*BITORDERINOCTET*

The attribute has the same meaning and syntax as `BITORDER`. In new developments only the attribute `BITORDER` may be used.

*TOPLEVEL BITORDER*

Attribute syntax: `TOPLEVEL( BITORDER(<parameter>))`

Parameters allowed: `msb`, `lsb`

Default value: `msb`

Can be used with: a toplevel type.

Description: This attribute specifies the order of the bits within an octet. When set to `lsb`, the first bit sent will be the least significant bit of the original byte.

Comment:

Example:
[source]
----
type record WholePDU {
Field1 field1,
Field2 field2
}

with { variant "TOPLEVEL( BITORDER(lsb) )" }
const WholePDU c_pdu := {
’12’O,
’12’O
}

//Encoding of c_pdu will result in ’4848’O.
----

[[ttcn-3-types-and-their-attributes]]
=== TTCN-3 Types and Their Attributes

This section lists the TTCN-3 types along with the attributes allowed to be used with the types.

*BITSTRING*

Coding: The `bitstring` is represented by its binary value. The LSB of the binary form of a bitstring is concatenated to the LSB of the bitfield. If the length of the `bitstring` is shorter than the specified `FIELDLENGTH`, aligning is governed by the attribute `ALIGN. The FIELDLENGTH` default value for `bitstring` type is `variable`.

Attributes allowed:

* `ALIGN (0)`,
* `BITORDER (0)`,
* `BITORDERINFIELD (0)`,
* `BYTEORDER (0)`,
* `FIELDLENGTH (0)`,
* `N bit / unsigned N bit` (0).

Example:
[source]
----
*//Example number 1): variable length bitstring*
const bitstring c_mystring:=’1011000101’B
//The resulting bitfield: 1011000101
//The encoding will have the following result:
// 11000101
// ……10

*//Example number 2): fixed length bitstring*
type bitstring BIT7 with { variant "FIELDLENGTH(7)" }
const BIT7 c_ourstring:=’0101’B
//The resulting bitfield: 0000101

*//Example number 3): left aligned bitstring*
type bitstring BIT7align with {
variant "FIELDLENGTH(7), ALIGN(left)" }
const BIT7align c_yourstring:=’0101’B
//The resulting bitfield: 0101000
----

*BOOLEAN*

Coding: The `boolean` value `true` coded as ’1’B,the `boolean` value `false` coded as ’0’B.If `FIELDLENGTH` is specified, the given number of ones (`true`) or zeros (`false`) is coded. If the decoded bitfield is zero the decoded value will be false otherwise true. The default `FIELDLENGTH` for `boolean` type is 1.

Attributes allowed: `FIELDLENGTH (0)`, `N bit` (0).

Examples:
[source]
----
*//Example number 1): boolean coded with default length*
const boolean c_myvar:=true
//The resulting bitfield: 1
*//Example number 2): boolean coded with fixed length*
type boolean Mybool with { variant "FIELDLENGTH(8)"}
const Mybool c_ourvar:=true
//The resulting bitfield: 11111111
----

*CHARSTRING*

Coding: The characters are represented by their ASCII binary value. The first character is put into the first octet of the bitfield. The second character is put into the second octet of the bitfield and so on. Thus, the first character is put first into the buffer. If the actual value of `charstring` is shorter than the specified `FIELDLENGTH`, aligning is governed by the attribute `ALIGN`. The default `FIELDLENGTH` for bitstring type is variable. The `FIELDLENGTH` is measured in chars.

Attributes allowed:

* `ALIGN (0)`,
* `BITORDER (0)`,
* `BITORDERINFIELD (0)`,
* `BYTEORDER (0)`,
* `FIELDLENGTH (0)`,
* `N bit (0)`

Examples:
[source]
----
*//Example number 1): variable length charstring*
const charstring c_mystring:="Hello"
//The resulting bitfield: 01101111 01101100 01101100
// 01100101 01001000
//The encoding will have the following result:
// 01001000 "H"
// 01100101 "e"
// 01101100 "l"
// 01101100 "l"
// 01101111 "o"

*//Example number 2): fixed length charstring*
type charstring CHR6 with { variant "FIELDLENGTH(6)" }
const CHR6 c_yourstring:="Hello"
//The resulting bitfield: 00000000 01101111 01101100 01101100
// 01100101 01001000

//The encoding will have the following result:
// 01001000 "H"
// 01100101 "e"
// 01101100 "l"
// 01101100 "l"
// 01101111 "o"
// 00000000 " "

*//Example number 3): left aligned charstring*
type charstring CHR6align with {
variant "FIELDLENGTH(6), ALIGN(left)" }
const CHR6align c_string:="Hello"

//The resulting bitfield: 01101111 01101100 01101100 01100101
// 01001000 00000000
//The encoding will have the following result:
// 00000000 " "
// 01001000 "H"
// 01100101 "e"
// 01101100 "l"
// 01101100 "l"
// 01101111 "o"
----

*ENUMERATED*

Coding: The `enumerated` type is coded as an integer value. This numerical value is used during encoding. The default `FIELDLENGTH` for `enumerated` type is the minimum number of bits required to display the highest `enumerated` value.

Attributes allowed:

* `BITORDER (0)`,
* `BITORDERINFIELD (0)`,
* `BYTEORDER (0)`,
* `COMP (0)`,
* `FIELDLENGTH (0)`,
* `N bit / unsigned N bit` (0).

Example:
[source]
----
type enumerated Enumm {zero, one, two, three, four, five}

const Enumm myenum:=two

//The maximum enumerated value: 5 (five)
//Minimum 3 to represent 5.
//The FIELDLENGTH will be 3
//The resulting bitfield: 010

type enumerated Enum { zero(2), one(23), two(4), three(1), four(0), five(5) }
const Enum c_myenum:=two

//The maximum enumerated value: 23 (one)
//Minimum 5 bits are needed to represent 23.
//The FIELDLENGTH will be 5
//The resulting bitfield: 00010
----

*FLOAT*

Coding: The `float` value is represented according to IEEE 754 standard. The `FORMAT` attribute specifies the number of the bits used in exponent and mantissa. `IEEE754 double`: The float value is encoded as specified in IEEE754 standard using 1 sign bit, 11 exponent bits and 52 bits for mantissa. `IEEE754 float`: The float value is encoded as specified in IEEE754 standard using 1 sign bit, 8 exponent bits and 23 bits for mantissa. The default `FORMAT` for float is IEEE754 double.

Attributes allowed:

* `BITORDER (0)`,
* `BITORDERINFIELD (0)`,
* `BYTEORDER (0)`,
* `FORMAT (0)`

Example:
[source]
----
//S - sign bit
//E - exponent bits
//M - mantissa bits

*//Example number 1): single precision float*
type float SingleFloat
with {
variant "FORMAT(IEEE754 float)"
}

const SingleFloat c_float:=1432432.125
//The resulting bitfield: 10000001 11011011 10101110 01001001
// MMMMMMMM MMMMMMMM EMMMMMMM SEEEEEEE

//The encoding will have the following result:
// 01001001 SEEEEEEE
// 10101110 EMMMMMMM
// 11011011 MMMMMMMM
// 10000001 MMMMMMMM

//The encoding will result in the octetstring ’49AEDB81’O

*//Example number 2): double precision float*
type float DoubleFloat
with {
variant "FORMAT(IEEE754 double)"
}

const DoubleFloat c_floatd:=1432432.112232

//The resulting bitfield:
//82 3c bb 1c70 db 35 41
//10000010 00111100 10111011 00011100
//01110000 11011011 00110101 01000001
//MMMMMMMM MMMMMMMM MMMMMMMM MMMMMMMM
//MMMMMMMM MMMMMMMM EEEEMMMM SEEEEEEE

//The encoding will have the following result:

// 01000001 SEEEEEEE
// 00110101 EEEEMMMM
// 11011011 MMMMMMMM
// 01110000 MMMMMMMM
// 00011100 MMMMMMMM
// 10111011 MMMMMMMM
// 00111100 MMMMMMMM
// 10000010 MMMMMMMM

//The encoding will result in the octetstring

// ’4135DB701CBB3C82’O
----

*HEXSTRING*

Coding: The hexadecimal digit is represented by its binary value. The first hexadecimal digit is put into the lower nibble of first octet of the bitfield. The second hexadecimal digit is put into the higher nibble of first octet of the bitfield. The 3^rd^ hexadecimal digit is put into the lower nibble of second octet of bitfield and so on. Thus, the first hexadecimal digit is put first into the buffer. Is the actual length of hexstring shorter than the specified by `FIELDLENGTH`, aligning is governed by the attribute `ALIGN`. The default `FIELDLENGTH` value for `hexstring` type is `variable`. In this case, `FIELDLENGTH` is measured in hexdigits.

Attributes allowed:

* `ALIGN (0)`,
* `BITORDER (0)`,
* `BITORDERINFIELD (0)`,
* `BYTEORDER (0)`,
* `FIELDLENGTH (0)`,
* `N bit (0)`.

Example:
[source]
----
*//Example number 1): variable length hexstring*
const hexstring c_mystring:=’5AF’H

//The resulting bitfield: 1111 10100101
//The encoding will have the following result:
// 10100101 A5
// ….1111 .F

*//Example number 2): fixed length hexstring*
type hexstring HEX4 with { variant "FIELDLENGTH(4)" }
const HEX4 c_yourstring:=’5AF’H
//The resulting bitfield: 00001111 10100101
//The encoding will have the following result:
// 10100101 A5
// 00001111 0F

*//Example number 3): left aligned hexstring*
type hexstring HEX4align with {
variant "FIELDLENGTH(4), ALIGN(left)" }
const HEX4align c_ourstring:=’5AF’H

//The resulting bitfield: 11111010 01010000
//The encoding will have the following result:
// 01010000 50
// 11111010 FA
----

*INTEGER*

Coding: The LSB of the binary form of an `integer` is concatenated to the LSB of the bitfield. The value of the attribute `COMP` determines how the value of an `integer` type will be coded to binary form. The integer is always of fixed length and fills the space specified by `FIELDLENGTH`. The default value of `FIELDLENGTH` for integer is 8 bit. The `ALIGN` attribute has no meaning for `integer`.

Attributes allowed:

* `BITORDER (0)`,
* `BITORDERINFIELD (0)`,
* `BYTEORDER (0)`,
* `COMP (0)`,
* `FIELDLENGTH (0)`,
* `IntX (0)`,
* `N bit / unsigned N bit (0)`.

Example:
[source]
----
*//Example number 1)*

type integer Int12
with{ variant "FIELDLENGTH(12)"}
const Int12 c_myint:=1052

//The resulting bitfield is 010000011100
//The encoding will have the following result:
// 00011100
// ….0100

//The same result represented as octetstring: ’1C.4’O

*//Example number 2)*

type integer Int12sg
with{ variant "FIELDLENGTH(12), COMP(signbit)"}
const Int12sg c_mysignedint:=-1052

//The resulting bitfield: 110000011100
//The encoding will have the following result:
// 00011100
// ….1100
//The same result represented as octetstring: ’1C.C’O

*//Example number 3)*

type integer Int12c
with{ variant "FIELDLENGTH(12), COMP(2scompl)"}
const int12c c_hisint:=-1052
//The resulted bitfield: 101111100111
//The encoding will have the following result:
// 11100111
// ….1011
//The same result represented as octetstring: ’E7.B’O
----

*OCTETSTRING*

Coding: The octets are represented by their binary value. The first octet is put into first octet of bitfield. The second octet is put second octet of bitfield and so on. Thus, the first octet is put first into the buffer. If the length of the `octetstring` is shorter than the specified `FIELDLENGTH`, aligning is governed by the attribute `ALIGN`. The default `FIELDLENGTH` value for `octetstring` type is `variable`. In this case, `FIELDLENGTH` is measured in octets.

Attributes allowed:

* `ALIGN` (0),
* `BITORDER` (0),
* `BITORDERINFIELD` (0),
* `BYTEORDER` (0),
* `FIELDLENGTH` (0),
* `N bit` (0).

Example:
[source]
----
*//Example number 1): variable length octetstring*
const octetstring c_mystring:=’25AF’O

//The resulting bitfield: 10101111 00100101
//The encoding will have the following result:
// 00100101 25
// 10101111 AF

*//Example number 2): fixed length octetstring*

type octetstring OCT3 with { variant "FIELDLENGTH(3)" }
const OCT3 c_yourstring:=’25AF’H
//The resulting bitfield: 00000000 10101111 00100101
//The encoding will have the following result:
// 00100101 25
// 10101111 AF
// 00000000 00

*//Example number 3): left aligned octetstring*
type octetstring OCT3align with {
variant "FIELDLENGTH(3), ALIGN(left)" }
const OCT3align c_string:=’25AF’H

//The resulting bitfield: 10101111 00100101 00000000
//The encoding will have the following result:
// 00000000 00
// 00100101 25
// 10101111 AF
----

*SET*

Encoding: During encoding the fields present are encoded one by one. If `TAG` is specified for one field, the value of the key field is checked for a valid value. If a valid value is not found, the value of the key field will be substituted with a valid key value.

Decoding: The fields can be received in any order. If `TAG` is specified, the value of the key field identifies the fields. If `TAG` is not specified for any field, the decoder tries to decode a field. If the decoding is successful, the decoder assumes that the field was received. The matching algorithm is the following: First try to identify the received fields by `TAGs`; if it fails, try to decode the fields; if it fails and `OTHERWISE` is specified in `TAG`, try that field; if it fails: unknown field is received. If all mandatory fields have already been decoded, then the set is successfully decoded, else the decoding of set has failed.

*RECORD*

Encoding: The fields present are encoded one by one. The value of length and pointer fields are calculated and substituted. If `TAG`, `CROSSTAG` or `PRESENCE` are specified for one field, the value of the key field is checked for a valid value. If a valid value is not found, the value of key field will be substituted with a valid key value. Finally, the extension bits are set.

Decoding: Fields are decoded one by one. The presence of optional fields is determined by the attributes `TAG`, `PRESENCE`, by extension bits and by the value of the length field. The chosen field of union is determined by `CROSSTAG`, if present. The value of pointer field is used to determine the beginning of the pointed field. Have all of the mandatory fields been received and successfully decoded, the decoding of the record is successful.

*RECORD OF, SET OF*

Encoding: The elements of `record` of or `set of` are encoded one by one. Finally, the extension bits are set, if needed.

Decoding: The items of `record` of or `set of` are decoded one by one. The number of items is determined by the attribute `FIELDLENGTH`, by extension bits or the number of available bits in buffer. The decoding of `record of` or `set of` is successful if at least one item has been decoded.

*UNION*

Encoding: The chosen field will be encoded according to its own encoding rules. If `TAG` is specified for this field, the value of the key field is checked for a valid value. If a valid value is not found, the value of the key field will be substituted with a valid key value.

Decoding: The decoder tries to identify the received union field. If `TAG` is present, the decoder uses the value of the key fields to identify the fields. If `TAG` is not present, the decoder tries to decode the fields and if it succeeds, the decoder assumes that field is received. If the decoding of field is not successful, the decoder checks the next field. The decoding of the union will be unsuccessful if none of the fields can be decoded.

Examples:
[source]
----
type record Rec{
OCT1 key,
OCT1 values
}

type union MyUnion{
Rec field1,
Rec field2,
Rec field3
} with { variant "TAG( field1,{key = ’56’O, key=’7A’}; field2, key = ’FF’; field3,{key = ’A4’O, key = ’99’O})"
}

*//Example number 1): successful encoding*
const MyUnion c_PDU:={
field1:={ key:=’7A’O, values:=’B2’O}
}

//Chosen field: field1
//Value of key field: ’7A’O; valid
//No substitution will take place.
//The encoding will have the following result:
// 01111010 7A
// 10110010 B2

*//Example number 2): key field substituted*

const MyUnion c_PDU2:={
field1:={ key:=’00’O, values:=’B2’O}
}

//Chosen field: field1
//Value of key field: ’00’O not valid
//The value of key field will be substituted with:’56’O
//The encoding will have the following result:
// 01010110 56
// 10110010 B2
----

*UNIVERSAL CHARSTRING*

Coding: The characters are first converted to UTF-8 format, and the resulting octets are encoded as if they were an `octetstring`. That is, the octets are represented by their binary value. The first octet is put into the first octet of the bit field. The second octet is put into the second octet of the bit field, and so on. Thus, the first octet is put first into the buffer.

The RAW encoding of a `universal` `charstring` value with no non-ASCII characters is equal to the RAW encoding of a `charstring` containing the same characters (with the same attributes).

If the length of the UTF-8 encoded `universal` `charstring` is shorter than the specified `FIELDLENGTH`, aligning is governed by the attribute `ALIGN`. The default `FIELDLENGTH` for the `universal` `charstring` type is `variable`. The `FIELDLENGTH` is measured in UTF-8 octets.

Attributes allowed:

* `ALIGN` (0),
* `BITORDER` (0),
* `BITORDERINFIELD` (0),
* `BYTEORDER` (0),
* `FIELDLENGTH` (0),
* `N bit` (0).

Examples:
[source]
----
*//Example number 1): variable length universal charstring*

const universal charstring c_mystring := "sepr" & char(0, 0, 1, 113);

//The encoding will have the following result:
// 01110011 "s"
// 01100101 "e"
// 01110000 "p"
// 01110010 "r"
// 11000101 C5
// 10110001 B1 C5B1 is the UTF-8 encoding of char(0, 0, 1, 113)

*//Example number 2): fixed length universal charstring*
type universal charstring USTR8 with { variant "FIELDLENGTH(8)" }
const USTR8 c_yourstring := "sepr" & char(0, 0, 1, 113);

//The encoding will have the following result:
// 01110011 "s"
// 01100101 "e"
// 01110000 "p"
// 01110010 "r"
// 11000101 C5
// 10110001 B1 C5B1 is the UTF-8 encoding of char(0, 0, 1, 113)
// 00000000 " "
// 00000000 " "

*//Example number 3): left aligned universal charstring*
type universal charstring USTR8align with {
variant "FIELDLENGTH(8), ALIGN(left)" }
const USTR8align c_string := "sepr" & char(0, 0, 1, 113);
//The encoding will have the following result:
// 00000000 " "
// 00000000 " "
// 01110011 "s"
// 01100101 "e"
// 01110000 "p"
// 01110010 "r"
// 11000101 C5
// 10110001 B1 C5B1 is the UTF-8 encoding of char(0, 0, 1, 113)
----

== TEXT Encoder and Decoder

The TEXT encoder and decoder are general purpose functionalities developed originally for handling verbose and tokenized protocols.

The encoder converts abstract TTCN-3 structures (or types) into a bitstream suitable for serial transmission. The decoder, on the contrary, converts the received bitstream into values of abstract TTCN-3 structures.

TITAN provides a special encoding scheme for coding elements into a textual representation. This is called TEXT and is used like `encoding "TEXT"`.

This section covers the attributes controlling the <<general-rules-and-restrictions-0, coding process>> and <<bnf-of-the-attributes, BNF specification of the attributes>>.

Error encountered during the encoding or decoding process are handled as defined in section "Setting error behavior" in <<13-references.adoc#_16, [16]>>.

[[attributes-0]]
=== Attributes

An `attribute` determines coding and encoding rules.

NOTE: the section 27.5 of the TTCN–3 standard (<<13-references.adoc#_1, [1]>>) states that an `attribute` is used to refine the current encoding scheme defined with the keyword `encode`. Because of backward compatibility the presence of the `encode` attribute is not required, but might result in a compile time warning (which in the future might turn into an error).

*BEGIN*

Role: The `BEGIN` attribute defines the leading token of the type.

Format: `BEGIN(token_to_encode, <matching_exp>,<modifier>)`

Description: The attribute defines the leading token of the type. This token defines the beginning of the value of the type and will be written into the encoded string before the value of the type is encoded. `BEGIN` can be used with any type.

Parameters: `token_to_encode` +
The token is used during encoding. +

`Mandatory.matching_exp` +
This TTCN–3 character pattern is used during decoding to identify the leading token of the type. The format of the parameter is described in clause B.1.5 of the TTCN–3 standard (<<13-references.adoc#_1, [1]>>). This parameter is optional; when omitted, the parameter token_to_encode will be used as the matching pattern. +

`modifier` +
Modifies the behavior of the matching algorithm. Optional parameter. When omitted the default value will be used. The available modifiers: +
* `case_sensitive` The matching is case sensitive. Default value. +
* `case_insensitive` The matching is case insensitive.

Example:
[source]
----
//SIP header Subject header:

type record Subject{
charstring subject_value
}

with { variant “BEGIN(’Subject: ’,’
(Subject[ ]#(,):[ ]#(,))|"
“(s[ ]#(,):[ ]#(,))’,
case_insensitive)"
}

var Subject v_subj:= "the_subject";
//The encoded string will be: "Subject: the subject"
//The decoder will accept the long (Subject: the subject)
//and the short (s: the subject) format regardless
//of the case of the character of the header.
----

*END*

Role: The `END` attribute defines the closing token of the type.

Format: `END(token_to_encode, <matching exp>,<modifier>)`

Description: The attribute defines the closing token of the type. This token defines the end of the value of the type and will be written into the encoded string after the encoded value of the type. `END` can be used with any type.

Parameters: `token_to_encode` +
The token used during encoding. Mandatory.

`matching_exp` +
This TTCN–3 character pattern is used during decoding to identify the leading token of the type. The format of the parameter is described in clause B.1.5 of the TTCN–3 standard (<<13-references.adoc#_1, [1]>>). This parameter is optional; when omitted, the `token_to_encode` will be used as matching pattern.

`modifier` +
Modifies the behavior of the matching algorithm. Optional parameter. When omitted, the default value will be used. The available modifiers: +
* `case_sensitive`: The matching is case sensitive. Default value. +
* `case_insensitive`: The matching is case insensitive.

Example:
[source]
----
//SIP header Subject header:

type record Subject{
charstring subject_value
}

with { variant “BEGIN(’Subject: ’,’
(Subject[ ]#(,):[ ]#(,))|"
“(s[ ]#(,):[ ]#(,))’,
case_insensitive)“;
variant "END(’’,’([])|([])’)"
}

var Subject v_subj:= "the_subject";
//The encoded string will be: "Subject: the_subject"
//The decoder will accept both "Subject: the_subject" and //"Subject: the_subject" format.
----

*SEPARATOR*

Role: The attribute `SEPARATOR` defines the field separator token of the type.

Format: `SEPARATOR(token to encode, <matching exp>,<modifier>)`

Description: The attribute defines the field separator token of the type. This token separates the value of fields and will be written into the encoded string between the fields of the type. `SEPARATOR` can be used with any type.

Parameters: `token_to_encode` +
The token used during encoding. Mandatory.

`matching_exp` +
This TTCN–3 character pattern is used during decoding to identify the leading token of the type. The format of the parameter is described in clause B.1.5 of the TTCN–3 standard (<<13-references.adoc#_1, [1]>>). Optional parameter. When omitted, the token to encode will be used as matching pattern.

`modifier` +
Modifies the behavior of the matching algorithm. Optional parameter. When omitted, the default value will be used. The available modifiers: +
* `case_sensitive` The matching is case sensitive. Default value. +
* `case_insensitive` The matching is case insensitive.

Example:
[source]
----
type record Rec_1{
charstring field_1,
charstring field_2
}

with {
variant "BEGIN(’Header: ’)"
variant "SEPARATOR(’;’)"
}

var Rec_1 v_rec:={field1:="value_field1",
field2:="value_field2"}
//The encoded will result in the string:
//"Header: value_field1; value_field2"
----

*TEXT_CODING*

Role: The attribute TEXT_CODING defines the encoding and decoding rules of the value

Format: `TEXT_CODING(encoding_rule,<decoding_rule>,<matching_exp>,<modifier>)`

Description: The attribute controls the encoding and the decoding of the values.

Parameters: `encoding_rule` +
Controls the encoding of the value. For syntax see the two tables below.

`decoding_rule` +
Controls the decoding of the value. For syntax see the two tables below.

`matching_exp` +
TTCN–3 character pattern, used during decoding to identify the value of the type. The format of the parameter is described in clause B.1.5 of the TTCN–3 standard (<<13-references.adoc#_1, [1]>>). Optional parameter.

`modifier` +
Modifies the behavior of the matching algorithm. Optional parameter. When omitted, the default value will be used. The available modifiers: +
* `case_sensitive` The matching is case sensitive. Default value. +
* `case_insensitive` The matching is case insensitive.

.Format of `encoding_rule` and `decoding_rule`
[cols=",,",options="header",]
|===
|*Type* |*encoding_rule* |*decoding_rule*
|`charstring` |The format of encoding_rule: `attr=value[;attr=value]` +
Usable attributes: `length`, `convert`, `just`
 |The format of decoding_rule: `attr=value[;attr=value]` +
Usable attributes: `length`, `convert`

|`integer` |The format of the encoding rule: +
`attr=value[;attr=value]` +
Usable attributes: `length`, `leading0`
 |The format of the decoding rule: +
 `attr=value[;attr=value]` +
Usable attribute: `length`
|`boolean` |The encoded value of `true` and `false` value: +
`true:’token’[;false:’token’]` +
The default encoded value of `true` is ’true’; the default encoded value of `false` is ’false’
|The matching pattern of the value true and false: +
`true:{’pattern’[,modifier]}[;false:{’pattern’[,modifier]}]` +
The default decoding method is case sensitive
|`enumerated` |The encoded value of enumeration: +
`value:’token’[;value:’token’]` +
The default encoded value of enumerations is the TTCN–3 identifier of the enumerations.
 |The matching pattern of enumerations: +
`value:{’pattern’[,modifier]}[;value:{’pattern’[,modifier]}]`
The default decoding method is case sensitive.
|`set` `ofrecord` `of` |Not applicable |The format of the decoding rule: +
`attr=value[;attr=value]` +
Usable attribute: `repeatable`
|structured types |Not applicable |Not applicable
|===

.Attributes used with encoding_rule and decoding_rule
[cols=",,,",options="header",]
|===
|*attr* |*Description* |*Parameter* |*Default value*
|`length` |Determines the length of the coded value. |value |number of charactersof value
|`convert` |Converts string values to lower or upper case during encoding or decoding. |`lower_case`, `upper_case` |no conversion
|`just` |If the string is shorter than the value defined by the length attribute, just controls the justification of the value. |`left`, `right`, `center` |`left`
|`leading0` |Controls the presence of the leading zeros of the coded integer value. |`true`, `false` |`false`
|`repeatable` |The attribute repeatable controls whether the element of the record of or set of can be mixed with other elements of the set or they are grouped together. |`true`, `false` |`false`
|===

Example:
[source]
----
*//Example number 1): integer with leading zero*
type integer My_int with {
variant "TEXT_CODING(length=5;leading0=true)"
}

var My_int v_a:=4;
// The encoded value: ’00004’
*//Example number 2): integer without leading zero*
type integer My_int2 with {
variant "TEXT_CODING(length=5)"
}

var My_int2 v_aa:=4;
// The encoded value: ’ 4’
*//Example number 3): character string*
type charstring My_char with {
variant "TEXT_CODING(length=5)"
}

var My_char v_aaa:=’str’;
// The encoded value: ’ str’
*//Example number 4): centered character string*

type charstring My_char2 with {
variant "TEXT_CODING(length=5;just=center)"
}

var My_char2 v_aaaa:=’str’;
// The encoded value: ’ str ’
*//Example number 5): character string converted to upper case*
type charstring My_char3 with {
variant "TEXT_CODING(length=5;convert=upper_case)"
}

var my_char3 v_b:=’str’;

// The encoded value: ’ STR’
*//Example number 6): case converted character string*

type charstring My_char4 with {
variant "TEXT_CODING(convert=upper_case,convert=lower_case)"
}

var My_char4 v_bb:=’str’;
// The encoded value: ’STR’
// The decoded value: ’str’
*//Example number 6): boolean*
type boolean My_bool with {
variant "TEXT_CODING(true:’good’;false:’bad’)"
}

var my_bool v_bbb=false;
// The encoded value: ’bad’
----

[[bnf-of-the-attributes]]
=== BNF of the Attributes
[source]
----
COMMA = ","

SEMI = ";"

token = any valid character literal, "’" must be escaped

pattern = valid TTCN-3 character pattern, the reference is not supported

number = positive integer number

enumerated = the name of the enumerated value

attributes = attribute *(COMMA attribute)

attribute = begin-attr / end-attr / separator-attr / coding-attr

begin-attr = "BEGIN(" encode-token [ COMMA [ match-expr ] [COMMA modifier] ] ")"

end-attr = "END(" encode-token [ COMMA [ match-expr ] [COMMA modifier] ] ")"

separator-attr = "SEPARATOR(" encode-token [ COMMA [ match-expr ] [COMMA modifier] ] ")"

coding-attr = "TEXT_CODING(" [ [encoding-rules] [COMMA [decoding-rules] [ COMMA match-expr [COMMA modifier] ] ] ] ")"

encode-token = "’" token "’"

match-expr = "’" pattern "’"

modifier = "case_sensitive" / "case_insensitive"

encoding-rules = encoding-rule *(SEMI encoding-rule)

encoding-rule = attr-def / enc-enum / enc-bool

decoding-rules = decoding-rule *(SEMI decoding-rule)

decoding-rule = attr-def / dec-enum / dec-bool

attr-def = ("length=" number )/ ("convert=" ("lower_case" / "upper_case") )/ ("just=" ("left"/"right"/"center") )/ ("leading0=" ("true"/"false") )/ ("repeatable=" ("true"/"false") )

enc-enu = enumerated ":" encode-token

enc-bool = ("true:" encode-token) / ("true:" encode-token)

dec-enum = enumerated ":" "{" [match-expr] [COMMA modifier] "}"

dec-bool = (true ":" "{" [match-expr] [COMMA modifier] "}")/(false ":" "{" [match-expr] [COMMA modifier] "}")
----

== XML Encoder and Decoder

The XML encoder and decoder are handling XML-based protocols. The encoder converts abstract TTCN-3 structures (or types) into an XML representation. The decoder converts the XML data into values of abstract TTCN-3 structures.

[[general-rules-and-restrictions-0]]
=== General Rules and Restrictions

The TTCN-3 standard defines a mechanism using attributes to define encoding variants. The attributes concerning the XML encoding are standardized in <<13-references.adoc#_4, [4]>> (annex B of the standard lists the attributes and their effects).

Faults in the XML encoding/decoding process are set to error by default, but it can be modified with the `errorbehavior` TTCN–3 attribute. (<<codec-error-handling, Codec error handling>>)

[[attributes-1]]
=== Attributes

The following sections describe the TTCN-3 attributes that influence the XML coding.

*Abstract*

Attribute syntax: abstract

Applicable to (TTCN-3) Fields of unions

Description This attribute shall be generated for each field with the XSD attribute "abstract`' set to true (usually during type substitution or element substitution). It can be used to distinguish XML messages with valid type or element substitutions from XML documents containing invalid substitutions.

If the decoder finds an XML element or `xsi:type` attribute corresponding to an abstract union field, a coding error is displayed. The attribute has no effect on encoding.

*Any element*

Attribute syntax:
[source]
anyElement [ except ( 'freetext' | unqualified ) | from [unqualified ,] [ { 'freetext' , } 'freetext' ] ]

Applicable to (TTCN-3) Fields of structured types generated for the XSD _any_ element

Description One TTCN-3 attribute shall be generated for each field corresponding to an XSD any element. The freetext part(s) shall contain the URI(s) identified by the namespace attribute of the XSD any element. The namespace attribute may also contain wildcard. They shall be mapped as given in the following table:

.XSD namespace attributes
[cols=",,",options="header",]
|===
|_Value of the XSDnamespace attribute_ |*Except or from clause in the TTCN-3 attribute* |*Remark*
|*##any* |_<nor except neither from clause present>_ |
|*##local* |from unqualified |
|*##other* |except '_<target namespace of the ancestor schema element of the given any element>'_ |Also disallows unqualified elements, i.e. elements without a target namespace
|*##other* |except unqualified |In the case no target namespace is ancestor schema element of the given any element
|*##targetNamespace* |from '_<target namespace of the ancestor schema element of the given any element >'_ |
|*"http://www.w3.org/1999/xhtml ##targetNamespace"* |from `http://www.w3.org/1999/xhtml', '_<target namespace of the ancestor schema element of the given any element >'_ |
|===

The abstract value of the field will be encoded as an XML element in place of an XML element that would be generated for the field (ignoring the name of the field). During decoding, the abstract value of the field will contain the entire XML element.

Example:
[source]
----
type record AEProduct {
  charstring name,
  integer    price,
  universal charstring info
}
with {
  variant (info) "anyElement from 'http://www.example.com/A', "
  "'http://www.example.com/B', unqualified"
}
const AEProduct aep := {
  name  := "Trousers",
  price := 20,
  info  := "<xyz:color xmlns:xyz=""http://www.example.com/A"" available=""true"">red</xyz:color>"
}

/* XML encoding:
<AEProduct>
 <name>Trousers</name>
 <price>20</price>
 <xyz:color xmlns:xyz="http://www.example.com/A" available="true">red</xyz:color>
</AEProduct>
*/
----

*Any attributes*

Attribute syntax:

[source]
anyAttributes[ except 'freetext' | from [unqualified ,] { 'freetext', } 'freetext']

Applicable to (TTCN-3) Fields of structured types generated for the XSD _anyAttribute_ element

Description This TTCN-3 attribute can be applied to a field which is of type *`record of universal charstring`*. Each component shall contain a valid XML attribute (name/value pair), optionally preceded by a namespace identifier (URI). The encoder shall remove the URI and insert it as a namespace declaration into the enclosing XML element, followed by the content of the *`universal charstring`* as an XML attribute. The decoder should recover each attribute into a component of the *`record of`*, preceded by its namespace URI if applicable. The mapping of namespaces behaves in the same way as the anyElement TTCN-3 attribute.

Example:
[source]
----
type record of universal charstring AttrList;
type record AAProduct {
  AttrList   info,
  charstring name,
  integer    price
}
with {
  variant (info) "anyAttributes from 'http://www.example.com/A', "
  "'http://www.example.com/B', unqualified"
}

const AAProduct aap := {
  info := {
    "http://www.example.com/A size=""small""",
    "http://www.example.com/B color=""red""",
    "available=""yes"""},
  name := "Trousers",
  price:= 20
}

/* XML encoding:
<AAProduct
 xmlns:b0="http://www.example.com/A" b0:size="small"
 xmlns:b1="http://www.example.com/B" b1:color="red" available="yes">
 <name>Trousers</name>
 <price>20</price>
</AAProduct>
*/
----

*Attribute*

Attribute syntax: attribute

Applicable to (TTCN-3) Top-level type definitions and fields of structured types generated for XSD _attribute_ elements.

Description This encoding instruction causes the instances of the TTCN3 type or field to be encoded and decoded as attributes.

Comment Titan currently requires during decoding that attributes are present in the same order as they are declared in the enclosing record/set.

Example
[source]
----
type charstring Color
with {
  variant "attribute"
}
type record Product {
  Color      color,
  charstring material,
  charstring name,
  integer    price
}
with {
  variant (available) "attribute"
}

const Product shoes := {
  color := "blue",
  material := "suede",
  name := "Shoes",
  price:= 25
}
/* XML encoding
<Product color="blue" material="suede">
 <name>Shoes</name>
 <price>25</price>
</Product>
*/
----

*AttributeFormQualified*

Attribute syntax: `attributeFormQualified`

Applicable to (TTCN-3) Modules

Description This encoding instruction cause names of XML attributes that are instances of TTCN-3 definitions in the given module to be encoded as qualified names. At decoding time qualified names are expected as valid attribute names.

*Control namespace identification*

Attribute syntax: `controlNamespace` '__freetext__' `prefix` '__freetext__'

Applicable to (TTCN-3) Module

Description The control namespace is the namespace to be used for the type identification attributes and schema instances (e.g. in the special XML attribute value "xsi:nil". It shall be specified globally, with an encoding instruction attached to the TTCN-3 module.The first _freetext_ component identifies the namespace (normally `http://www.w3.org/2001/XMLSchema-instance' is used), the second _freetext_ component identifies the namespace prefix (normally `xsi' is used).

Please see the example for nillable elements, for example usage of `controlNamespace`.

*Block*

Attribute syntax: block

Applicable to (TTCN-3) Fields of unions

Description This attribute shall be generated for each field referred to by XSD `block` attributes (usually during type substitution or element substitution). It can be used to distinguish XML messages with valid type or element substitutions from XML documents containing invalid substitutions.

If the decoder finds an XML element or `xsi:type` attribute corresponding to a blocked union field, a coding error is displayed. The attribute has no effect on encoding.

*Default for empty*

Attribute syntax: defaultForEmpty as '__freetext__'

Applicable to (TTCN-3) TTCN-3 components generated for XSD _attribute_ or _element_ elements with a _fixed_ or _default_ attribute.

Description The '__freetext__' component shall designate a valid value of the type to which the encoding instruction is attached to. This encoding instruction has no effect on the encoding process and causes the decoder to insert the value specified by _freetext_ if the corresponding attribute or element is omitted in the received XML document.

Example
[source]
----
type record DFEProduct {
charstring color,
charstring name,
float price,
charstring currency
}

with {
variant (color) "attribute";
variant (currency) "defaultForEmpty as `US Dollars"';
}

const DFEProduct rval := {
color := "red",
name := "shirt",
price := 12.33,
currency := "US Dollars"
}

/* The following XML fragment will be decoded to the value of rval:

<DFEProduct color="red">
<name>shirt</name>
<price>12.33</price>
<currency/>
</DFEProduct>

*/
----

NOTE: TITAN allows the usage of constants and module parameters instead of the text value of the encoding instruction. The type of the field must be compatible with the type of the constant or module parameter. The form where constants and module parameters are allowed looks like this:

[source]
variant "defaultForEmpty as reference";

where reference is a constant or a module parameter. (Notice the missing apostrophe).

For example:
[source]
----
const integer c_int := 3;const charstring c_str := "abc";

type record MyRecord {
  integer i,
  charstring cs,
  float f
  }
  with {
    variant (i) "defaultForEmpty as c_int"; // allowed
    variant (cs) "defaultForEmpty as c_str"; // allowed
    variant (f) "defaultForEmpty as c_str"; // not allowed
    // incompatible types
  }
----

*Element*

Attribute syntax: element

Applicable to (TTCN-3): Top-level type definitions generated for XSD _element_ elements that are direct children of a _schema_ element.

Description: This encoding instruction causes the instances of the TTCN3 type to be encoded and decoded as XML elements.

Comment: This is the default behaviour. TTCN-3 types are encoded as elements unless altered by an encoding instruction. This encoding instruction can be used to cancel that effect.

*ElementFormQualified*

Attribute syntax: elementFormQualified

Applicable to (TTCN-3): Modules

Description: This encoding instruction causes tags of XML local elements and templates of XSD definitions in the given module to be encoded as qualified names, and inserts the namespace specification in the encoded XML. Tags of XML global elements are always encoded as qualified names, regardless of elementFormQualified. At decoding time only qualified names are accepted as valid element tag names.

*Embed values*

Attribute syntax: embedValues

Applicable to (TTCN-3): TTCN-3 record types generated for XSD _complexType_-s and _complexContent_-s with the value of the _mixed_ attribute "true".

Description: The encoder shall encode the record type to which this attribute is applied in a way that produces the same result as the following procedure: first a partial encoding of the record is produced, ignoring the `embed_values` field. The first string of the `embed_values` field (the first record of element) shall be inserted at the beginning of the partial encoding, before the start-tag of the first XML element (if any). Each subsequent string shall be inserted between the end-tag of the XML element and the start-tag of the next XML element (if any), until all strings are inserted. In the case the maximum allowed number of strings is present in the TTCN-3 value (the number of the XML elements in the partial encoding plus one) the last string will be inserted after end-tag of the last element (to the very end of the partial encoding). The following special cases apply:

. At decoding, strings before, in-between and following the XML elements shall be collected as individual components of the `embed_values` field.If no XML elements are present, and there is also a defaultForEmptyencoding instruction on the sequence type, and the encoding is empty, a decoder shall interpret it as an encoding for the _freetext_ part specified in the defaultForEmptyencoding instruction and assign this abstract value to the first (and only) component of the embed_values field.
. If the type also has the useNilencoding instruction and the optional component is absent, then the embedValues encoding instruction has no effect.
. If the type has a useNilencoding instruction and if a decoder determines, by the absence of a nil identification attribute (or its presence with the value false) that the optionalcomponent is present, then item a) above shall apply.

NOTE: Titan currently does not decode the values of the embed_values member. They will appear as empty strings.

Example
[source]
----
type record EmbProduct {
record of universal charstring embed_values,
universal charstring companyName,
universal charstring productColor,
universal charstring productName
}

with {
variant "embedValues"
}

const EmbProduct rval := {
embed_values := {"My Company", "produces", "", "which is very popular"},
ompanyName := "ABC",
productColor := "red",
productName := "shirt"
}

/* XML encoding

<EmbProduct>My Company<companyName>ABC</companyName>produces<productColor>red</productColor> <productName>shirt</productName>which is very popular</EmbProduct>

*/
----

*Form*

Attribute syntax: form as (qualified | unqualified)

Applicable to (TTCN-3): Top-level type definitions generated for XSD _attribute_ elements and fields of structured type definitions generated for XSD _attribute_ or _element_ elements.

Description: This encoding instruction designates that names of XML attributes or tags of XML local elements corresponding to instances of the TTCN-3 type or field of type to which the form encoding instruction is attached, shall be encoded as qualified or unqualified names respectively and at decoding qualified or unqualified names shall be expected respectively as valid attribute names or element tags.

*List*

Attribute syntax: list

Applicable to (TTCN-3): Record-of types mapped from XSD _simpleType_-s derived as a list type.

Description: This encoding instruction designates that the record of type shall be handled as an XSD list type, namely, record of elements of instances shall be combined into a single XML list value using a single SP(32) (space) character as separator between the list elements. At decoding the XML list value shall be mapped to a TTCN-3 record of value by separating the list into its itemType elements (the whitespaces between the itemType elements shall not be part of the TTCN-3 value).

Example
[source]
----
type record of integer Pi;
with {
variant "list"
}

const Pi digits := {
3, 14, 15, 9, 26
}

/* XML encoding
<S>3 14 15 9 26</S>
*/
----

*Name*

[[changeCase]]
Attribute syntax:
[source]
name (as ("freetext" | changeCase ) | all as changeCase ), wherechangeCase := ( capitalized | uncapitalized | lowercased | uppercased )

Applicable to (TTCN-3): Type or field of structured type. The form when _freetext_ is empty shall be applied to fields of union types with the "useUnion" encoding instruction only

Description: The name encoding instruction is used when the name of the XML element or attribute differs from the name of the TTCN3 definition or field. The name resulted from applying the name encoding attribute shall be used as the non-qualified part of the name of the corresponding XML attribute or element tag.

When the "name as `__freetext__"' form is used, _freetext_ shall be used as the attribute name or element tag, instead of the name of the related TTCN-3 definition (e.g. TTCN-3 type name or field name).

The "name as "" (i.e. freetext is empty) form designates that the TTCN-3 field corresponds to an XSD unnamed type, thus its name shall not be used when encoding and decoding XML documents.

The "name as capitalized" and "name as uncapitalized" forms identify that only the first character of the related TTCN3 type or field name shall be changed to lower case or upper case respectively.

The "name as lowercased“ and "name as uppercased" forms identify that each character of the related TTCN3 type or field name shall be changed to lower case or upper case respectively.

The "name all as capitalized", "name all as uncapitalized", "name as lowercased" and "name as uppercased" forms has effect on all direct fields of the TTCN-3 definition to which the encoding instruction is applied (e.g. in case of a structured type definition to the names of its fields in a non-recursive way but not to the name of the definition itself and not to the name of fields embedded to other fields).

Example
[source]
----
type record S {
charstring r,
charstring blue,
charstring black
}

with {
variant (r) "name as `Red"';
variant (blue) "name as uppercased";
variant (black) "name as capitalized";
}

const NM outfit := { r := "shirt", blue := "trousers", black := "shoes" }

/* XML encoding

<S>

<Red>shirt</Red>
<BLUE>trousers</BLUE>
<Black>shoes</Black>
</S>

*/
----

*Namespace identification*

Attribute syntax: namespace as '__freetext__' [prefix "freetext"]

Applicable to (TTCN-3): Modules; fields of record types generated for _attribute_s of _complexTypes_ taken in to _complexType_ definitions by referencing _attributeGroup_(s), defined in _schema_ elements with a different (but not absent) target namespace and imported into the _schema_ element which is the ancestor of the _complexType._

Description: The first _freetext_ component identifies the namespace to be used in qualified XML attribute names and element tags at encoding, and to be expected in received XML documents. The second _freetext_ component is optional and identifies the namespace prefix to be used at XML encoding. If the prefix is not specified, the encoder shall either identify the namespace as the default namespace (if all other namespaces involved in encoding the XML document have prefixes) or shall allocate a prefix to the namespace (if more than one namespace encoding instructions are missing the prefix part).

Example
[source]
----
type record S {
charstring firstName,
charstring lastName,
charstring middleInitial
}

with { variant "namespace as `http://www.example.org/test' prefix `tst"' }
const S jrh := { "John", "Doe", "M" }

/* XML encoding

<tst:S xmlns:tst="http://www.example.org/test">
<firstName>John</firstName>
<lastName>Doe</lastName>
<middleInitial>M</middleInitial>
</tst:S>

*/
----

*Nillable elements*

Attribute syntax: useNil

Applicable to (TTCN-3): Top-level record types or record fields generated for nillable XSD _element_ elements.

Description: The encoding instruction designates that the encoder, when the optional field of the record (corresponding to the nillable element) is omitted, shall produce the XML element with the xsi:nil="true" attribute and no value. When the nillable XML element is present in the received XML document and carries the xsi:nil="true" attribute, the optional field of the record in the corresponding TTCN-3 value shall be omitted. If the nillable XML element carries the xsi:nil="true" attribute and has children (either any character or element information item) at the same time, the decoder shall initiate a test case error.

Example
[source]
----
module UseNil {
type record Size {
  integer sizeval optional
}
with { variant "useNil" }

type record NilProduct {
  charstring name,
  ProductColor color,
  Size size
}

const NilProduct absent := {
  name  := "no shirt",
  color := red,
  size  := { omit }
}

const NilProduct present := {
  name  := "shirt",
  color := red,
  size  := { 10 }
}

}
with {
  encode "XML";
  variant "controlNamespace 'http://www.w3.org/2001/XMLSchema-instance' prefix 'xsi'"
}
/* XML encoding of absent:
<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<name>no shirt</name>
 <color>red</color>
 <size xsi:nil="true"/>
</Product>

XML encoding of present:
<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<name>shirt</name>
 <color>red</color>
 <size xsi:nil="false">10</size>
</Product>

Another possible XML encoding of present:
<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<name>shirt</name>
 <color>red</color>
 <size>10</size>
</Product>
*/
----

*Text*

Attribute syntax:

[source]
text ("name" as ("freetext"|) | all as changeCase)

where `changeCase` has been defined as seen <<changeCase, here>>.

Applicable to (TTCN-3) Enumeration types generated for XSD enumeration facets where the enumeration base is a string type, and the name(s) of one or more TTCN-3 enumeration values are different from the related XSD enumeration item. Also applies to XSD.Boolean types, instances of XSD.Boolean types.

Description When _name_ is used, it shall be generated for the differing enumerated values only. The _name_ shall be the identifier of the TTCN-3 enumerated value the given instruction relates to. If the difference is that the first character of the XSD enumeration item value is a capital letter while the identifier of the related TTCN-3 enumeration value starts with a small letter, the "text `__name__' as capitalized" form shall be used. Otherwise, _freetext_ shall contain the value of the related XSD enumeration item. If the first characters of all XSD enumeration items are capital letters, while the names of all related TTCN-3 enumeration values are identical to them except the case of their first characters, the "text all as capitalized" form shall be used. The encoding instruction designates that the encoder shall use _freetext_ or the capitalized name(s) when encoding the TTCN-3 enumeration value(s) and vice versa. When the text encoding attribute is used with XSD.Boolean types, the decoder shall accept all four possible XSD boolean values and map the received value 1 to the TTCN-3 boolean value *true* and the received value 0 to the TTCN-3 boolean value *false*. When the text encoding attribute is used on the instances of the XSD.Boolean type, the encoder shall encode the TTCN3 values according to the encoding attribute (i.e. *true* as 1 and *false* as 0).

Comment For XSD.Boolean types, either of the forms "text 'true' as "1" and "text 'false' as '0' implies the other, i.e. Titan considers that both have been specified. Together, these two forms have the same effect as "text" (detailed in the last paragraph of Description).

Example
[source]
----
type enumerated ProductColor { red(0), light_green(1), blue(2) }
with {
variant "text `red' as uppercased";
variant "text `light_green' as `Light Green"'
variant "text `blue' as capitalized"
};

type boolean Availability
with {
variant "text"
}

type record T {
ProductColor color,
Availability available
}

const T prod := {
color := light_green,
available := true
}

/* XML encoding

<S>
<color>Light Green</color>
<available>1</available>
</S>

*/
----

*Untagged*

Attribute syntax: untagged

Applicable to (TCN-3): Type; or field of a record, set, union; or the embedded type of a record-of or set-of. This encoding instruction is ignored if applied to a type which is encoded as the top-level type, unless the top-level type is a union or anytype. It will take effect when a field of this type is encoded as a component of the enclosing structured type.

Description: The encoding instruction designates that the encoder shall omit the tag.

Example: "untagged" applied to a field.
[source]
----
*type* *record* Prod {
*charstring* name,
*float* price,
*charstring* description
}

*with* {
*variant* (description) "untagged"
}

*const* Prod prod := {
name := "Danish Blue",
price := 3.49,
description := "Soft blue cheese"
}

/* generated XML:
<Prod>
<name>Danish Blue</name>
<price>3.490000</price>
Soft blue cheese</Prod>
*/

Example: "untagged" applied to a union type.
*type* *union* ProdUnion {
*Prod* prod1,
*OtherProd* prod2
}

*with* {
*variant* "untagged"
}*const* ProdUnion produnion := { prod1 := {
name := "ProdName",
price := 66,
description := "The best product" }
}

/* generated XML:
<Prod>
<name>ProdName</name>
<price>66</price>
The best product</Prod>
*/
----

*Use number*

Attribute syntax: useNumber

Applicable to (TTCN-3) Enumeration types generated for XSD enumeration facets where the enumeration base is integer

Description The encoding instruction designates that the encoder shall use the integer values associated to the TTCN-3 enumeration values to produce the value of the corresponding XML attribute or element (as opposed to the names of the TTCN-3 enumeration values) and the decoder shall map the integer values in the received XML attribute or element to the appropriate TTCN-3 enumeration values.

Example
[source]
[source]
----
type enumerated ProductColor { red(0), green(1), blue(2) }
with {
variant "useNumber"
}

type record NrProduct {
charstring name,
ProductColor color,
integer size
}

const NrProduct rval := {
name := "shirt",
color := red,
size := { sizeval := 10 }
}

/* XML encoding:
<NrProduct>
<name>shirt</name>
<color>0</color>
<size>10</size>
</NrProduct>
*/
----

*Use order*

Attribute syntax: useOrder

Applicable to (TTCN-3) Record type definition, generated for XSD _complexType_-s with _all_ constructor

Description The encoding instruction designates that the encoder shall encode the values of the fields corresponding to the children elements of the _all_ constructor according to the order identified by the elements of the *order* field. At decoding, the received values of the XML elements shall be placed in their corresponding record fields and a new record of element shall be inserted into the *order* field for each XML element processed (the final order of the record of elements shall reflect the order of the XML elements in the encoded XML document).

Example
[source]
----
type record UOProduct {
record of enumerated { id, name, price, color } order,
integer id,
charstring name,
float price,
charstring color
}

with {
variant "useOrder";
}

const UOProduct rval := {
order := { id, color, price, name },
id := 100,
name := "shirt",
price := 12.23,
color := "red"
}

/* XML encoding:
<UOProduct>
<id>100</id>
<color>red</color>
<price>12.230000</price>
<name>shirt</name>
</UOProduct>
*/
----

*Use union*

Attribute syntax: useUnion

Applicable to (TTCN-3) unions (all alternatives of the union must be character-encodable)

Description The encoding instruction designates that the encoder shall not use the start-tag and the end-tag around the encoding of the selected alternative (field of the TTCN-3 union type). A type identification attribute (`xsi:type`, where `xsi` is the prefix of the control namespace) can be used to identify the selected alternative, or the encoding of the alternatives must be distinct enough that the decoder can determine the selected field based solely on its value. The decoder shall place the received XML value into the corresponding alternative of the TTCN-3 `union` type, based on the received value and the type identification attribute, if present. The encoder will always use the type identification `attribute` to identify the selected field whenever possible. If the union has the attribute or `untagged` encoding instructions, or is the component of a `record` `of` or set of with the `list` encoding instruction, then the insertion of the type identification attribute is not possible.

Comment There is no check implemented to ensure the fields are sufficiently distinct. If no type identification attribute is present, the first field (in the order of declaration) that manages to successfully decode the XML value will be the selected alternative.

Restrictions The use of the XSD type `QName` or other unions with the `useType` or `useUnion` coding instructions as alternatives are not supported. The `useType` or `useUnion` coding instructions cannot be applied to `anytype`.

Example 1
[source]
----
type union ProductId {
integer c1,
integer c2,
integer c3
}

with {
variant "useUnion"
}

const Product rval := {
id := { c2 := 100 },
price := 25.34,
color := "green"
}

/*
<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<id xsi:type="c2">100</id>
<price>2.534E1</price>
<color>green</color>
</Product>

*/
Example 2
type union IntStr {
integer int,
charstring str
}

with {
variant "useUnion"
}

type record Data {
IntStr atr,
record of IntStr values
}

with {
variant(atr) "attribute";
variant(values) "list";
}

const Data d := {
atr := { int := 26 },
values := { { str := "abc" }, { str := "x" }, { int := -7 } }
}

/*

<Data xmlns:xsi=`http://www.w3.org/2001/XMLSchema-instance' atr=`26'>
<values>abc x -7</values>
</Data>
*/
----

*Use type*

Attribute syntax: useType

Applicable to (TTCN-3) unions

Description The encoding instruction designates that the encoder shall not use the start-tag and the end-tag around the encoding of the selected alternative (field of the TTCN-3 union type), a type identification attribute (`xsi:type`, where `xsi` is the prefix of the control namespace) will be used to identify the selected alternative. This attribute may be omitted in the case of the first alternative. The decoder shall place the received XML value into the corresponding alternative of the TTCN-3 `union` type, based on the received value and the type identification attribute. The first alternative will be selected if this attribute is not present. The encoder will never insert the type identification attribute for the first alternative. Any attributes the selected alternative might have will be inserted to the union’s XML tag instead (after the type identification attribute, if it exists).

The `useType` or `useUnion` coding instructions cannot be applied to anytype.

Example
[source]
----
type record Shirt {
charstring color,
charstring make,
integer size
}

type record Trousers {
boolean available,
charstring color,
charstring make
} with {
variant(available) "attribute"
}

type record Shoes {
boolean available,
string color,
integer size
} with {
variant(available) "attribute"
}

type union Product {
Shirt shirt,
Trousers trousers,
Shoes shoes
} with {
variant "useType"
}

const Product pr1 := {
shoes := {
available := false,
color := "red",
size := 9
}
}
/*

<Product xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance’ xsi:type=’shoes’ available=’false’>
<color>red</color>
<size>9</size>
</Product>

*/
const Product pr2 := {
shirt := {
color := "red",
make := "ABC Company",
size := 9
}
}

/*

<Product xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance’>
<color>red</color>
<make>ABC Company</make>
<size>9</size>
</Product>
*/
----

*Whitespace control*

Attribute syntax: whitespace (preserve|replace|collapse)

Applicable to (TTCN-3) String types or fields of structured types generated for XSD components with the _whitespace_ facet.

Description The encoding instruction designates that the encoder shall normalize the encoded XML values corresponding to the TTCN-3 construct with the whitespace encoding instruction, and the received XML value shall be normalized before decoding as below.

* preserve: no normalization shall be done, the value is not changed.
* replace: all occurrences of HT(9) (horizontal tabulation), LF(10) (line feed) and CR(13) (carriage return) shall be replaced with an SP(32) (space) character.
* collapse: after the processing implied by replace, contiguous sequences of SP(32) (space) characters are collapsed to a single SP(32) (space) character, and leading and trailing SP(32) (space) characters are removed.

Example 1
[source]
----
type charstring R
with {
variant "whiteSpace replace"
}

const R rval := "First Line Second Line";
/* The following is a possible XML encoding of `rval'. During decoding it will be normalized to the value of `rval'.
<R>First
Line
Second
Line</R>
*/
----

Example 2
[source]
----
type charstring C
with {
variant "whiteSpace collapse"
}

const C cval := "First Line Second Line";
/* The follwing is a possible XML encoding of `cval'. During decoding it will be normalized to the value of `cval'.
<C>
First Line
Second Line
</C>
*/
----

[[external-functions]]
=== External functions

XML encoder / decoder functions must have the "`encode(XER)`" / "`decode(XER)`" attribute set.

The following XML coding options can be specified: `XER_BASIC`, `XER_EXTENDED`, `XER_CANONICAL`. These can be used by writing for example: "`encode(XER:XER_EXTENDED)`" / "`decode(XER:XER_EXTENDED)`".

Faults in the XML encoding/decoding process produce errors by default, but this can be modified with the `errorbehavior` attribute. (link:#codec-error-handling[Codec error handling])

XML encoder functions can also have the "`printing(compact)`" or "`printing(pretty)`" attributes. This specifies whether the encoder should add extra white spaces to the XML code or not. This attribute cannot be set at module level.

If compact printing is selected no white spaces are added to the XML code, making it as short as possible, except at the end of the XML code there will always be a new-line character.

Pretty printing makes the code easier to read by adding spaces, new lines and indenting.

For example:
[source]
----
external function f_enc_MyRecord(in MyRecord par) return octetstring with { extension "prototype(convert) encode(XER:XER_EXTENDED) printing(pretty)" }

external function f_dec_MyRecord(in MyRecord par) return octetstring with { extension "prototype(convert) decode(XER:XER_EXTENDED) printing(pretty)" }
----

== JSON Encoder and Decoder

The JSON encoder and decoder handles JSON-based protocols. The encoder converts abstract TTCN-3 structures (or types) into a JSON representation (see RFC 7159). The decoder converts JSON data into values of abstract TTCN-3 structures.

This section covers the coding rules in general, the attributes controlling them and the encoder / decoder external functions.

[[general-rules-and-restrictions-1]]
=== General rules and restrictions

You can use the encoding rules defined in this section to encode and decode the following TTCN–3 types:
* anytype
* array
* bitstring
* boolean
* charstring
* enumerated
* float
* hexstring
* integer
* objid
* octetstring
* record, set
* record of, set of
* union
* universal charstring
* verdicttype

The rules also apply to the following ASN.1 types (if imported to a TTCN-3 module):

* ANY
* BIT STRING
* BOOLEAN
* BMPString
* CHOICE, open type (in instances of parameterized types)
* ENUMERATED
* GeneralString
* GraphicString
* IA5String
* INTEGER
* NULL
* NumericString
* OBJECT IDENTIFIER
* OCTET STRING
* PrintableString
* RELATIVE-OID
* SEQUENCE, SET
* SEQUENCE OF, SET OF
* TeletexString
* UniversalString
* UTF8String
* VideotexString
* VisibleString

JSON encoding and decoding is allowed for types with the attribute "encode` "`JSON`"'. The basic types specified in the list above support JSON encoding and decoding by default.

The attribute "encode` "`JSON`"' can also be set globally (at module level), allowing JSON coding for all types defined in that module.

Types imported from ASN.1 modules (from the list above) automatically have JSON coding allowed and cannot have JSON variant attributes.

When using <<legacy-codec-handling, legacy codec handling>> the encode attribute can be omitted if the type has at least one JSON variant attribute (see <<attributes-2, here>>).

Additional requirements for JSON encoding and decoding when using legacy codec handling:
* in case of records, sets, unions and ASN.1 open types every field must also support JSON coding;
* in case of array, record of and set of structures the element type must also support JSON coding.

[[basic-types]]
==== Basic types

The basic TTCN-3 types are encoded as JSON values.

All integer values and most float values are encoded as JSON numbers. The special float values `infinity`, `-infinity` and `not_a_number` are encoded as JSON strings.

Boolean values are encoded with the JSON literals `true` and `false`.

Bitstring, hexstring and octetstring values (and values of the ASN.1 ANY type) appear as JSON strings containing the bits or hex digits as characters.

Charstrings, universal charstrings and values of ASN.1 string types are encoded as JSON strings. Charstrings appear exactly like in TTCN-3. Universal charstrings will appear in UTF-8 encoding. JSON strings may contain the escaped character `\u` followed by 4 hex digit characters, the decoder will convert this into the character represented by the hex digits.

Object identifiers are encoded as JSON strings containing the components (in number form) separated by dots.

Verdicttype and enumerated types are encoded as JSON strings. The string contains the name of the verdict type or enumerated value.

The ASN.1 NULL value is encoded with the JSON literal `null`.

NOTE: the JSON decoder ignores all type restrictions and will successfully decode values that contradict them (e.g.: a `record of/set of` type with the `length (3..5)` restriction will successfully decode an array of 8 elements), with the exception of arrays. The restrictions of ASN.1 string types are ignored aswell (e.g.: `NumericStrings` can decode strings containing letters).

==== Structured types

Array, record of and set of structures are encoded as JSON arrays. Their elements will appear in the order they appear in TITAN.

Records and sets are encoded as JSON objects. The JSON object will contain the field name and value pairs of each field in the order they are declared in. Omitted optional fields will be skipped.

The decoder will accept the record / set field name and value pairs in any order, but every non-optional field must be present. Optional fields that do not appear in the JSON object will be omitted.

Unions, anytypes and ASN.1 open types are encoded as JSON objects. The object will contain one name-value pair: the name of the selected field and its value.

[[attributes-2]]
=== Attributes

The following sections describe the TTCN-3 attributes that influence JSON coding (only affects TTCN-3 types, ASN.1 types cannot have attributes that influence JSON coding).

All JSON attributes begin with the word `JSON' followed by a colon (`JSON:<attribute>`). Any number of white spaces (spaces and tabs only) can be added between each word or identifier in the attribute syntax, but at least one is necessary if the syntax does not specify a separator (a comma or a colon). The attribute can also start and end with white spaces.

Alternatively the syntaxes defined in <<13-references.adoc#_25, [25]>> can also be used, for the supported attributes (without the need for the `JSON`: prefix).

Example:
[source]
----
variant(field1) “JSON:omit as null”;			// ok
variant(field2) “ JSON : omit as null ”;			// ok (extra spaces)
variant(field3) “JSON	:	omit	as	null”;	// ok (with tabs)
variant(field4) “JSON:omitasnull”;			// not ok
----

*Omit as null*

Attribute syntax: omit as null

Applicable to (TTCN-3): Optional fields of records and sets

Description: If set, the value of the specified optional field will be encoded with the JSON literal `null` if the value is omitted. By default omitted fields (both their name and value) are skipped entirely. The decoder ignores this attribute and accepts both versions.

Example:
[source]
----
type record PhoneNumber {
  integer countryPrefix optional,
  integer networkPrefix,
  integer localNumber
} with {
  variant(countryPrefix) “JSON:omit as null”
}
var PhoneNumber pn := { omit, 20, 1234567 }
// JSON code with the attribute:
// {“countryPrefix”:null,”networkPrefix”:20, “localNumber”:1234567}
// JSON code without the attribute:
// {”networkPrefix”:20, “localNumber”:1234567}
----

*Name as …*

Attribute syntax: name as <alias>

Applicable to (TTCN-3): Fields of records, sets and unions

Description: Gives the specified field a different name in the JSON code. The encoder will use this alias instead of the field’s name in TTCN-3, and the decoder will look for this alias when decoding this field. The syntax of the alias is the same as the syntax of an identifier in TITAN (regex: [A-Za-z][A-Za-z0-9_]*).

Example:
[source]
----
type union PersionID {
  integer numericID,
  charstring email,
  charstring name
} with {
  variant(numericID) "JSON:name as ID";
  variant(email) "JSON:name as Email";
  variant(name) "JSON:name as Name";
}
type record of PersionID PersionIDs;
var persionIDs pids := { { numericID := 189249214 }, { email := “jdoe@mail.com” }, { name := “John Doe” } };
// JSON code:
// [{“ID”:189249214},{“Email”:“jdoe@mail.com”},{“Name”:“John Doe”}]

----

*As value*

Attribute syntax: as value

Applicable to (TTCN-3): Unions, the anytype, or records or sets with one field

Description: The union, record, set or anytype will be encoded as a JSON value instead of as a JSON object with one name-value pair (the name of the selected field in case of unions and the anytype, or the name of the one field in case of records and sets will be omitted, as well as the surrounding braces). This allows the creation of heterogenous arrays in the JSON document (e.g. ["text",10,true,null]).Since the field name no longer appears in the JSON document, the decoder will determine the selected field (in case of unions and the anytype) based on the type of the value. The first field (in the order of declaration) that can successfully decode the value will be the selected one.

This attribute can also be applied to fields of records, sets or unions, or to the element types of records of, sets of or arrays, if they meet the mentioned restrictions. In this case these fields or elements are encoded as JSON values when they are encoded as part of their larger structure (but the types of these fields or elements might be encoded as JSON objects when encoded alone, or as parts of other structures).

NOTE: Pay close attention to the order of the fields when using this attribute on unions and the anytype. It’s a good idea to declare more restrictive fields before less restrictive ones (e.g.: hexstring is more restrictive than universal charstring, because hexstring can only decode hex digits, whereas universal charstring can decode any character; see also examples below).

Examples:
[source]
----
// Example 1: unions
type union U1 { // good order of fields
  integer i,
  float f,
  octetstring os,
  charstring cs
} with {
  variant “JSON : as value”
}

type union U2 { // bad order of fields
  float f,
  integer i,
  charstring cs,
  octetstring os
} with {
  variant “JSON : as value”
}

type record of U1 RoU1;
type record of U2 RoU2;

var RoU1 v_rou1 := { { i := 10 }, { f := 6.4 }, { os := ‘1ED5’O }, { cs := “hello” } };
var RoU2 v_rou2 := { { i := 10 }, { f := 6.4 }, { os := ‘1ED5’O }, { cs := “hello” } };

// Both v_rou1 and v_rou2 will be encoded into:
// [10,6.4,“1ED5”,“hello”]
// This JSON document will be decoded into v_rou1, when decoding as type RoU1,
// however it will not be decoded into v_rou2, when decoding as RoU2, instead // the float field will decode both numbers and the charstring field will
// decode both strings: { { f := 10.0 }, { f := 6.4 }, { cs := “1ED5” },
// { cs := “hello” } };

// Example 2: record with one field
type record R {
  integer field
}
with {
  variant “JSON: as value”
}
type record of R RoR;
const RoR c_recs := { { field := 3 }, { field := 6 } };
// is encoded into: [3,6]

// Example 3: anytype (this can only be done as a field or element of a
// structure, since coding instructions cannot be defined for the anytype)
module MyModule {
type record AnyRec {
  anytype val
}
with {
  variant (val) “JSON: as value”;
  variant (val) “JSON: name as value”;
}
const AnyRec c_val := { val := { charstring := “abc” } };
// is encoded into: {“value”:“abc”}
...
} // end of module
with {
  extension “anytype integer, charstring”
}
----

*Default*

Attribute syntax: default(<value>)

Applicable to (TTCN-3): Fields of records and sets

Description: The decoder will set the given value to the field if it does not appear in the JSON document. The <value> can contain the JSON encoding of a value of the field’s type (only basic types are allowed). String types don’t need the starting and ending quotes. All JSON escaped characters can be used, plus the escape sequence ")" will add a ")" (right round bracket) character.

The only allowed structured value is the empty structure value `{}`, which can be set for `record of` and `set of` types, as well as empty `record` and `set` types.

Optional fields with a default value will be set to `omit` if the field is set to `null` in JSON code, and will use the default value if the field does not appear in the JSON document.

Example:
[source]
----
type record Product {
  charstring name,
  float price,
  octetstring id optional,
  charstring from
} with {
  variant(id) “JSON : default (FFFF)”
  variant(from) “JSON:default(Hungary)”
}

// { “name” : “Shoe”, “price” : 29.50 } will be decoded into:
// { name := “Shoe”, price := 29.5, id := ‘FFFF’O, from := “Hungary” }

// { “name” : “Shirt”, “price” : 12.99, “id” : null } will be decoded into:
// { name := “Shirt”, price := 12.99, id := omit, from := “Hungary” }
----

*Extend*

Attribute syntax: extend(<key>):(<value>)

Applicable to (TTCN-3): Any type

Description: Extends the JSON schema segment generated for this type with the specified key-value pair. The <value> is inserted as a string value.

Both <key> and <value> are strings that can contain any character of a JSON string, plus the escape sequence `)' can be used to add a `)' (right round bracket) character.

This attribute can be set multiple times for a type, each key-value pair is inserted as a field to the end of the type’s schema. Extending a schema with multiple fields with the same key produces a warning. Using one of the keywords used in the generated schema also produces a warning.

This attribute only influences schema generation. It has no effect on encoding or decoding values.

*Metainfo for unbound*

Attribute syntax metainfo for unbound

Applicable to (TTCN-3) Records, sets and fields of records and sets

Description Allows the encoding and decoding of unbound fields with the help of a meta info field. The attribute can be set to fields individually, or to the whole `record/set` (which is equal to setting the attribute for each of its fields).

The encoder sets the field’s value in JSON to `null` and inserts an extra (meta info) field into the JSON object. The meta info field’s name is `metainfo <fieldname>`, where <fieldname> is the name of the unbound field (or its alias, if the `name as …` attribute is set). Its value is `unbound` (as a JSON string).

The decoder accepts the meta info field regardless of its position in the JSON object (it can even appear before the field it refers to). If the meta info field’s value is not `unbound`, or it refers to a field that does not exist or does not have this attribute set, then an encoding error is displayed. The referenced field must either be `null` or a valid JSON value decodable by the field.

Example:
[source]
----
// Example 1: meta info for a single field
type record Rec {
  integer num,
  charstring str
}
with {
  variant(str) "JSON: metainfo for unbound";
}

// { num := 6, str := <unbound> } is encoded into:
// {“num”:6,”str”:null,”metainfo str”:”unbound”}

// Example 2: meta info for the whole set (with “name as” and optional field)
type set Set {
  integer num,
  charstring str,
  octetstring octets optional
}
with {
  variant " JSON : metainfo for unbound ";
  variant (num) " JSON : name as int ";
}

// { num := <unbound>, str := "abc", octets := <unbound> } is encoded into:
// {“int”:null,”metainfo int”:”unbound”,”str”:”abc”,”octets”:null,
// ”metainfo octets”:”unbound”}

// Example 3: other values accepted by the decoder
// (these cannot be produced by the encoder)

// { "int" : 3, "str" : "abc", "octets" : "1234", "metainfo int" : "unbound" }
// is decoded into: { num := <unbound>, str := “abc”, octets := ‘1234’O }

// {"metainfo int" : "unbound", "int" : null, "str" : "abc", "octets" : "1234"}
// is decoded into: { num := <unbound>, str := “abc”, octets := ‘1234’O }
----

*As number*

Attribute syntax: as number

Applicable to (TTCN-3): Enumerated types

Description: If set, the enumerated value’s numeric form will be encoded as a JSON number, instead of its name form as a JSON string.

Similarly, the decoder will only accept JSON numbers equal to an enumerated value, if this attribute is set.

Example:
[source]
----
type enumerated Length { Short (0), Medium, Long(10) }
with {
  variant “JSON: as number”
}
type record of Length Lengths;
const Lengths c_len := { Short, Medium, Long };
// is encoded into: [ 0, 1, 10 ]
----

*Chosen*

Attribute syntax: chosen (<parameters>)

Applicable to (TTCN-3): Union fields of records and sets

Description: This attribute indicates that the fields of the target `union` will be encoded without field names (as if the `union` had the attribute as `value`), and that the selected field in the `union` will be determined by the values of other fields in the parent `record`/`set`, as described by the rules in the attribute’s parameters.

The attribute’s parameters are a list of rules, separated by semicolons (;). Each rule consists of a field name from the `union` (or `omit`, if the `union` is an optional field in the parent `record`/`set`), and a condition (or list of conditions). If the condition is true, then the specified field will be selected (or the field will be omitted). If there are multiple conditions, then only one of them needs to be true for the specified field to be selected.

The rules have the following syntax:

_<field or omit>, <condition>;_

if there’s only one condition, *or*

_<field or omit>, { <condition1>, <condition2>, … };_

if there are multiple conditions.

The syntax of a condition is

_<field reference> = <value>_

or the keyword `otherwise` (which is true if all other conditions are false).

The <field reference> is a reference to a field within the record/set. It can contain multiple field names to indicate an embedded field, but it cannot contain array indexes.

The <value> can be any value of a built-in type.

The rules do not affect JSON encoding, only decoding (i.e. this attribute is equivalent to the attribute `as value`, when encoding).

Example:
[source]
----
type record PduWithId {
  integer protocolId,
  Choices field optional
}
with {
  variant (field) “chosen ( type1, { protocolId = 1, protocolId = 11 };
                            type2, protocolId = 2;
                            type3, protocolId = 3;
                            omit, otherwise)”;
  // variant (protocolId) “default (2)”;
}
type union Choices {
  StructType1 type1,
  StructType2 type2,
  StructType3 type3
}
// When decoding a value of type PduWithId, type1 will be selected if
// protocolId is 1 or 11, type2 if protocolId is 2, type3 if protocolId is 3,
// and the field will be omitted in all other cases.
// For example { “protocolId” : 2, “field” : { ... } } is decoded into:
// { protocolId := 2, field := { type2 := { ... } } }
// Note: the conditions in the attribute are evaluated when the decoder reaches
// the union field, so the protocolId field must precede the union field in the
// JSON document. Otherwise the decoder will use whatever value the protocolId
// field had before decoding began (likely <unbound>, which will cause a DTE).

// Note: If the protocolId field had the attribute ‘default’ (see commented
// line in the example), then the default value would be used to determine the
// selected field in the union, if the protocolId field is not decoded before
// the union field.

----

*As map*

Attribute syntax: as map

Applicable to (TTCN-3): Record of/set of with a record/set element type, that has 2 fields, the first of which is a non-optional universal charstring

Description: If set, the mentioned structure is encoded as a JSON object containing key-value pairs. The universal charstrings in the element records/sets are the keys, and the second field in each record/set contains the value. This allows the creation of heterogenous objects in the JSON document (i.e. JSON objects with any combination of field names and values).

Affects both encoding and decoding.

Example:
[source]
----
type record MapItem {
  universal charstring key,
  integer value_ optional
}

type set of MapItem Map
with { variant "as map" }

const Map c_map := { { "one", 1 }, { "two", 2 }, { "three", 3 }, { "zero", omit } };
// is encoded into: { "one" : 1, "two" : 2, "three" : 3, "zero" : null }
----

*Text ... as ...*

Attribute syntax: text '<enum text>' as '<new text>'

Applicable to (TTCN-3): Enumerated types

Description: This attribute can be used to change the encoding of certain enumerated values. Each attribute changes the encoding of one enumerated option.

Affects both encoding and decoding.

Example:
[source]
----
type enumerated EnumNumber { One, Two, Three }
with {
  variant "text 'One' as '1'";
  variant "text 'Two' as '2'";
  variant "text 'Three' as '3'";
}
type record of EnumNumber EnumNumberList;

const EnumNumberList c_numbers := { One, Two, Three };
// is encoded into: [ "1", "2", "3" ]
----

[[external-functions-0]]
=== External functions

JSON encoder / decoder functions must have the `encode(JSON)` / `decode(JSON)` attribute set.

Faults in the JSON encoding/decoding process produce errors by default, but this can be modified with the `errorbehavior` attribute. (link:#codec-error-handling[Codec error handling])

JSON encoder functions can also have the `printing(compact)` or `printing(pretty)` attributes. This specifies whether the encoder should add extra white spaces to the JSON code or not. This attribute cannot be set at module level.

If compact printing is selected (or if the printing attribute is not set) no white spaces are added to the JSON code, making it as short as possible.

Pretty printing makes the code easier to read by adding spaces, new lines and indenting.

Example:
[source]
----
type enumerated Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
type record Date {
  charstring month,
  integer dayIdx,
  Day dayName
}
type record of Date Dates;
type record PhoneNumber {
  integer countryPrefix optional,
  integer networkPrefix,
  integer localNumber
} with {
  variant(countryPrefix) “JSON:omit as null”
}
type record Profile {
  charstring name,
  PhoneNumber phoneNo,
  charstring emailAddr,
  Dates meetings
} with {
  variant(phoneNo) "JSON: name as phone";
  variant(emailAddr) "JSON: name as email";
}
external function f_enc_profile(in Profile par) return octetstring
  with { extension “prototype(convert) encode(JSON) printing(pretty)” }
var Profile prof := { "John Doe", { omit, 20, 1234567 }, "jdoe@mail.com", { { "December", 31, Saturday }, { "February", 7, Friday } } };
log(f_enc_profile(prof));
// JSON code:
// {
//     "name" : "John Doe",
//     "phone" : {
//         "countryPrefix" : null,
//         "networkPrefix" : 20,
//         "localNumber" : 1234567
//     },
//     "email" : "jdoe@mail.com",
//     "meetings" : [
//         {
//             "month" : "December",
//             "dayIdx" : 31,
//             "dayName" : "Saturday"
//         },
//         {
//             "month" : "February",
//             "dayIdx" : 7,
//             "dayName" : "Friday"
//         }
//     ]
// }

----

[[converting-ttcn-3-and-asn-1-types-to-a-json-schema]]
=== Converting TTCN-3 and ASN.1 types to a JSON schema

The TITAN compiler can convert type definitions in TTCN-3 and ASN.1 modules into a JSON schema that validates the JSON encoding of these types.

NOTE: the names of ASN.1 modules, types and fields will appear in TTCN-3 form (as if they were imported into a TTCN-3 module). E.g.: the ASN.1 names `Protocol-Elem` and `value` will appear as `Protocol_Elem` and `value_` respectively.

==== Usage

The compiler option `–-ttcn2json` shall be used for the conversion, followed by JSON schema generator specific options and the list of TTCN-3 and ASN.1 file names.

The option `–j` restricts the TTCN-3 types used in the conversion: only those that have JSON coding enabled will be converted. By default all TTCN-3 types that can be converted will be used. This option does not affect ASN.1 types, these will always be converted.

If option `–f` is set, then the schema will only validate types that have JSON encoding and/or decoding functions, otherwise all types it will validate all types included in the schema.

The options `-A` and `–T` can be used before each input file to specify its type (`-A` for ASN.1 files and `–T` for TTCN-3 files). If a file is not preceeded by either of these option, then the compiler will attempt to determine its type based on its contents.

The last parameter specifies the name of the JSON schema file if it is preceded by a dash (-). Otherwise the name of the schema will be created using the first input file name (its `.asn` or `.ttcn` extension will be replaced by `.json`, or, if it doesn’t have either of these extension, then `.json` will simply be appended to its end).

Usage examples:compiler –ttcn2json –T module1.ttcn –A module2.asn – schema.jsoncompiler –-ttcn2json –j module1.ttcn module2.asn

The first example will generate the `schema.json` JSON document containing the schema, the second one will generate `module1.json` (and only JSON-encodable types will be included). These documents will have the "pretty" printing format mentioned in 4.26.3.

[[top-level]]
==== Top level

On the top level the schema contains a JSON object with 2 properties.

The first property, "definitions", has the schema segments of the type definitions in the TTCN-3 and ASN.1 modules as its value. This value is a JSON object with one property (key-value pair) for each module. Each property has the module name as its key and an object containing the schema segments for the types definied in that module as its key. Similarly, each type definition’s key is the type name and its value is the type’s schema segment (these will be described in the next sections).

The second top level property is an "anyOf" structure, which contains references to the TTCN-3 and ASN.1 types’ schema segments under "definitions". The types listed here are the ones validated by the schema. If the compiler option `–f` is set, then only the schema segments of types that have either a JSON encoding or decoding function (or both) will be referenced (ASN.1 types can have JSON encoding/decoding functions declared in TTCN-3 modules that import them). Extra information related to the encoding/decoding function(s) is stored after each reference.

Example:
[source]
----
module MyModule {
  type enumerated Height { Short, Medium, Tall };
  type set Num {
    integer num
  }
  external function f_enc_h(in Height h) return octetstring
    with { extension “prototype(convert) encode(JSON)” }
  external function f_dec_n(in octetstring o) return Num
    with { extension “prototype(convert) decode(JSON)” }
} with {
  encode ”JSON”
}
// Generated JSON schema:
// {
//     “definitions” : {
//         “MyModule” : {
//             “Height” : {
//                 “enum” : [
//                     “Short”,
//                     “Medium”,
//                     “Tall”
//                 ],
//                 “numericValues” : [
//                     0,
//                     1,
//                     2
//                 ]
//             },
//             “Num” : {
//                 “type” : “object”,
//                 “subType” : “set”,
//                 “properties” : {
//                     “num” : {
//                         “type” : “integer”
//                     }
//                 },
//                 “additionalProperties” : false,
//                 “required” : [
//                     “num”
//                 ]
//             }
//         }
//     },
//     “anyOf” : [
//         {
//             “$ref” : “#/definitions/MyModule/Height”,
//             ”encoding” : {
//                 ”prototype” : [
//                     ”convert”,
//                     ”f_enc_h”,
//                     ”h”
//                 ]
//             }
//         },
//         {
//             “$ref” : “#/definitions/MyModule/Num”,
//             ”decoding” : {
//                 ”prototype” : [
//                     ”convert”,
//                     ”f_dec_n”,
//                     ”o”
//                 ]
//             }
//         }
//     ]
// }

----

==== Rules and extra keywords

The JSON schema will be generated according to the rules of the IETF draft v4 (see http://json-schema.org/documentation.html).

In addition to the "definitions" keyword specified above, the schema segments of the type definitions can use the following extra keywords:

* `"subType"`: distinguishes 2 or more types from each other, that otherwise have no other differences in their schema segments (such as: charstring and universal charstring; record and set; record of and set of)
* `"fieldOrder"`: stores the order of the fields of a record or set (value: an array containing the field names) – only needed if there are at least 2 fields
* `"originalName"`: stores the original name of a record/set field (see <<effect-of-coding-instructions-on-the-schema, here>>)
* `"unusedAlias"`: stores the alias of a record/set/union field name, if it doesn’t appear under a "properties" keyword (see <<effect-of-coding-instructions-on-the-schema, here>>)
* `"omitAsNull"`: specifies if the "omit as null" JSON encoding instruction is present for an optional field of a record or set (see <<schema-segments-for-records-and-sets, here>> and <<effect-of-coding-instructions-on-the-schema, here>>)
* `"numericValues"`: lists the numeric values of the enumerated items (in the same order as the items themselves)

A schema segment is generated for each type that has its own definition in TTCN-3. References to other types in TTCN-3 type definitions are converted into references in the JSON schema. Schema segments for embedded TTCN-3 type definitions are defined inside their parent type’s schema segment (see <<schema-segments-for-records-and-sets, here>> and <<schema-segments-for-records-of-sets-of-and-arrays, here>> for examples).

The examples in the following sections will only contain JSON schema segments, not complete schemas (generated for one or more TTCN-3/ASN.1 type definitions, not the whole module). These schema segments contain the type name and the schema that validates the type. In a complete JSON schema these segments would be directly under the module’s property, which is under "definitions" (for examples see section <<top-level, Top Level>>, types "Height" and "Num").

==== Schema segments for basic types

The JSON encoding of basic types is detailed in section <<basic-types, Basic Types>>. Here are their schema segments:
[source]
----
// integer(TTCN-3) and INTEGER(ANS.1):
// {
//     “type” : “integer”
// }
// float(TTCN-3) and REAL(ASN.1):
// {
//     “anyOf” : [
//         {
//             “type” : “number”
//         },
//         {
//             “enum” : [
//                 “not_a_number”,
//                 “infinity”,
//                 “-infinity”
//             ]
//         }
//     ]
// }
// boolean(TTCN-3) and BOOLEAN(ASN.1):
// {
//     “type” : “boolean”
// }
// charstring(TTCN-3), NumericString(ASN.1), PrintableString(ASN.1),
// IA5String(ASN.1) and VisibleString(ASN.1):
// {
//     “type” : “string”,
//     “subType” : “charstring”
// }
// universal charstring(TTCN-3), GeneralString(ASN.1), UTF8String(ASN.1),
// UniversalString(ASN.1), BMPString(ASN.1), GraphicString(ASN.1),
// TeletexString(ASN.1) and VideotexString(ASN.1):
// {
//     “type” : “string”,
//     “subType” : “universal charstring”
// }
// bitstring(TTCN-3) and BIT STRING(ASN.1):
// {
//     “type” : “string”,
//     “subType” : “bitstring”,
//     “pattern” : “^[01]*$”
// }
// hexstring(TTCN-3):
// {
//     “type” : “string”,
//     “subType” : “hexstring”,
//     “pattern” : “^[0-9A-Fa-f]*$”
// }
// octetstring(TTCN-3), OCTET STRING(ASN.1) and ANY(ASN.1):
// {
//     “type” : “string”,
//     “subType” : “octetstring”,
//     “pattern” : “^([0-9A-Fa-f][0-9A-Fa-f])*$”
// }
// NULL(ASN.1):
// {
//     “type” : “null”
// }
// objid(TTCN-3), OBJECT IDENTIFIER(ASN.1) and RELATIVE-OID(ASN.1):
// {
//     “type” : “string”,
//     “subType” : “objid”,
//     “pattern” : “^[0-2][.][1-3]?[0-9]([.][0-9]|([1-9][0-9]+))*$”
// }
// verdicttype:
// {
//     “enum” : [
//         “none”,
//         “pass”,
//         “inconc”,
//         “fail”,
//         “error”
//     ]
// }
// Enumerated types are converted the same way as the verdicttype with the
// addition of the numeric values. Example:
// TTCN-3:
type enumerated Season {
  spring (1), summer (2), fall (3), winter (4)
}
// ASN.1:
Season ::= ENUMERATED {
  spring (1), summer (2), fall (3), winter (4)
}
// JSON schema segment for type “Season”:
// “Season” : {
//     “enum” : [
//         “spring”,
//         “summer”,
//         “fall”,
//         “winter”
//     ],
//     “numericValues” : [
//         1,
//         2,
//         3,
//         4
// }
----

[[schema-segments-for-records-and-sets]]
==== Schema segments for records and sets

The JSON object type is used for records and sets. The "properties" keyword specifies the fields of the record (each property’s key is the field name, and the value is the field’s schema segment). Additional properties are not accepted ("additionalProperties" : false). The "required" keyword determines which fields are mandatory (the names of all non-optional fields are listed here).

Optional fields have an "anyOf" structure directly under "properties" (instead of the field’s schema segment). The "anyOf" structure contains the JSON null value and the field’s schema segment. The "omitAsNull" keyword is used to specify how omitted optional values are encoded (after the "anyOf" structure).

Examples:
[source]
----
// Example 1:
// TTCN-3:
type record Product {
  charstring name,
  float price,
  octetstring id optional,
  charstring from
}
// ASN.1:
Product ::= SEQUENCE {
  name VisibleString,
  price REAL,
  id OCTET STRING OPTIONAL,
  from VisibleString
}
// Schema segment for type “Product”:
// “Product” : {
//     “type” : “object”,
//     “subType” : “record”,
//     “properties” : {
//         “name” : {
//             “type” : “string”,
//             “subType” : “charstring”
//         },
//         “price” : {
//             “anyOf” : [
//                 {
//                     “type” : “number”
//                 },
//                 {
//                     “enum” : [
//                     “not_a_number”,
//                     “infinity”,
//                     “-infinity”
//                 }
//             ],
//         }
//         “id” : {
//             “anyOf” : [
//                 {
//                     “type” : “null”
//                 },
//                 {
//                     “type” : “string”,
//                     “subType” : “octetstring”,
//                     “pattern” : “^([0-9A-Fa-f][0-9A-Fa-f])*$”
//                 },
//             ],
//             “omitAsNull” : false
//         },
//         “from” : {
//             “type” : “string”,
//             “subType” : “charstring”
//         }
//     },
//     “additionalProperties” : false,
//     “fieldOrder” : [
//         “name”,
//         “price”,
//         “id”,
//         “from”
//     ],
//     “required” : [
//         “name”,
//         “price”,
//         “from”
//     ]
// }
// Example 2: embedded type definition
// TTCN-3:
type set Barrels {
  integer numBarrels,
  record {
    enumerated { Small, Medium, Large } size,
    boolean filled
  } barrelType
}
// ASN.1:
Barrels ::= SET {
  numBarrels INTEGER,
  barrelType SEQUENCE {
    size ENUMERATED { Small, Medium, Large },
    filled BOOLEAN
  }
}
// JSON schema segment for type “Barrels”:
// “Barrels” : {
//     “type” : “object”,
//     “subType” : “set”,
//     “properties” : {
//         “numBarrels” : {
//             “type” : “integer”
//         },
//         “barrelType” : {
//             “type” : “object”,
//             “subType” : “record”,
//             “properties” : {
//                 “size” : {
//                     “enum” : [
//                         “Small”,
//                         “Medium”,
//                         “Large”
//                     ],
//                     “numericValues” : [
//                         0,
//                         1,
//                         2
//                     ]
//                 },
//                 “filled” : {
//                     “type” : “boolean”
//                 }
//             },
//             “additionalProperties” : false,
//             “fieldOrder” : [
//                 “size”,
//                 “filled”
//             ],
//             “required” : [
//                 “size”,
//                 “filled”
//             ]
//         }
//     },
//     “additionalProperties” : false,
//     “fieldOrder” : [
//         “numBarrels”,
//         “barrelType”
//     ],
//     “required” : [
//         “numBarrels”,
//         “barrelType”
//     ]
// }
// Example 3: separate type definitions and references
// (the module name is “MyModule”)
// TTCN-3:
type enumerated Size { Small, Medium, Large };
type record BarrelType {
  Size size,
  boolean filled
}
type set Barrels {
  integer numBarrels,
  BarrelType barrelType
}
// ASN.1:
Size ::= ENUMERATED { Small, Medium, Large }
BarrelType ::= SEQUENCE {
  size Size,
  filled BOOLEAN
}
Barrels ::= SET {
  numBarrels INTEGER,
  barrelType BarrelType
}
// Schema segments for types “Size”, “BarrelType” and “Barrels”:
// ”Size” : {
//     ”enum” : [
//         ”Small”,
//         ”Medium”,
//         ”Large”
//     ],
//     “numericValues” : [
//         0,
//         1,
//         2
//     ]
// }
// “BarrelType” : {
//     “type” : “object”,
//     “subType” : “record”,
//     “properties” : {
//         “size” : {
//             “$ref” : “#/definitions/MyModule/Size”
//         },
//         “filled” : {
//             “type” : “boolean”
//         }
//     },
//     ”additionalProperties” : false,
//     ”fieldOrder” : [
//         ”size”,
//         ”filled”
//     ],
//     ”required” : [
//         ”size”,
//         ”filled”
//     ]
// },
// ”Barrels” : {
//     ”type” : ”object”,
//     ”subType” : ”set”,
//     ”properties” : {
//         ”numBarrels” : {
//             ”type” : ”integer”
//         },
//         ”barrelType” : {
//             ”$ref” : ”#/definitions/MyModule/BarrelType”
//         }
//     },
//     ”additionalProperties” : false,
//     ”fieldOrder” : [
//         ”numBarrels”,
//         ”barrelType”
//     ],
//     ”required” : [
//         ”numBarrels”,
//         ”barrelType”
//     ]
// }
----

[[schema-segments-for-records-of-sets-of-and-arrays]]
==== Schema segments for records of, sets of and arrays

The JSON array type is used for records of, sets of and arrays. The "items" keyword specifies the schema segment of the items. In case of arrays, the "minItems" and "maxItems" properties are set to the array length.

Arrays are distinguishable from records of and sets of by the "minItems" and "maxItems" keywords, so there is no need for them to have the "subType" property.

Examples:
[source]
----
// Example 1:
// TTCN-3:
type record of bitstring Bits;
// ASN.1:
Bits ::= SEQUENCE OF BIT STRING
// Schema segment for type “Bits”:
// “Bits” : {
//     “type” : “array”,
//     “subType” : “record of”,
//     “items” : {
//         “type” : “string”,
//         “subType” : “bitstring”,
//         “pattern” : “^[01]*$”
//     }
// }
// Example 2 (TTCN-3 only):
type integer Ints[4];
// Schema segment for type “Ints”:
// “Ints” : {
//     “type” : “array”,
//     “minItems” : 4,
//     “maxItems” : 4,
//     “items” : {
//         “type” : “integer”
//     }
// }
// Example 3:
// reference to record type Num defined in section Top Level.
// TTCN-3:
type set of Num Nums;
// ASN.1:
Nums ::= SET OF Num
// JSON schema segment for type “Nums”:
// “Nums” : {
//     “type” : “array”,
//     “subType” : “set of”,
//     “items” : {
//         “$ref” : “#/definitions/MyModule/Num”
//     }
// }
// Example 4:
// the same thing with Num as an embedded type
// TTCN-3:
type set of set { integer num } Nums;
// ASN.1:
Nums ::= SET OF SET { num INTEGER }
// JSON schema segment for type “Nums”:
// “Nums” : {
//     “type” : “array”,
//     “subType” : “set of”,
//     “items” : {
//         “type” : “object”,
//         “subType” : “set”,
//         “properties” : {
//             “num” : {
//                 “type” : “integer”
//             }
//         },
//         “additionalProperties” : false,
//         “required” : [
//             “num”
//         ]
//     }
// }
----

==== Schema segments for unions, anytype, selection type and open type

The "anyOf" structure is used for unions, open types and the anytype (if they have at least 2 fields). Each item in the "anyOf" structure represents one field of the union; they are each a JSON object with one key-value pair (one property). Same as with records, the "additionalProperties" keyword is set to false, and the one property is marked as required.

Examples:
[source]
----
// Example 1: union
// TTCN-3:
type union Thing {
  boolean b,
  integer i,
  charstring cs,
  record { integer num } rec
}
// ASN.1:
Thing ::= CHOICE {
  b BOOLEAN,
  i INTEGER,
  cs VisibleString,
  rec SEQUENCE { num INTEGER }
}
// Schema segment for type “Thing”:
// “Thing” : {
//     “anyOf” : [
//         {
//             “type” : “object”,
//             “properties” : {
//                 “b” : {
//                     “type” : “boolean”
//                 }
//             },
//             “additionalProperties” : false,
//             “required” : [
//                 “b”
//             ]
//         },
//         {
//             “type” : “object”,
//             “properties” : {
//                 “i” : {
//                     “type” : “integer”
//                 }
//             },
//             “additionalProperties” : false,
//             “required” : [
//                 “i”
//             ]
//         },
//         {
//             “type” : “object”,
//             “properties” : {
//                 “cs” : {
//                     “type” : “string”,
//                     “subType” : “charstring”
//                 }
//             },
//             “additionalProperties” : false,
//             “required” : [
//                 “cs”
//             ]
//         },
//         {
//             “type” : “object”,
//             “properties” : {
//                 “rec” : {
//                     “type” : “object”,
//                     “subType” : “record”,
//                     “properties” : {
//                         “num” : {
//                             “type” : “integer”
//                         }
//                     },
//                     “additionalProperties” : false,
//                     “required” : [
//                         “num”
//                     ]
//                 }
//             },
//             “additionalProperties” : false,
//             “required” : [
//                 “rec”
//             ]
//         }
//     ]
// }
// Example 2: anytype (TTCN-3 only)
module … {
} with {
  extension “anytype integer,charstring”
  // the anytype must be referenced at least one,
  // otherwise its schema segment won’t be generated
}
// JSON schema segment for the anytype:
// “anytype” : {
//     “anyOf” : [
//         {
//             “type” : “object”,
//             “properties” : {
//                 “integer” : {
//                     “type” : “integer”
//                 }
//             },
//             “additionalProperties” : false,
//             “required” : [
//                 “integer”
//             ]
//         },
//         {
//             “type” : “object”,
//             “properties” : {
//                 “charstring” : {
//                     “type” : “string”,
//                     “subType” : “charstring”
//                 }
//             },
//             “additionalProperties” : false,
//             “required” : [
//                 “charstring”
//             ]
//         }
//     ]
// }
----

The ASN.1 selection type generates the same schema segment as the specified alternative of the CHOICE would.

Example:
[source]
----
// Continuing example 1 (ASN.1 only):
NumRec ::= rec < Thing
// JSON schema segment for type NumRec:
// “NumRec” : {
//     “type” : “object”,
//     “subType” : “record”,
//     “properties” : {
//         “num” : {
//             “type” : “integer”
//         }
//     },
//     “additionalProperties” : false,
//     “required” : [
//         “num”
//     ]
// }
----

[[effect-of-coding-instructions-on-the-schema]]
==== Effect of coding instructions on the schema

For the list of JSON coding instructions see <<attributes-1, here>>. As mentioned before, only TTCN-3 types can have coding instructions, ASN.1 types can’t.

* _omit as null_ – its presence is indicated by the "omitAsNull" keyword (true, if it’s present)
* _name as …_ - the alias is used under "properties" instead of the field’s name in TTCN-3; the original name is stored under the "originalName" key
* _as value_ – the union’s "anyOf" structure contains the fields’ schema segments instead of the JSON objects with one property; the field’s name is stored under the "originalName" key
* _default_ – specified by the "default" keyword
* _extend_ – adds a custom key-value pair to the type’s schema segment
* _as value_ + _name as …_ - the field name aliases are stored under the "unusedAlias" keyword, as there are no more JSON objects with one property to store them in (they are also ignored by both the schema and the encoder/decoder, and a compiler warning is displayed in this case)
* _metainfo for unbound_ – is ignored by the schema generator

Examples:
[source]
----
// Example 1: omit as null
type record Rec {
  integer num optional,
  universal charstring str optional
} with {
  variant(num) “JSON : omit as null”
}
// Schema segment for type “Rec”:
// “Rec” : {
//     “type” : “object”,
//     “subType” : “record”,
//     “properties” : {
//         “num” : {
//             “anyOf” : [
//                 {
//                     “type” : “null”
//                 },
//                 {
//                     “type” : “integer”
//                 }
//             ],
//             “omitAsNull” : true
//         },
//         “str” : {
//             “anyOf” : [
//                 {
//                     “type” : “null”
//                 },
//                 {
//                     “type” : “string”,
//                     “subType” : “universal charstring”
//                 }
//             ],
//             “omitAsNull” : false
//         }
//     },
//     “additionalProperties” : false,
//     “fieldOrder” : [
//         “num”,
//         “str”
//     ]
// }
// Example 2: name as ...
type set Num {
  integer num
} with {
    variant(num) ”JSON : name as number”
}
// Schema segment for type “Num”:
// ”Num” : {
//     ”type” : ”object”,
//     ”subType” : ”set”,
//     “properties” : {
//         “number” : {
//             “originalName” : “num”,
//             “type” : “integer”
//         }
//     },
//     “additionalProperties” : false,
//     “required” : [
//         “number”
//     ]
// }
// Example 3: as value and name as ...
type union Thing {
  boolean b,
  integer i,
  charstring cs,
  record { integer num } rec
} with {
  variant “JSON : as value”;
  variant(i) “JSON : name as int”;
  variant(cs) “JSON : name as str”;
}
// Schema segment for type “Thing”:
// “Thing” : {
//     “anyOf” : [
//         {
//             “originalName” : “b”,
//             “type” : “boolean”
//         },
//         {
//             “originalName” : “i”,
//             “unusedAlias” : “int”,
//             “type” : “integer”
//         },
//         {
//             “originalName” : “cs”,
//             “unusedAlias” : “str”,
//             “type” : “string”,
//             “subType” : “charstring”
//         },
//         {
//             “originalName” : “rec”,
//             “type” : “object”,
//             “subType” : “record”,
//             “properties” : {
//                 “num” : {
//                     “type” : “integer”
//                 }
//             },
//             “additionalProperties” : false,
//             “required” : [
//                 “num”
//             ]
//         }
//     ]
// }
// Example 4: default
type record Rec {
  integer num,
  universal charstring str
} with {
  variant(num) “JSON : default(0)”;
  variant(str) “JSON : default(empty)”;
}
// JSON schema segment for type “Rec”:
// “Rec” : {
//     “type” : “object”,
//     “subType” : “record”,
//     “properties” : {
//         “num” : {
//             “type” : “integer”,
//             “default” : 0
//         },
//         “str” : {
//             “type” : “string”,
//             “subType” : “universal charstring”,
//             “default” : “empty”
//         }
//     },
//     “additionalProperties” : false,
//     “fieldOrder” : [
//         “num”,
//         “str”
//     ],
//     “required” : [
//         “num”,
//         “str”
//     ]
// }
// Example 5: extend
type record Number {
  integer val
} with {
  variant “JSON:extend(comment):(first)”;
  variant “ JSON : extend (comment) : (second (todo: add more fields\)) ”;
  variant “JSON: extend(description):(a record housing an integer)”;
  variant(val) “JSON: extend(description):(an integer)”;
  variant(val) “JSON: extend(subType):(positive integer)”;
}

// Schema segment for type “Number”:
// "Number" : {
//     "type" : "object",
//     "subType" : "record",
//     "properties" : {
//         "val" : {
//             "type" : "integer",
//             "description" : "an integer",
//             "subType" : "positive integer"
//         }
//     },
//     "additionalProperties" : false,
//     "required" : [
//         "val"
//     ],
//     "comment" : "first",
//     "comment" : "second (todo: add more fields)",
//     "description" : "a record housing an integer"
// }

// Displayed warnings:
// warning: JSON schema keyword 'subType' should not be used as the key of
// attribute 'extend'
// warning: Key 'comment' is used multiple times in 'extend' attributes of type
// '@MyModule.Number'
// (The multiple uses of ‘description’ don’t generate a warning, since these
// belong to different types.)
----

==== External function properties in the schema

JSON encoding/decoding functions can only be declared in TTCN-3 modules, however they can be defined for both TTCN-3 types and imported ASN.1 types.

Information related to a type’s JSON encoding/decoding external function is stored after the reference to the type’s schema segment in the top level "anyOf" structure.

Extra JSON schema keywords for the external function properties:

* `"encoding"` and `"decoding"`: stores the specifics of the encoding or decoding function as properties (directly under the top level `"anyOf"`, after the reference to the type’s schema segment)
* `"prototype"`: an array containing the prototype of the encoding function (as a string), the function name, and the parameter names used in its declaration (directly under `"encoding"` or `"decoding"`)
* `"printing"`: stores the printing settings (values: `"compact"` or `"pretty"`; directly under `"encoding"`)
* `"errorBehavior"`: an object containing the error behavior modifications as its properties, each modification has the error type as key and the error handling as value (directly under `"encoding"` or `"decoding"`)

Example:
[source]
----
module Mod {
  type record Rec {
    integer num,
    boolean b
  }
  external function f_enc(in Rec x) return octetstring with {
    extension “prototype(convert) encode(JSON) printing(pretty)”
  }
  external function f_dec(in octetstring o, out Rec x) with {
    extension “prototype(fast) decode(JSON)”
    extension “errorbehavior(ALL:WARNING,INVAL_MSG:ERROR)”
  }

} with {
  encode “JSON”
}
// JSON schema:
// {
//     “definitions” : {
//         “Mod” : {
//             “Rec” : {
//                 “type” : “object”,
//                 “subType” : “record”,
//                 “properties” : {
//                     “num” : {
//                         “type” : “integer”
//                     },
//                     “b” : {
//                         “type” : “boolean”
//                     }
//                 },
//                 “additionalProperties” : false,
//                 “fieldOrder” : [
//                     “num”,
//                     “b”
//                 ],
//                 “required” : [
//                     “num”,
//                     “b”
//                 ]
//             }
//         }
//     },
//     “anyOf” : [
//         {
//             “$ref” : “#/definitions/Mod/Rec”,
//             “encoding” : {
//                 “prototype” : [
//                     “convert”,
//                     “f_enc”,
//                     “x”
//                 ],
//                 “printing” : “pretty”
//             },
//             “decoding” : {
//                 “prototype” : [
//                     “fast”,
//                     “f_dec”,
//                     “o”,
//                     “x”
//                 ],
//                 “errorBehavior” : {
//                     “ALL” : “WARNING”,
//                     “INVAL_MSG” : “ERROR”
//                 }
//             }
//         }
//     ]
// }
----

==== Schema segments for type restrictions

The compiler’s `–ttcn2json` option also generates schema segments for type restrictions (subtyping constraints), even though these are ignored by the JSON encoder and decoder. Only restrictions of TTCN-3 types are converted to JSON schema format, ASN.1 type restrictions are ignored.

The generated schema segments only contain basic JSON schema keywords, no extra keywords are needed.

.Converting TTCN-3 type constraints to JSON schema segments
[cols=",",options="header",]
|===
|TTCN-3 type restriction |JSON schema segment
|Length restrictions of string types |Keywords `minLength` and `maxLength` are used.
|Length restrictions of array types |Keywords `minItems` and `maxItems` are used.
|Single values |All single values (more specifically their JSON encodings) are gathered into one JSON `enum`. Keyword valueList is used to store single values of unions with the as value coding instruction (encoded as if they did not have this coding instruction).
|Value range restrictions of `integers` and `floats` |The keywords minimum and maximum are used to specify the range, and keywords `exclusiveMinimum` and `exclusiveMaximum` indicate whether the limits are exclusive or not. All value range and single value restrictions are placed in an `anyOf` structure, if there are at least two value ranges, or if there is one value range and at least one single value.
|Value range restrictions of charstrings and universal charstrings |All value range restrictions are gathered into a set expression in a JSON schema `pattern`.
|String pattern restrictions |The TTCN-3 pattern is converted into an extended regular expression and inserted into the schema as a JSON `pattern`. Since the pattern is a JSON string, it cannot contain control characters. These are replaced with the corresponding JSON escape sequences, if available, or with the escape sequence `\u`, followed by the character’s ASCII code in 4 hexadecimal digits. Furthermore all backslashes in the string are doubled.
|===

These schema elements are inserted after the type’s schema segment. If the type’s schema segment only contains a reference to another type (in case it’s a `record`/`set`/`union` field of a type with its own definition or it’s an alias to a type with its own definition), then an `allOf` structure is inserted, which contains the reference as its first element and the restrictions as its second element (since the referenced type may contain some of the schema elements used in this type’s restrictions).

If the value list restriction contains references to other subtypes, then the schema segments of their restrictions are inserted, too.

The JSON coding instructions `as` `value` (for unions) and `name as...` (for `records`, `sets` and `unions`) are taken into consideration when generating the schema elements for the single values.

All non-ASCII characters in `universal` `charstring` single values and patterns are inserted into the schema in UTF-8 encoding.

Special cases:

. The restrictions of `floats` are inserted at the end of the first element in the `anyOf` structure, except those that are related to the special values (`infinity`, `-infinity` and `not_a_number`). The `enum` containing the special values is changed, if any of the special values is not allowed by the type’s restrictions. If neither of the special values are allowed, then the `anyOf` structure is omitted, and the type’s schema only contains `type` : `number`, followed by the rest of the restrictions. Similarly, if only special values are allowed by the restrictions, then the type’s schema only contains the `enum` with the valid values.
. If a verdicttype is restricted (with single values), then only the `enum` containing the list of single values is generated (since it would conflict with the type’s schema segment, which is also an `enum`).
. If a single value restriction contains one or more `omit` values, then all possible JSON encodings of the single value are inserted into the `enum`. There are 2^N^ different encodings, where _N_ is the number of `omits` in the single value, since each omitted field can be encoded in 2 ways (by not adding the field to the JSON object, or by adding the field with a `null` value).
. Single value restrictions of unions with the `as value` coding instruction do not specify which alternative the value was encoded from. Thus, the single values are generated a second time, under the extra keyword `valueList`, as if they belonged to a union without `as value` (with alternative names). This second list does not contain all the combinations of omitted field encodings (mentioned in the previous point), only the one, where omitted fields are not added to their JSON objects.

Examples:
[source]
----
// Example 1: Type definition with value range restriction and its subtype
// with value list restriction
type integer PosInt (!0..infinity);
type PosInt PosIntValues (1, 5, 7, 10);

// Schema segment generated for type “PosInt”:
// “PosInt” : {
//     “type” : “integer”,
//     “minimum” : 0,
//     “exclusiveMinimum” : true
// }

// Schema segment generated for type “PosIntValues”:
// “PosIntValues” : {
//     “allOf” : [
//         {
//             “$ref” : “#/definitions/MyModule/PosInt”
//         },
//         {
//             “enum” : [
//                 1,
//                 5,
//                 7,
//                 10
//             ]
//         }
//     ]
// }

// Example 2: String type definitions with length, value range and pattern
// constraints
type charstring CapitalLetters (“A”..“Z”) length (1..6);
type charstring CharstringPattern
  (pattern “*ab?\*\?\(\+[0-9a-fA-F*?\n]#(2,4)\d\w\n\r\s\”x”\\d);

type universal charstring UnicodeStringRanges
  (“a”.. “z”, char(0, 0, 1, 81)..char(0, 0, 1, 113));
type universal charstring UnicodePattern
  (pattern “abc?\q{ 0, 0, 1, 113 }z\\q1\q{0,0,0,2}”);

// Schema segment generated for type “CapitalLetters”:
// “CapitalLetters” : {
//     “type” : “string”,
//     “subType” : “charstring”,
//     “minLength” : 1,
//     “maxLength” : 6,
//     “pattern” : “^[A-Z]*$”
// }

// Schema segment generated for type “CharstringPattern”:
// “CharstringPattern” : {
//     “type” : “string”,
//     “subType” : “charstring”,
//     “pattern” : “^.*ab.\\*\\?\\(\\+[\n-\r*0-9?A-Fa-f]{2,4}[0-9][0-9A-Za-z]
//[\n-\r]\r[\t-\r ]\”x\”\\\\d$”
// }

// Schema segment generated for type “UnicodeStringRanges”:
// “UnicodeStringRanges” : {
//     “type” : “string”,
//     “subType” : “universal charstring”,
//     “pattern” : “^[a-ző-ű]*$”
// }

// Schema segment generated for type “UnicodePattern”:
// “UnicodePattern” : {
//     “type” : “string”,
//     “subType” : “universal charstring”,
//     “pattern” : “^abc.űz\\\\q1\u0002$”
// }

// Example 3: Array type definitions with length restrictions and
// restrictions for the element type
type record length (3..infinity) of PosInt PosIntList;
type set length (2) of integer OnesAndTwos (1, 2);

// Schema segment generated for type “PosIntList”:
// “PosIntList” : {
//     “type” : “array”,
//     “subType” : “record of”,
//     “items” : {
//         “$ref” : “#/definitions/MyModule/PosInt”
//     },
//     “minItems” : 3
// }

// Schema segment generated for type “OnesAndTwos”:
// “OnesAndTwos” : {
//     “type” : “array”,
//     “subType” : “set of”,
//     “items” : {
//         “type” : “integer”,
//         “enum” : [
//             1,
//             2
//         ]
//     },
//     “minItems” : 2,
//     “maxItems” : 2
// }

// Example 4: Float type definitions with all kinds of restrictions
type float RestrictedFloat (-infinity..-1.0, 0.0, 0.5, 1.0, not_a_number);
type float NegativeFloat (!-infinity..!0.0);
type float InfiniteFloat (-infinity, infinity);

// Schema segment generated for type “RestrictedFloat”:
// “RestrictedFloat” : {
//     “anyOf” : [
//         {
//             “type” : “number”,
//             “anyOf” : [
//                 {
//                     “enum” : [
//                         0.000000,
//                         0.500000,
//                         1.000000,
//                     ]
//                 },
//                 {
//                     “maximum” : -1.000000,
//                     “exclusiveMaximum” : false
//                 }
//             ]
//         },
//         {
//             “enum” : [
//                 “not_a_number”,
//                 “-infinity”
//             ]
//         }
//     ]
// }

// Schema segment generated for type “NegativeFloat”:
// “NegativeFloat” : {
//     “type” : “number”,
//     “maximum” : 0.000000,
//     “exclusiveMaximum” : true
// }

// Schema segment generated for type “InfiniteFloat”:
// “InfiniteFloat” : {
//     “enum” : [
//         “infinity”,
//         “-infinity”
//     ]
// }

// Example 5: verdicttype definition with restrictions (single values)
type verdicttype SimpleVerdict (pass, fail, error);

// Schema segment generated for type “SimpleVerdict”:
// “SimpleVerdict” : {
//     “enum” : [
//         “pass”,
//         “fail”,
//         “error”
//     ]
// }

// Example 6: Union type definition with the “as value” coding instruction and
// its subtypes (one of which references the other)
type union AsValueUnion {
  integer i,
  charstring str
}
with {
  variant “JSON: as value”
}

type AsValueUnion AsValueUnionValues (
  { i := 3 },
  { str := “abc” }
);

type AsValueUnion MoreAsValueUnionValues (
  AsValueUnionValues,
  { i := 6 }
);

// Schema segment generated for type “AsValueUnion”:
// “AsValueUnion” : {
//     “anyOf” : [
//         {
//             “originalName” : “i”,
//             “type” : “integer”
//         },
//         {
//             “originalName” : “str”,
//             “type” : “string”,
//             “subType” : “charstring”
//         }
//     ]
// }

// Schema segment generated for type “AsValueUnionValues”:
// “AsValueUnionValues” : {
//     “allOf” : [
//         {
//             “$ref” : “#/definitions/MyModule/AsValueUnion”
//         },
//         {
//             “enum” : [
//                 3,
//                 “abc”
//             ],
//             “valueList” : [
//                 {
//                     “i” : 3
//                 },
//                 {
//                     “str” : “abc”
//                 }
//             ]
//         }
//     ]
// }

// Schema segment generated for type “MoreAsValueUnionValues”:
// “MoreAsValueUnionValues” : {
//     “allOf” : [
//         {
//             “$ref” : “#/definitions/MyModule/AsValueUnion”
//         },
//         {
//             “enum” : [
//                 3,
//                 “abc”,
//                 6
//             ],
//             “valueList” : [
//                 {
//                     “i” : 3
//                 },
//                 {
//                     “str” : “abc”
//                 },
//                 {
//                     “i” : 6
//                 }
//             ]
//         }
//     ]
// }

// Example 7: Record definition with field name aliases and extra restrictions
// to its fields, plus its subtype, which contains omit values
type record Rec {
  PosIntValues val optional,
  integer i (0..6-3),
  octetstring os (‘1010’O, ‘1001’O, ‘1100’O) optional
}
with {
  variant(val) “JSON: name as posInt”;
  variant(i) “JSON: name as int”;
}

type Rec RecValues (
  { 1, 0, ‘1010’O },
  { 5, 0, ‘1001’O },
  { 7, 2, omit },
  { omit, 1, omit }
);

// Schema segment generated for type “Rec”:
// “Rec” : {
//     “type” : “object”,
//     “subType” : “record”,
//     “properties” : {
//         “posInt” : {
//             “anyOf” : [
//                 {
//                     “type” : “null”
//                 },
//                     “originalName” : “val”,
//                     “#ref” : “#/definitions/MyModule/PosIntValues”
//                 }
//             ],
//             “omitAsNull” : false
//         },
//         “int” : {
//             “originalName” : “i”,
//             “type” : “integer”,
//             “minimum” : 0,
//             “exclusiveMinimum” : false,
//             “maximum” : 3,
//             “exclusiveMaximum” : false
//         },
//         “os” : {
//             “anyOf” : [
//                 {
//                     “type” : “null”,
//                 },
//                 {
//                     “type” : “string”,
//                     “subType” : “octetstring”,
//                     “pattern” : “^([0-9A-Fa-f][0-9A-Fa-f])*$”,
//                     “enum” : [
//                         “1010”,
//                         “1001”,
//                         “1100”
//                     ]
//                 }
//             ],
//             “omitAsNull” : false
//         }
//     },
//     “additionalProperties” : false,
//     “fieldOrder” : [
//         “posInt”,
//         “int”,
//         “os”
//     ],
//     “required” : [
//         “int”
//     ]
// }

// Schema segment for type “RecValues”:
// “RecValues” : {
//     “allOf” : [
//         {
//             “$ref” : “#/definitions/MyModule/Rec”
//         },
//         {
//             “enum” : [
//                 {
//                     “posInt” : 1,
//                     “int” : 0,
//                     “os” : “1010”
//                 },
//                 {
//                     “posInt” : 5,
//                     “int” : 0,
//                     “os” : “1001”
//                 },
//                 {
//                     “posInt” : 7,
//                     “int” : 2
//                 },
//                 {
//                     “posInt” : 7,
//                     “int” : 2,
//                     “os” : null
//                 },
//                 {
//                     “int” : 1,
//                 },
//                 {
//                     “posInt” : null,
//                     “int” : 1
//                 },
//                 {
//                     “int” : 1,
//                     “os” : null
//                 },
//                 {
//                     “posInt” : null,
//                     “int” : 1,
//                     “os” : null
//                 }
//             ]
//         }
//     ]
// }
----
=== Differences from the TTCN-3 standard

The JSON encoder and decoder work according to the rules defined in the JSON part of the TTCN-3 standard <<13-references.adoc#_25, [25]>> with the following differences:

* No wrapper JSON object is added around the JSON representation of the encoded value, i.e. all values are encoded as if they had the JSON variant attribute `noType` (from the standard). Similarly, the decoder expects the JSON document to only contain the value’s JSON representation (without the wrapper). If a wrapper object is desired, then the type in question should be placed in a `record`, `set` or `union`.
* The JSON encoder and decoder only accept the variant attributes listed <<top-level, here>>. Some of these have the same effect as variant attributes (with similar names) from the standard. The rest of the variant attributes from the standard are not supported. See <<external-functions, here>> regarding the variant attributes `normalize` and `errorbehavior` (from the standard).
* The syntax of the JSON encode attribute is `encode JSON`. The attribute `encode JSON RFC7159` is not supported.
* The decoder converts the JSON number `-0.0 `(in any form) to the TTCN-3 float `-0.0`, i.e. float values are decoded as if they had the JSON variant attribute `useMinus` (from the standard).The same is not true for integers, since there is no integer value `-0` in TITAN.

== OER Encoder and Decoder

The OER (Octet Encoding Rules) encoder and decoder handles OER-based protocols. The encoder converts abstract ASN.1 structures (or types) into an octetstring representation. The decoder converts octetstring data into values of abstract ASN.1 structures. The encoding and decoding rules of the structures can be found in the [20] standard.

This section covers the not supported parts of the standard and the encoder / decoder external functions.

=== Not supported parts of the standard

Generally, TITAN does not have full ASN.1 support, therefore some parts of the OER coding are not supported.

The following parts of the standard are not supported:

* In clause 12 (Encoding of real values) of the standard: the coding of real values, whether there are any constraints or not on a REAL ASN.1 type, is handled as it is declared in the clause 12.4 of the standard.
* Clause 23 and 24 are not supported.
* In clause 25 (Encoding of values of the embedded-pdv type): only the "general" case (sub clause 25.3) is supported. The "predefined" case (sub clause 25.2) will be handled as the "general" case.
* In clause 28 (Encoding of the unrestricted character string type): only the "general" case (sub clause 28.3) is supported. The "predefined" case (sub clause 28.2) will be handled as the "general" case.
* Clause 29 (Encoding of values of the time types) is not supported.
* Clause 31 (Canonical Octet Encoding Rules) is not fully supported, as currently there is no way to choose BASIC-OER or CANONICAL-OER coding.

[[external-functions-1]]
=== External functions

OER encoder / decoder functions must have the `encode(OER)` / `decode(OER)` attribute set.

Faults in the OER encoding/decoding process produce errors by default, but this can be modified with the `errorbehavior` attribute. (<<codec-error-handling, Codec error handling>>)

[[build-consistency-checks]]
== Build Consistency Checks

Executable test suites are typically put together from many sources, some of which (test ports, function libraries, etc.) are not written by the test writers themselves, but are developed independently. Sometimes, a test suite requires an external component with a certain feature or bug fix, or a certain minimum TITAN version. Building with a component which does not meet a requirement, or an old TITAN version, typically results in malfunction during execution or cryptic error messages during build. If version dependencies are specified explicitly, they can be checked during build and the mismatches can be reported.

=== Version Information in TTCN-3 Files

TITAN allows test writers to specify that a certain TTCN-3 module requires a minimum version of another TTCN-3 module or a minimum version of TITAN.

==== Format of Version Information

The format of the version information follows the format of Product Identity (Ericsson standard version information <<13-references.adoc#_19, [19]>>); a combination of letters and digits according to the template pruductNumber/suffix RmXnn, where

* Product number identifies the product. It is 3 characters representing the ABC class, 3 digits called the type number and 2 to 4 digits called the sequence number. This part is optional for backward compatibility reasons.
* Suffix indicates new major versions, which are not backward compatible with previous versions ("Revision suffix"). This part is optional for backward compatibility reasons.
* R is the literal character `R'
* m is a single digit ("Revision digit"). It changes when the product (module) functionality is extended with new features (switching to this version is possible, but switching back might not be).
* X is an uppercase letter of the English alphabet (between A and Z inclusive) which changes when the product (module) realization changes ("Revision letter"). The following letters are not allowed: IOPQRW. Versions of a product where only this letter changes can be switched without side effect.
* nn (optional) is a two-digit number ("Verification step") which specifies a prerelease, a version made available during development.

If the final digits are not present, the version is considered a full release, which is a higher version than any prerelease.

Example accepted formats: CRL 113 200/1 R9A; CRL 113 200 R9A; R9APlease note, that only these are supported from the Ericsson Naming Scheme.

Here is a possible progression of release numbers, in strictly ascending order:

R1A01, R1A02…, R1A (first full release), R1B01, R1B02…, R1B, R1C, R2A, R2B01, R2B02…, R2B, R2C, R3A, etc.

==== Required TITAN Version

A TTCN-3 module can specify the minimum required version of TITAN which can be used to compile it. The format of the extension attribute is"requiresTITAN <version>". For example, the following snippet:
[source]
----
module X {
  // …
}
with {
  extension “requiresTITAN R8C”;
}
----

specifies that module X has to be compiled with TITAN R8D (1.8.pl3) or later. Compiling the module with a TITAN which does not satisfy the requirement will cause a compilation error, stating that the version of the compiler is too low.

Compiling this module with TITAN R8B or below may result in a different compiler error, because the syntax of the attribute is not understood by earlier versions.

==== Specifying the Version of a TTCN-3 Module

A module’s own version information can be specified in an extension attribute. The format of the extension attribute is "version <version data>" that is, the literal string "version" followed by the version information (R-state).

Example:
[source]
----
module supplier {
  // …
}
with {
  extension “version R1A”;
}
----

The version of the module should be set to match the R-state of the product it belongs to.

For backward compatibility, the lack of version information (no extension attribute with "version" in the module’s "with" block) is equivalent to the highest possible version and satisfies any version requirement.

==== Required Version of an Imported Module

The minimum version of an imported module can be specified with an extension attribute. The format of the extension attribute is "requires <module name> <required version>" that is, the literal string "requires" followed by the actual module name and required version.

Example:
[source]
----
module importer {
  import from supplier all;
}
with {
  extension “requires supplier R2A”
}
----

The module name must be one that is imported into the module. Specifying a module which is not imported is flagged as an error.

In general, a module should require the full version of another module or TITAN (the R1A format). Depending on a prerelease version should be avoided whenever possible.

=== Consistency Check in the Generated Code

A number of checks are performed during the build to ensure consistency of the TITAN compiler, TITAN runtime, {cpp} compiler used during the build. The compiler generates checking code that verifies:

* The version of the TITAN compiler matches the version of the TITAN runtime
* The platform on which the build is being performed matches the platform of the TITAN compiler
* The compiler used to build the TITAN compiler matches the compiler used to build the TITAN runtime
* Some of this information (in form of {cpp} preprocessor macros definitions and instructions) is available to test port writers to express dependency on a particular TITAN version. When a {cpp} file includes a header generated by the TITAN compiler, that header includes the definitions for the TITAN runtime, including version information. These macro dependencies can be used in user-written {cpp} code.
* TTCN3_VERSION is a C/{cpp} macro defined by the TITAN runtime headers. It contains an aggregated value of the TITAN major version, minor version and patch level. So, to express that a certain {cpp} file must be compiled together with TITAN R8C, the following code can be used:
+
[source]
----
#if TTCN3_VERSION < 10802
#error This file requires TITAN 1.8.2
#endif
----
* There is a preprocessor macro defined in the makefile which identifies the platform (operating system). It can be one of SOLARIS (for Solaris 6), SOLARIS8 (for Solaris 8 and above), LINUX, WIN32. Platform-dependent code can be isolated using conditional compilation based on these macro definitions.
* If the TITAN runtime was compiled with the GNU Compiler Collection (GCC), the macro GCC_VERSION is defined by the TITAN runtime headers. Its value is 10000 * (GCC major version) + 100 * (GCC minor version). For example, for GCC 3.4.6, GCC_VERSION will be defined to the value 30400; for GCC 4.1.2 it will be 40100. The value of this macro is compared during {cpp} compilation to the version of the compiler that was used to build TITAN itself to ensure consistency of the build. The GCC patch level is ignored for this comparison; code generated by a compiler with the same major and minor version is considered compatible. User-written code can use this value if it requires a certain version of the compiler. Alternatively, the predefined macros of the GNU compiler (*GNUC* and *GNUC_MINOR*) can be used for this purpose.
* If the TITAN runtime was built with the SunPro compiler, the compiler itself defines the __SUNPRO_CC macro. Please consult the compiler documentation for the possible values.

== Negative Testing

=== Overview

As a TTCN-3 language extension Titan can generate invalid messages for the purpose of negative testing. The purpose is to generate wrong messages that do not conform to a given type that the SUT is expecting, and send them to the SUT and observe the SUT’s reaction. In Titan only the encoding is implemented, the decoding of wrong messages is not in the scope of this feature.

In protocol testing the term of abstract syntax and transport syntax can be distinguished. In TTCN-3 abstract syntaxes are the data type definitions, while transport syntax is defined using with attributes (encode, variant) that are attached to type definitions. The negative testing feature defines modifications in the transport syntax, thus it does not affect TTCN-3 type definitions. This means that the content of the values, which shall be called *erroneous values* and *erroneous templates*, will not be modified; only their encoding will be. This encoding (transport syntax) is determined by the with attributes attached to the type definition, in case of negative testing the encoding of a value is modified by attaching special with attributes to the value which is to be encoded. TTCN-3 with attributes can be attached only to module level constants and templates; this is a limitation of the TTCN-3 standard.

Values and templates of the following structured types can be made erroneous:

* record
* set
* record of
* set of
* union

The corresponding ASN.1 types can also be used when imported from an ASN.1 module.

The following *erroneous* behaviors can be defined for the encoding of an *erroneous value* or *template*:

* omit specified fields
* change the specified field’s value or both type and value
* omit all fields before or after the specified field
* insert a new field before or after the specified field

The inserted data can be either the value of a given constant or any "raw" binary data.

All encoding types (RAW, TEXT, BER, XER, JSON, OER) supported by TITAN can be used in negative testing.

=== Syntax

Erroneous attributes follow the syntax laid out in section A.1.6.6 (with statement) of the TTCN-3 standard with the following modifications:

[source]
AttribKeyword ::= EncodeKeyword | VariantKeyword | DisplayKeyword | ExtensionKeyword | OptionalKeyword |

[source]
ErroneousKeywordErroneousKeyword ::= "erroneous"

For an erroneous attribute the syntax of the AttribSpec, a free text within double quotes, is as follows:

[source]
AttribSpecForErroneous := IndicatorKeyword [ “(“ RawKeyword ")" ] ":=" TemplateInstance [ AllKeyword ]

[source]
IndicatorKeyword := "before" | "value" | "after"

[source]
RawKeyword := "raw"

Example (the meaning of this code will be explained in the next chapter):
[source]
----
type record MyRec {
  integer i,
  boolean b
}
const MyRec c_myrec := {i:=1,b:=true}
with {
  erroneous (i) “before := 123”
  erroneous (b) “value := omit”
}
----

=== Semantics

The TemplateInstance is defined in the TTCN-3 standard, however the compiler will accept only constant values that have no matching symbols. The reason for using the TemplateInstance syntax is that it can contain also a type reference, allowing to define both the value and its type.

For example:
[source]
----
template MyRec t_myrec := {i:=2,b:=false}
with {
  erroneous (i) “after := MyRec.i:123”
  erroneous (i) “before := MyInteger:123”
}
----

It is important to be able to specify the type of the inserted value because the encoding attributes are attached to the type. In the example above two integer values were inserted, both integers have the same value, however one has type MyRec.i and the other has type MyInteger, this will result in different encodings of the same value if the encoding attributes for the two types are different. In TTCN-3 the encoding attributes are specified using the with attribute syntax, in ASN.1 BER encoding the tagging specifies the encoding attributes. If no type is given then the compiler will use the default type if it can be determined.

For example:
[source]
----
erroneous (i) "value := 123"
----

NOTE: The compiler will use the integer type and NOT the MyRec.i type.

Both references to constant values and literal values can be used:
[source]
----
const MyRec c_myrec := {i:=3,b:=true}
template MyRec t_myrec := {i:=2,b:=false}
with {
  erroneous (i) “after := c_myrec” // type determined by the definition of c_myrec
  erroneous (i) “before := MyRec: {i:=4,b:=true}” // type must be specified
}
----
One or more field qualifiers must be used in the AttribQualifier part. If more than one field is specified, then the erroneous behavior will be attached to all specified fields, for example:
[source]
----
erroneous (i,b) "after := MyInteger:123"
----

In this case the value of 123 which has type MyInteger will be inserted both after field i and after field b.

The field qualifiers may reference any field at any depth inside a structured type that can have embedded other structured types. An example for ASN.1 types:
[source]
----
MyUnion ::= CHOICE { sof MySeqOf }
MySeqOf ::= SEQUENCE OF MySeq
MySeq ::= SEQUENCE { i INTEGER }
const MyUnion c_myunion := { … }
with { erroneous (sof[5].i) “value := 3.14” }
This also works in case of recursive types:
type record MyRRec { MyRRec r optional }
const MyRRec c_myrrec := { … }
with { erroneous (r.r.r.r.r) “value := omit” }
----

If the erroneous value does not contain a field which was referred by the erroneous qualifier then the erroneous behavior specified for that field will have no effect. For example:

[source]
----
type union MyUni { integer i, boolean b }
const MyUni c_myuni := { i:=11}
with {
  erroneous (i) “value := MyUni.i:22”
  erroneous (b) “value := MyUni.b:false” // this rule has no effect
}
----

The reason for allowing the second rule is that the erroneous information can be transferred by using assignment. By assigning an erroneous constant to a local variable in a testcase or function it can be used with variables too. For example:
[source]
----
function func() {
  var MyUni vl_myuni := c_myuni;
  vl_myuni.b := true;
  // now field b is selected in vl_myuni, therefore the erroneous rule on
  // field b will be active, the rule on field i will have no effect
}
----

The erroneous attribute data is attached to the defined constant or template and not to its fields. The fields of this erroneous constant or template do not contain any information on how they are erroneous; this information is attached to the top level. If a field is encoded on its own or is assigned to some other variable it will not contain any erroneous information. Example:
[source]
----
module Example1
{
type record R {
  integer i,
  R r optional
} with { encode "TEXT" variant "BEGIN('[BEGIN]')"; variant "END('[END]')"; variant "SEPARATOR('[*]')" }
external function encode_R( in R pdu) return charstring with { extension "prototype(convert) encode(TEXT)" }
const R r1 := { i:=1, r:={ i:=2, r:=omit } }
with { erroneous (r.i) "value:=3" }
control {
  log(encode_R(r1)); // output: "[BEGIN]1[*][BEGIN]3[END][END]"
  log(encode_R(r1.r)); // output: "[BEGIN]2[END]"
  // r1.r is not erroneous if used on its own!
}
}
----

Erroneous constants can be assigned to fields of other erroneous constants and templates, however if the original field or any field embedded in that field was made erroneous then the top level erroneous data will be used and the referenced constant’s erroneous data ignored. Erroneous data can be visualized as a tree that is a sub-tree of the tree of a type (in the examples the R type, which is recursive). If two erroneous sub-trees overlap then the one which was attached to the constant used as the value of that field where the overlapping happens will be ignored.

Example:
[source]
----
module Example2
{
type record R {
  integer i,
  R r optional
} with { encode "TEXT" variant "BEGIN('[BEGIN]')"; variant "END('[END]')"; variant "SEPARATOR('[*]')" }
external function encode_R( in R pdu) return charstring with { extension "prototype(convert) encode(TEXT)" }
const R r0 := { i:=0, r:=omit } with { erroneous (i) "value:=4" }
const R r1 := { i:=1, r:=r0 } with { erroneous (r.i) "value:=3" }
const R r2 := { i:=1, r:=r0 }
const R r3 := { i:=1, r:=r0 } with { erroneous (r.r) "value:=R:{i:=5,r:=omit}" }
control {
  log(encode_R(r0)); // output: "[BEGIN]4[END]"

  log(encode_R(r1)); // output: "[BEGIN]1[*][BEGIN]3[END][END]"
  // the value of r1.r.i is determined by the erroneous attribute of r1!

  log(encode_R(r2)); // output: "[BEGIN]1[*][BEGIN]4[END][END]"
  // the value of r2.r.i is determined by the erroneous attribute of r0

  log(encode_R(r3)); // output: "[BEGIN]1[*][BEGIN]0[*][BEGIN]5[END][END][END]"
  // the value of r3.r.i is 0, the erroneous attribute on r0.i was dropped because
  // when r0 is used as field r3.r then this r3.r field has embedded erroneous data
}
}
----

Meaning of IndicatorKeyword:

* `"before"`: the specified value will be inserted before the specified field(s)
* `"value"`: the specified value will be inserted instead of the value of the specified field(s)
* `"after"`: the specified value will be inserted after the specified field(s)

In case of unions only the "value" keyword can be used.

The optional "raw" keyword that can follow the IndicatorKeyword should be used when raw binary data has to be inserted instead of a value. The specified binary data will be inserted into the encoder’s output stream at the specified position. The specified data will not be checked in any way for correctness. For convenience this binary data can be specified using TTCN-3 constants as containers. For different encoding types the different containers are as follows:

[cols=",,,,,,,",options="header",]
|===
| |RAW |TEXT |XER |BER |JSON |PER (encoding not yet supported) |OER
|octetstring |X |X |X |X |X |X |X
|bitstring |X | | | | |X |
|charstring | |X |X | |X | |
|universal charstring | | |X | |X | |
|===

Bitstrings can be used for encoding types that support the insertion of not only whole octets but also bits. For example to insert one zero bit between two fields:

[source]
----
erroneous (i) "after(raw) := ‘0’B"
replace a field with bits 101:
erroneous (b) "value(raw) := ‘101’B"
----

Charstring types can be used in case of text based encodings. For example insert some XML string between two fields:
[source]
----
erroneous (i) "after(raw) := ""<ERROR>erroneous element</ERROR>"””
----

Notice that the double quotes surrounding the charstring must be doubled because it’s inside another string.

The optional "all" keyword after the TemplateInstance must be used when omitting all fields before or after a specified field, in all other cases it must not be used.

=== Typical Use Cases

Types used in the examples:
[source]
----
type record MyRec {
  integer i,
  boolean b,
  charstring s length (3),
  MyRec r optional
} with { encode “RAW” variant “ ….. “ }
type record of integer MyRecOf;
type MyRec.i MyInteger with { encode “RAW” variant “ ….. “ }
----

==== Discard Mandatory Fields

[source]
----
type record of integer IntList;
var IntList vl_myList := { 1, 2, 3 };
var IntList vl_emptyList := {};
replace(vl_myList, 1, 2, vl_emptyList); // returns { 1 }
replace(“abcdef”, 2, 1, “”); // returns “abdef”
replace(‘12FFF’H, 3, 2, ‘’H); // returns ‘12F’H
----

==== Insert New Fields

[source]
----
const MyRec c_myrec3 := { i:=1, b:=true, s:=”str”, r:=omit }
with {
  erroneous (i) “before := MyRec.i:3” // has same type as field i
  erroneous (b) “after := MyInteger:4”
}
const MyRecOf c_myrecof2 := { 1, 2, 3 }
with { erroneous ([1]) “after := MyRecOf[-]:99” }
----

==== Ignore Subtype Restrictions

[source]
----
const MyRec c_myrec4 := { i:=1, b:=true, s:=”str”, r:=omit }
with { erroneous (s) “value :=””too long string””” }
----

==== Change the Encoding of a Field

Here the TTCN-3 root type and value of field i are not changed but the encoding is changed:
[source]
----
const MyRec c_myrec5 := { i:=1, b:=true, s:=”str”, r:=omit }
with { erroneous (i) “value := MyInteger:1” }
----

==== Completely Change a Field to a Different Type and Value

The second field is changed from a boolean to an integer:
[source]
----
const MyRec c_myrec6 := { i:=1, b:=true, s:=”str”, r:=omit }
with { erroneous (b) “value := MyInteger:1” }
----

=== Summary

Main features of negative testing in TITAN:

* This feature is supported only by the Function Test runtime of TITAN; when doing negative testing this feature must be turned on using the *–R* switch to switch from the default Load Test runtime to the Function Test runtime

* Performance and functionality in case of positive testing is not affected by this feature

* Existing types can be used without modifications (both TTCN-3 and ASN.1 types)

* The erroneous attribute of a value or template does not modify its content, the erroneous feature of that value or template can be seen only when encoding or logging

* `ErroneousKeyword`, `IndicatorKeyword`, `RawKeyword` were not introduced as new keywords in TTCN-3, thus these can be used as identifiers, the compiler is backward compatible

* The erroneousness of a value is lost when sending it between components or using it as parameter of the start() function. In TTCN-3 sending and receiving of values is done by specifying the type of data, but the erroneous information is attached to a value and not the type, thus the receiving side cannot handle erroneous information.

=== Special Considerations for XML Encoding

There are a number of particularities related to negative testing of XML encoding.

* Inserted and replaced values are encoded using the normal XML encoding functions. These values are encoded as if they were top-level types: the name of the XML element is derived from the TTCN-3 or ASN.1 type name. For built-in types (e.g. integer, boolean, universal charstring) the XML name will be according to Table 4 at the end of clause 11.25 in X.680 (<<13-references.adoc#_6, [6]>>), usually the uppercased name of the type (e.g. INTEGER, BOOLEAN, UNIVERSAL_CHARSTRING). If a particular XML name is desired, an appropriate type alias can be defined.

For example, encoding the following value:

[source]
----
type record R { integer i }
const R c_r := { 42 } with { erroneous (i) “value := \“fourty-two\” ” }
----

will result in the following XML:

[source]
----
<R>
  <CHARSTRING>fourty-two</CHARSTRING>
</R>
----

To generate an XML element with a given name, e.g. "s", the following code can be used:

[source]
----
type record R { integer i }
type charstring s; // a type alias
const R c_r := { 42 } with { erroneous (i) “value := s : \“fourty-two\” ” }
----

The resulting XML will be (erroneous values highlighted in yellow):

[source,subs="+quotes"]
----
<R>
[yellow-background]#  <s>fourty-two</s>#
</R>
----

A `name as "…"` TTCN-3 attribute could also be used, but that also requires a separate type.

* By default, fields of ASN.1 SEQUENCE /TTCN-3 record are encoded as XML elements. Only those fields which have a `with { variant "attribute" }` TTCN-3 attribute applied are encoded as XML attributes. If a field having a `with { variant "attribute" }` has an erroneous value (`before/value/after`), this erroneous value will also be encoded amongst the XML attributes. However, by default the erroneous value will be encoded as an XML element; the resulting XML will not be well-formed:

[source,subs="+quotes"]
----
type record R2 {
  charstring at,
  charstring el
}
with { variant (at) “attribute” }

const R2 c_r2 := {
  at := “tack”, el := “le”
} with { erroneous (at) “before := 13 ” }
results in:

<R2[yellow-background]##<INTEGER>13</INTEGER>## at='tack'>
  <el>le</el>
</R2>
----

To ensure the erroneous value is encoded as an XML attribute, a TTCN-3 type alias can be created which also has a `with { variant "attribute" }` TTCN-3 attribute. The name of the XML attribute can also be controlled either with the name of the type or a name as `"…"` TTCN-3 attribute.

[source,subs="+quotes"]
----
// type record R2 as above
type integer newatt with { variant “attribute” } // type alias for integer

const R2 c_r2a := {
  at := “tack”, el := “le”
} with { erroneous (at) “before := newatt : 13 ” }

<R2 [yellow-background]##newatt='13'## at='tack'>
  <el>le</el>
</R2>
----

* One particularity of the Titan XML encoder is that the space before the name of an XML attribute "belongs" to that attribute (it is written together with the attribute name). If the field (encoded as an XML attribute) is omitted or replaced, the space will also be removed. If a well-formed XML output is desired, the loss of the space must be compensated when using raw erroneous values (non-raw erroneous values encoded as attributes will supply the space, as can be seen in the previous example).

[source,subs="+quotes"]
----
// type record R2 as above
const R2 c_r2r := {
  at := “tack”, el := “le”
} with { erroneous (at) “before(raw) := ""ax='xx'"" ” } // not compensated

<R2[yellow-background]##ax='xx'## at='tack'>
  <el>le</el>
</R2>
----

The resulting XML is not well formed.

[source,subs="+quotes"]
----
// type record R2 as above
const R2 c_r2r := {
  at := “tack”, el := “le”
} with { erroneous (at) “before(raw) := "" ax='xx'"" ” }
// compensated, note space here-----------^

<R2 [yellow-background]##ax='xx'# at='tack'>
  <el>le</el>
</R2>
----

Now the XML is well-formed.

* When using `"before := omit all"` or `"after := omit all"` on a member of a record which has a `with { variant "useOrder" }` TTCN-3 attribute, omit-before/omit-after refers to the order of the fields in the record, not the order in which they appear in the XML. In othe