Skip to main content

ferriorm_codegen/
formatter.rs

1//! Source code formatting for generated Rust code.
2//!
3//! Uses `syn` to parse the token stream and `prettyplease` to pretty-print it.
4//! This ensures that all generated files are human-readable and consistently
5//! formatted.
6
7/// Format a token stream into a pretty-printed Rust source string.
8///
9/// # Panics
10///
11/// Panics if the generated token stream is not valid Rust syntax, which
12/// indicates a bug in the code generator.
13#[must_use]
14#[allow(clippy::needless_pass_by_value)] // Clone needed for error fallback
15pub fn format_token_stream(tokens: proc_macro2::TokenStream) -> String {
16    match syn::parse2::<syn::File>(tokens.clone()) {
17        Ok(file) => prettyplease::unparse(&file),
18        Err(e) => {
19            // On parse failure, output the raw tokens for debugging
20            eprintln!("Code generation syntax error: {e}");
21            eprintln!("Raw tokens:\n{tokens}");
22            panic!("generated code should be valid syntax: {e}");
23        }
24    }
25}