openscenario-rs 0.3.0

Rust library for parsing and manipulating OpenSCENARIO 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
//! Error types and error handling for the OpenSCENARIO library

use thiserror::Error;

/// Main error type for the OpenSCENARIO library
#[derive(Error, Debug)]
pub enum Error {
    // XML/Serialization
    /// XML deserialization failures
    #[error("XML parsing error: {0}")]
    XmlParseError(#[from] quick_xml::DeError),

    /// XML serialization failures
    #[error("XML serialization error: {0}")]
    XmlSerializeError(#[from] quick_xml::SeError),

    // I/O
    /// File I/O failures
    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),

    // File System Errors
    /// File not found at specified path
    #[error("File not found: {path}")]
    FileNotFound { path: String },

    /// Directory not found at specified path
    #[error("Directory not found: {path}")]
    DirectoryNotFound { path: String },

    /// Cannot read file
    #[error("Cannot read file {path}: {reason}")]
    FileReadError { path: String, reason: String },

    /// Cannot write file
    #[error("Cannot write file {path}: {reason}")]
    FileWriteError { path: String, reason: String },

    // Reference Errors
    /// Entity reference not found
    #[error("Entity '{entity}' not found")]
    EntityNotFound {
        entity: String,
        available: Vec<String>,
    },

    /// Catalog entry not found
    #[error("Catalog entry '{entry}' not found in catalog '{catalog}'")]
    CatalogEntryNotFound { catalog: String, entry: String },

    /// Catalog not found
    #[error("Catalog '{catalog}' not found")]
    CatalogNotFound {
        catalog: String,
        available: Vec<String>,
    },

    // Validation Errors
    /// Schema validation failures
    #[error("Validation error in field '{field}': {message}")]
    ValidationError { field: String, message: String },

    /// Missing required field
    #[error("Missing required field: {field}")]
    MissingRequiredField { field: String },

    /// Invalid value for field
    #[error("Invalid value for field '{field}': {value}. {hint}")]
    InvalidValue {
        field: String,
        value: String,
        hint: String,
    },

    /// Value out of expected range
    #[error("Value out of range for field '{field}': {value}. Expected {min} to {max}")]
    OutOfRange {
        field: String,
        value: String,
        min: String,
        max: String,
    },

    /// Type mismatch
    #[error("Type mismatch for field '{field}': expected {expected}, got {actual}")]
    TypeMismatch {
        field: String,
        expected: String,
        actual: String,
    },

    // Parameter Errors
    /// Parameter resolution failures
    #[error("Parameter '{param}' error: {message}")]
    ParameterError { param: String, message: String },

    /// Parameter not found
    #[error("Parameter '{param}' not found")]
    ParameterNotFound {
        param: String,
        available: Vec<String>,
    },

    /// Circular dependency detected
    #[error("Circular dependency detected: {cycle}")]
    CircularDependency { cycle: String },

    // XML/Structure Errors
    /// Invalid XML structure
    #[error("Invalid XML structure: {message}")]
    InvalidXmlStructure { message: String },

    /// Malformed XML with location context
    #[error("Malformed XML: expected {expected}, found {found} at {location}")]
    MalformedXml {
        expected: String,
        found: String,
        location: String,
    },

    // Catalog Errors (remaining generic cases)
    /// Generic catalog system error
    #[error("Catalog error: {0}")]
    CatalogError(String),

    /// XSD Choice Group parsing errors
    #[error("Choice group error: {message}")]
    ChoiceGroupError { message: String },

    // Parsing/Expression Errors
    /// Failed to parse input
    #[error("Failed to parse '{input}': {reason}")]
    ParseError { input: String, reason: String },

    /// Expression evaluation failed
    #[error("Expression evaluation failed: {expression} - {reason}")]
    ExpressionError { expression: String, reason: String },

    // Constraint Violations
    /// Constraint violation
    #[error("Constraint violation: {constraint}")]
    ConstraintViolation { constraint: String },

    /// Inconsistent state
    #[error("Inconsistent state: {message}")]
    InconsistentState { message: String },
}

impl Error {
    // File System Errors

    /// Create a file not found error
    pub fn file_not_found(path: &str) -> Self {
        Error::FileNotFound {
            path: path.to_string(),
        }
    }

    /// Create a directory not found error
    pub fn directory_not_found(path: &str) -> Self {
        Error::DirectoryNotFound {
            path: path.to_string(),
        }
    }

    /// Create a file read error
    pub fn file_read_error(path: &str, reason: &str) -> Self {
        Error::FileReadError {
            path: path.to_string(),
            reason: reason.to_string(),
        }
    }

    /// Create a file write error
    pub fn file_write_error(path: &str, reason: &str) -> Self {
        Error::FileWriteError {
            path: path.to_string(),
            reason: reason.to_string(),
        }
    }

    // Reference Errors

    /// Create an entity not found error
    pub fn entity_not_found(entity: &str, available: &[String]) -> Self {
        Error::EntityNotFound {
            entity: entity.to_string(),
            available: available.to_vec(),
        }
    }

