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

use std::fs::File;
use std::io::Write;

use proc_macro2::{Literal, TokenStream};
use quote::{format_ident, quote};

use blend_inspect_rs::{Blend, inspect, Type};
use itertools::Itertools;


pub fn generate(source_file: &str, target_dir: &str) -> String {

    let data = std::fs::read(source_file).unwrap();
    let blend = inspect(&data).ok().unwrap();

    let module_name = format!("blender{}_{}", blend.version().major, blend.version().minor);
    let module_name_ident = format_ident!("{}", module_name);
    let file_name = format!("{}/{}.rs", target_dir, module_name);

    let quoted_structs: Vec<TokenStream> = blend.structs()
        .sorted_by(|a, b| Ord::cmp(a.name(), b.name()))
        .map(|structure| {
            let name = format_ident!("{}", structure.name());
            let fields: Vec<TokenStream> = structure.fields()
                .map(|field| {
                    let name = match field.name() {
                        "type" => "type_",
                        "macro" => "macro_",
                        "match" => "match_",
                        "ref" => "ref_",
                        name => name,
                    };
                    let name = format_ident!("{}", name);
                    let ty = quote_type(field.data_type());
                    quote! {
                        pub #name: #ty
                    }
                })
                .collect();
            let major_version = Literal::character(blend.version().major);
            let minor_version = Literal::character(blend.version().minor);
            let patch_version = Literal::character(blend.version().patch);
            let struct_name = Literal::string(structure.name());
            let struct_index = Literal::usize_unsuffixed(structure.index());
            quote! {
                #[repr(C, packed(4))]
                pub struct #name {
                    #(#fields),*
                }
                impl GeneratedBlendStruct for #name {
                    const BLEND_VERSION: Version = Version {
                        major: #major_version,
                        minor: #minor_version,
                        patch: #patch_version
                    };
                    const STRUCT_NAME: &'static str = #struct_name;
                    const STRUCT_INDEX: usize = #struct_index;
                }
            }
        })
        .collect();

    let primitive_types_verifications = quote_primitive_types_verifications();
    let struct_verifications = quote_struct_verifications(&blend);

    let code = quote! {
        pub mod #module_name_ident {
            #![allow(non_snake_case)]
            #![allow(dead_code)]

            use crate::blend::{Function, GeneratedBlendStruct, Pointer, Version, Void};

            #(#quoted_structs)*

            #[cfg(test)]
            mod verifications {
                use super::*;
                #primitive_types_verifications
                #struct_verifications
            }
        }
    };

    let mut generated_file = File::create(&file_name).expect(&file_name);
    write!(&mut generated_file, "{:#}", code).expect("Unable to write generated.ts");

    file_name
}

fn quote_type(ty: &Type) -> TokenStream {
    match ty {
        Type::Char => {
            let ident = format_ident!("{}", "i8");
            quote!(#ident)
        },
        Type::UChar => {
            let ident = format_ident!("{}", "u8");
            quote! {
                #ident
            }
        },
        Type::Short => {
            let ident = format_ident!("{}", "i16");
            quote! {
                #ident
            }
        }
        Type::UShort => {
            let ident = format_ident!("{}", "u16");
            quote!(#ident)
        }
        Type::Int => {
            let ident = format_ident!("{}", "i32");
            quote!(#ident)
        }
        Type::Int8 => {
            let ident = format_ident!("{}", "i8");
            quote!(#ident)
        }
        Type::Int64 => {
            let ident = format_ident!("{}", "i64");
            quote!(#ident)
        }
        Type::UInt64 => {
            let ident = format_ident!("{}", "u64");
            quote!(#ident)
        }
        Type::Long => {
            let ident = format_ident!("{}", "i32");
            quote!(#ident)
        }
        Type::ULong => {
            let ident = format_ident!("{}", "u32");
            quote!(#ident)
        }
        Type::Float => {
            let ident = format_ident!("{}", "f32");
            quote!(#ident)
        }
        Type::Double => {
            let ident = format_ident!("{}", "f64");
            quote!(#ident)
        }
        Type::Void => quote!(Void),
        Type::Struct { name, size: _size } => {
            let name = format_ident!("{}", name);
            quote!(#name)
        },
        Type::Pointer { base_type, size } => {
            let size = Literal::usize_unsuffixed(*size);
            let ty = quote_type(base_type);
            quote! {
                Pointer<#ty, #size>
            }
        }
        Type::Array { base_type, length } => {
            let size = Literal::usize_unsuffixed(*length);
            let ty = quote_type(base_type);
            quote! {
                [#ty; #size]
            }
        }
        Type::Function { size } => {
            let size = Literal::usize_unsuffixed(*size );
            quote! {
                Function<#size>
            }
        },
        Type::Special { .. } => quote!(()),
    }
}

fn quote_primitive_types_verifications() -> TokenStream {
    let assertions: Vec<TokenStream> = Type::PRIMITIVES.iter()
        .map(|ty| {
            let expectation_literal = Literal::usize_unsuffixed(ty.size());
            let type_ident = quote_type(ty);
            quote! {
                assert_eq!(std::mem::size_of::<#type_ident>(), #expectation_literal);
            }
        })
        .collect();
    quote! {
        #[test]
        fn verify_primitive_types_size() {
            #(#assertions);*
        }
    }
}

fn quote_struct_verifications(blend: &Blend) -> TokenStream {
    let verifications = blend.structs()
        .map(|structure| {
            let function_name = format_ident!("verify_{}_size", structure.name());
            let type_ident = format_ident!("{}", structure.name());
            let expected_size = Literal::usize_unsuffixed(structure.size());
            quote! {
                #[test]
                fn #function_name() {
                    assert_eq!(std::mem::size_of::<#type_ident>(), #expected_size);
                }
            }
        });
    quote! {
        #(#verifications)*
    }
}