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
use a2lmacros::a2l_specification;

use crate::a2ml;
use crate::writer;
use crate::tokenizer::A2lTokenType;
use crate::parser::{ParseContext, ParseError, ParserState};
use crate::ifdata;


/// Describes the location and formatting of an a2l block within a file
#[derive(PartialEq, Clone)]
pub struct BlockInfo<T> {
    pub incfile: Option<String>,
    pub line: u32,
    pub uid: u32,
    pub start_offset: u32,
    pub end_offset: u32,
    pub item_location: T
}


/// The trait A2lObject is implemented for all a2l objects as well as all objects generated by the a2ml_specification! macro.
/// It gives access to layout and location data which is tracked for each object in an a2l file.
pub trait A2lObject<T> {
    /// get a reference to the BlockInfo that describes the layout of the a2l object
    fn get_layout(&self) -> &BlockInfo<T>;

    /// get a mutable reference to the BlockInfo that describes the layout of the a2l object
    fn get_layout_mut(&mut self) -> &mut BlockInfo<T>;

    /// reset the location information on the a2l object. It will be treated like a new object when writing a file
    fn reset_location(&mut self);

    /// reset the reference to an include file on this objct and its children.
    /// This causes the object to be written into the output file instead of referenced through /include "filename"
    fn merge_includes(&mut self);

    /// get the source line number from which the current a2l object was loaded.
    /// Returns 0 if the object was newly created and not loaded from a file
    fn get_line(&self) -> u32;
}


/// The trait A2lObjectName is automatically implemented for named a2l objects
pub trait A2lObjectName {
    /// get the name of an a2l object.
    /// this trait is only implemented for those objects that have names, which is a subset of all objects
    fn get_name(&self) -> &str;
}


