ros2msg 0.5.3

A Rust parser for ROS2 message, service, action, and IDL files with 100% ROS2 Jazzy compatibility
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
use ros2msg::generator::{Generator, ItemInfo, ParseCallbacks};
use std::fs;
use tempfile::TempDir;

/// Custom callback for testing
struct TestCallbacks;

impl ParseCallbacks for TestCallbacks {
    fn add_derives(&self, info: &ItemInfo) -> Vec<String> {
        // Add serde derives for all types
        if info.name().contains("Message") {
            vec![
                "serde::Serialize".to_string(),
                "serde::Deserialize".to_string(),
            ]
        } else {
            vec![]
        }
    }

    fn custom_impl(&self, info: &ItemInfo) -> Option<String> {
        // Add a custom trait implementation
        Some(format!(
            "\nimpl CustomTrait for {} {{\n    fn custom_method(&self) -> &'static str {{\n        \"{}\"\n    }}\n}}\n",
            info.name(),
            info.name()
        ))
    }
}

/// Helper to create a temporary test message file
fn create_test_msg_file(
    dir: &TempDir,
    package: &str,
    name: &str,
    content: &str,
) -> std::path::PathBuf {
    let msg_dir = dir.path().join(package).join("msg");
    fs::create_dir_all(&msg_dir).unwrap();
    let file_path = msg_dir.join(format!("{}.msg", name));
    fs::write(&file_path, content).unwrap();
    file_path
}

#[test]
fn test_callbacks_add_derives() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("generated");

    let msg_file = create_test_msg_file(&temp_dir, "test_msgs", "TestMessage", "int32 value\n");

    let result = Generator::new()
        .derive_debug(true)
        .parse_callbacks(Box::new(TestCallbacks))
        .include(msg_file.to_str().unwrap())
        .output_dir(output_dir.to_str().unwrap())
        .generate();

    assert!(result.is_ok());

    let generated_file = output_dir
        .join("test_msgs")
        .join("msg")
        .join("test_message.rs");
    let content = fs::read_to_string(&generated_file).unwrap();

    // Check that serde derives were added
    assert!(content.contains("serde::Serialize"));
    assert!(content.contains("serde::Deserialize"));
}

#[test]
fn test_callbacks_custom_impl() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("generated");

    let msg_file = create_test_msg_file(&temp_dir, "test_msgs", "TestMessage", "int32 value\n");

    let result = Generator::new()
        .derive_debug(true)
        .parse_callbacks(Box::new(TestCallbacks))
        .include(msg_file.to_str().unwrap())
        .output_dir(output_dir.to_str().unwrap())
        .generate();

    assert!(result.is_ok());

    let generated_file = output_dir
        .join("test_msgs")
        .join("msg")
        .join("test_message.rs");
    let content = fs::read_to_string(&generated_file).unwrap();

    // Check that custom trait implementation was added
    assert!(content.contains("impl CustomTrait for TestMessage"));
    assert!(content.contains("fn custom_method(&self)"));
}

#[test]
fn test_callbacks_with_non_message_type() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("generated");

    let msg_file = create_test_msg_file(
        &temp_dir,
        "test_msgs",
        "Data", // Name doesn't contain "Message"
        "int32 value\n",
    );

    let result = Generator::new()
        .derive_debug(true)
        .parse_callbacks(Box::new(TestCallbacks))
        .include(msg_file.to_str().unwrap())
        .output_dir(output_dir.to_str().unwrap())
        .generate();

    assert!(result.is_ok());

    let generated_file = output_dir.join("test_msgs").join("msg").join("data.rs");
    let content = fs::read_to_string(&generated_file).unwrap();

    // Serde derives should not be added for non-Message types
    assert!(!content.contains("serde::Serialize") || content.contains("impl CustomTrait"));
}

/// No-op callback for testing
struct NoOpCallbacks;

impl ParseCallbacks for NoOpCallbacks {
    fn add_derives(&self, _info: &ItemInfo) -> Vec<String> {
        vec![]
    }

    fn custom_impl(&self, _info: &ItemInfo) -> Option<String> {
        None
    }
}

