a2lfile 3.4.0

read, modify and write a2l files
Documentation
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
use num_traits::{AsPrimitive, Num};
use std::fmt::Display;
use thiserror::Error;

use crate::a2ml::A2mlTypeSpec;
use crate::tokenizer::{A2lToken, A2lTokenType, TokenResult};
use crate::{A2lError, Filename, ParseableA2lObject};

const MAX_IDENT: usize = 1024;

struct TokenIter<'a> {
    tokens: &'a [A2lToken],
    pos: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum A2lVersion {
    V1_5_0,
    V1_5_1,
    V1_6_0,
    V1_6_1,
    V1_7_0,
    V1_7_1,
}

pub struct ParserState<'a> {
    token_cursor: TokenIter<'a>,
    filedata: &'a [String],
    pub(crate) filenames: &'a [Filename],
    pub(crate) last_token_position: u32,
    sequential_id: u32,
    pub(crate) log_msgs: &'a mut Vec<A2lError>,
    strict: bool,
    file_ver: A2lVersion,
    pub(crate) a2mlspec: Vec<A2mlTypeSpec>,
}

/// describes the current parser context, giving the name of the current element and its file and line number
#[derive(Debug, Clone)]
pub struct ParseContext {
    pub element: String,
    pub fileid: usize,
    pub line: u32,
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ParserError {
    #[error(
        "{filename}:{error_line}: expected token of type {expected_ttype:?}, got {actual_ttype:?} (\"{actual_text}\") inside block {element} starting on line {block_line}"
    )]
    UnexpectedTokenType {
        filename: String,
        error_line: u32,
        block_line: u32,
        element: String,
        actual_ttype: A2lTokenType,
        actual_text: String,
        expected_ttype: A2lTokenType,
    },

    #[error("{filename}:{error_line}: string \"{numstr}\" could not be interpreted as a number")]
    MalformedNumber {
        filename: String,
        error_line: u32,
        numstr: String,
    },

    #[error(
        "{filename}:{error_line}: expected an enum value, but \"{enumtxt}\" is not part of the enum (located inside block {block} starting on line {block_line})"
    )]
    InvalidEnumValue {
        filename: String,
        error_line: u32,
        enumtxt: String,
        block: String,
        block_line: u32,
    },

    #[error(
        "{filename}:{error_line}: optional element {tag} occurs too often within block {block} starting on line {block_line}"
    )]
    InvalidMultiplicityTooMany {
        filename: String,
        error_line: u32,
        tag: String,
        block: String,
        block_line: u32,
    },

    #[error(
        "{filename}:{error_line}: element {tag} is missing in block {block} starting on line {block_line}"
    )]
    InvalidMultiplicityNotPresent {
        filename: String,
        error_line: u32,
        tag: String,
        block: String,
        block_line: u32,
    },

    #[error(
        "{filename}:{error_line}: element {tag} in block {block} starting on line {block_line} must be enclosed in /begin and /end"
    )]
    IncorrectBlockError {
        filename: String,
        error_line: u32,
        tag: String,
        block: String,
        block_line: u32,
    },

    #[error(
        "{filename}:{error_line}: element {tag} in block {block} starting on line {block_line} may not be enclosed in /begin and /end"
    )]
    IncorrectKeywordError {
        filename: String,
        error_line: u32,
        tag: String,
        block: String,
        block_line: u32,
    },

    #[error(
        "{filename}:{error_line}: Wrong end tag {tag} found at the end of block {block} starting on line {block_line}"
    )]
    IncorrectEndTag {
        filename: String,
        error_line: u32,
        tag: String,
        block: String,
        block_line: u32,
    },

    #[error(
        "{filename}:{error_line}: Unknown sub-block {tag} found inside block {block} starting on line {block_line}"
    )]
    UnknownSubBlock {
        filename: String,
        error_line: u32,
        tag: String,
        block: String,
        block_line: u32,
    },

    #[error(
        "{filename}:{error_line}: encountered end of file while not done parsing block {block} starting on line {block_line}"
    )]
    UnexpectedEOF {
        filename: String,
        error_line: u32,
        block: String,
        block_line: u32,
    },

    #[error(
        "{filename}:{error_line}: String \"{text}\" in block {block} is {length} bytes long, but the maximum allowed length is {max_length}"
    )]
    StringTooLong {
        filename: String,
        error_line: u32,
        block: String,
        text: String,
        length: usize,
        max_length: usize,
    },

    #[error(
        "{filename}:{error_line}: Sub-block \"{tag}\" in block {block} is deprecated after version {limit_ver:.2}, but the file declares version {file_ver:.2}"
    )]
    BlockRefDeprecated {
        filename: String,
        error_line: u32,
        block: String,
        tag: String,
        limit_ver: A2lVersion,
        file_ver: A2lVersion,
    },

    #[error(
        "{filename}:{error_line}: Sub-block \"{tag}\" in block {block} is available from version {limit_ver:.2}, but the file declares version {file_ver:.2}"
    )]
    BlockRefTooNew {
        filename: String,
        error_line: u32,
        block: String,
        tag: String,
        limit_ver: A2lVersion,
        file_ver: A2lVersion,
    },

    #[error(
        "{filename}:{error_line}: Enum item \"{tag}\" in block {block} is deprecated after version {limit_ver:.2}, but the file declares version {file_ver:.2}"
    )]
    EnumRefDeprecated {
        filename: String,
        error_line: u32,
        block: String,
        tag: String,
        limit_ver: A2lVersion,
        file_ver: A2lVersion,
    },

    #[error(
        "{filename}:{error_line}: Enum item \"{tag}\" in block {block} is available from version {limit_ver:.2}, but the file declares version {file_ver:.2}"
    )]
    EnumRefTooNew {
        filename: String,
        error_line: u32,
        block: String,
        tag: String,
        limit_ver: A2lVersion,
        file_ver: A2lVersion,
    },

    #[error("{filename}:{error_line}: /begin in block {block} is not followed by a valid tag")]
    InvalidBegin {
        filename: String,
        error_line: u32,
        block: String,
    },

    #[error(
        "{filename}:{error_line}: The string '{ident}' in block {block} is not a valid identifier"
    )]
    InvalidIdentifier {
        filename: String,
        error_line: u32,
        ident: String,
        block: String,
    },

    #[error("{filename}:{error_line}: A2ML parser reports {errmsg}")]
    A2mlError {
        filename: String,
        error_line: u32,
        errmsg: String,
    },

    /// `AdditionalTokensError` parsing finished without consuming all data in the file
    #[error(
        "{filename}:{error_line}: unexpected additional data \"{text}...\" after parsed a2l file content"
    )]
    AdditionalTokensError {
        filename: String,
        error_line: u32,
        text: String,
    },

    /// `MissingVerionInfo`: no version information in the file
    #[error("File is not recognized as an a2l file. Mandatory version information is missing.")]
    MissingVersionInfo,

    /// Theversion number in the file dos not correspond to a known A2L specification
    #[error("File has invalid version {major} {minor}")]
    InvalidVersion { major: u16, minor: u16 },
}