a2l_specification! {
    /// Contains all the objects of an A2lfile
    ///
    /// An instance of this struct is returned when an a2l file is loaded successfully
    keyword A2L_FILE {
        [-> ASAP2_VERSION]
        [-> A2ML_VERSION]   
        [-> PROJECT]!
    }

    /// Description of the addressing of table values or axis point values.
    ///
    /// Specification: predefined data types
    enum AddrType {
        PBYTE,
        PWORD,
        PLONG,
        PLONGLONG   (1.70 ..),
        DIRECT
    }

    /// Description of the word lengths in the ECU program.
    ///
    /// Specification: predefined data types (datasize)
    enum DataTypeSize {
        BYTE,
        WORD,
        LONG
    }

    /// Description of the basic data types in the ECU program.
    ///
    /// Specification: predefined data types
    enum DataType {
        UBYTE,
        SBYTE,
        UWORD,
        SWORD,
        ULONG,
        SLONG,
        A_UINT64       (1.60 ..),
        A_INT64        (1.60 ..),
        FLOAT16_IEEE   (1.71 ..),
        FLOAT32_IEEE,
        FLOAT64_IEEE
    }

    /// Description of the axis point sequence in the memory.
    ///
    /// Specification: predefined data types
    enum IndexOrder {
        INDEX_INCR,
        INDEX_DECR
    }

    /// Contains AML code for description of interface specific description data.
    ///
    /// Specification: 3.5.2
    block A2ML {
        // the A2ML block gets special treatment in the code generator based on the block name
    }

    /// A2ML_VERSION is currently ignored
    keyword A2ML_VERSION {
        uint version_no
        uint upgrade_no
    }

    /// Address of the EPROM identifier
    keyword ADDR_EPK {
        ulong address
    }

    
    /// Description of the addressing of table values or axis point values.
    keyword ADDRESS_TYPE {
        AddrType address_type
    }

    /// Defines the alignment of byte-sized values in complex objects (maps and axis)
    keyword ALIGNMENT_BYTE {
        uint alignment_border
    }

    /// Defines the alignment of 16bit floats in complex objects (maps and axis)
    keyword ALIGNMENT_FLOAT16_IEEE {
        uint alignment_border
    }

    /// Defines the alignment of 32bit floats in complex objects (maps and axis)
    keyword ALIGNMENT_FLOAT32_IEEE {
        uint alignment_border
    }

    /// Defines the alignment of 64bit floats in complex objects (maps and axis)
    keyword ALIGNMENT_FLOAT64_IEEE {
        uint alignment_border
    }

    /// Defines the alignment of int64 values in complex objects (maps and axis)
    keyword ALIGNMENT_INT64 {
        uint alignment_border
    }

    /// Defines the alignment of long-sized values in complex objects (maps and axis)
    keyword ALIGNMENT_LONG {
        uint alignment_border
    }

    /// Defines the alignment of word-sized values in complex objects (maps and axis)
    keyword ALIGNMENT_WORD {
        uint alignment_border
    }

    /// An extended description text
    ///
    /// One ANNOTATION may represent a voluminous description. Its purpose is to be e.g.
    /// an application note which explains the function of an identifier for the calibration
    /// engineer.
    block ANNOTATION {
        [-> ANNOTATION_LABEL]
        [-> ANNOTATION_ORIGIN]
        [-> ANNOTATION_TEXT]
    }

    /// The label or title of an annotation
    keyword ANNOTATION_LABEL {
        string label
    }

    /// Identify who or which system has created an annotation
    keyword ANNOTATION_ORIGIN {
        string origin
    }

    /// Text of an annotation
    ///
    /// One ANNOTATION_TEXT may represent a multi-line description text.
    block ANNOTATION_TEXT {
        {string annotation_text}* annotation_text_list
    }

    /// marks a measurement object as an array of <Number> measurement values
    /// 
    /// ARRAY_SIZE is obsolete: MATRIX_DIM should be used instead.
    keyword ARRAY_SIZE {
        uint number
    }

    /// describes the Autosar component type of a function
    keyword AR_COMPONENT {
        string component_type
        [-> AR_PROTOTYPE_OF]
    }

    /// Describes the resationship of the component type to to a component prototype in the Autosar system
    keyword AR_PROTOTYPE_OF {
        ident name
    }

    /// Version of the ASAM MCD-2MC standard used by this file
    ///
    /// This keyword is mandatory. Example:
    ///     ASAP2_VERSION 1 61
    keyword ASAP2_VERSION {
        uint version_no
        uint upgrade_no
    }

    /// Description of the axis points
    enum AxisDescrAttribute {
        CURVE_AXIS,
        COM_AXIS,
        FIX_AXIS,
        RES_AXIS,
        STD_AXIS
    }

    /// Axis description within an adjustable object
    block AXIS_DESCR {
        AxisDescrAttribute attribute
        ident input_quantity
        ident conversion
        uint max_axis_points
        float lower_limit
        float upper_limit
        [-> ANNOTATION]*
        [-> AXIS_PTS_REF]
        [-> BYTE_ORDER]
        [-> CURVE_AXIS_REF]
        [-> DEPOSIT]
        [-> EXTENDED_LIMITS]
        [-> FIX_AXIS_PAR]
        [-> FIX_AXIS_PAR_DIST]
        [-> FIX_AXIS_PAR_LIST]
        [-> FORMAT]
        [-> MAX_GRAD]
        [-> MONOTONY]
        [-> PHYS_UNIT]    (1.60 ..)
        [-> READ_ONLY]
        [-> STEP_SIZE]    (1.60 ..)
    }

    /// Parameters for the handling of an axis points distribution
    block AXIS_PTS {
        ident name
        string long_identifier
        ulong address
        ident input_quantity
        ident deposit_record
        float max_diff
        ident conversion
        uint max_axis_points
        float lower_limit
        float upper_limit
        [-> ANNOTATION]*
        [-> BYTE_ORDER]
        [-> CALIBRATION_ACCESS]
        [-> DEPOSIT]
        [-> DISPLAY_IDENTIFIER]
        [-> ECU_ADDRESS_EXTENSION]
        [-> EXTENDED_LIMITS]
        [-> FORMAT]
        [-> FUNCTION_LIST]
        [-> GUARD_RAILS]
        [-> IF_DATA]*
        [-> MAX_REFRESH]   (1.70 ..)
        [-> MODEL_LINK]    (1.70 ..)
        [-> MONOTONY]
        [-> PHYS_UNIT]     (1.60 ..)
        [-> READ_ONLY]
        [-> REF_MEMORY_SEGMENT]
        [-> STEP_SIZE]     (1.60 ..)
        [-> SYMBOL_LINK]
    }

    /// Reference to an AXIS_PTS record
    keyword AXIS_PTS_REF {
        ident axis_points
    }

    /// Description of the X, Y, Z, Z4 or Z5 axis points in memory
    keyword AXIS_PTS_X / _Y / _Z / _4 / _5 {
        uint position
        DataType datatype
        IndexOrder index_incr
        AddrType addressing
    }

    /// Description of rescaling the axis values of an adjustable object
    keyword AXIS_RESCALE_X /_Y /_Z / _4 / _5 {
        uint position
        DataType datatype
        uint max_number_of_rescale_pairs
        IndexOrder index_incr
        AddrType addressing
    }

    /// The BIT_MASK keyword can be used to mask out single bits of the value to be processed.
    keyword BIT_MASK {
        ulong mask
    }

    /// Used to perform bit operation on a value
    block BIT_OPERATION {
        [-> LEFT_SHIFT]
        [-> RIGHT_SHIFT]
        [-> SIGN_EXTEND]
    }

    /// Special data object that can be used to handle domain specific data, which are processed inside the ECU in a dedicated way
    /// 
    /// To the MCD system a blob is just an array of bytes without any interpretation
    block BLOB {
        ident name
        string long_identifier
        ulong start_address
        ulong size
        [-> ADDRESS_TYPE]
        [-> ANNOTATION]*
        [-> CALIBRATION_ACCESS]
        [-> DISPLAY_IDENTIFIER]
        [-> ECU_ADDRESS_EXTENSION]
        [-> IF_DATA]*
        [-> MAX_REFRESH]
        [-> MODEL_LINK]
        [-> SYMBOL_LINK]
    }

    /// Byte ordering of a value on the ECU
    enum ByteOrderEnum {
        LITTLE_ENDIAN        (.. 1.51),
        BIG_ENDIAN           (.. 1.51),
        MSB_LAST,
        MSB_FIRST,
        MSB_FIRST_MSW_LAST   (1.70 ..),
        MSB_LAST_MSW_FIRST   (1.70 ..)
    }

    /// Where the standard value does not apply this parameter can be used to specify the byte order
    ///
    /// Specification: 3.5.24
    keyword BYTE_ORDER {
        ByteOrderEnum byte_order
    }

    /// Type of access that is possible for a CHARACTERISTIC or AXIS_PTS object
    enum CalibrationAccessEnum {
        CALIBRATION,
        NO_CALIBRATION,
        NOT_IN_MCD_SYSTEM,
        OFFLINE_CALIBRATION
    }

    /// Specifies the access of a CHARACTERISTIC or AXIS_PTS for calibration
    keyword CALIBRATION_ACCESS {
        CalibrationAccessEnum calibration_access
    }

    /// calibration method specific data
    block CALIBRATION_HANDLE {
        {long handle}* handle_list
        [-> CALIBRATION_HANDLE_TEXT] (1.60 ..)
    }

    /// Additional text for a calibration handle
    ///
    /// Specification: 3.5.27
    keyword CALIBRATION_HANDLE_TEXT {
        string text
    }

    /// Indicates the different methods of access that are implemented in the ECU
    ///
    /// Valid method strings are: "InCircuit", "SERAM", "DSERAP", "BSERAP"
    block CALIBRATION_METHOD {
        string method
        ulong version
        [-> CALIBRATION_HANDLE]
    }

    /// Specifies the type of an adjustable object
    enum CharacteristicType {
        ASCII,
        CURVE,
        MAP,
        CUBOID,
        CUBE_4  (1.60 ..),
        CUBE_5  (1.60 ..),
        VAL_BLK,
        VALUE
    }

    /// Specifies all the parameters of an adjustable object
    block CHARACTERISTIC {
        ident name
        string long_identifier
        CharacteristicType characteristic_type
        ulong address
        ident deposit
        float max_diff
        ident conversion
        float lower_limit
        float upper_limit
        [-> ANNOTATION]*
        [-> AXIS_DESCR]*
        [-> BIT_MASK]
        [-> BYTE_ORDER]
        [-> CALIBRATION_ACCESS]
        [-> COMPARISON_QUANTITY]
        [-> DEPENDENT_CHARACTERISTIC]
        [-> DISCRETE]   (1.60 ..)
        [-> DISPLAY_IDENTIFIER]
        [-> ECU_ADDRESS_EXTENSION]
        [-> ENCODING]   (1.70 ..)
        [-> EXTENDED_LIMITS]
        [-> FORMAT]
        [-> FUNCTION_LIST]
        [-> GUARD_RAILS]
        [-> IF_DATA]*
        [-> MAP_LIST]
        [-> MATRIX_DIM]
        [-> MAX_REFRESH]
        [-> MODEL_LINK]  (1.70 ..)
        [-> NUMBER]      // (.. 1.51) - causes too many deprecation warnings in real files
        [-> PHYS_UNIT]   (1.60 ..)
        [-> READ_ONLY]
        [-> REF_MEMORY_SEGMENT]
        [-> STEP_SIZE]   (1.60 ..)
        [-> SYMBOL_LINK] (1.60 ..)
        [-> VIRTUAL_CHARACTERISTIC]
    }

    /// Specifies the coefficients for the formula f(x) = (axx + bx + c) / (dxx + ex + f)
    keyword COEFFS {
        float a
        float b
        float c
        float d
        float e
        float f
    }

    /// Specifies the coefficients for the linear formula f(x) = ax + b
    keyword COEFFS_LINEAR {
        float a
        float b
    }

    /// references a valid MEASUREMENT
    keyword COMPARISON_QUANTITY {
        ident name
    }

    /// Describes how to convert internal input values to physical values
    enum ConversionType {
        IDENTICAL  (1.60 ..),
        FORM,
        LINEAR  (1.60 ..),
        RAT_FUNC,
        TAB_INTP,
        TAB_NOINTP,
        TAB_VERB
    }

    /// Specification of a conversion method from internal values to physical values
    block COMPU_METHOD {
        ident name
        string long_identifier
        ConversionType conversion_type
        string format
        string unit
        [-> COEFFS]
        [-> COEFFS_LINEAR]
        [-> COMPU_TAB_REF]
        [-> FORMULA]
        [-> REF_UNIT]
        [-> STATUS_STRING_REF]    (1.60 ..)
    }

    /// Conversion table for conversions that cannot be represented as a function
    block COMPU_TAB {
        ident name
        string long_identifier
        ConversionType conversion_type
        uint number_value_pairs
        {
            float in_val
            float out_val
        }* tab_entry
        [-> DEFAULT_VALUE]
        [-> DEFAULT_VALUE_NUMERIC]  (1.60 ..)
    }

    /// reference to a conversion table
    keyword COMPU_TAB_REF {
        ident conversion_table
    }

    /// Conversion table for the assignment of display strings to values. Typically used for enums.
    block COMPU_VTAB {
        ident name
        string long_identifier
        ConversionType conversion_type
        uint number_value_pairs
        {
            float in_val
            string out_val
        }* value_pairs
        [-> DEFAULT_VALUE]
    }

    /// Conversion table for the assignment of display strings to a value range
    block COMPU_VTAB_RANGE {
        ident name
        string long_identifier
        uint number_value_triples
        {
            float in_val_min
            float in_val_max
            string out_val
        }* value_triples
        [-> DEFAULT_VALUE]
    }

    /// indicates that an instance of a structure should always be handled completely    
    keyword CONSISTENT_EXCHANGE {}

    /// CONVERSION is used inside OVERWRITE to override the default conversion method
    keyword CONVERSION {
        ident name
    }

    /// Identifies the CPU used in the ECU
    keyword CPU_TYPE {
        string cpu
    }

    /// Used to specify the adjustable CURVE CHARACTERISTIC that is used to normalize or scale the axis in an AXIS_DESCR
    keyword CURVE_AXIS_REF {
        ident curve_axis
    }

    /// Allows a customer name to be specified
    keyword CUSTOMER {
        string customer
    }

    /// specify a customer number or identifier as a string
    keyword CUSTOMER_NO {
        string number
    }

    /// Data size in bits
    keyword DATA_SIZE {
        uint size
    }

    /// Defines which adjustable objects are used by a FUNCTION
    block DEF_CHARACTERISTIC {
        { ident identifier }* identifier_list
    }

    /// Sets the default text value of COMPU_TAB, COMPU_VTAB or COMPU_VTAB_RANGE
    keyword DEFAULT_VALUE {
        string display_string
    }

    /// Sets the default numerical value of COMPU_TAB, COMPU_VTAB or COMPU_VTAB_RANGE
    keyword DEFAULT_VALUE_NUMERIC {
        float display_value
    }

    /// Specify characteristics that depend on a formula
    block DEPENDENT_CHARACTERISTIC {
        string formula
        {ident characteristic}* characteristic_list
    }

    /// Deposit of the axis points of a characteristic curve or map
    enum DepositMode {
        ABSOLUTE,
        DIFFERENCE
    }

    /// Specifies how the axis points of a characteristic are deposited in memory
    keyword DEPOSIT {
        DepositMode mode
    }

    /// Indicates that a measurement or calibration object has discrete values which should not be interpolated
    keyword DISCRETE {}

    /// Gives the display name of a CHARACTERISTIC or MEASUREMENT value
    keyword DISPLAY_IDENTIFIER {
        ident display_name
    }

    /// Description of the distance operand in the deposit structure to compute the axis points for fixed characteristic curves and fixed characteristic maps
    keyword DIST_OP_X / _Y / _Z / _4 / _5 {
        uint position
        DataType datatype
    }

    /// String for identification of the control unit.
    keyword ECU {
        string control_unit
    }

    /// Provides the address of a MEASUREMENT
    keyword ECU_ADDRESS {
        ulong address
    }

    /// Used to specify additional address information
    keyword ECU_ADDRESS_EXTENSION {
        int extension
    }

    /// Provide an address offset in order to handle near pointers or variant coding
    keyword ECU_CALIBRATION_OFFSET {
        long offset
    }

    /// Describes the encoding of a string, if it is not ASCII
    enum CharacterEncoding {
        UTF8,
        UTF16,
        UTF32
    }

    /// a CHARACTERISTIC of type ASCII can be configured to use a multi-byte encoding instead
    keyword ENCODING {
        CharacterEncoding encoding
    }

    /// EPROM identifier
    keyword EPK {
        string identifier
    }

    /// Used to mask bits of a MEASUREMENT which indicate that the value is in error
    keyword ERROR_MASK {
        ulong mask
    }

    /// used to specify an extended range of values
    keyword EXTENDED_LIMITS {
        float lower_limit
        float upper_limit
    }

    /// Parameters for the calculation of fixed axis points: X_i = Offset + (i - 1)*2^shift 
    keyword FIX_AXIS_PAR {
        int offset
        int shift
        uint number_apo
    }

    /// Parameters for the calculation of fixed axis points: X_i = Offset + (i - 1)*distance 
    keyword FIX_AXIS_PAR_DIST {
        int offset
        int distance
        uint number_apo
    }

    /// A list of fixed axis point, as implemented on the ECU
    block FIX_AXIS_PAR_LIST {
        { float axis_pts_value }* axis_pts_value_list
    }

    /// Specifies the number of axis points available to CURVE, MAP, CUBOID, CUBE_4 or CUBE_5
    keyword FIX_NO_AXIS_PTS_X / _Y / _Z / _4 / _5 {
        uint number_of_axis_points
    }

    /// Describes how the 2-dimensional table values are mapped onto the 1-dimensional address space
    enum IndexMode {
        ALTERNATE_CURVES,
        ALTERNATE_WITH_X,
        ALTERNATE_WITH_Y,
        COLUMN_DIR,
        ROW_DIR
    }

    /// Description of the table values (function values) of an adjustable object
    keyword FNC_VALUES {
        uint position
        DataType datatype
        IndexMode index_mode
        AddrType address_type
    }

    /// Allows a display format string to be specified for a MEASUREMENT, CHARACTERISTIC or AXIS_PTS object
    keyword FORMAT {
        string format_string
    }

    /// Allows any kind of formula to be specified
    block FORMULA {
        string fx
        [-> FORMULA_INV]
    }

    /// Allows an inverse formula to be specified
    keyword FORMULA_INV {
        string gx
    }

    /// Defines a function frame to structure large amounts of measurement objects
    block FRAME {
        ident name
        string long_identifier
        uint scaling_unit
        ulong rate
        [-> FRAME_MEASUREMENT]
        [-> IF_DATA]*
    }

    /// Contains a list of identifiers of measurement objects
    keyword FRAME_MEASUREMENT {
        { ident identifier}* identifier_list
    }

    /// Describes the input, local, and output variables of a function on the ECU
    block FUNCTION {
        ident name
        string long_identifier
        [-> ANNOTATION]*
        [-> AR_COMPONENT]   (1.70 ..)
        [-> DEF_CHARACTERISTIC]
        [-> FUNCTION_VERSION]
        [-> IF_DATA]*    (1.60 ..)
        [-> IN_MEASUREMENT]
        [-> LOC_MEASUREMENT]
        [-> OUT_MEASUREMENT]
        [-> REF_CHARACTERISTIC]
        [-> SUB_FUNCTION]
    }

    /// a list of FUNCTION objects
    block FUNCTION_LIST {
        {ident name}* name_list
    }

    /// A string containing the version of a FUNCTION
    keyword FUNCTION_VERSION {
        string version_identifier
    }

    /// Defines a group of releated CHARACTERISTIC and MEASUREMENT objects
    block GROUP {
        ident name
        string long_identifier
        [-> ANNOTATION]*
        [-> FUNCTION_LIST]
        [-> IF_DATA]*     (1.60 ..)
        [-> REF_CHARACTERISTIC]
        [-> REF_MEASUREMENT]
        [-> ROOT]
        [-> SUB_GROUP]
    }

    /// Used to indicate that an adjustable CURVE, MAP or AXIS_PTS uses guard rails
    keyword GUARD_RAILS {}

    /// The header of a project
    block HEADER {
        string comment
        [-> PROJECT_NO]
        [-> VERSION]
    }

    /// used to describe that an 'identifier' is deposited in a specific position in the adjustable object
    keyword IDENTIFICATION {
        uint position
        DataType datatype
    }

    /// Interface specific data
    block IF_DATA {
        // the A2ML block gets special treatment in the code generator based on the block name
    }

    /// A list of measurement objects that are used as the inputs of a function
    block IN_MEASUREMENT {
        {ident identifier}* identifier_list
    }

    ///INPUT_QUANTITY is used inside OVERWRITE to override the input_quantity of an INSTANCE
    keyword INPUT_QUANTITY {
        ident name
    }

    /// Creates an instance of a type defined using TYPEDEF_STRUCTURE, TYPEDEF_MEASUREMENT or TYPEDEF_CHARACTERISTIC
    block INSTANCE {
        ident name
        string long_identifier
        ident type_ref
        ulong start_address
        [-> ADDRESS_TYPE]  (1.71 ..)
        [-> ANNOTATION]*
        [-> CALIBRATION_ACCESS]
        [-> DISPLAY_IDENTIFIER]
        [-> ECU_ADDRESS_EXTENSION]
        [-> IF_DATA]*
        [-> LAYOUT]
        [-> MATRIX_DIM]
        [-> MAX_REFRESH]
        [-> MODEL_LINK]
        [-> OVERWRITE]*
        [-> READ_ONLY]
        [-> SYMBOL_LINK]
    }

    /// describes the layout of a multi-dimensional measurement array
    keyword LAYOUT {
        IndexMode index_mode
    }

    /// Used within BIT_OPERATION to left-shift the bits of a value
    keyword LEFT_SHIFT {
        ulong bitcount
    }

    /// LIMITS is used inside OVERWRITE to override the limits of an INSTANCE
    keyword LIMITS {
        float lower_limit
        float upper_limit
    }

    /// A list of measurement objects that are local variables of a function
    block LOC_MEASUREMENT {
        {ident identifier}* identifier_list
    }

    /// used to specify the list of MAPs which comprise a CUBOID
    block MAP_LIST {
        {ident name}* name_list
    }

    /// describes the dimensions of a multidimensional array of values
    keyword MATRIX_DIM {
        {uint dim}* dim_list // note: changed for 1.70
    }

    /// specifies a maximum permissible gradient for an adjustable object
    keyword MAX_GRAD {
        float max_gradient
    }

    /// specifies the maximum refresh rate in the control unit
    keyword MAX_REFRESH {
        uint scaling_unit
        ulong rate
    }

    /// describes the parameters for a measurement object
    block MEASUREMENT {
        ident name
        string long_identifier
        DataType datatype
        ident conversion
        uint resolution
        float accuracy
        float lower_limit
        float upper_limit
        [-> ADDRESS_TYPE] (1.70 ..)
        [-> ANNOTATION]*
        [-> ARRAY_SIZE] (.. 1.51)
        [-> BIT_MASK]
        [-> BIT_OPERATION]
        [-> BYTE_ORDER]
        [-> DISCRETE]  (1.60 ..)
        [-> DISPLAY_IDENTIFIER]
        [-> ECU_ADDRESS]
        [-> ECU_ADDRESS_EXTENSION]
        [-> ERROR_MASK]
        [-> FORMAT]
        [-> FUNCTION_LIST]
        [-> IF_DATA]*
        [-> LAYOUT]   (1.60 ..)
        [-> MATRIX_DIM]
        [-> MAX_REFRESH]
        [-> MODEL_LINK] (1.70 ..)
        [-> PHYS_UNIT]   (1.60 ..)
        [-> READ_WRITE]
        [-> REF_MEMORY_SEGMENT]
        [-> SYMBOL_LINK]   (1.60 ..)
        [-> VIRTUAL]
    }

    /// describes the types of program segments
    enum ProgType {
        PRG_CODE,
        PRG_DATA,
        PRG_RESERVED
    }

    /// describes the layout of the ECU memory
    block MEMORY_LAYOUT {
        ProgType prog_type
        ulong address
        ulong size
        long[5] offset
        [-> IF_DATA]*
    }

    /// Describes the types of data in the ECU program
    enum PrgType {
        CALIBRATION_VARIABLES,
        CODE,
        DATA,
        EXCLUDE_FROM_FLASH,
        OFFLINE_DATA,
        RESERVED,
        SERAM,
        VARIABLES
    }

    /// describes the type of memory used
    enum MemoryType {
        EEPROM,
        EPROM,
        FLASH,
        RAM,
        ROM,
        REGISTER,
        NOT_IN_ECU   (1.70 ..)
    }

    /// specifies if a given memory region is internal or external
    enum MemoryAttribute {
        INTERN,
        EXTERN
    }

    /// describes a memory segment of the ECU program
    block MEMORY_SEGMENT {
        ident name
        string long_identifier
        PrgType prg_type
        MemoryType memory_type
        MemoryAttribute attribute
        ulong address
        ulong size
        long[5] offset
        [-> IF_DATA]*
    }

    /// defines default values for the  entire module
    block MOD_COMMON {
        string comment
        [-> ALIGNMENT_BYTE]
        [-> ALIGNMENT_FLOAT16_IEEE]   (1.71 ..)
        [-> ALIGNMENT_FLOAT32_IEEE]
        [-> ALIGNMENT_FLOAT64_IEEE]
        [-> ALIGNMENT_INT64]    (1.60 ..)
        [-> ALIGNMENT_LONG]
        [-> ALIGNMENT_WORD]
        [-> BYTE_ORDER]
        [-> DATA_SIZE]
        [-> DEPOSIT]
        [-> S_REC_LAYOUT] (.. 1.60) // deprecated in 1.61: RECORD_LAYOUT is always mandatory
    }

    /// defines system information and management data for the module
    block MOD_PAR {
        string comment
        [-> ADDR_EPK]*
        [-> CALIBRATION_METHOD]*
        [-> CPU_TYPE]
        [-> CUSTOMER]
        [-> CUSTOMER_NO]
        [-> ECU]
        [-> ECU_CALIBRATION_OFFSET]
        [-> EPK]
        [-> MEMORY_LAYOUT]*
        [-> MEMORY_SEGMENT]*
        [-> NO_OF_INTERFACES]
        [-> PHONE_NO]
        [-> SUPPLIER]
        [-> SYSTEM_CONSTANT]*
        [-> USER]
        [-> VERSION]
    }

    /// add a string to a CHARACTERISTIC linking it to a name in the model
    keyword MODEL_LINK {
        string model_link
    }

    /// The MODULE keyword describes a complete ECU or device with all adjustable and measurement objects, conversion methods and functions
    ///
    /// At least one module must be defined within the PROJECT
    block MODULE {
        ident name
        string long_identifier
        [-> A2ML]
        [-> AXIS_PTS]*
        [-> BLOB]*                     (1.70 ..)
        [-> CHARACTERISTIC]*
        [-> COMPU_METHOD]*
        [-> COMPU_TAB]*
        [-> COMPU_VTAB]*
        [-> COMPU_VTAB_RANGE]*
        [-> FRAME]*
        [-> FUNCTION]*
        [-> GROUP]*
        [-> IF_DATA]*
        [-> INSTANCE]*                 (1.70 ..)
        [-> MEASUREMENT]*
        [-> MOD_COMMON]
        [-> MOD_PAR]
        [-> RECORD_LAYOUT]*
        [-> TRANSFORMER]*              (1.70 ..)
        [-> TYPEDEF_AXIS]*             (1.70 ..)
        [-> TYPEDEF_BLOB]*             (1.70 ..)
        [-> TYPEDEF_CHARACTERISTIC]*   (1.70 ..)
        [-> TYPEDEF_MEASUREMENT]*      (1.70 ..)
        [-> TYPEDEF_STRUCTURE]*        (1.70 ..)
        [-> UNIT]*
        [-> USER_RIGHTS]*
        [-> VARIANT_CODING]
    }

    /// describes the possible ways an adjustment object can be monotonous
    enum MonotonyType {
        MON_DECREASE,
        MON_INCREASE,
        STRICT_DECREASE,
        STRICT_INCREASE,
        MONOTONOUS    (1.60 ..),
        STRICT_MON    (1.60 ..),
        NOT_MON       (1.60 ..)
    }


    /// specifies the monotony of an adjustment object
    keyword MONOTONY {
        MonotonyType monotony
    }

    /// Description of the number of axis points in an adjustable object
    keyword NO_AXIS_PTS_X / _Y / _Z / _4 / _5 {
        uint position
        DataType datatype
    }

    /// the number of interfaces
    keyword NO_OF_INTERFACES {
        uint num
    }

    /// number of rescaling axis point value pairs
    keyword NO_RESCALE_X / _Y / _Z / _4 / _5 {
        uint position
        DataType datatype
    }

    /// specifies the number of values in an array. Obsolete, replaced by MATRIX_DIM
    keyword NUMBER {
        uint number
    }

    /// Description of the 'offset' parameter in the deposit structure
    keyword OFFSET_X / _Y / _Z / _4 / _5 {
        uint position
        DataType datatype
    }

    /// defines output quantities of a function
    block OUT_MEASUREMENT {
        {ident identifier}* identifier_list
    }

    /// override some default attributes of a type definition in a specific INSTANCE.
    keyword OVERWRITE {
        ident name
        ulong axis_number
        [-> CONVERSION]
        [-> EXTENDED_LIMITS]
        [-> FORMAT]
        [-> INPUT_QUANTITY]
        [-> LIMITS]
        [-> MONOTONY]
        [-> PHYS_UNIT]
    }

    /// contains a phone number, e.g. of the calibration engineer
    keyword PHONE_NO {
        string telnum
    }

    /// specifies the physical unit of a measurement or calibration object as a string
    keyword PHYS_UNIT {
        string unit
    }

    /// Project description with project header and all modules belonging to the project. Required.
    block PROJECT {
        ident name
        string long_identifier
        [-> HEADER]
        [-> MODULE]+
    }

    /// Gives the project identifier
    keyword PROJECT_NO {
        ident project_number
    }

    /// used to indicate that an adjustable object is read-only
    keyword READ_ONLY {}

    /// used to indicate that a measurement object is writeable
    keyword READ_WRITE {}

    /// specifies the various data structures of an adjustable objects in memory
    block RECORD_LAYOUT {
        ident name
        [-> ALIGNMENT_BYTE]
        [-> ALIGNMENT_FLOAT16_IEEE]  (1.71 ..)
        [-> ALIGNMENT_FLOAT32_IEEE]
        [-> ALIGNMENT_FLOAT64_IEEE]
        [-> ALIGNMENT_INT64]
        [-> ALIGNMENT_LONG]
        [-> ALIGNMENT_WORD]
        [-> AXIS_PTS_X/_Y/_Z/_4/_5]
        [-> AXIS_RESCALE_X/_Y/_Z/_4/_5]
        [-> DIST_OP_X/_Y/_Z/_4/_5]
        [-> FIX_NO_AXIS_PTS_X/_Y/_Z/_4/_5]
        [-> FNC_VALUES]
        [-> IDENTIFICATION]
        [-> NO_AXIS_PTS_X/_Y/_Z/_4/_5]
        [-> NO_RESCALE_X/_Y/_Z/_4/_5]
        [-> OFFSET_X/_Y/_Z/_4/_5]
        [-> RESERVED]*
        [-> RIP_ADDR_W/_X/_Y/_Z/_4/_5]
        [-> SRC_ADDR_X/_Y/_Z/_4/_5]
        [-> SHIFT_OP_X/_Y/_Z/_4/_5]
        [-> STATIC_RECORD_LAYOUT]    (1.60 ..)
        [-> STATIC_ADDRESS_OFFSETS]  (1.70 ..)
    }

    /// defines a list of adjustable objects that can be referenced by a function or group
    block REF_CHARACTERISTIC {
        { ident identifier}* identifier_list
    }

    /// defines a list of groups for use by USER_RIGHTS
    block REF_GROUP {
        { ident identifier}* identifier_list
    }

    /// defines a list of measurement objects that can be referenced by a group
    block REF_MEASUREMENT {
        { ident identifier}* identifier_list
    }

    /// reference to a MEMORY_SEGMENT
    block REF_MEMORY_SEGMENT {
        ident name
    }

    /// reference to a UNIT
    block REF_UNIT {
        ident unit
    }

    /// indicates that the data at the given position is reserved and should not be interpreted by the MCD system
    keyword RESERVED {
        uint position
        DataTypeSize data_size
    }

    /// Used within BIT_OPERATION to right-shift the bits of a value
    keyword RIGHT_SHIFT {
        ulong bitcount
    }

    /// Describes the storage of the ECU-internal result of interpolation (RIP)
    keyword RIP_ADDR_W / _X / _Y / _Z / _4 / _5 {
        uint position
        DataType datatype
    }
    
    /// indicates that the current group is at the root of the navigation tree
    keyword ROOT {}

    /// Description of the shift operand in the deposit structure to compute the axis points for fixed characteristic curves and fixed characteristic maps
    keyword SHIFT_OP_X / _Y / _Z / _4 / _5 {
        uint position
        DataType datatype
    }
    
    /// used in BIT_OPERATION to specify that sign extension should be performed
    keyword SIGN_EXTEND {}

    /// the seven base dimensions required to define an extended SI unit
    keyword SI_EXPONENTS {
        int length
        int mass
        int time
        int electric_current
        int temperature
        int amount_of_substance
        int luminous_intensity
    }

    /// Description of the address of the input quantity in an adjustable object
    keyword SRC_ADDR_X / _Y / _Z / _4 / _5 {
        uint position
        DataType datatype
    }

    /// indicates that the start addresses of axes and function values of an adjustable object do not change when removing or inserting axis points
    keyword STATIC_ADDRESS_OFFSETS {}

    /// indicates that an adjustable object with dynamic number of axis points does not compact or expand data when removing or inserting axis points
    keyword STATIC_RECORD_LAYOUT {}

    /// used to split up the value range of ECU internal values into a numerical and a verbal part
    keyword STATUS_STRING_REF {
        ident conversion_table
    }

    /// step size when adjusting the value of a CHARACTERISTIC, AXIS_PTS or AXIS_DESCR
    keyword STEP_SIZE {
        float step_size
    }

    /// defines a single component of a TYPEDEF_STRUCTURE
    block STRUCTURE_COMPONENT {
        ident component_name
        ident component_type
        ulong size
        [-> ADDRESS_TYPE]  (1.71 ..)
        [-> LAYOUT]
        [-> MATRIX_DIM]
        [-> SYMBOL_TYPE_LINK]
    }

    /// a list of identifiers of functions which are sub-functions of the current function
    block SUB_FUNCTION {
        { ident identifier}* identifier_list
    }

    /// a list of identifiers of groups which are subgroups of the current group
    block SUB_GROUP {
        { ident identifier}* identifier_list
    }

    /// Name of the ECU manufacturer
    keyword SUPPLIER {
        string manufacturer
    }

    /// specifes the name of a symbol within a linker map file that corresponds to the a2l object
    keyword SYMBOL_LINK {
        string symbol_name
        long offset
    }

    /// Specifies the name of a symbol within a linker map file or debug file that describes a class, class member, structure or structure component
    keyword SYMBOL_TYPE_LINK {
        string symbol_type
    }

    /// defines a system constant that can be used in conversion formulas
    keyword SYSTEM_CONSTANT {
        string name
        string value
    }

    /// sets the standard record layout for the module
    keyword S_REC_LAYOUT {
        ident name
    }

    /// the trigger conditions of a TRANSFORMER
    enum TransformerTrigger {
        ON_USER_REQUEST,
        ON_CHANGE
    }

    /// Definition of call to an external function (32-bit or 64-bit DLL) for converting calibration object values between their implementation format and physical format
    block TRANSFORMER {
        ident name
        string version
        string dllname_32bit
        string dllname_64bit
        uint timeout
        TransformerTrigger trigger
        ident inverse_transformer
        [-> TRANSFORMER_IN_OBJECTS]
        [-> TRANSFORMER_OUT_OBJECTS]
    }

    /// provides a list of inputs for a TRANSFORMER
    block TRANSFORMER_IN_OBJECTS {
        {ident identifier}* identifier_list
    }

    /// provides a list of outputs for a TRANSFORMER
    block TRANSFORMER_OUT_OBJECTS {
        {ident identifier}* identifier_list
    }

    /// Type definition of an axis object
    block TYPEDEF_AXIS {
        ident name
        string long_identifier
        ident input_quantity
        ident record_layout
        float max_diff
        ident conversion
        uint max_axis_points
        float lower_limit
        float upper_limit
        [-> BYTE_ORDER]
        [-> DEPOSIT]
        [-> EXTENDED_LIMITS]
        [-> FORMAT]
        [-> MONOTONY]
        [-> PHYS_UNIT]
        [-> STEP_SIZE]
    }

    /// Type definition of a BLOB
    block TYPEDEF_BLOB {
        ident name
        string long_identifier
        ulong size
        [-> ADDRESS_TYPE]  (1.71 ..)
    }

    /// Type definition of a calibration object
    block TYPEDEF_CHARACTERISTIC {
        ident name
        string long_identifier
        CharacteristicType characteristic_type
        ident record_layout
        float max_diff
        ident conversion
        float lower_limit
        float upper_limit
        [-> AXIS_DESCR]*
        [-> BIT_MASK]
        [-> BYTE_ORDER]
        [-> DISCRETE]
        [-> ENCODING]
        [-> EXTENDED_LIMITS]
        [-> FORMAT]
        [-> MATRIX_DIM]
        [-> NUMBER]
        [-> PHYS_UNIT]
        [-> STEP_SIZE]
    }

    /// Type definition of a measurement object
    block TYPEDEF_MEASUREMENT {
        ident name
        string long_identifier
        DataType datatype
        ident conversion
        uint resolution
        float accuracy
        float lower_limit
        float upper_limit
        [-> ADDRESS_TYPE]
        [-> BIT_MASK]
        [-> BIT_OPERATION]
        [-> BYTE_ORDER]
        [-> DISCRETE]
        [-> ERROR_MASK]
        [-> FORMAT]
        [-> LAYOUT]
        [-> MATRIX_DIM]
        [-> PHYS_UNIT]
    }

    /// Definition of structured data types similar to the "typedef" command in C
    block TYPEDEF_STRUCTURE {
        ident name
        string long_identifier
        ulong total_size
        [-> ADDRESS_TYPE]
        [-> CONSISTENT_EXCHANGE]
        [-> STRUCTURE_COMPONENT]*
        [-> SYMBOL_TYPE_LINK]
    }

    /// Type of the UNIT
    enum UnitType {
        DERIVED,
        EXTENDED_SI
    }

    /// Specification of a measurement unit
    block UNIT {
        ident name
        string long_identifier
        string display
        UnitType unit_type
        [-> REF_UNIT]
        [-> SI_EXPONENTS]
        [-> UNIT_CONVERSION]
    }

    /// Specification of the linear relationship between two measurement units
    keyword UNIT_CONVERSION {
        float gradient
        float offset
    }

    /// Name of the user
    keyword USER {
        string user_name
    }

    /// used to define groups accessible only for certain users
    block USER_RIGHTS {
        ident user_level_id
        [-> READ_ONLY]
        [-> REF_GROUP]*
    }

    /// define a list of start addresses of variant coded adjustable objects
    block VAR_ADDRESS {
        { ulong address}* address_list
    }

    /// defines one adjustable object to be variant coded
    block VAR_CHARACTERISTIC {
        ident name
        { ident criterion_name }* criterion_name_list
        [-> VAR_ADDRESS]
    }

    /// describes a variant criterion
    block VAR_CRITERION {
        ident name
        string long_identifier
        {ident  value}* value_list
        [-> VAR_MEASUREMENT]
        [-> VAR_SELECTION_CHARACTERISTIC]
    }

    /// describes a forbidden combination of values of different variant criteria
    block VAR_FORBIDDEN_COMB {
        {
            ident criterion_name
            ident criterion_value
        }* combination
    }

    /// specify a special measurement object which indicates the currently active variant
    keyword VAR_MEASUREMENT {
        ident name
    }

    /// intended to define the format of the variant extension. Currently only one format is supported
    enum VarNamingTag {
        NUMERIC
    }

    /// defines the format of the variant extension (index) of adjustable object names
    keyword VAR_NAMING {
        VarNamingTag tag
    }

    /// used to specify a special characteristic object which can change the currently active variant
    keyword VAR_SELECTION_CHARACTERISTIC {
        ident name
    }

    /// defines the separating symbol between the two parts of an adjustable object name
    keyword VAR_SEPARATOR {
        string separator
    }

    /// All information related to variant coding is grouped in this structure
    block VARIANT_CODING {
        [-> VAR_CHARACTERISTIC]*
        [-> VAR_CRITERION]*
        [-> VAR_FORBIDDEN_COMB]*
        [-> VAR_NAMING]
        [-> VAR_SEPARATOR]
    }

    /// version identifier
    keyword VERSION {
        string version_identifier
    }

    /// specification of the measurement objects for a virtual measurement channel
    block VIRTUAL {
        { ident measuring_channel }* measuring_channel_list
    }

    /// defines characteristics that are not deposited in the memory of the control unit, but can be used to indirectly calibrate other characteristic values
    block VIRTUAL_CHARACTERISTIC {
        string formula
        {ident characteristic }* characteristic_list
    }
}


