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
//! Implementation of procedural macros for barse.

#![warn(
    clippy::all,
    clippy::pedantic,
    clippy::perf,
    clippy::style,
    clippy::disallowed_types,
    clippy::indexing_slicing,
    clippy::clone_on_ref_ptr,
    clippy::create_dir,
    clippy::default_numeric_fallback,
    clippy::empty_drop,
    clippy::empty_structs_with_brackets,
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::float_equality_without_abs,
    clippy::float_cmp,
    clippy::float_cmp_const,
    clippy::format_push_string,
    clippy::get_unwrap,
    clippy::if_then_some_else_none,
    clippy::impl_trait_in_params,
    clippy::mixed_read_write_in_expression,
    clippy::mod_module_files,
    clippy::multiple_unsafe_ops_per_block,
    clippy::undocumented_unsafe_blocks,
    clippy::partial_pub_fields,
    clippy::panic,
    clippy::semicolon_if_nothing_returned,
    clippy::semicolon_inside_block,
    clippy::str_to_string,
    clippy::todo,
    clippy::try_err,
    clippy::unneeded_field_pattern,
    clippy::unseparated_literal_suffix,
    clippy::fallible_impl_from,
    clippy::future_not_send,
    clippy::option_if_let_else,
    clippy::or_fun_call,
    clippy::path_buf_push_overwrite,
    clippy::redundant_pub_crate,
    clippy::redundant_allocation,
    clippy::significant_drop_tightening,
    clippy::useless_let_if_seq,
    rustdoc::all,
    missing_copy_implementations,
    missing_debug_implementations,
    missing_docs
)]

use std::fmt;

use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote, quote_spanned};
use syn::{spanned::Spanned, FnArg, ItemFn, Type, TypeReference};

mod condition;
mod from_byte_reader;
mod size_query;
mod vec_len_query;

/// Derive a `FromByteReader` implementation.
#[must_use]
pub fn derive_from_byte_reader(item: TokenStream) -> TokenStream {
    let ast = parse_as!(item as syn::DeriveInput);
    simplify_result(from_byte_reader::impl_trait(&ast))
}

/// Create a `ByteSizeQuery` implementor from a function.
#[must_use]
pub fn byte_size_query(attr: TokenStream, item: TokenStream) -> TokenStream {
    let name = parse_as!(attr as Ident);
    let body = parse_as!(item as ItemFn);

    let gen_trait = simplify_result(size_query::generate_impl(&name, &body));

    quote! {
        #body
        #gen_trait
    }
}

/// Create a Condition implementor from a function.
#[must_use]
pub fn condition(attr: TokenStream, item: TokenStream) -> TokenStream {
    let name = parse_as!(attr as Ident);
    let body = parse_as!(item as ItemFn);

    let gen_trait = simplify_result(condition::generate_impl(&name, &body));

    quote! {
        #body
        #gen_trait
    }
}

/// Create a `VecLenQuery` implementor from a function.
#[must_use]
pub fn vec_len_query(attr: TokenStream, item: TokenStream) -> TokenStream {
    let name = parse_as!(attr as Ident);
    let body = parse_as!(item as ItemFn);

    let gen_trait = simplify_result(vec_len_query::generate_impl(&name, &body));

    quote! {
        #body
        #gen_trait
    }
}

fn simplify_result<T>(res: Result<T, T>) -> T {
    match res {
        Ok(t) | Err(t) => t,
    }
}

fn dyn_mangle(ident: &Ident) -> Ident {
    format_ident!("__dyn_barse_derive_i{ident}")
}

fn dyn_mangle_display<D>(disp: D) -> Ident
where
    D: fmt::Display,
{
    format_ident!("__dyn_disp_barse_derive_i{disp}")
}

fn static_mangle(ident: &str) -> Ident {
    format_ident!("__static_barse_derive_i{ident}")
}

fn fn_name_and_type(body: &ItemFn) -> Result<(&Ident, &Type), proc_macro2::TokenStream> {
    let fn_name = &body.sig.ident;

    if !body.sig.generics.params.is_empty() {
        let span = body.sig.generics.span();
        return Err(quote_spanned! {
            span=> compile_error!("annotated function can not have generic params or lifetimes")
        });
    }

    if body.sig.inputs.len() != 1 {
        let span = body.sig.inputs.span();
        return Err(quote_spanned! {
            span=> compile_error!("annotated function should have one and only have one parameter")
        });
    }

    let Some(FnArg::Typed(flag_param)) = &body.sig.inputs.first() else {
        let span = body.sig.inputs.span();
        return Err(quote_spanned!{
            span=> compile_error!("annotated function should have a non-self parameter")
        });
    };

    let Type::Reference(TypeReference {
        lifetime: None,
        mutability: None,
        elem: ty,
        ..
    }) = &*flag_param.ty else {
        let span = flag_param.span();
        return Err(quote_spanned!{
            span=> compile_error!("annotaded function should have it's param be a immutable reference with no specified lifetime")
        });
    };

    Ok((fn_name, ty))
}

macro_rules! parse_as {
    ($e:path as $ty:ty) => {
        match syn::parse2::<$ty>($e) {
            Err(err) => return err.into_compile_error(),
            Ok(val) => val,
        }
    };
}
use parse_as;