pub(crate) enum BlockContent<'a> {
    Block(&'a A2lToken, bool, u32),
    Comment(&'a A2lToken, u32),
    None,
}

// it pretends to be an Iter, but it really isn't
impl<'a> TokenIter<'a> {
    fn next(&mut self) -> Option<&'a A2lToken> {
        if self.pos < self.tokens.len() {
            let item = &self.tokens[self.pos];
            self.pos += 1;
            Some(item)
        } else {
            None
        }
    }

    fn peek(&mut self) -> Option<&'a A2lToken> {
        if self.pos < self.tokens.len() {
            let item = &self.tokens[self.pos];
            Some(item)
        } else {
            None
        }
    }

    fn back(&mut self) {
        self.pos -= 1;
    }
}

impl<'a> ParserState<'a> {
    pub(crate) fn new<'b>(
        tokenresult: &'b TokenResult,
        log_msgs: &'b mut Vec<A2lError>,
        strict: bool,
    ) -> ParserState<'b> {
        Self::new_internal(
            &tokenresult.tokens,
            &tokenresult.filedata,
            &tokenresult.filenames,
            log_msgs,
            strict,
        )
    }

    pub(crate) fn new_internal<'b>(
        tokens: &'b [A2lToken],
        filedata: &'b [String],
        filenames: &'b [Filename],
        log_msgs: &'b mut Vec<A2lError>,
        strict: bool,
    ) -> ParserState<'b> {
        ParserState {
            token_cursor: TokenIter { tokens, pos: 0 },
            filedata,
            filenames,
            last_token_position: 0,
            sequential_id: 0,
            log_msgs,
            strict,
            file_ver: A2lVersion::V1_7_1,
            a2mlspec: Vec::new(),
        }
    }

    pub(crate) fn parse_file(&mut self) -> Result<crate::A2lFile, ParserError> {
        let firstline = self.token_cursor.tokens.first().map_or(1, |tok| tok.line);
        // create a context for the parser
        let context = ParseContext {
            element: "A2L_FILE".to_string(),
            fileid: 0,
            line: firstline,
        };

        // try to get the file version. Starting with 1.60, the ASAP2_VERSION element is mandatory. For
        // compatibility with old files, a missing version is only an error if strict parsing is requested
        self.file_ver = self.parse_version(&context)?;

        // parse the file
        let a2l_file = crate::A2lFile::parse(self, &context, 0)?;

        // make sure this is the end of the input, i.e. no additional data after the parsed data
        if let Some(token) = self.peek_token() {
            self.error_or_log(ParserError::AdditionalTokensError {
                filename: self.filenames[token.fileid].to_string(),
                error_line: self.last_token_position,
                text: self.get_token_text(token).to_owned(),
            })?;
        }

        Ok(a2l_file)
    }

    fn parse_version(&mut self, context: &ParseContext) -> Result<crate::A2lVersion, ParserError> {
        if let Some(token) = self.peek_token() {
            let ident = self.get_identifier(context);
            let ver_context = ParseContext::from_token("", token);
            if let Ok("ASAP2_VERSION") = ident.as_deref() {
                let version_result = crate::Asap2Version::parse(self, &ver_context, 0)
                    .map_err(|_| ParserError::MissingVersionInfo)
                    .and_then(|ver| A2lVersion::new(ver.version_no, ver.upgrade_no));

                // reset the input, the consumed tokens will be needed again by A2lFile::parse
                self.set_tokenpos(0);

                return match version_result {
                    Ok(ver) => Ok(ver),
                    Err(err) => {
                        // couldn't parse the version, but the file appears to have one
                        self.error_or_log(err)?;
                        Ok(A2lVersion::V1_7_1)
                    }
                };
            }
        }
        // for compatibility with 1.50 and earlier, also make it possible to catch the error and continue
        self.set_tokenpos(0);
        self.error_or_log(ParserError::MissingVersionInfo)?;
        Ok(A2lVersion::V1_5_1)
    }
    // get_token
    // get one token from the list of tokens and unwrap it
    pub(crate) fn get_token(
        &mut self,
        context: &ParseContext,
    ) -> Result<&'a A2lToken, ParserError> {
        if let Some(token) = self.token_cursor.next() {
            self.last_token_position = token.line;
            Ok(token)
        } else {
            Err(ParserError::unexpected_eof(self, context))
        }
    }

    pub(crate) fn undo_get_token(&mut self) {
        self.token_cursor.back();
    }

    pub(crate) fn peek_token(&mut self) -> Option<&'a A2lToken> {
        self.token_cursor.peek()
    }

    pub(crate) fn log_warning(&mut self, parse_error: ParserError) {
        self.log_msgs.push(A2lError::ParserError {
            parser_error: parse_error,
        });
    }

    pub(crate) fn error_or_log(&mut self, err: ParserError) -> Result<(), ParserError> {
        if self.strict {
            Err(err)
        } else {
            self.log_warning(err);
            Ok(())
        }
    }

    pub(crate) fn get_tokenpos(&self) -> usize {
        self.token_cursor.pos
    }

    pub(crate) fn set_tokenpos(&mut self, newpos: usize) {
        self.token_cursor.pos = newpos;
    }

    pub(crate) fn get_token_text(&self, token: &'a A2lToken) -> &'a str {
        let data = &self.filedata[token.fileid];
        &data[token.startpos..token.endpos]
    }

    /// get the line offset of the token that was just consumed
    /// this means that seff.token_cursor.pos is already incremented
    /// - usually we're calculating token[pos-1] - token[pos-2]
    /// - for token[pos==1] it returns the line number of the first token - 1
    /// - the function shouldn't be called while pos == 0, but this case would behave like pos==1
    pub(crate) fn get_line_offset(&self) -> u32 {
        if self.token_cursor.pos > 1 && self.token_cursor.pos < self.token_cursor.tokens.len() {
            let cur_line = self.token_cursor.tokens[self.token_cursor.pos - 1].line;
            let cur_fileid = self.token_cursor.tokens[self.token_cursor.pos - 1].fileid;
            let mut idx = (self.token_cursor.pos - 2) as isize;
            // look for the previous non-comment token on the same line
            // to deal a case like this:
            // /* comment */ current_token
            // if the previous token is a comment on other line, a newline should be inserted before current_token
            while idx >= 0 {
                let token = &self.token_cursor.tokens[idx as usize];
                if token.ttype != A2lTokenType::Comment || token.line != cur_line {
                    break;
                }
                // if the last token is a comment on the same line, skip it
                idx -= 1;
            }
            let (prev_line, prev_fileid) = if idx >= 0 {
                let prev_token = &self.token_cursor.tokens[idx as usize];
                if prev_token.ttype == A2lTokenType::Comment {
                    // if the previous token was a comment on a different line, use cur_line minus 1, so one newline is inserted
                    (cur_line - 1, cur_fileid)
                } else {
                    (prev_token.line, prev_token.fileid)
                }
            } else {
                (cur_line - 1, cur_fileid) // this case should never happen, fail-safe with a newline
            };

            // subtracting line numbers is only sane within a file
            if prev_fileid == cur_fileid {
                cur_line - prev_line
            } else {
                // if the tokens come from different files then there is no line offset and the
                // value 2 is used for formatting: 2 newlines leave one line empty
                2
            }
        } else {
            self.token_cursor.tokens[0].line - 1
        }
    }

    pub(crate) fn get_next_id(&mut self) -> u32 {
        self.sequential_id += 1;
        self.sequential_id
    }

    pub(crate) fn get_incfilename(&self, fileid: usize) -> Option<String> {
        if fileid == 0 || fileid >= self.filenames.len() {
            None
        } else {
            Some(self.filenames[fileid].to_string())
        }
    }

    pub(crate) fn set_file_version(&mut self, version: A2lVersion) {
        self.file_ver = version;
    }

    pub(crate) fn check_block_version_lower(
        &mut self,
        context: &ParseContext,
        tag: &str,
        min_ver: A2lVersion,
    ) -> Result<(), ParserError> {
        if self.file_ver < min_ver {
            self.error_or_log(ParserError::BlockRefTooNew {
                filename: self.filenames[context.fileid].to_string(),
                error_line: self.last_token_position,
                block: context.element.clone(),
                tag: tag.to_string(),
                limit_ver: min_ver,
                file_ver: self.file_ver,
            })?;
        }
        Ok(())
    }

    pub(crate) fn check_block_version_upper(
        &mut self,
        context: &ParseContext,
        tag: &str,
        max_ver: A2lVersion,
    ) {
        if self.file_ver > max_ver {
            self.log_warning(ParserError::BlockRefDeprecated {
                filename: self.filenames[context.fileid].to_string(),
                error_line: self.last_token_position,
                block: context.element.clone(),
                tag: tag.to_string(),
                limit_ver: max_ver,
                file_ver: self.file_ver,
            });
        }
    }

    pub(crate) fn check_enumitem_version_lower(
        &mut self,
        context: &ParseContext,
        tag: &str,
        min_ver: A2lVersion,
    ) -> Result<(), ParserError> {
        if self.file_ver < min_ver {
            self.error_or_log(ParserError::EnumRefTooNew {
                filename: self.filenames[context.fileid].to_string(),
                error_line: self.last_token_position,
                block: context.element.clone(),
                tag: tag.to_string(),
                limit_ver: min_ver,
                file_ver: self.file_ver,
            })?;
        }
        Ok(())
    }

    pub(crate) fn check_enumitem_version_upper(
        &mut self,
        context: &ParseContext,
        tag: &str,
        max_ver: A2lVersion,
    ) {
        if self.file_ver > max_ver {
            self.log_warning(ParserError::EnumRefDeprecated {
                filename: self.filenames[context.fileid].to_string(),
                error_line: self.last_token_position,
                block: context.element.clone(),
                tag: tag.to_string(),
                limit_ver: max_ver,
                file_ver: self.file_ver,
            });
        }
    }

    // expect_token get a token which has to be of a particular type (hence: expect)
    // getting a token of any other type is a ParserError
    pub(crate) fn expect_token(
        &mut self,
        context: &ParseContext,
        token_type: A2lTokenType,
    ) -> Result<&'a A2lToken, ParserError> {
        let mut token = self.get_token(context)?;
        // we never "expect" a comment token, so we skip it
        while token.ttype == A2lTokenType::Comment {
            token = self.get_token(context)?;
        }

        if token.ttype != token_type {
            return Err(ParserError::unexpected_token_type(
                self, context, token, token_type,
            ));
        }

        Ok(token)
    }

    // get_string()
    // Get the content of a String token as a string
    pub(crate) fn get_string(&mut self, context: &ParseContext) -> Result<String, ParserError> {
        // Consume leading comment tokens
        while let Some(A2lToken {
            ttype: A2lTokenType::Comment,
            ..
        }) = self.peek_token()
        {
            // Intentionally ignore the returned token; we just want to advance
            let _ = self.get_token(context);
        }
        let text = if let Some(
            token @ A2lToken {
                ttype: A2lTokenType::Identifier,
                ..
            },
        ) = self.peek_token()
        {
            // an identifier can be used in place of a string, if the parser is not strict
            let text = self.get_identifier(context)?;
            self.error_or_log(ParserError::unexpected_token_type(
                self,
                context,
                token,
                A2lTokenType::String,
            ))?;
            text
        } else {
            let token = self.expect_token(context, A2lTokenType::String)?;
            let mut text = self.get_token_text(token);

            if text.starts_with('\"') {
                text = &text[1..text.len() - 1];
            }

            unescape_string(text)
        };

        Ok(text)
    }

    // get_string_maxlen()
    // Get the content of a String token as a string. Trigger an error if the string is longer than maxlen
    pub(crate) fn get_string_maxlen(
        &mut self,
        context: &ParseContext,
        maxlen: usize,
    ) -> Result<String, ParserError> {
        let text = self.get_string(context)?;
        if text.len() > maxlen {
            self.error_or_log(ParserError::StringTooLong {
                filename: self.filenames[context.fileid].to_string(),
                error_line: self.last_token_position,
                block: context.element.clone(),
                text: text.clone(),
                length: text.len(),
                max_length: maxlen,
            })?;
        }
        Ok(text)
    }

    // get_identifier()
    // Get the content of an Identifier token as a string
    pub(crate) fn get_identifier(&mut self, context: &ParseContext) -> Result<String, ParserError> {
        let token = self.expect_token(context, A2lTokenType::Identifier)?;
        let text = self.get_token_text(token);
        if text.as_bytes()[0].is_ascii_digit() || text.len() > MAX_IDENT {
            self.error_or_log(ParserError::InvalidIdentifier {
                filename: self.filenames[context.fileid].to_string(),
                error_line: self.last_token_position,
                block: context.element.clone(),
                ident: text.to_owned(),
            })?;
        }
        Ok(String::from(text))
    }

    // get_float()
    // Get the content of a Number token as a float
    // Since the Number token stores text internally, the text must be converted first
    pub(crate) fn get_float(&mut self, context: &ParseContext) -> Result<f32, ParserError> {
        let token = self.expect_token(context, A2lTokenType::Number)?;
        let text = self.get_token_text(token);
        // some vendor tools are defining the characteristic UpperLimit and LowerLimit
        // (float values from specifications) using 0xNNN for characteristics that
        // are actually integers.
        if text.starts_with("0x") || text.starts_with("0X") {
            match u64::from_str_radix(&text[2..], 16) {
                Ok(num) => Ok(num as f32),
                Err(_) => Err(ParserError::malformed_number(self, context, text)),
            }
        } else {
            match text.parse::<f32>() {
                Ok(num) => Ok(num),
                Err(_) => Err(ParserError::malformed_number(self, context, text)),
            }
        }
    }

    // get_double()
    // Get the content of a Number token as a double(f64)
    // Since the Number token stores text internally, the text must be converted first
    pub(crate) fn get_double(&mut self, context: &ParseContext) -> Result<f64, ParserError> {
        let token = self.expect_token(context, A2lTokenType::Number)?;
        let text = self.get_token_text(token);
        // some vendor tools are defining the characteristic UpperLimit and LowerLimit
        // (float values from specifications) using 0xNNN for characteristics that
        // are actually integers.
        if text.starts_with("0x") || text.starts_with("0X") {
            match u64::from_str_radix(&text[2..], 16) {
                Ok(num) => Ok(num as f64),
                Err(_) => Err(ParserError::malformed_number(self, context, text)),
            }
        } else {
            match text.parse::<f64>() {
                Ok(num) => Ok(num),
                Err(_) => Err(ParserError::malformed_number(self, context, text)),
            }
        }
    }

    pub(crate) fn get_integer<T>(
        &mut self,
        context: &ParseContext,
    ) -> Result<(T, bool), ParserError>
    where
        T: Num + std::str::FromStr + Copy + 'static,
        u64: AsPrimitive<T>,
    {
        let token = self.expect_token(context, A2lTokenType::Number)?;
        let text = self.get_token_text(token);
        if text.len() > 2 && (text.starts_with("0x") || text.starts_with("0X")) {
            match u64::from_str_radix(&text[2..], 16) {
                Ok(num_u64) => Ok((num_u64.as_(), true)),
                Err(_) => Err(ParserError::malformed_number(self, context, text)),
            }
        } else {
            match text.parse() {
                Ok(num) => Ok((num, false)),
                Err(_) => Err(ParserError::malformed_number(self, context, text)),
            }
        }
    }

    // get_next_tag()
    // get the tag of the next item of a taggedstruct or taggedunion
    // alternatively, get the next comment
    //
    // Handling tags and comments in the same function makes sense, because the current parser
    // implementation can only handle comments where blocks are permitted. If the parser is ever
    // extended to handle comments in other locations, then this function will need to be split.
    pub(crate) fn get_next_tag_or_comment(
        &mut self,
        context: &ParseContext,
    ) -> Result<BlockContent<'a>, ParserError> {
        let mut is_block = false;
        let tokenpos = self.get_tokenpos();

        if let Some(
            tokenval @ A2lToken {
                ttype: A2lTokenType::Comment,
                ..
            },
        ) = self.token_cursor.peek()
        {
            self.token_cursor.next(); // consume the peeked token
            let start_offset = self.get_line_offset();
            Ok(BlockContent::Comment(tokenval, start_offset))
        } else {
            // if the next token is /begin, then set is_block and skip the token
            let (token_result, start_offset) = if let Some(A2lToken {
                ttype: A2lTokenType::Begin,
                ..
            }) = self.token_cursor.peek()
            {
                is_block = true;
                self.get_token(context)?;
                // for blocks, we went to set start_offset to the offset of the /begin token,
                // and then get the tag from the next token
                let start_offset = self.get_line_offset();
                (
                    self.expect_token(context, A2lTokenType::Identifier),
                    start_offset,
                )
            } else {
                // if this is not a block, then just get the tag and the offset of the tag
                (
                    self.expect_token(context, A2lTokenType::Identifier),
                    self.get_line_offset(),
                )
            };

            // get the tag or return None if the token is not an Identifier
            match token_result {
                Ok(token) => Ok(BlockContent::Block(token, is_block, start_offset)),
                Err(error) => {
                    self.set_tokenpos(tokenpos);
                    if is_block {
                        Err(error)
                    } else {
                        // no tag? no problem!
                        Ok(BlockContent::None)
                    }
                }
            }
        }
    }

    // handle_unknown_taggedstruct_tag
    // perform error recovery if an unknown tag is found inside a taggedstruct and strict parsing is off
    pub(crate) fn handle_unknown_taggedstruct_tag(
        &mut self,
        context: &ParseContext,
        item_tag: &str,
        item_is_block: bool,
        stoplist: &[&str],
    ) -> Result<(), ParserError> {
        self.error_or_log(ParserError::unknown_sub_block(self, context, item_tag))?;
        // make sure there actually is a next token by doing get_token() + undo_get_token() rather than peek()
        let _ = self.get_token(context)?;
        self.undo_get_token();
        let startpos = self.get_tokenpos();
        let text = self.get_token_text(&self.token_cursor.tokens[startpos]);
        let errcontext = ParseContext::from_token(text, &self.token_cursor.tokens[startpos]);

        let mut balance = 0;
        if item_is_block {
            balance = 1;
        }

        loop {
            let token = self.get_token(context)?;
            let text = self.get_token_text(token);
            match token.ttype {
                A2lTokenType::Begin => balance += 1,
                A2lTokenType::End => {
                    balance -= 1;
                    if balance == -1 {
                        self.token_cursor.back();
                        break;
                    }
                }
                A2lTokenType::Identifier => {
                    if item_is_block {
                        // the current unknown item started with /begin ITEM_TAG, so it must end with /end ITEM_TAG.
                        // the stoplist is not relevant
                        if balance == 0 {
                            if text == item_tag {
                                break;
                            } else {
                                return Err(ParserError::incorrect_end_tag(
                                    self,
                                    &errcontext,
                                    text,
                                ));
                            }
                        }
                    } else {
                        // this unknown item did not begin with /begin, so the end is reached when either:
                        // - the end tag of the parent block is found (balance == -1)
                        // - a tag belonging to the parent block (on the stoplist) is found (balance == 0)
                        // - the sequence /begin TAG for a tag on the stoplist is encountered (balance == 1)
                        if balance == 0 || balance == 1 {
                            let found = stoplist.iter().find(|entry| **entry == text);
                            if found.is_some() {
                                // found a tag belonging to a different TaggedItem of the parent struct. Put the token back and let the parent handle it
                                self.token_cursor.back();
                                if balance == 1 {
                                    self.token_cursor.back();
                                }
                                break;
                            }
                        }
                    }
                }
                _ => {
                    // once balance == 0 is reached for a block, the next tag should be an Identifier
                    if item_is_block && balance == 0 {
                        return Err(ParserError::incorrect_end_tag(self, &errcontext, text));
                    }
                    // else: ignore the token
                }
            }
        }

        Ok(())
    }

    pub(crate) fn handle_multiplicity_error(
        &mut self,
        context: &ParseContext,
        tag: &str,
        is_error: bool,
    ) -> Result<(), ParserError> {
        if is_error {
            self.error_or_log(ParserError::invalid_multiplicity_too_many(
                self, context, tag,
            ))?;
        }
        Ok(())
    }

    pub(crate) fn require_block(
        &self,
        tag: &str,
        is_block: bool,
        context: &ParseContext,
    ) -> Result<(), ParserError> {
        if !is_block {
            Err(ParserError::IncorrectBlockError {
                filename: self.filenames[context.fileid].to_string(),
                error_line: self.last_token_position,
                tag: tag.to_string(),
                block: context.element.clone(),
                block_line: context.line,
            })
        } else {
            Ok(())
        }
    }

    pub(crate) fn require_keyword(
        &self,
        tag: &str,
        is_block: bool,
        context: &ParseContext,
    ) -> Result<(), ParserError> {
        if is_block {
            Err(ParserError::IncorrectKeywordError {
                filename: self.filenames[context.fileid].to_string(),
                error_line: self.last_token_position,
                tag: tag.to_string(),
                block: context.element.clone(),
                block_line: context.line,
            })
        } else {
            Ok(())
        }
    }
}