/// A2ML is a special case in the specification.
/// It contains the ASAP2 metalanguage code that describes the content of IF_DATA blocks
#[derive(Clone)]
pub struct A2ml {
    pub a2ml_text: String,
    pub(crate) __block_info: BlockInfo<(u32, ())>
}

impl std::fmt::Debug for A2ml {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("A2ml")
        .field("a2ml_text", &self.a2ml_text)
        .finish()
    }
}

impl A2ml {
    pub fn new(a2ml_text: String) -> Self {
        Self {
            a2ml_text,
            __block_info: BlockInfo {
                incfile: None,
                line: 0,
                uid: 0,
                start_offset: 1,
                end_offset: 1,
                item_location: (0, ())
            }
        }
    }

    pub(crate) fn parse(parser: &mut ParserState, context: &ParseContext, start_offset: u32) -> Result<Self, ParseError> {
        let fileid = parser.get_incfilename(context.fileid);
        let line = context.line;
        let uid = parser.get_next_id();

        let __a2ml_text_location = parser.get_current_line_offset();
        let token = parser.expect_token(context, A2lTokenType::String)?;
        let a2ml_text = parser.get_token_text(token).to_string();

        match a2ml::parse_a2ml(&a2ml_text) {
            Ok(a2mlspec) => parser.file_a2mlspec = Some(a2mlspec),
            Err(errmsg) => parser.error_or_log(ParseError::A2mlError(errmsg))?,
        }

        parser.expect_token(context, A2lTokenType::End)?;
        let ident = parser.get_identifier(context)?;
        if ident != "A2ML" {
            parser.error_or_log(ParseError::IncorrectEndTag(context.clone(), ident))?;
        }

        Ok(A2ml {
            a2ml_text,
            __block_info: BlockInfo {
                incfile: fileid,
                line,
                uid,
                start_offset,
                end_offset: 1, // the real offset is more difficult to calculate, because the a2ml text is the only multi-line element
                item_location: (__a2ml_text_location, ())
            }
        })
    }

