rustbridge-cli 1.0.1

Build tool and code generator for rustbridge
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
//! C header generation from Rust `#[repr(C)]` structs
//!
//! This module parses Rust source files and generates C header files
//! containing equivalent struct definitions for FFI binary transport.

use anyhow::{Context, Result};
use std::fs;
use std::path::Path;
use syn::{Attribute, Fields, Item, Type};

/// Type mapping from Rust to C
struct TypeMapping {
    rust_type: &'static str,
    c_type: &'static str,
}

const TYPE_MAPPINGS: &[TypeMapping] = &[
    TypeMapping {
        rust_type: "u8",
        c_type: "uint8_t",
    },
    TypeMapping {
        rust_type: "i8",
        c_type: "int8_t",
    },
    TypeMapping {
        rust_type: "u16",
        c_type: "uint16_t",
    },
    TypeMapping {
        rust_type: "i16",
        c_type: "int16_t",
    },
    TypeMapping {
        rust_type: "u32",
        c_type: "uint32_t",
    },
    TypeMapping {
        rust_type: "i32",
        c_type: "int32_t",
    },
    TypeMapping {
        rust_type: "u64",
        c_type: "uint64_t",
    },
    TypeMapping {
        rust_type: "i64",
        c_type: "int64_t",
    },
    TypeMapping {
        rust_type: "usize",
        c_type: "size_t",
    },
    TypeMapping {
        rust_type: "isize",
        c_type: "ptrdiff_t",
    },
    TypeMapping {
        rust_type: "f32",
        c_type: "float",
    },
    TypeMapping {
        rust_type: "f64",
        c_type: "double",
    },
    TypeMapping {
        rust_type: "bool",
        c_type: "bool",
    },
];

/// A parsed `#[repr(C)]` struct
#[derive(Debug)]
struct CStruct {
    name: String,
    fields: Vec<CField>,
    doc_comment: Option<String>,
}

/// A field within a C struct
#[derive(Debug)]
struct CField {
    name: String,
    c_type: String,
    doc_comment: Option<String>,
}

/// A constant definition (e.g., message IDs)
#[derive(Debug)]
struct CConstant {
    name: String,
    c_type: String,
    value: String,
    doc_comment: Option<String>,
}

/// Parse a Rust source file and extract `#[repr(C)]` structs and constants
fn parse_rust_file(source_path: &Path) -> Result<(Vec<CStruct>, Vec<CConstant>)> {
    let source = fs::read_to_string(source_path)
        .with_context(|| format!("Failed to read source file: {}", source_path.display()))?;

    let ast = syn::parse_file(&source)
        .with_context(|| format!("Failed to parse Rust file: {}", source_path.display()))?;

    let mut structs = Vec::new();
    let mut constants = Vec::new();

    for item in ast.items {
        match item {
            Item::Struct(s) => {
                if is_repr_c(&s.attrs)
                    && let Some(c_struct) = parse_struct(&s)
                {
                    structs.push(c_struct);
                }
            }
            Item::Const(c) => {
                if let Some(constant) = parse_constant(&c) {
                    constants.push(constant);
                }
            }
            _ => {}
        }
    }

    Ok((structs, constants))
}

/// Check if a struct has `#[repr(C)]` attribute
fn is_repr_c(attrs: &[Attribute]) -> bool {
    attrs.iter().any(|attr| {
        if attr.path().is_ident("repr")
            && let Ok(nested) = attr.parse_args::<syn::Ident>()
        {
            return nested == "C";
        }
        false
    })
}

/// Extract doc comment from attributes
fn extract_doc_comment(attrs: &[Attribute]) -> Option<String> {
    let docs: Vec<String> = attrs
        .iter()
        .filter_map(|attr| {
            if attr.path().is_ident("doc")
                && let syn::Meta::NameValue(meta) = &attr.meta
                && let syn::Expr::Lit(syn::ExprLit {
                    lit: syn::Lit::Str(s),
                    ..
                }) = &meta.value
            {
                return Some(s.value().trim().to_string());
            }
            None
        })
        .collect();

    if docs.is_empty() {
        None
    } else {
        Some(docs.join("\n"))
    }
}