impl ParseContext {
    pub(crate) fn from_token(text: &str, token: &A2lToken) -> ParseContext {
        ParseContext {
            element: text.to_string(),
            fileid: token.fileid,
            line: token.line,
        }
    }
}

impl ParserError {
    pub(crate) fn unexpected_token_type(
        parser: &ParserState,
        context: &ParseContext,
        token: &A2lToken,
        expected_ttype: A2lTokenType,
    ) -> Self {
        Self::UnexpectedTokenType {
            filename: parser.filenames[context.fileid].to_string(),
            error_line: parser.last_token_position,
            block_line: context.line,
            element: context.element.clone(),
            actual_ttype: token.ttype.clone(),
            actual_text: parser.get_token_text(token).to_owned(),
            expected_ttype,
        }
    }

    pub(crate) fn malformed_number(
        parser: &ParserState,
        context: &ParseContext,
        numstr: &str,
    ) -> Self {
        Self::MalformedNumber {
            filename: parser.filenames[context.fileid].to_string(),
            error_line: parser.last_token_position,
            numstr: numstr.to_owned(),
        }
    }

    pub(crate) fn invalid_enum_value(
        parser: &ParserState,
        context: &ParseContext,
        enumitem: &str,
    ) -> Self {
        Self::InvalidEnumValue {
            filename: parser.filenames[context.fileid].to_string(),
            error_line: parser.last_token_position,
            enumtxt: enumitem.to_owned(),
            block: context.element.clone(),
            block_line: context.line,
        }
    }