    pub(crate) fn stringify(&self, indent: usize) -> String {
        let mut writer = writer::Writer::new(indent);
        // force the a2ml string to use only "\n" instead of (potentially) "\r\n" to conform with all the other output
        let text_fixed = self.a2ml_text.split("\r\n").collect::<Vec<&str>>().join("\n");
        writer.add_str(&text_fixed, self.__block_info.item_location.0);
        writer.finish()
    }
}

impl A2lObject<(u32, ())> for A2ml {
    fn get_layout(&self) -> &BlockInfo<(u32, ())> {
        &self.__block_info
    }

    fn get_layout_mut(&mut self) -> &mut BlockInfo<(u32, ())> {
        &mut self.__block_info
    }

    // clear the location info (include filename and uid) of an object
    // unlike merge_includes() this function does not operate recursively
    fn reset_location(&mut self) {
        self.merge_includes();
        self.__block_info.uid = 0;
    }

    fn merge_includes(&mut self) {
        self.__block_info.incfile = None;
    }

    fn get_line(&self) -> u32 {
        self.__block_info.line
    }
}

// manual implementation of PartialEq that ignores __block_info: the layout/location doesn't matter when testing equality
impl PartialEq for A2ml {
    fn eq(&self, other: &Self) -> bool {
        self.a2ml_text == other.a2ml_text
    }
}


