Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Exercise: Display Derive

In this exercise, you will walk through the conceptual implementation of a custom Display derive macro using the syn and quote crates.

Since we are running this in a single-file environment without a separate proc-macro = true crate setup, we will write a normal Rust function that takes simulated token streams (using proc_macro2 and quote!), parses them with syn, generates the output with quote!, and asserts that the generated code is correct.

Your task:

Implement the derive_display_impl function to:

  1. Parse the incoming token stream input into a syn::DeriveInput struct.

  2. Extract the name (identifier) of the struct.

  3. Generate and return a token stream implementing std::fmt::Display for that struct name, which formats the struct using its name, names of its fields, and their values. (e.g., printing MyAwesomeType { a: 50, }).

    The names of the struct’s fields can be obtained with the provided struct_fields function.

This will rely on a Cargo.toml resembling:

[package]
name = "proc-macro-exercise"
version = "0.1.0"
edition = "2024"
publish = false

[[bin]]
name = "proc-macro-exercise"
path = "exercise.rs"

[dependencies]
proc-macro2 = "1.0"
quote = "1.0"
syn = "2.0"
use proc_macro2::TokenStream;
use quote::{ToTokens, quote};
use syn::{DeriveInput, parse2};

fn struct_fields(ast: &syn::DeriveInput) -> Vec<proc_macro2::TokenStream> {
    if let syn::Data::Struct(syn::DataStruct { fields, .. }) = &ast.data {
        match fields {
            syn::Fields::Named(n) => n
                .named
                .iter()
                .map(|f| {
                    f.ident.as_ref().expect("named field name").to_token_stream()
                })
                .collect(),
            syn::Fields::Unnamed(un) => (0..un.unnamed.len())
                .map(|i| syn::Index::from(i).to_token_stream())
                .collect(),
            syn::Fields::Unit => vec![],
        }
    } else {
        vec![]
    }
}

fn derive_display_impl(input: TokenStream) -> TokenStream {
    // TODO: Parse the input TokenStream into DeriveInput.
    // TODO: Extract the identifier of the struct.
    // TODO: Generate the impl std::fmt::Display using quote!.
    todo!()
}

fn main() {
    let input = quote! {
        struct MyAwesomeType {
            field: i32,
        }
    };

    let output = derive_display_impl(input.clone());
    let output_str = output.to_string();

    println!("Generated code:\n{}", output_str);

    // Check for patterns that should definitely be present in generated code.
    assert!(output_str.contains("impl std :: fmt :: Display for MyAwesomeType"));
    assert!(output_str.contains("\"MyAwesomeType\""));
    assert!(output_str.contains("self . field"));

    // Compile program using the impl to ensure generated code impls `Display`.
    let use_display = quote! {
        fn main() {
            let a = MyAwesomeType { field: 42 };
            println!("{a}");
        }
    };
    let source_str = input.to_string() + &output_str + &use_display.to_string();
    invoke_rustc(&source_str)
        .expect("rustc on generated code produced errors or warnings")
}

fn invoke_rustc(input: &str) -> Result<(), String> {
    use std::io::Write;
    use std::process::Command;

    // Invoke the rustc binary to compile generated code
    let mut child = Command::new("rustc")
        .args(["--verbose", "-"])
        .stdin(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to spawn child process");
    {
        let mut stdin = child.stdin.take().expect("Failed to open stdin");
        stdin.write_all(input.as_bytes()).unwrap();
    }

    // Print the stderr retrieved from rustc
    let stderr = child.wait_with_output().unwrap().stderr;
    let stderr = String::from_utf8_lossy(&stderr).into_owned();
    // Return error on non-empty stderr
    if stderr.is_empty() { Ok(()) } else { Err(stderr) }
}
  • parse2(input) is the proc_macro2 version of parse_macro_input!, which we can use for unit testing or within normal Rust functions.
  • The return value of derive_display_impl is a proc_macro2::TokenStream, which can be converted to a string using to_string() for easy debugging.