#[test]
fn test_noop_callbacks() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("generated");

    let msg_file = create_test_msg_file(&temp_dir, "test_msgs", "TestMessage", "int32 value\n");

    let result = Generator::new()
        .derive_debug(true)
        .parse_callbacks(Box::new(NoOpCallbacks))
        .include(msg_file.to_str().unwrap())
        .output_dir(output_dir.to_str().unwrap())
        .generate();

    assert!(result.is_ok(), "Generation failed: {:?}", result.err());

    let generated_file = output_dir
        .join("test_msgs")
        .join("msg")
        .join("test_message.rs");
    let content = fs::read_to_string(&generated_file).unwrap();

    // Should only have the standard derives
    assert!(content.contains("Debug"));
    assert!(!content.contains("serde::"));
    assert!(!content.contains("impl CustomTrait"));
}

/// Custom callback for testing sequence/string type mapping
struct TypeMappingCallbacks;

impl ParseCallbacks for TypeMappingCallbacks {
    fn sequence_type(
        &self,
        element_type: &str,
        max_size: Option<u32>,
        _ros2_type: &str,
    ) -> Option<String> {
        // Use custom BoundedVec for bounded sequences, regular Vec for unbounded
        if let Some(size) = max_size {
            Some(format!("BoundedVec<{}, {}>", element_type, size))
        } else {
            Some(format!("MyVec<{}>", element_type))
        }
    }

    fn string_type(&self, max_size: Option<u32>) -> Option<String> {
        // Use custom bounded string for bounded, regular for unbounded
        if let Some(size) = max_size {
            Some(format!("BoundedString<{}>", size))
        } else {
            Some("MyString".to_string())
        }
    }

    fn wstring_type(&self, max_size: Option<u32>) -> Option<String> {
        // Use custom wide string types
        if let Some(size) = max_size {
            Some(format!("BoundedWString<{}>", size))
        } else {
            Some("WideString".to_string())
        }
    }
}

#[test]
fn test_callbacks_custom_sequence_type() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("generated");

    // Create message with unbounded sequence
    let msg_file =
        create_test_msg_file(&temp_dir, "test_msgs", "SeqTest", "int32[] unbounded_seq\n");

    let result = Generator::new()
        .derive_debug(true)
        .parse_callbacks(Box::new(TypeMappingCallbacks))
        .include(msg_file.to_str().unwrap())
        .output_dir(output_dir.to_str().unwrap())
        .generate();

    assert!(result.is_ok(), "Generation failed: {:?}", result.err());

    let generated_file = output_dir.join("test_msgs").join("msg").join("seq_test.rs");
    let content = fs::read_to_string(&generated_file).unwrap();

    // Should use custom MyVec type for unbounded sequence
    assert!(
        content.contains("MyVec<i32>"),
        "Expected MyVec<i32> in: {}",
        content
    );
}

#[test]
fn test_callbacks_custom_bounded_sequence_type() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("generated");

    // Create message with bounded sequence
    let msg_file = create_test_msg_file(
        &temp_dir,
        "test_msgs",
        "BoundedSeqTest",
        "float64[<=10] bounded_seq\n",
    );

    let result = Generator::new()
        .derive_debug(true)
        .parse_callbacks(Box::new(TypeMappingCallbacks))
        .include(msg_file.to_str().unwrap())
        .output_dir(output_dir.to_str().unwrap())
        .generate();

    assert!(result.is_ok(), "Generation failed: {:?}", result.err());

    let generated_file = output_dir
        .join("test_msgs")
        .join("msg")
        .join("bounded_seq_test.rs");
    let content = fs::read_to_string(&generated_file).unwrap();

    // Should use custom BoundedVec type for bounded sequence
    assert!(
        content.contains("BoundedVec<f64, 10>"),
        "Expected BoundedVec<f64, 10> in: {}",
        content
    );
}

#[test]
fn test_callbacks_custom_string_type() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("generated");

    // Create message with unbounded string
    let msg_file = create_test_msg_file(
        &temp_dir,
        "test_msgs",
        "StringTest",
        "string unbounded_str\n",
    );

    let result = Generator::new()
        .derive_debug(true)
        .parse_callbacks(Box::new(TypeMappingCallbacks))
        .include(msg_file.to_str().unwrap())
        .output_dir(output_dir.to_str().unwrap())
        .generate();

    assert!(result.is_ok(), "Generation failed: {:?}", result.err());

    let generated_file = output_dir
        .join("test_msgs")
        .join("msg")
        .join("string_test.rs");
    let content = fs::read_to_string(&generated_file).unwrap();

    // Should use custom MyString type
    assert!(
        content.contains("MyString"),
        "Expected MyString in: {}",
        content
    );
}