    /// Create a catalog entry not found error
    pub fn catalog_entry_not_found(catalog: &str, entry: &str) -> Self {
        Error::CatalogEntryNotFound {
            catalog: catalog.to_string(),
            entry: entry.to_string(),
        }
    }

    /// Create a catalog not found error
    pub fn catalog_not_found(catalog: &str, available: &[String]) -> Self {
        Error::CatalogNotFound {
            catalog: catalog.to_string(),
            available: available.to_vec(),
        }
    }

    // Validation Errors

    /// Create a validation error
    pub fn validation_error(field: &str, message: &str) -> Self {
        Error::ValidationError {
            field: field.to_string(),
            message: message.to_string(),
        }
    }

    /// Create a missing required field error
    pub fn missing_field(field: &str) -> Self {
        Error::MissingRequiredField {
            field: field.to_string(),
        }
    }

    /// Create an invalid value error
    pub fn invalid_value(field: &str, value: &str, hint: &str) -> Self {
        Error::InvalidValue {
            field: field.to_string(),
            value: value.to_string(),
            hint: hint.to_string(),
        }
    }

    /// Create an out of range error
    pub fn out_of_range(field: &str, value: &str, min: &str, max: &str) -> Self {
        Error::OutOfRange {
            field: field.to_string(),
            value: value.to_string(),
            min: min.to_string(),
            max: max.to_string(),
        }
    }

    /// Create a type mismatch error
    pub fn type_mismatch(field: &str, expected: &str, actual: &str) -> Self {
        Error::TypeMismatch {
            field: field.to_string(),
            expected: expected.to_string(),
            actual: actual.to_string(),
        }
    }

    // Parameter Errors

    /// Create a parameter error
    pub fn parameter_error(param: &str, message: &str) -> Self {
        Error::ParameterError {
            param: param.to_string(),
            message: message.to_string(),
        }
    }

    /// Create a parameter not found error
    pub fn parameter_not_found(param: &str, available: &[String]) -> Self {
        Error::ParameterNotFound {
            param: param.to_string(),
            available: available.to_vec(),
        }
    }

    // XML/Structure Errors

    /// Create an invalid XML structure error
    pub fn invalid_xml(message: &str) -> Self {
        Error::InvalidXmlStructure {
            message: message.to_string(),
        }
    }

    /// Create a malformed XML error with location
    pub fn malformed_xml(expected: &str, found: &str, location: &str) -> Self {
        Error::MalformedXml {
            expected: expected.to_string(),
            found: found.to_string(),
            location: location.to_string(),
        }
    }

    /// Create a parsing error with location information
    pub fn parsing_error(msg: &str, line: usize, col: usize) -> Self {
        Error::ValidationError {
            field: format!("line {}, column {}", line, col),
            message: msg.to_string(),
        }
    }

    // Other Errors

    /// Create a circular dependency error
    pub fn circular_dependency(cycle: &str) -> Self {
        Error::CircularDependency {
            cycle: cycle.to_string(),
        }
    }

    /// Create a parse error
    pub fn parse_error(input: &str, reason: &str) -> Self {
        Error::ParseError {
            input: input.to_string(),
            reason: reason.to_string(),
        }
    }

    /// Create an expression error
    pub fn expression_error(expression: &str, reason: &str) -> Self {
        Error::ExpressionError {
            expression: expression.to_string(),
            reason: reason.to_string(),
        }
    }

    /// Create a constraint violation error
    pub fn constraint_violation(constraint: &str) -> Self {
        Error::ConstraintViolation {
            constraint: constraint.to_string(),
        }
    }

    /// Create a catalog error
    pub fn catalog_error(message: &str) -> Self {
        Error::CatalogError(message.to_string())
    }

    /// Create a choice group error
    pub fn choice_group_error(message: &str) -> Self {
        Error::ChoiceGroupError {
            message: message.to_string(),
        }
    }

    /// Add context to an error
    pub fn with_context(mut self, context: &str) -> Self {
        match &mut self {
            Error::ValidationError {
                ref mut message, ..
            } => {
                *message = format!("{}: {}", context, message);
            }
            Error::CatalogError(ref mut msg) => {
                *msg = format!("{}: {}", context, msg);
            }
            Error::ChoiceGroupError { ref mut message } => {
                *message = format!("{}: {}", context, message);
            }
            Error::ParameterError {
                ref mut message, ..
            } => {
                *message = format!("{}: {}", context, message);
            }
            Error::FileReadError { ref mut reason, .. } => {
                *reason = format!("{}: {}", context, reason);
            }
            Error::FileWriteError { ref mut reason, .. } => {
                *reason = format!("{}: {}", context, reason);
            }
            Error::ParseError { ref mut reason, .. } => {
                *reason = format!("{}: {}", context, reason);
            }
            Error::ExpressionError { ref mut reason, .. } => {
                *reason = format!("{}: {}", context, reason);
            }
            Error::InvalidValue { ref mut hint, .. } => {
                *hint = format!("{}: {}", context, hint);
            }
            Error::OutOfRange { ref mut value, .. } => {
                *value = format!("{}: {}", context, value);
            }
            _ => {}
        }
        self
    }
}

/// Result type alias for the OpenSCENARIO library
pub type Result<T> = std::result::Result<T, Error>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_creation() {
        let err = Error::file_not_found("/path/to/file.xosc");
        assert!(matches!(err, Error::FileNotFound { path } if path == "/path/to/file.xosc"));
    }

