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
// Do not use this crate. It is only meant for internal use. Use `format-bytes`
// instead.
//
// Copyright 2020, Raphaël Gomès <rgomes@octobus.net>

/// `extern crate` Required even for 2018 edition
extern crate proc_macro;

mod utils;

use proc_macro2::TokenStream;
use proc_macro_hack::proc_macro_hack;
use quote::quote;
use syn::parse_macro_input;

/// This macro is documented in the main crate.
#[proc_macro_hack]
pub fn write_bytes(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let args = parse_macro_input!(input as utils::WriteBytesArgs);
    inner_write_bytes(&args).into()
}

/// This is the unit-testable version using `proc_macro2`
fn inner_write_bytes(args: &utils::WriteBytesArgs) -> TokenStream {
    let format_string = &args.format_string;
    let input = format_string.value();
    let positions = match utils::extract_formatting_positions(&input) {
        Ok(pos) => pos,
        Err(_) => {
            return quote! {compile_error!("unclosed formatting delimiter")}
        }
    };

    if positions.len() > args.positional_args.len() {
        return quote! {compile_error!("not enough arguments for formatting")};
    }
    if positions.len() < args.positional_args.len() {
        return quote! {compile_error!("too many arguments for formatting")};
    }

    let calls = utils::generate_write_calls(args, &input, &positions);
    let output = &args.output;
    let combined = utils::combine_result_expressions(calls);

    quote! {
        {
            let mut output: &mut _ = #output;
            #combined
        }
    }
}