#[test]
fn test_callbacks_custom_bounded_string_type() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("generated");

    // Create message with bounded string
    let msg_file = create_test_msg_file(
        &temp_dir,
        "test_msgs",
        "BoundedStringTest",
        "string<=50 bounded_str\n",
    );

    let result = Generator::new()
        .derive_debug(true)
        .parse_callbacks(Box::new(TypeMappingCallbacks))
        .include(msg_file.to_str().unwrap())
        .output_dir(output_dir.to_str().unwrap())
        .generate();

    assert!(result.is_ok(), "Generation failed: {:?}", result.err());

    let generated_file = output_dir
        .join("test_msgs")
        .join("msg")
        .join("bounded_string_test.rs");
    let content = fs::read_to_string(&generated_file).unwrap();

    // Should use custom BoundedString type
    assert!(
        content.contains("BoundedString<50>"),
        "Expected BoundedString<50> in: {}",
        content
    );
}

#[test]
fn test_callbacks_custom_wstring_type() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("generated");

    // Create message with wstring
    let msg_file =
        create_test_msg_file(&temp_dir, "test_msgs", "WStringTest", "wstring wide_str\n");

    let result = Generator::new()
        .derive_debug(true)
        .parse_callbacks(Box::new(TypeMappingCallbacks))
        .include(msg_file.to_str().unwrap())
        .output_dir(output_dir.to_str().unwrap())
        .generate();

    assert!(result.is_ok(), "Generation failed: {:?}", result.err());

    // Note: WStringTest becomes w_string_test.rs (snake_case)
    let generated_file = output_dir
        .join("test_msgs")
        .join("msg")
        .join("w_string_test.rs");
    let content = fs::read_to_string(&generated_file).unwrap();

    // Should use custom WideString type
    assert!(
        content.contains("WideString"),
        "Expected WideString in: {}",
        content
    );
}

#[test]
fn test_callbacks_custom_bounded_wstring_type() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("generated");

    // Create message with bounded wstring
    let msg_file = create_test_msg_file(
        &temp_dir,
        "test_msgs",
        "BoundedWStringTest",
        "wstring<=100 bounded_wide_str\n",
    );

    let result = Generator::new()
        .derive_debug(true)
        .parse_callbacks(Box::new(TypeMappingCallbacks))
        .include(msg_file.to_str().unwrap())
        .output_dir(output_dir.to_str().unwrap())
        .generate();

    assert!(result.is_ok(), "Generation failed: {:?}", result.err());

    // Note: BoundedWStringTest becomes bounded_w_string_test.rs (snake_case)
    let generated_file = output_dir
        .join("test_msgs")
        .join("msg")
        .join("bounded_w_string_test.rs");
    let content = fs::read_to_string(&generated_file).unwrap();

    // Should use custom BoundedWString type
    assert!(
        content.contains("BoundedWString<100>"),
        "Expected BoundedWString<100> in: {}",
        content
    );
}

// ============================================================================
// Module callback tests
// ============================================================================

use ros2msg::generator::{ModuleInfo, ModuleLevel};

/// Callbacks that add re-exports after type modules
struct ReexportCallbacks;

impl ParseCallbacks for ReexportCallbacks {
    fn post_module(&self, info: &ModuleInfo) -> Option<String> {
        // Re-export all items from type modules
        if matches!(info.module_level(), ModuleLevel::Type(_)) {
            Some(format!("pub use {}::*;", info.module_name()))
        } else {
            None
        }
    }
}

#[test]
fn test_callbacks_post_module_reexport() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("generated");

    let msg_file = create_test_msg_file(&temp_dir, "test_msgs", "Header", "int32 seq\n");

    let result = Generator::new()
        .derive_debug(true)
        .parse_callbacks(Box::new(ReexportCallbacks))
        .include(msg_file.to_str().unwrap())
        .output_dir(output_dir.to_str().unwrap())
        .generate();

    assert!(result.is_ok(), "Generation failed: {:?}", result.err());

    // Check the msg/mod.rs file has the re-export
    let msg_mod = output_dir.join("test_msgs").join("msg").join("mod.rs");
    let content = fs::read_to_string(&msg_mod).unwrap();

    assert!(
        content.contains("pub mod header;"),
        "Expected 'pub mod header;' in: {}",
        content
    );
    assert!(
        content.contains("pub use header::*;"),
        "Expected 'pub use header::*;' in: {}",
        content
    );
}

