ergo-sbe 0.1.6

Opinionated, idiomatic Rust code generation for Simple Binary Encoding.
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
//! Helpers for Cargo `build.rs` scripts.
//!
//! Prefer these over hand-rolling parse → generate → write → `rerun-if-changed`.
//!
//! ```rust,no_run
//! // build.rs — ergo_sbe::miette::Result renders schema errors with a source
//! // snippet by default; Box<dyn std::error::Error> prints a raw Debug dump.
//! fn main() -> ergo_sbe::miette::Result<()> {
//!     ergo_sbe::generate_to_out_dir(
//!         "schemas/messages.xml",
//!         ergo_sbe::GenerationConfig::new("messages"),
//!     )?;
//!     Ok(())
//! }
//! ```
//!
//! Then include the generated module from `lib.rs` or `main.rs`:
//!
//! ```text
//! ergo_sbe::sbe_mod!(messages);
//! ```

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use crate::codegen::{GenerateError, GeneratedModuleSet, Generator};
use crate::config::GenerationConfig;
use crate::schema::Schema;
use crate::xml::{ParseError, parse, parse_file};

/// Errors from [`generate_to_out_dir`] / [`generate_str_to_out_dir`].
///
/// Implements [`miette::Diagnostic`] so `fn main() -> miette::Result<()>` in a
/// `build.rs` renders schema parse errors with a source snippet and span
/// instead of a raw `Debug` dump. Plain `Box<dyn std::error::Error>` prints
/// `{:?}` on failure — use `miette::Result` to get the readable form.
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
pub enum BuildError {
    /// Schema XML could not be parsed or resolved.
    #[error(transparent)]
    #[diagnostic(transparent)]
    Parse(#[from] ParseError),
    /// Code generation failed (e.g. invalid conversion config).
    #[error(transparent)]
    Generate(#[from] GenerateError),
    /// `OUT_DIR` is unset — this helper is meant for Cargo `build.rs` only.
    #[error("OUT_DIR is not set (run from a Cargo build.rs script)")]
    MissingOutDir,
    /// Failed to write a generated file.
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    /// Generator produced no modules.
    #[error("schema generated no modules")]
    Empty,
}

/// Parse a schema **file**, generate codecs, write every module under `OUT_DIR`.
///
/// Also prints `cargo::rerun-if-changed=<schema_path>` and
/// `cargo::warning=…` for non-fatal generation warnings.
///
/// `config.module_name` becomes `{module_name}.rs` (e.g. `"messages"` →
/// `$OUT_DIR/messages.rs`).
///
/// # Errors
///
/// Parse, generate, missing `OUT_DIR`, or I/O failures.
///
/// # Example
///
/// ```rust,no_run
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     ergo_sbe::generate_to_out_dir(
///         "schemas/messages.xml",
///         ergo_sbe::GenerationConfig::new("messages")
///             .enable_domain_objects(ergo_sbe::DomainVarData::Bytes),
///     )?;
///     Ok(())
/// }
/// ```
pub fn generate_to_out_dir(
    schema_path: impl AsRef<Path>,
    config: GenerationConfig,
) -> Result<GeneratedModuleSet, BuildError> {
    generate_to_dir(schema_path, config, &out_dir()?)
}

/// Parse a schema **file**, generate codecs, write every module under `out_dir`.
///
/// Same as [`generate_to_out_dir`] but with an explicit output directory.
///
/// **Samples:** write to `src/generated/` (gitignored) so rust-analyzer / IDE
/// go-to-definition works on real `.rs` files. Do **not** commit those files —
/// they are large and change whenever the generator does.
///
/// Prints `cargo::rerun-if-changed=<schema_path>` and generation warnings.
///
/// # Errors
///
/// Parse, generate, or I/O failures.
///
/// # Example
///
/// ```rust,no_run
/// // build.rs
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let out = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/generated");
///     ergo_sbe::generate_to_dir(
///         "schemas/feature-tour.xml",
///         ergo_sbe::GenerationConfig::new("feature_tour"),
///         &out,
///     )?;
///     Ok(())
/// }
///
/// ```
///
/// In `src/lib.rs`, use the real path so the IDE can jump into the implementation:
///
/// ```text
/// #[path = "generated/feature_tour.rs"]
/// mod feature_tour;
/// ```
pub fn generate_to_dir(
    schema_path: impl AsRef<Path>,
    config: GenerationConfig,
    out_dir: impl AsRef<Path>,
) -> Result<GeneratedModuleSet, BuildError> {
    let schema_path = schema_path.as_ref();
    let out_dir = out_dir.as_ref();
    fs::create_dir_all(out_dir)?;
    let ir = parse_file(schema_path)?;
    let modules = write_generated(Schema::from_ir(ir), config, out_dir)?;
    println!("cargo::rerun-if-changed={}", schema_path.display());
    // Point at stable IDE paths (e.g. src/generated). Skip for hashed OUT_DIR —
    // that would spam every product/sample build that only uses generate_to_out_dir.
    let is_cargo_out = env::var_os("OUT_DIR")
        .map(|od| out_dir.starts_with(Path::new(&od)))
        .unwrap_or(false);
    if !is_cargo_out {
        println!(
            "cargo::warning=ergo-sbe wrote {} module(s) under {} (open for go-to-definition)",
            modules.modules().len(),
            out_dir.display()
        );
    }
    Ok(modules)
}

/// Like [`generate_to_out_dir`], but from an XML string (e.g. `include_str!`).
///
/// Does **not** emit `rerun-if-changed` (no file path). Prefer
/// [`generate_to_out_dir`] when the schema lives on disk so Cargo rebuilds
/// when it changes. If you use `include_str!`, add your own
/// `cargo::rerun-if-changed` for that path.
///
/// # Errors
///
/// Parse, generate, missing `OUT_DIR`, or I/O failures.
pub fn generate_str_to_out_dir(
    schema_xml: &str,
    config: GenerationConfig,
) -> Result<GeneratedModuleSet, BuildError> {
    generate_str_to_dir(schema_xml, config, &out_dir()?)
}

/// Parse schema XML, generate codecs, write every module under `out_dir`.
///
/// Same as [`generate_str_to_out_dir`] but with an explicit output directory
/// (useful in tests or non-Cargo drivers). Does not emit `rerun-if-changed`.
///
/// # Errors
///
/// Parse, generate, or I/O failures.
pub fn generate_str_to_dir(
    schema_xml: &str,
    config: GenerationConfig,
    out_dir: &Path,
) -> Result<GeneratedModuleSet, BuildError> {
    let ir = parse(schema_xml)?;
    write_generated(Schema::from_ir(ir), config, out_dir)
}

/// Absolute path to Cargo's `OUT_DIR` (build scripts only).
///
/// # Errors
///
/// [`BuildError::MissingOutDir`] when not running under Cargo.
pub fn out_dir() -> Result<PathBuf, BuildError> {
    env::var_os("OUT_DIR")
        .map(PathBuf::from)
        .ok_or(BuildError::MissingOutDir)
}

fn write_generated(
    schema: Schema,
    config: GenerationConfig,
    out: &Path,
) -> Result<GeneratedModuleSet, BuildError> {
    let modules = Generator::new(config).generate(&schema)?;
    if modules.modules().len() == 0 {
        return Err(BuildError::Empty);
    }
    for m in modules.modules() {
        let dest = out.join(&m.path);
        if let Some(parent) = dest.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::write(&dest, &m.source)?;
    }
    for w in modules.warnings() {
        println!("cargo::warning={w}");
    }
    Ok(modules)
}

/// Include a module written by [`generate_to_out_dir`] / [`generate_str_to_out_dir`].
///
/// After `generate_to_out_dir(..., GenerationConfig::new("messages"))`:
/// `ergo_sbe::include_sbe!("messages");`
///
/// → [`samples/sbe-feature-tour/build.rs`](https://github.com/mimran1980/ergon/blob/main/samples/sbe-feature-tour/build.rs)
///
/// Expands to `include!(concat!(env!("OUT_DIR"), "/messages.rs"))`.
#[macro_export]
macro_rules! include_sbe {
    ($module:literal) => {
        include!(concat!(env!("OUT_DIR"), "/", $module, ".rs"));
    };
    ($module:ident) => {
        include!(concat!(env!("OUT_DIR"), "/", stringify!($module), ".rs"));
    };
}

/// Declare a module that includes generated SBE codecs from `OUT_DIR`.
///
/// Applies the usual `allow`s for generated code (snake/camel, unused, …).
///
/// After build.rs generates `$OUT_DIR/messages.rs`:
/// `ergo_sbe::sbe_mod!(messages);` → `mod messages { ... include!(.../messages.rs); }`
/// `ergo_sbe::sbe_mod!(pub codecs);` → public module `codecs` → `codecs.rs`
/// `ergo_sbe::sbe_mod!(pub ergo_car = "car_bench");` → `car_bench.rs`
///
/// → [`samples/sbe-feature-tour/src/lib.rs`](https://github.com/mimran1980/ergon/blob/main/samples/sbe-feature-tour/src/lib.rs)
#[macro_export]
macro_rules! sbe_mod {
    ($name:ident) => {
        mod $name {
            #![allow(
                dead_code,
                unused_imports,
                unused_variables,
                unused_mut,
                unused_assignments,
                unused_must_use,
                unused_comparisons,
                non_camel_case_types,
                non_snake_case,
                unexpected_cfgs,
                clippy::all
            )]
            include!(concat!(env!("OUT_DIR"), "/", stringify!($name), ".rs"));
        }
    };
    ($vis:vis $name:ident) => {
        $vis mod $name {
            #![allow(
                dead_code,
                unused_imports,
                unused_variables,
                unused_mut,
                unused_assignments,
                unused_must_use,
                unused_comparisons,
                non_camel_case_types,
                non_snake_case,
                unexpected_cfgs,
                clippy::all
            )]
            include!(concat!(env!("OUT_DIR"), "/", stringify!($name), ".rs"));
        }
    };
    ($name:ident = $file:literal) => {
        mod $name {
            #![allow(
                dead_code,
                unused_imports,
                unused_variables,
                unused_mut,
                unused_assignments,
                unused_must_use,
                unused_comparisons,
                non_camel_case_types,
                non_snake_case,
                unexpected_cfgs,
                clippy::all
            )]
            include!(concat!(env!("OUT_DIR"), "/", $file, ".rs"));
        }
    };
    ($vis:vis $name:ident = $file:literal) => {
        $vis mod $name {
            #![allow(
                dead_code,
                unused_imports,
                unused_variables,
                unused_mut,
                unused_assignments,
                unused_must_use,
                unused_comparisons,
                non_camel_case_types,
                non_snake_case,
                unexpected_cfgs,
                clippy::all
            )]
            include!(concat!(env!("OUT_DIR"), "/", $file, ".rs"));
        }
    };
}

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

    fn minimal_schema() -> &'static str {
        r#"<?xml version="1.0"?>
        <messageSchema package="t" id="1" version="0" byteOrder="littleEndian">
          <types>
            <composite name="messageHeader">
              <type name="blockLength" primitiveType="uint16"/>
              <type name="templateId" primitiveType="uint16"/>
              <type name="schemaId" primitiveType="uint16"/>
              <type name="version" primitiveType="uint16"/>
            </composite>
          </types>
          <message name="Ping" id="1">
            <field name="seq" id="1" type="uint32" offset="0"/>
          </message>
        </messageSchema>"#
    }

    /// Proves `ergo_sbe::miette` is publicly re-exported and usable as a
    /// `build.rs` return type without the caller adding a direct `miette`
    /// dependency. If this re-export is ever removed or made private, this
    /// fails to compile.
    #[test]
    fn miette_is_reexported_for_build_rs_return_type() {
        fn _build_rs_main() -> crate::miette::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn generate_str_to_dir_writes_module() -> Result<(), Box<dyn std::error::Error>> {
        let dir = tempfile_dir()?;
        let set = generate_str_to_dir(minimal_schema(), GenerationConfig::new("ping"), &dir)?;
        assert_eq!(set.modules().len(), 1);
        let path = dir.join("ping.rs");
        assert!(path.is_file(), "expected {}", path.display());
        let src = fs::read_to_string(&path)?;
        assert!(src.contains("PingEncoder"), "{src}");
        assert!(src.contains("PingDecoder"), "{src}");
        let _ = fs::remove_dir_all(&dir);
        Ok(())
    }

    #[test]
    fn generate_to_dir_reads_schema_file() -> Result<(), Box<dyn std::error::Error>> {
        let dir = tempfile_dir()?;
        let schema_path = dir.join("messages.xml");
        fs::write(&schema_path, minimal_schema())?;

        let explicit = dir.join("explicit");
        let set = generate_to_dir(&schema_path, GenerationConfig::new("from_file"), &explicit)?;
        assert_eq!(set.modules().len(), 1);
        assert!(explicit.join("from_file.rs").is_file());

        fs::remove_dir_all(&dir)?;
        Ok(())
    }

    /// Proves `BuildError::Parse` forwards the inner `ParseError`'s source +
    /// span through `#[diagnostic(transparent)]` — the wrapped error still
    /// renders a real snippet, not just the outer `{}`/`{:?}` message. This is
    /// what a `build.rs` returning `miette::Result<()>` actually shows on a
    /// malformed schema, instead of the raw `Debug` dump you get from
    /// `Box<dyn std::error::Error>`.
    #[test]
    fn build_error_parse_variant_renders_source_snippet_via_miette()
    -> Result<(), Box<dyn std::error::Error>> {
        let bad_xml = r#"<messageSchema package="x" id="1" version="0">
  <types><composite name="messageHeader"><type name="blockLength" primitiveType="uint16"/><type name="templateId" primitiveType="uint16"/><type name="schemaId" primitiveType="uint16"/><type name="version" primitiveType="uint16"/></composite></types>
  <message name="M" id="1"><field name="f" id="1" type="bogus"/></message>
</messageSchema>"#;

        let dir = tempfile_dir()?;
        let err = generate_str_to_dir(bad_xml, GenerationConfig::new("bad"), &dir).unwrap_err();
        let _ = fs::remove_dir_all(&dir);

        assert!(
            matches!(err, BuildError::Parse(_)),
            "expected BuildError::Parse, got {err:?}"
        );

        let mut rendered = String::new();
        miette::GraphicalReportHandler::new_themed(miette::GraphicalTheme::unicode_nocolor())
            .render_report(&mut rendered, &err)?;

        assert!(rendered.contains("bogus"), "rendered:\n{rendered}");
        assert!(
            rendered.lines().count() > 1,
            "expected a multi-line snippet through the transparent wrapper, got:\n{rendered}"
        );

        Ok(())
    }

    fn tempfile_dir() -> Result<PathBuf, Box<dyn std::error::Error>> {
        let dir = env::temp_dir().join(format!(
            "ergo_sbe_build_test_{}_{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)?
                .as_nanos()
        ));
        fs::create_dir_all(&dir)?;
        Ok(dir)
    }
}