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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/*!
One-line description.

More detailed description, with

# Example

YYYYY

# Features

*/

#![warn(
    unknown_lints,
    // ---------- Stylistic
    absolute_paths_not_starting_with_crate,
    elided_lifetimes_in_paths,
    explicit_outlives_requirements,
    macro_use_extern_crate,
    nonstandard_style, /* group */
    noop_method_call,
    rust_2018_idioms,
    single_use_lifetimes,
    trivial_casts,
    trivial_numeric_casts,
    // ---------- Future
    future_incompatible, /* group */
    rust_2021_compatibility, /* group */
    // ---------- Public
    missing_debug_implementations,
    // missing_docs,
    unreachable_pub,
    // ---------- Unsafe
    unsafe_code,
    unsafe_op_in_unsafe_fn,
    // ---------- Unused
    unused, /* group */
)]
#![deny(
    // ---------- Public
    exported_private_dependencies,
    private_in_public,
    // ---------- Deprecated
    anonymous_parameters,
    bare_trait_objects,
    ellipsis_inclusive_range_patterns,
    // ---------- Unsafe
    deref_nullptr,
    drop_bounds,
    dyn_drop,
)]

use std::{
    collections::BTreeMap,
    env,
    fmt::{Debug, Display},
    fs::File,
    path::Path,
    str::FromStr,
};

// ------------------------------------------------------------------------------------------------
// Public Types
// ------------------------------------------------------------------------------------------------

pub const DEFAULT_DATA_DIR: &str = "data";

pub const DEFAULT_TEMPLATE_DIR: &str = "templates";

pub trait Code<T1, T2: ?Sized>: Debug + Display + FromStr + Into<T1> + AsRef<T2> {}

pub trait Data {
    fn new(type_name: &'static str) -> Self
    where
        Self: Sized;
    fn type_name(&self) -> &'static str;
    fn all_ids(&self) -> Vec<&String> {
        self.rows().keys().collect()
    }
    fn all_ids_sorted(&self) -> Value {
        let mut all_ids = self.all_ids();
        all_ids.sort();
        all_ids.dedup();
        Value::Array(
            all_ids
                .into_iter()
                .map(|s| Value::String(s.into()))
                .collect(),
        )
    }
    fn rows(&self) -> &BTreeMap<String, Map<String, Value>>;
    fn rows_mut(&mut self) -> &mut BTreeMap<String, Map<String, Value>>;
    fn into_rows(self) -> BTreeMap<String, Map<String, Value>>;
    fn contains(&self, id: &str) -> bool {
        self.rows().contains_key(id)
    }
    fn get(&self, id: &str) -> Option<&Map<String, Value>> {
        self.rows().get(id)
    }
    fn get_mut(&mut self, id: &str) -> Option<&mut Map<String, Value>> {
        self.rows_mut().get_mut(id)
    }
    fn insert_row(&mut self, id: &str, row: Map<String, Value>) {
        self.rows_mut().insert(id.to_string(), row);
    }
    fn insert_row_value(&mut self, id: &str, key: &str, value: Value) {
        let row = self.get_mut(id).unwrap();
        row.insert(key.to_string(), value);
    }
}

#[derive(Debug, Default)]
pub struct SimpleData {
    type_name: &'static str,
    rows: BTreeMap<String, Map<String, Value>>,
}

// ------------------------------------------------------------------------------------------------
// Public Macros
// ------------------------------------------------------------------------------------------------

#[macro_export]
macro_rules! code_impl {
    ($type_name:ty, $id_field:ident, $ltime:lifetime $id_type_ref:ty, $id_type:ty, $from_fn:ident) => {
        impl ::std::fmt::Display for $type_name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                write!(f, "{}", self.as_ref())
            }
        }

        impl ::std::convert::AsRef<$id_type_ref> for $type_name {
            fn as_ref(&self) -> &$ltime $id_type_ref {
                &self.$id_field()
            }
        }

        impl ::std::convert::From<$type_name> for $id_type {
            fn from(v: $type_name) -> Self {
                v.$id_field().$from_fn()
            }
        }