    pub(crate) fn invalid_multiplicity_too_many(
        parser: &ParserState,
        context: &ParseContext,
        tag: &str,
    ) -> Self {
        Self::InvalidMultiplicityTooMany {
            filename: parser.filenames[context.fileid].to_string(),
            error_line: parser.last_token_position,
            tag: tag.to_string(),
            block: context.element.clone(),
            block_line: context.line,
        }
    }

    pub(crate) fn incorrect_end_tag(
        parser: &ParserState,
        context: &ParseContext,
        tag: &str,
    ) -> Self {
        Self::IncorrectEndTag {
            filename: parser.filenames[context.fileid].to_string(),
            error_line: parser.last_token_position,
            tag: tag.to_owned(),
            block: context.element.clone(),
            block_line: context.line,
        }
    }

    pub(crate) fn unknown_sub_block(
        parser: &ParserState,
        context: &ParseContext,
        tag: &str,
    ) -> Self {
        Self::UnknownSubBlock {
            filename: parser.filenames[context.fileid].to_string(),
            error_line: parser.last_token_position,
            tag: tag.to_owned(),
            block: context.element.clone(),
            block_line: context.line,
        }
    }

    pub(crate) fn unexpected_eof(parser: &ParserState, context: &ParseContext) -> Self {
        Self::UnexpectedEOF {
            filename: parser.filenames[context.fileid].to_string(),
            error_line: parser.last_token_position,
            block: context.element.clone(),
            block_line: context.line,
        }
    }
}