/// The content of IF_DATA blocks is not directly described in the specification.
/// Instead the content description is provided at runtime through the A2ML block.
#[derive(Clone)]
pub struct IfData {
    /// contains the content of the IF_DATA in generic form
    pub ifdata_items: Option<a2ml::GenericIfData>,
    /// ifdata_valid indicates if the data matched an A2ML specification during parsing or not
    pub ifdata_valid: bool,
    pub(crate) __block_info: BlockInfo<()>
}

impl std::fmt::Debug for IfData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IfData")
        .field("ifdata_items", &self.ifdata_items)
        .finish()
    }
}


impl IfData {
    pub fn new() -> Self {
        Self {
            ifdata_items: None,
            ifdata_valid: false,
            __block_info: BlockInfo {
                incfile: None,
                line: 0,
                uid: 0,
                start_offset: 1,
                end_offset: 1,
                item_location: ()
            }
        }
    }

    pub(crate) fn parse(parser: &mut ParserState, context: &ParseContext, start_offset: u32) -> Result<Self, ParseError> {
        let fileid = parser.get_incfilename(context.fileid);
        let line = context.line;
        let uid = parser.get_next_id();

        let (ifdata_items, ifdata_valid) = ifdata::parse_ifdata(parser, context)?;

        let end_offset = parser.get_current_line_offset();
        parser.expect_token(context, A2lTokenType::End)?;
        let ident = parser.get_identifier(context)?;
        if ident != "IF_DATA" {
            parser.error_or_log(ParseError::IncorrectEndTag(context.clone(), ident))?;
        }

        Ok(IfData {
            ifdata_items,
            ifdata_valid,
            __block_info: BlockInfo {
                incfile: fileid,
                line,
                uid,
                start_offset,
                end_offset,
                item_location: ()
            }
        })
    }