        impl $crate::Code<$id_type, $id_type_ref> for $type_name {}
    };
    ($type_name:ty, $id_field:ident, $id_type_ref:ty, $id_type:ty) => {
        code_impl!($type_name, $id_field, $id_type_ref, $id_type_ref, clone);
    };

    ($type_name:ty, $id_field:ident, $id_type_ref:ty) => {
        code_impl!($type_name, $id_field, $id_type_ref, $id_type_ref, clone);
    };

    ($type_name:ty, $id_field:ident) => {
        code_impl!($type_name, $id_field, 'static str, String, to_string);
    };

    ($type_name:ty) => {
        code_impl!($type_name, code, 'static str, String, to_string);
    };
}

// ------------------------------------------------------------------------------------------------
// Public Functions
// ------------------------------------------------------------------------------------------------

pub fn process<T, I, P, F, R>(
    init: I,
    process_data: P,
    finalize: F,
    render: R,
) -> Result<(), Box<dyn std::error::Error>>
where
    I: FnOnce() -> Result<T, Box<dyn std::error::Error>>,
    P: FnOnce(T) -> Result<T, Box<dyn std::error::Error>>,
    F: FnOnce(T) -> Result<tera::Context, Box<dyn std::error::Error>>,
    R: FnOnce(tera::Context) -> Result<tera::Context, Box<dyn std::error::Error>>,
{
    init()
        .and_then(process_data)
        .and_then(finalize)
        .and_then(render)?;
    Ok(())
}

pub fn default_init<T>() -> Result<T, Box<dyn std::error::Error>>
where
    T: Default,
{
    Ok(Default::default())
}

pub fn default_finalize<T>(data: T) -> Result<tera::Context, Box<dyn std::error::Error>>
where
    T: Into<tera::Context>,
{
    Ok(data.into())
}

pub fn default_finalize_for<T>(data: T) -> Result<tera::Context, Box<dyn std::error::Error>>
where
    T: Data,
{
    let mut ctx = tera::Context::new();

    ctx.insert("type_name", &Value::String(data.type_name().into()));

    ctx.insert("all_ids", &data.all_ids_sorted());

    ctx.insert(
        "codes",
        &Value::Object(
            data.into_rows()
                .into_iter()
                .map(|(key, value)| (key, Value::Object(value)))
                .collect(),
        ),
    );

    Ok(ctx)
}

#[inline]
pub fn input_file_name(name: &str) -> String {
    let file_name = format!("{}/{}", DEFAULT_DATA_DIR, name);
    rerun_if_changed(&file_name);
    file_name
}

#[inline]
pub fn rerun_if_changed(file_name: &str) {
    println!("cargo:rerun-if-changed={}", file_name);
}

#[inline]
pub fn rerun_if_template_changed(file_name: &str) {
    println!(
        "cargo:rerun-if-changed={}/{}",
        DEFAULT_TEMPLATE_DIR, file_name
    );
}

pub fn make_default_renderer<S1, S2>(
    template_name: S1,
    generated_file_name: S2,
) -> impl Fn(tera::Context) -> Result<tera::Context, Box<dyn std::error::Error>>
where
    S1: Into<String>,
    S2: Into<String>,
{
    let template_name = template_name.into();
    let generated_file_name = generated_file_name.into();
    move |ctx: tera::Context| -> Result<tera::Context, Box<dyn std::error::Error>> {
        let output_dir: String = env::var("OUT_DIR").unwrap();
        let file_name = Path::new(&output_dir).join(&generated_file_name);

        rerun_if_template_changed(&template_name);

        let tera = tera::Tera::new(&format!("{}/*._rs", DEFAULT_TEMPLATE_DIR))?;

        let file = File::create(&file_name)?;
        tera.render_to(&template_name, &ctx, file)?;

        Ok(ctx)
    }
}

// ------------------------------------------------------------------------------------------------
// Implementations
// ------------------------------------------------------------------------------------------------

impl Data for SimpleData {
    fn new(type_name: &'static str) -> Self
    where
        Self: Sized,
    {
        Self {
            type_name,
            rows: Default::default(),
        }
    }

    fn type_name(&self) -> &'static str {
        self.type_name
    }

    fn rows(&self) -> &BTreeMap<String, Map<String, Value>> {
        &self.rows
    }

    fn rows_mut(&mut self) -> &mut BTreeMap<String, Map<String, Value>> {
        &mut self.rows
    }

    fn into_rows(self) -> BTreeMap<String, Map<String, Value>> {
        self.rows
    }
}

// ------------------------------------------------------------------------------------------------
// Modules
// ------------------------------------------------------------------------------------------------

#[doc(hidden)]
mod error;
pub use error::{invalid_format, invalid_length, unknown_value, CodeParseError};
use tera::{Map, Value};