fn unescape_string(text: &str) -> String {
    /* first check if any unescaping is needed at all */
    if text.chars().any(|c| c == '\\' || c == '"') {
        let input_chars: Vec<char> = text.chars().collect();
        let mut output_chars = Vec::<char>::new();

        let mut idx = 1;
        while idx < input_chars.len() {
            if (input_chars[idx - 1] == '\\' || input_chars[idx - 1] == '"')
                && input_chars[idx] == '"'
            {
                output_chars.push('"');
                idx += 1;
            } else if input_chars[idx - 1] == '\\' && input_chars[idx] == '\'' {
                output_chars.push('\'');
                idx += 1;
            } else if input_chars[idx - 1] == '\\' && input_chars[idx] == '\\' {
                output_chars.push('\\');
                idx += 1;
            } else if input_chars[idx - 1] == '\\' && input_chars[idx] == 'n' {
                output_chars.push('\n');
                idx += 1;
            } else if input_chars[idx - 1] == '\\' && input_chars[idx] == 'r' {
                output_chars.push('\r');
                idx += 1;
            } else if input_chars[idx - 1] == '\\' && input_chars[idx] == 't' {
                output_chars.push('\t');
                idx += 1;
            } else {
                output_chars.push(input_chars[idx - 1]);
            }

            idx += 1;
        }
        if idx == input_chars.len() {
            output_chars.push(input_chars[idx - 1]);
        }

        output_chars.iter().collect()
    } else {
        text.to_owned()
    }
}

impl A2lVersion {
    pub fn new(major: u16, minor: u16) -> Result<Self, ParserError> {
        match (major, minor) {
            (1, 50) => Ok(A2lVersion::V1_5_0),
            (1, 51) => Ok(A2lVersion::V1_5_1),
            (1, 60) => Ok(A2lVersion::V1_6_0),
            (1, 61) => Ok(A2lVersion::V1_6_1),
            (1, 70) => Ok(A2lVersion::V1_7_0),
            (1, 71) => Ok(A2lVersion::V1_7_1),
            _ => Err(ParserError::InvalidVersion { major, minor }),
        }
    }
}