/// Parse a syn struct into our CStruct representation
fn parse_struct(s: &syn::ItemStruct) -> Option<CStruct> {
    let name = s.ident.to_string();
    let doc_comment = extract_doc_comment(&s.attrs);

    let fields = match &s.fields {
        Fields::Named(named) => named
            .named
            .iter()
            .filter_map(|field| {
                let field_name = field.ident.as_ref()?.to_string();
                let c_type = rust_type_to_c(&field.ty)?;
                let doc_comment = extract_doc_comment(&field.attrs);

                Some(CField {
                    name: field_name,
                    c_type,
                    doc_comment,
                })
            })
            .collect(),
        _ => return None, // Only support named fields
    };

    Some(CStruct {
        name,
        fields,
        doc_comment,
    })
}

/// Parse a constant definition
fn parse_constant(c: &syn::ItemConst) -> Option<CConstant> {
    let name = c.ident.to_string();

    // Only export MSG_ prefixed constants (message IDs)
    if !name.starts_with("MSG_") {
        return None;
    }

    let c_type = rust_type_to_c(&c.ty)?;

    // Extract the literal value
    let value = match c.expr.as_ref() {
        syn::Expr::Lit(syn::ExprLit {
            lit: syn::Lit::Int(i),
            ..
        }) => i.base10_digits().to_string(),
        _ => return None,
    };

    let doc_comment = extract_doc_comment(&c.attrs);

    Some(CConstant {
        name,
        c_type,
        value,
        doc_comment,
    })
}

/// Convert a Rust type to its C equivalent
fn rust_type_to_c(ty: &Type) -> Option<String> {
    match ty {
        Type::Path(path) => {
            let ident = path.path.segments.last()?.ident.to_string();
            TYPE_MAPPINGS
                .iter()
                .find(|m| m.rust_type == ident)
                .map(|m| m.c_type.to_string())
        }
        Type::Array(arr) => {
            // Handle fixed-size arrays like [u8; 64]
            let elem_type = rust_type_to_c(&arr.elem)?;
            let len = match &arr.len {
                syn::Expr::Lit(syn::ExprLit {
                    lit: syn::Lit::Int(i),
                    ..
                }) => i.base10_digits().to_string(),
                _ => return None,
            };
            Some(format!("{elem_type}[{len}]"))
        }
        Type::Ptr(ptr) => {
            let elem_type = rust_type_to_c(&ptr.elem)?;
            if ptr.mutability.is_some() {
                Some(format!("{elem_type}*"))
            } else {
                Some(format!("const {elem_type}*"))
            }
        }
        _ => None,
    }
}

/// Generate C header content from parsed structs and constants
fn generate_header(structs: &[CStruct], constants: &[CConstant], source_name: &str) -> String {
    let mut output = String::new();

    // Header guard
    let guard_name = source_name.to_uppercase().replace(['.', '-'], "_");
    output.push_str("// Auto-generated by rustbridge generate-header\n");
    output.push_str(&format!("// Source: {source_name}\n"));
    output.push_str("// DO NOT EDIT - regenerate with: rustbridge generate-header\n\n");
    output.push_str(&format!("#ifndef {guard_name}_H\n"));
    output.push_str(&format!("#define {guard_name}_H\n\n"));
    output.push_str("#include <stdint.h>\n");
    output.push_str("#include <stdbool.h>\n");
    output.push_str("#include <stddef.h>\n\n");
    output.push_str("#ifdef __cplusplus\n");
    output.push_str("extern \"C\" {\n");
    output.push_str("#endif\n\n");

    // Constants
    if !constants.is_empty() {
        output.push_str("// Message IDs\n");
        for constant in constants {
            if let Some(doc) = &constant.doc_comment {
                output.push_str(&format!("/** {} */\n", doc));
            }
            output.push_str(&format!(
                "#define {} (({}){})\n",
                constant.name, constant.c_type, constant.value
            ));
        }
        output.push('\n');
    }

    // Structs
    for c_struct in structs {
        if let Some(doc) = &c_struct.doc_comment {
            output.push_str("/**\n");
            for line in doc.lines() {
                output.push_str(&format!(" * {line}\n"));
            }
            output.push_str(" */\n");
        }
        output.push_str(&format!("typedef struct {} {{\n", c_struct.name));

        for field in &c_struct.fields {
            if let Some(doc) = &field.doc_comment {
                output.push_str(&format!("    /** {} */\n", doc));
            }

            // Handle array types specially (C syntax: type name[size])
            if field.c_type.contains('[') {
                let parts: Vec<&str> = field.c_type.splitn(2, '[').collect();
                output.push_str(&format!("    {} {}[{};\n", parts[0], field.name, parts[1]));
            } else {
                output.push_str(&format!("    {} {};\n", field.c_type, field.name));
            }
        }

        output.push_str(&format!("}} {};\n\n", c_struct.name));
    }

    // Footer
    output.push_str("#ifdef __cplusplus\n");
    output.push_str("}\n");
    output.push_str("#endif\n\n");
    output.push_str(&format!("#endif // {guard_name}_H\n"));

    output
}