/// Callbacks that add doc comments before modules
struct DocCommentCallbacks;

impl ParseCallbacks for DocCommentCallbacks {
    fn pre_module(&self, info: &ModuleInfo) -> Option<String> {
        match info.module_level() {
            ModuleLevel::Package => Some(format!("/// Package: {}\n", info.module_name())),
            ModuleLevel::InterfaceKind(kind) => Some(format!("/// Interface: {:?}\n", kind)),
            ModuleLevel::Type(kind) => Some(format!(
                "/// Type module: {} ({:?})\n",
                info.module_name(),
                kind
            )),
        }
    }
}

#[test]
fn test_callbacks_pre_module_doc_comments() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("generated");

    let msg_file = create_test_msg_file(&temp_dir, "my_pkg", "Point", "float64 x\nfloat64 y\n");

    let result = Generator::new()
        .derive_debug(true)
        .parse_callbacks(Box::new(DocCommentCallbacks))
        .include(msg_file.to_str().unwrap())
        .output_dir(output_dir.to_str().unwrap())
        .generate();

    assert!(result.is_ok(), "Generation failed: {:?}", result.err());

    // Check root mod.rs has package doc comment
    let root_mod = output_dir.join("mod.rs");
    let root_content = fs::read_to_string(&root_mod).unwrap();
    assert!(
        root_content.contains("/// Package: my_pkg"),
        "Expected package doc comment in root mod.rs: {}",
        root_content
    );

    // Check package mod.rs has interface doc comment
    let pkg_mod = output_dir.join("my_pkg").join("mod.rs");
    let pkg_content = fs::read_to_string(&pkg_mod).unwrap();
    assert!(
        pkg_content.contains("/// Interface: Message"),
        "Expected interface doc comment in package mod.rs: {}",
        pkg_content
    );

    // Check msg/mod.rs has type doc comment
    let msg_mod = output_dir.join("my_pkg").join("msg").join("mod.rs");
    let msg_content = fs::read_to_string(&msg_mod).unwrap();
    assert!(
        msg_content.contains("/// Type module: point (Message)"),
        "Expected type doc comment in msg mod.rs: {}",
        msg_content
    );
}

/// Callbacks that test ModuleInfo accessors by verifying full_path
struct FullPathCallbacks;

impl ParseCallbacks for FullPathCallbacks {
    fn post_module(&self, info: &ModuleInfo) -> Option<String> {
        // Add a comment with the full path for verification
        Some(format!("// full_path: {}\n", info.full_path()))
    }
}

#[test]
fn test_module_info_full_path() {
    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("generated");

    let msg_file = create_test_msg_file(&temp_dir, "geometry_msgs", "Pose", "float64 x\n");

    let result = Generator::new()
        .derive_debug(true)
        .parse_callbacks(Box::new(FullPathCallbacks))
        .include(msg_file.to_str().unwrap())
        .output_dir(output_dir.to_str().unwrap())
        .generate();

    assert!(result.is_ok(), "Generation failed: {:?}", result.err());

    // Check root mod.rs has package full_path
    let root_mod = output_dir.join("mod.rs");
    let root_content = fs::read_to_string(&root_mod).unwrap();
    assert!(
        root_content.contains("// full_path: geometry_msgs"),
        "Expected full_path comment in root mod.rs: {}",
        root_content
    );

    // Check package mod.rs has interface full_path
    let pkg_mod = output_dir.join("geometry_msgs").join("mod.rs");
    let pkg_content = fs::read_to_string(&pkg_mod).unwrap();
    assert!(
        pkg_content.contains("// full_path: geometry_msgs::msg"),
        "Expected full_path comment in package mod.rs: {}",
        pkg_content
    );

    // Check msg/mod.rs has type full_path
    let msg_mod = output_dir.join("geometry_msgs").join("msg").join("mod.rs");
    let msg_content = fs::read_to_string(&msg_mod).unwrap();
    assert!(
        msg_content.contains("// full_path: geometry_msgs::msg::pose"),
        "Expected full_path comment in msg mod.rs: {}",
        msg_content
    );
}