impl Display for A2lVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            A2lVersion::V1_5_0 => f.write_str("1.5.0"),
            A2lVersion::V1_5_1 => f.write_str("1.5.1"),
            A2lVersion::V1_6_0 => f.write_str("1.6.0"),
            A2lVersion::V1_6_1 => f.write_str("1.6.1"),
            A2lVersion::V1_7_0 => f.write_str("1.7.0"),
            A2lVersion::V1_7_1 => f.write_str("1.7.1"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Filename, load_from_string, tokenizer};

    #[test]
    fn parsing_numbers_test() {
        let input_text = r##"0 0x1 1.0e+2 1000 0 0.1 0x11 1.0e+2 0X1f 0X2F 2F F"##;
        let tokenresult = tokenizer::tokenize(&Filename::from("test_input"), 0, input_text);
        assert!(tokenresult.is_ok());

        let tokenresult = tokenresult.unwrap();
        let mut log_msgs = Vec::<A2lError>::new();
        let mut parser = ParserState::new(&tokenresult, &mut log_msgs, true);
        let context = ParseContext {
            element: "TEST".to_string(),
            fileid: 0,
            line: 0,
        };

        // uint8: 0
        let res = parser.get_integer::<u8>(&context);
        assert!(res.is_ok());
        let val = res.unwrap();
        assert_eq!(val, (0, false));

        // uint8: 0x1
        let res = parser.get_integer::<u8>(&context);
        assert!(res.is_ok());
        let val = res.unwrap();
        assert_eq!(val, (1, true));

        // uint8: 1.0e+2
        let res = parser.get_integer::<u8>(&context);
        assert!(res.is_err());

        // uint8: 257
        let res = parser.get_integer::<u8>(&context);
        assert!(res.is_err());

        // float: 0
        let res = parser.get_float(&context);
        assert!(res.is_ok());
        let val = res.unwrap();
        assert_eq!(val, 0f32);

        // float: 0.1
        let res = parser.get_float(&context);
        assert!(res.is_ok());
        let val = res.unwrap();
        assert_eq!(val, 0.1f32);

        // float: 0x11
        let res = parser.get_float(&context);
        assert!(res.is_ok());
        let val = res.unwrap();
        assert_eq!(val, 17f32);

        // float: 1.0e+2
        let res = parser.get_float(&context);
        assert!(res.is_ok());
        let val = res.unwrap();
        assert_eq!(val, 100f32);

        // float: 0X1f
        let res = parser.get_float(&context);
        assert!(res.is_ok());
        let val = res.unwrap();
        assert_eq!(val, 31f32);

        // float: 0X2F
        let res = parser.get_float(&context);
        assert!(res.is_ok());
        let val = res.unwrap();
        assert_eq!(val, 47f32);

        // float: 2F
        let res = parser.get_float(&context);
        assert!(res.is_err());

        // float: F
        let res = parser.get_float(&context);
        assert!(res.is_err());
    }

    #[test]
    fn test_unescape_string() {
        // no escape
        let result = unescape_string(" ");
        assert_eq!(result, " ");
        // "" -> "
        let result = unescape_string(r#""""#);
        assert_eq!(result, r#"""#);
        // \" -> "
        let result = unescape_string(r#"\""#);
        assert_eq!(result, r#"""#);
        // \' -> '
        let result = unescape_string(r#"\'"#);
        assert_eq!(result, r#"'"#);
        // \\ -> \
        let result = unescape_string(r#"\\"#);
        assert_eq!(result, r#"\"#);
        // \n -> (newline)
        let result = unescape_string(r#"\n"#);
        assert_eq!(result, "\n");
        // \r -> (carriage return)
        let result = unescape_string(r#"\r"#);
        assert_eq!(result, "\r");
        // \t -> (tab)
        let result = unescape_string(r#"\txx"#);
        assert_eq!(result, "\txx");
    }

    #[test]
    fn parsing_identifiers_test() {
        let input_text = r##"ident 0ident 123"##;
        let tokenresult = tokenizer::tokenize(&Filename::from("test_input"), 0, input_text);
        assert!(tokenresult.is_ok());

        let tokenresult = tokenresult.unwrap();
        let mut log_msgs = Vec::<A2lError>::new();
        let mut parser = ParserState::new(&tokenresult, &mut log_msgs, true);
        let context = ParseContext {
            element: "TEST".to_string(),
            fileid: 0,
            line: 0,
        };

        // identifier: ident
        let res = parser.get_identifier(&context);
        assert!(res.is_ok());
        let val = res.unwrap();
        assert_eq!(val, "ident");

        // bad identifier - identifiers may not start with a number
        let res = parser.get_identifier(&context);
        assert!(matches!(res, Err(ParserError::InvalidIdentifier { .. })));

        // not an identifier
        let res = parser.get_identifier(&context);
        assert!(res.is_err());
    }

    #[test]
    fn test_check_version() {
        let tokenresult = tokenizer::tokenize(&Filename::from("test_input"), 0, "").unwrap();
        let mut log_msgs = Vec::<A2lError>::new();
        let mut parser = ParserState::new(&tokenresult, &mut log_msgs, true);
        let context = ParseContext {
            element: "TEST".to_string(),
            fileid: 0,
            line: 0,
        };
        parser.file_ver = A2lVersion::V1_6_0;

        // block version v1_5_0 <= file version V1_6_0
        let result = parser.check_block_version_lower(&context, "CHECK", A2lVersion::V1_5_0);
        assert!(result.is_ok());

        // !block version v1_7_0 <= file version V1_6_0
        let result = parser.check_block_version_lower(&context, "CHECK", A2lVersion::V1_7_0);
        assert!(result.is_err());

        // !block version v1_5_0 >= file version V1_6_0
        let num_warnings = parser.log_msgs.len();
        parser.check_block_version_upper(&context, "CHECK", A2lVersion::V1_5_0);
        assert_ne!(num_warnings, parser.log_msgs.len());

        // block version v1_7_0 >= file version V1_6_0
        let num_warnings = parser.log_msgs.len();
        parser.check_block_version_upper(&context, "CHECK", A2lVersion::V1_7_0);
        assert_eq!(num_warnings, parser.log_msgs.len());

        // enum item version V1_5_0 <= file version V1_6_0
        let result: Result<(), ParserError> =
            parser.check_enumitem_version_lower(&context, "CHECK", A2lVersion::V1_5_0);
        assert!(result.is_ok());

        // !enum item version V1_7_0 <= file version V1_6_0
        let result = parser.check_enumitem_version_lower(&context, "CHECK", A2lVersion::V1_7_0);
        assert!(result.is_err());

        // !enum item version V1_5_0 >= file version V1_6_0
        let num_warnings = parser.log_msgs.len();
        parser.check_enumitem_version_upper(&context, "CHECK", A2lVersion::V1_5_0);
        assert_ne!(num_warnings, parser.log_msgs.len());

        // enum item version V1_7_0 >= file version V1_6_0
        let num_warnings = parser.log_msgs.len();
        parser.check_enumitem_version_upper(&context, "CHECK", A2lVersion::V1_7_0);
        assert_eq!(num_warnings, parser.log_msgs.len());
    }

    #[test]
    fn a2lversion() {
        let v150 = A2lVersion::new(1, 50).unwrap();
        let v151 = A2lVersion::new(1, 51).unwrap();
        let v160 = A2lVersion::new(1, 60).unwrap();
        let v161 = A2lVersion::new(1, 61).unwrap();
        let v170 = A2lVersion::new(1, 70).unwrap();
        let v171 = A2lVersion::new(1, 71).unwrap();

        assert!(v150 < v151);
        assert!(v151 < v160);
        assert!(v160 < v161);
        assert!(v161 < v170);
        assert!(v170 < v171);

        let bad_version = A2lVersion::new(1, 80);
        assert!(bad_version.is_err());

        let cpy = v171;
        assert_eq!(cpy, v171);

        assert_eq!(format!("{v150}"), "1.5.0");
        assert_eq!(format!("{v151}"), "1.5.1");
        assert_eq!(format!("{v160}"), "1.6.0");
        assert_eq!(format!("{v161}"), "1.6.1");
        assert_eq!(format!("{v170}"), "1.7.0");
        assert_eq!(format!("{v171}"), "1.7.1");
    }

    #[test]
    fn error_missing_version() {
        static DATA: &str = r#"/begin PROJECT p "" /end PROJECT"#;
        let a2l_file = load_from_string(DATA, None, true);
        assert!(a2l_file.is_err());
        assert!(matches!(
            a2l_file,
            Err(A2lError::ParserError {
                parser_error: ParserError::MissingVersionInfo
            })
        ));
    }

    #[test]
    fn error_invalid_mult_not_present() {
        static DATA: &str = r#"ASAP2_VERSION 1 71"#;
        let a2l_file = load_from_string(DATA, None, true);
        assert!(matches!(
            a2l_file,
            Err(A2lError::ParserError {
                parser_error: ParserError::InvalidMultiplicityNotPresent { .. }
            })
        ));
    }

    #[test]
    fn error_invalid_mult_too_many() {
        static DATA: &str = r#"ASAP2_VERSION 1 71 /begin PROJECT p "" /begin MODULE m "" /end MODULE /end PROJECT /begin PROJECT p2 "" /begin MODULE m "" /end MODULE /end PROJECT"#;
        let a2l_file = load_from_string(DATA, None, true);
        assert!(matches!(
            a2l_file,
            Err(A2lError::ParserError {
                parser_error: ParserError::InvalidMultiplicityTooMany { .. }
            })
        ));
    }

    #[test]
    fn error_unknown_subblock() {
        static DATA: &str = r#"ASAP2_VERSION 1 71 /begin PROJECT p "" /begin MODULE m "" ABCDEF /end MODULE /end PROJECT"#;
        let a2l_file = load_from_string(DATA, None, true);
        assert!(matches!(
            a2l_file,
            Err(A2lError::ParserError {
                parser_error: ParserError::UnknownSubBlock { .. }
            })
        ));
    }

    #[test]
    fn error_incorrect_end_tag() {
        static DATA: &str =
            r#"ASAP2_VERSION 1 71 /begin PROJECT p "" /begin MODULE m "" /end MMMMM /end PROJECT"#;
        let a2l_file = load_from_string(DATA, None, true);
        assert!(matches!(
            a2l_file,
            Err(A2lError::ParserError {
                parser_error: ParserError::IncorrectEndTag { .. }
            })
        ));
    }

    #[test]
    fn error_unexpected_eof() {
        static DATA: &str = r#"ASAP2_VERSION 1 71 /begin PROJECT"#;
        let a2l_file = load_from_string(DATA, None, true);
        assert!(matches!(
            a2l_file,
            Err(A2lError::ParserError {
                parser_error: ParserError::UnexpectedEOF { .. }
            })
        ));
    }

    #[test]
    fn error_invalid_identifier() {
        let data = format!(
            r#"ASAP2_VERSION 1 71 /begin PROJECT {} "" /begin MODULE m "" /end MODULE /end PROJECT"#,
            ['a'; 1025].iter().collect::<String>()
        );
        let a2l_file = load_from_string(&data, None, true);
        println!("a2l_file: {:#?}", a2l_file);
        assert!(a2l_file.is_err());
        assert!(matches!(
            a2l_file,
            Err(A2lError::ParserError {
                parser_error: ParserError::InvalidIdentifier { .. }
            })
        ));
    }

    #[test]
    fn test_handle_unknown_taggedstruct_tag() {
        // balanced unknown block
        static DATA: &str = r#"ASAP2_VERSION 1 71 /begin PROJECT p "" /begin MODULE m ""
            /begin UNKNOWN_TAG abc def /begin ghi /end ghi /end UNKNOWN_TAG
        /end MODULE /end PROJECT"#;
        let result = load_from_string(DATA, None, false);
        assert!(result.is_ok());
        let (a2l_file, _) = result.unwrap();
        assert_eq!(a2l_file.project.module.len(), 1);

        // unbalanced unknown block
        static DATA2: &str = r#"ASAP2_VERSION 1 71 /begin PROJECT p "" /begin MODULE m ""
            /begin UNKNOWN_TAG abc def
        /end MODULE /end PROJECT"#;
        let result = load_from_string(DATA2, None, false);
        assert!(matches!(
            result,
            Err(A2lError::ParserError {
                parser_error: ParserError::IncorrectEndTag { .. }
            })
        ));

        //unknown keyword
        static DATA3: &str = r#"ASAP2_VERSION 1 71 /begin PROJECT p "" /begin MODULE m ""
            UNKNOWN_TAG abc def /begin ghi /end ghi
            /begin GROUP group_name "" ROOT
            /end GROUP
        /end MODULE /end PROJECT"#;
        let result = load_from_string(DATA3, None, false);
        assert!(result.is_ok());
        let (a2l_file, _) = result.unwrap();
        assert_eq!(a2l_file.project.module.len(), 1);
        assert_eq!(a2l_file.project.module[0].group.len(), 1);
    }

    #[test]
    fn parse_with_comments() {
        static DATA: &str = r#"
        /begin TRANSFORMER Transformer
            "1.0.0"                          // Version info
            "TransformerDll32.dll"           // Name of the 32bit DLL
            ""                               // Name of the 64bit DLL
            1500                             // timeout in [ms]
            ON_CHANGE
            InverseTransformer
        /end TRANSFORMER"#;
        let module = crate::load_fragment(DATA, None).unwrap();
        let bi = &module.transformer[0].__block_info;
        assert_eq!(bi.item_location.1, 1); // offset of the version
        assert_eq!(bi.item_location.2, 1); // offset of the 32-bit dll name
        assert_eq!(bi.item_location.3, 1); // offset of the 64-bit dll name
        assert_eq!(bi.item_location.4, (1, false)); // offset of the timeout
        assert_eq!(bi.item_location.5, 1); // offset of the trigger [ON_CHANGE]
        assert_eq!(bi.item_location.6, 1); // offset of the inverse transformer
        assert_eq!(bi.end_offset, 1); // offset of the /end TRANSFORMER
    }
    #[test]
    fn parse_with_comments_inline() {
        static DATA1: &str = r#"
        /begin CHARACTERISTIC
            /* Name                   */      characteristic_name
            /* Long Identifier        */      "long identifier with spaces and /* inside comments */"
            /* multible quotes here */ /* yet another quote */  /* Type                   */      VALUE
            /* ECU Address            */      0x0000 /* @ECU_Address@xxxxxxxx@ */
            /* Record Layout          */      Scalar_FLOAT32_IEEE
            /* Maximum Difference     */      0
            /* Conversion Method      */      single
            /* Lower Limit            */      -3.4E+38
            /* Upper Limit            */      3.4E+38
        /end CHARACTERISTIC
        "#;
        let module = crate::load_fragment(DATA1, None).unwrap();
        let bi = &module.characteristic[0].__block_info;
        assert_eq!(bi.item_location.0, 1); // offset of the identifier
        assert_eq!(bi.item_location.1, 1); // offset of the long identifier
        assert_eq!(bi.item_location.2, 1); // offset of the type
        assert_eq!(bi.item_location.3, (1, true)); // offset of the ecu address
        assert_eq!(bi.item_location.4, 1); // offset of the layout
        assert_eq!(bi.item_location.5, 1); // offset of the max diff
        assert_eq!(bi.item_location.6, 1); // offset of the conversion method
        assert_eq!(bi.item_location.7, 1); // offset of the lower limit
        assert_eq!(bi.item_location.8, 1); // offset of the upper limit
        assert_eq!(bi.end_offset, 1); // offset of the /end
        assert_eq!(
            module.characteristic[0].stringify(4),
            r#"
        characteristic_name
        "long identifier with spaces and /* inside comments */"
        VALUE
        0x0
        Scalar_FLOAT32_IEEE
        0
        single
        -3.4e38
        3.4e38"#
        );

        static DATA2: &str = r#"
        /begin MEASUREMENT
            /* Name                   */      measurement_name
            /* Long Identifier        */      "measurement long indentifier."
            /* Data type              */      FLOAT32_IEEE
            /* very very long comments here ; */
            /* Conversion Method      */      single
            /* Resolution (Not used)  */      0
            /* Accuracy (Not used)    */      0
            /* Lower Limit            */      -2000.0
            /* Upper Limit            */      2000.0
            ARRAY_SIZE                        4
            ECU_ADDRESS                       0x70031180 /* @ECU_Address@measurement_name@ */
        /end MEASUREMENT
      "#;
        let module = crate::load_fragment(DATA2, None).unwrap();
        let bi = &module.measurement[0].__block_info;
        assert_eq!(bi.item_location.0, 1); // offset of the name
        assert_eq!(bi.item_location.1, 1); // offset of the long identifier
        assert_eq!(bi.item_location.2, 1); // offset of the data type
        assert_eq!(bi.item_location.3, 1); // offset of the conversion method
        assert_eq!(bi.item_location.4, (1, false)); // offset of the resolution
        assert_eq!(bi.item_location.5, 1); // offset of the accuracy
        assert_eq!(bi.item_location.6, 1); // offset of the lower limit
        assert_eq!(bi.item_location.7, 1); // offset of the upper limit
        assert_eq!(
            module.measurement[0].stringify(4),
            r#"
        measurement_name
        "measurement long indentifier."
        FLOAT32_IEEE
        single
        0
        0
        -2000
        2000
        ARRAY_SIZE 4
        ECU_ADDRESS 0x70031180 /* @ECU_Address@measurement_name@ */"#
        );

        static DATA3: &str = r#"
        /begin MEASUREMENT
            /* Name                   */      measurement_name
            /* Long Identifier        */      "measurement long indentifier."
            /* Data type              */      FLOAT32_IEEE
            /* a very long
            and multiline-comments here ;
            situation is not optimal;
            not sure what to do about this kind of comments;
            */
            /* Conversion Method      */      single
            /* Resolution (Not used)  */      0
            /* Accuracy (Not used)    */      0
            /* Lower Limit            */      -2000.0
            /* Upper Limit            */      2000.0
            ARRAY_SIZE                        4
            ECU_ADDRESS                       0x70031180 /* @ECU_Address@measurement_name@ */
        /end MEASUREMENT
        "#;
        let module = crate::load_fragment(DATA3, None).unwrap();
        assert_eq!(
            module.measurement[0].stringify(4),
            r#"
        measurement_name
        "measurement long indentifier."
        FLOAT32_IEEE
        single
        0
        0
        -2000
        2000
        ARRAY_SIZE 4
        ECU_ADDRESS 0x70031180 /* @ECU_Address@measurement_name@ */"#
        );
    }

    #[test]
    fn parse_comments_preserved() {
        static DATA: &str = r#"
        /begin CHARACTERISTIC
        xxxxxxxxxxxxx "xxxxxxx" VALUE  0x0000  Scalar_FLOAT32_IEEE  0  single -3.4E+38  3.4E+38
        /* this characteristic is read only for very important reasons - this comment is preserved! */
        READ_ONLY
        /end CHARACTERISTIC
        "#;
        let module = crate::load_fragment(DATA, None).unwrap();
        assert_eq!(
            module.characteristic[0].stringify(4),
            r#"
        xxxxxxxxxxxxx "xxxxxxx" VALUE 0x0 Scalar_FLOAT32_IEEE 0 single -3.4e38 3.4e38
        /* this characteristic is read only for very important reasons - this comment is preserved! */
        READ_ONLY"#
        );

        static DATA1: &str = r#"
        /begin CHARACTERISTIC
        xxxxxxxxxxxxx "xxxxxxx" VALUE  0x0000  Scalar_FLOAT32_IEEE  0  single -3.4E+38  3.4E+38
        /* this characteristic is read only for very important reasons
        -
        -
        -
        this comment is preserved! */
        READ_ONLY
        /end CHARACTERISTIC
        "#;
        let module = crate::load_fragment(DATA1, None).unwrap();
        assert_eq!(
            module.characteristic[0].stringify(4),
            r#"
        xxxxxxxxxxxxx "xxxxxxx" VALUE 0x0 Scalar_FLOAT32_IEEE 0 single -3.4e38 3.4e38
        /* this characteristic is read only for very important reasons
        -
        -
        -
        this comment is preserved! */
        READ_ONLY"#
        );
    }

    #[test]
    fn parse_string_fallback() {
        // regression test for the issue fixed in PR #47
        // An identifier would not be accepted in a context where a string was expected if the identifier was preceded by a comment.
        static DATA: &str = r#"/* comment */ identifier "#;
        let tokenresult = tokenizer::tokenize(&Filename::from("test_input"), 0, DATA);
        assert!(tokenresult.is_ok());

        let tokenresult = tokenresult.unwrap();
        let mut log_msgs = Vec::<A2lError>::new();
        let mut parser = ParserState::new(&tokenresult, &mut log_msgs, false);
        let context = ParseContext {
            element: "TEST".to_string(),
            fileid: 0,
            line: 0,
        };

        // try to get a string, but the next token is an identifier. The parser should fall back to getting an identifier and return it as a string
        let res = parser.get_string(&context);
        assert!(res.is_ok());
        let val = res.unwrap();
        assert_eq!(val, "identifier");
    }
}