/// Run the header generation command
pub fn run(source: &str, output: &str, verify: bool) -> Result<()> {
    let source_path = Path::new(source);
    let output_path = Path::new(output);

    println!("Parsing Rust source: {}", source_path.display());
    let (structs, constants) = parse_rust_file(source_path)?;

    if structs.is_empty() {
        anyhow::bail!("No #[repr(C)] structs found in {}", source_path.display());
    }

    println!(
        "Found {} struct(s) and {} constant(s)",
        structs.len(),
        constants.len()
    );

    let source_name = source_path
        .file_name()
        .map(|s| s.to_string_lossy().to_string())
        .unwrap_or_else(|| "unknown".to_string());

    let header = generate_header(&structs, &constants, &source_name);

    fs::write(output_path, &header)
        .with_context(|| format!("Failed to write header file: {}", output_path.display()))?;

    println!("Generated header: {}", output_path.display());

    if verify {
        verify_header(output_path)?;
    }

    Ok(())
}

/// Verify the generated header compiles with a C compiler.
///
/// Uses the `cc` crate to find an available C compiler (gcc, clang, MSVC)
/// in a cross-platform way, then invokes it with syntax-check-only flags.
fn verify_header(header_path: &Path) -> Result<()> {
    println!("Verifying header with C compiler...");

    // Set minimal environment variables the cc crate expects
    // SAFETY: This is a single-threaded CLI tool, so modifying environment
    // variables is safe.
    setup_cc_env();

    // Use cc crate to find the C compiler
    let compiler = cc::Build::new()
        .cargo_metadata(false)
        .opt_level(0)
        .try_get_compiler()
        .with_context(|| "Failed to find C compiler. Install gcc, clang, or MSVC.")?;

    let cc_path = compiler.path();
    println!("Using compiler: {}", cc_path.display());

    // Create a temporary directory for the verification
    let temp_dir = std::env::temp_dir().join("rustbridge-header-verify");
    fs::create_dir_all(&temp_dir)
        .with_context(|| format!("Failed to create temp dir: {}", temp_dir.display()))?;

    // Create a minimal C file that includes the header
    let test_c_path = temp_dir.join("verify_header.c");
    let header_abs = header_path
        .canonicalize()
        .with_context(|| format!("Failed to resolve header path: {}", header_path.display()))?;

    // Convert path to a format suitable for C #include directive:
    // - Use forward slashes (works on all platforms in C)
    // - Remove Windows extended-length path prefix (\\?\)
    let header_include_path = {
        let path_str = header_abs.to_string_lossy();
        // Remove \\?\ prefix that Windows canonicalize() adds
        let path_str = path_str.strip_prefix(r"\\?\").unwrap_or(&path_str);
        // Convert backslashes to forward slashes for C compatibility
        path_str.replace('\\', "/")
    };

    let test_c_content = format!(
        r#"// Auto-generated verification file
#include "{}"

// Ensure structs are usable
int main(void) {{
    return 0;
}}
"#,
        header_include_path
    );

    // Write test file and ensure it's closed before invoking compiler
    fs::write(&test_c_path, test_c_content.as_bytes())
        .with_context(|| format!("Failed to create test file: {}", test_c_path.display()))?;

    // Build compiler command with appropriate syntax-check flags
    let mut cmd = compiler.to_command();

    // Add compiler-specific flags for syntax checking only
    if compiler.is_like_msvc() {
        // MSVC: /Zs for syntax check only, /nologo to suppress banner
        cmd.args(["/Zs", "/nologo"]);
    } else {
        // GCC/Clang: -fsyntax-only
        cmd.arg("-fsyntax-only");
    }

    cmd.arg(&test_c_path);

    let output = cmd
        .output()
        .with_context(|| format!("Failed to execute compiler: {}", cc_path.display()))?;

    // Clean up temp files (best effort)
    let _ = fs::remove_file(&test_c_path);
    let _ = fs::remove_dir_all(&temp_dir);

    if output.status.success() {
        println!("Header verification passed");
        Ok(())
    } else {
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        let combined = if stdout.is_empty() {
            stderr.to_string()
        } else if stderr.is_empty() {
            stdout.to_string()
        } else {
            format!("{}\n{}", stderr, stdout)
        };
        anyhow::bail!("Header verification failed:\n{}", combined);
    }
}

/// Set up minimal environment variables required by the cc crate.
///
/// The cc crate expects certain Cargo environment variables to be present.
/// This function sets them to reasonable defaults for the current platform.
fn setup_cc_env() {
    // SAFETY: This is a single-threaded CLI tool, so modifying environment
    // variables is safe. We only set them if they're not already present.
    unsafe {
        let target = get_current_target();

        if std::env::var("TARGET").is_err() {
            std::env::set_var("TARGET", &target);
        }
        if std::env::var("HOST").is_err() {
            std::env::set_var("HOST", &target);
        }
        if std::env::var("OPT_LEVEL").is_err() {
            std::env::set_var("OPT_LEVEL", "0");
        }
        if std::env::var("DEBUG").is_err() {
            std::env::set_var("DEBUG", "false");
        }
    }
}

/// Get the current target triple based on the platform.
fn get_current_target() -> String {
    let arch = std::env::consts::ARCH;
    let os = std::env::consts::OS;

    match (arch, os) {
        ("x86_64", "linux") => "x86_64-unknown-linux-gnu".to_string(),
        ("x86_64", "macos") => "x86_64-apple-darwin".to_string(),
        ("x86_64", "windows") => "x86_64-pc-windows-msvc".to_string(),
        ("aarch64", "linux") => "aarch64-unknown-linux-gnu".to_string(),
        ("aarch64", "macos") => "aarch64-apple-darwin".to_string(),
        ("aarch64", "windows") => "aarch64-pc-windows-msvc".to_string(),
        _ => format!("{arch}-unknown-{os}"),
    }
}

#[cfg(test)]
mod tests {
    #![allow(non_snake_case)]

    use super::*;

    #[test]
    fn rust_type_to_c___primitive_types___maps_correctly() {
        let ty: Type = syn::parse_quote!(u32);
        assert_eq!(rust_type_to_c(&ty), Some("uint32_t".to_string()));

        let ty: Type = syn::parse_quote!(i64);
        assert_eq!(rust_type_to_c(&ty), Some("int64_t".to_string()));

        let ty: Type = syn::parse_quote!(f32);
        assert_eq!(rust_type_to_c(&ty), Some("float".to_string()));
    }

    #[test]
    fn rust_type_to_c___array_types___maps_correctly() {
        let ty: Type = syn::parse_quote!([u8; 64]);
        assert_eq!(rust_type_to_c(&ty), Some("uint8_t[64]".to_string()));

        let ty: Type = syn::parse_quote!([i32; 10]);
        assert_eq!(rust_type_to_c(&ty), Some("int32_t[10]".to_string()));
    }

    #[test]
    fn rust_type_to_c___pointer_types___maps_correctly() {
        let ty: Type = syn::parse_quote!(*const u8);
        assert_eq!(rust_type_to_c(&ty), Some("const uint8_t*".to_string()));

        let ty: Type = syn::parse_quote!(*mut u8);
        assert_eq!(rust_type_to_c(&ty), Some("uint8_t*".to_string()));
    }

    #[test]
    fn generate_header___structs___produces_valid_c() {
        let structs = vec![CStruct {
            name: "TestStruct".to_string(),
            fields: vec![
                CField {
                    name: "value".to_string(),
                    c_type: "uint32_t".to_string(),
                    doc_comment: Some("The value".to_string()),
                },
                CField {
                    name: "data".to_string(),
                    c_type: "uint8_t[64]".to_string(),
                    doc_comment: None,
                },
            ],
            doc_comment: Some("A test struct".to_string()),
        }];

        let constants = vec![CConstant {
            name: "MSG_TEST".to_string(),
            c_type: "uint32_t".to_string(),
            value: "42".to_string(),
            doc_comment: Some("Test message ID".to_string()),
        }];

        let header = generate_header(&structs, &constants, "test.rs");

        assert!(header.contains("#ifndef TEST_RS_H"));
        assert!(header.contains("#define TEST_RS_H"));
        assert!(header.contains("typedef struct TestStruct"));
        assert!(header.contains("uint32_t value;"));
        assert!(header.contains("uint8_t data[64];"));
        assert!(header.contains("#define MSG_TEST ((uint32_t)42)"));
        assert!(header.contains("/** The value */"));
        assert!(header.contains(" * A test struct"));
    }
}