    pub(crate) fn stringify(&self, indent: usize) -> String {
        if let Some(ifdata_items) = &self.ifdata_items {
            // ifdata items were wrapped in an extra layer that would cause a double indent in the output
            ifdata_items.write(indent - 1)
        } else {
            "".to_string()
        }
    }
}

impl A2lObject<()> for IfData {
    fn get_layout(&self) -> &BlockInfo<()> {
        &self.__block_info
    }

    fn get_layout_mut(&mut self) -> &mut BlockInfo<()> {
        &mut self.__block_info
    }

    // clear the location info (include filename and uid) of an object
    // unlike merge_includes() this function does not operate recursively
    fn reset_location(&mut self) {
        self.merge_includes();
        self.__block_info.uid = 0;
    }

    fn merge_includes(&mut self) {
        self.__block_info.incfile = None;
        if let Some(ifdata_items) = &mut self.ifdata_items {
            // ifdata_items is an un-decoded GenericIfData. It can directly handle merge_includes()
            ifdata_items.merge_includes();
        }
    }

    fn get_line(&self) -> u32 {
        self.__block_info.line
    }
}

// manual implementation of PartialEq that ignores __block_info: the layout/location doesn't matter when testing equality
impl PartialEq for IfData {
    fn eq(&self, other: &Self) -> bool {
        self.ifdata_items == other.ifdata_items
    }
}