    #[test]
    fn test_entity_not_found() {
        let err = Error::entity_not_found("ego", &["target".to_string()]);
        match err {
            Error::EntityNotFound { entity, available } => {
                assert_eq!(entity, "ego");
                assert_eq!(available, vec!["target"]);
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_catalog_not_found() {
        let err = Error::catalog_not_found("vehicles", &["controllers".to_string()]);
        match err {
            Error::CatalogNotFound { catalog, available } => {
                assert_eq!(catalog, "vehicles");
                assert_eq!(available, vec!["controllers"]);
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_parameter_not_found() {
        let err = Error::parameter_not_found("speed", &["distance".to_string()]);
        match err {
            Error::ParameterNotFound { param, available } => {
                assert_eq!(param, "speed");
                assert_eq!(available, vec!["distance"]);
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_validation_error() {
        let err = Error::validation_error("speed", "must be positive");
        match err {
            Error::ValidationError { field, message } => {
                assert_eq!(field, "speed");
                assert_eq!(message, "must be positive");
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_missing_field() {
        let err = Error::missing_field("name");
        assert!(matches!(err, Error::MissingRequiredField { field } if field == "name"));
    }

    #[test]
    fn test_invalid_value() {
        let err = Error::invalid_value("speed", "-5", "must be positive");
        match err {
            Error::InvalidValue { field, value, hint } => {
                assert_eq!(field, "speed");
                assert_eq!(value, "-5");
                assert_eq!(hint, "must be positive");
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_out_of_range() {
        let err = Error::out_of_range("speed", "150", "0", "120");
        match err {
            Error::OutOfRange {
                field,
                value,
                min,
                max,
            } => {
                assert_eq!(field, "speed");
                assert_eq!(value, "150");
                assert_eq!(min, "0");
                assert_eq!(max, "120");
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_type_mismatch() {
        let err = Error::type_mismatch("speed", "number", "string");
        match err {
            Error::TypeMismatch {
                field,
                expected,
                actual,
            } => {
                assert_eq!(field, "speed");
                assert_eq!(expected, "number");
                assert_eq!(actual, "string");
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_parameter_error() {
        let err = Error::parameter_error("speed", "division by zero");
        match err {
            Error::ParameterError { param, message } => {
                assert_eq!(param, "speed");
                assert_eq!(message, "division by zero");
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_circular_dependency() {
        let err = Error::circular_dependency("A -> B -> C -> A");
        assert!(matches!(err, Error::CircularDependency { .. }));
    }

    #[test]
    fn test_invalid_xml() {
        let err = Error::invalid_xml("Document is empty");
        assert!(matches!(err, Error::InvalidXmlStructure { .. }));
    }

    #[test]
    fn test_malformed_xml() {
        let err = Error::malformed_xml(">", "<", "line 1");
        match err {
            Error::MalformedXml {
                expected,
                found,
                location,
            } => {
                assert_eq!(expected, ">");
                assert_eq!(found, "<");
                assert_eq!(location, "line 1");
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_parse_error() {
        let err = Error::parse_error("abc", "not a number");
        match err {
            Error::ParseError { input, reason } => {
                assert_eq!(input, "abc");
                assert_eq!(reason, "not a number");
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_expression_error() {
        let err = Error::expression_error("1/0", "division by zero");
        match err {
            Error::ExpressionError { expression, reason } => {
                assert_eq!(expression, "1/0");
                assert_eq!(reason, "division by zero");
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_constraint_violation() {
        let err = Error::constraint_violation("speed cannot be negative");
        assert!(matches!(err, Error::ConstraintViolation { .. }));
    }

    #[test]
    fn test_with_context() {
        let err = Error::validation_error("speed", "invalid").with_context("while parsing vehicle");
        match err {
            Error::ValidationError { message, .. } => {
                assert!(message.contains("while parsing vehicle"));
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_error_display() {
        let err = Error::entity_not_found("ego", &["target".to_string()]);
        let msg = format!("{}", err);
        assert!(msg.contains("ego"));
    }

    #[test]
    fn test_catalog_entry_not_found() {
        let err = Error::catalog_entry_not_found("vehicles", "car1");
        match err {
            Error::CatalogEntryNotFound { catalog, entry } => {
                assert_eq!(catalog, "vehicles");
                assert_eq!(entry, "car1");
            }
            _ => panic!("Wrong error type"),
        }
    }
}