manifest 0.2.0

Message catalogs with compile-time guarantees
Documentation
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
#![doc = include_str!("../README.md")]
//!
//! ## Feature flags
//!
#![cfg_attr(
    feature = "docs-features",
    cfg_attr(doc, doc = ::document_features::document_features!())
)]

#[cfg(feature = "objects")]
#[doc(hidden)]
pub use const_str::equal;

#[cfg(feature = "objects")]
/// Message is the trait implemented by all Message references returned by the `lookup` function.
pub trait Message: std::fmt::Display {
    /// Returns the unique identifier of the message.
    fn id(&self) -> u16;
    /// Returns the message text.
    ///
    /// Note that this is not the equivalent to the constant value but the raw message text from
    /// the catalogue. The constant equivalent is returned by the `Display` implementation required
    /// by the trait.
    fn message(&self) -> &'static str;
}

/// Includes a message catalogue defined in Manifest.toml as constants into the calling crate.
///
/// The messages in this catalogue look like this:
///
/// ```toml
/// [1]
/// message = "user login"
/// comment = "User successfully logged in"
///
/// [100]
/// message = "deprecated feature"
/// comment = "This feature is no longer supported"
/// deprecated = "Use feature XYZ instead"
/// ```
///
/// Keys (such as 1 or 100) are unique `u16` values. Duplicate entries lead to a build error.
///
/// The resulting constants must be used if the optional attribute deprecated is not present. If it is present,
/// the const is marked as deprecated instead. Comments are optional and will be included as documentation if set.
///
/// Constant names are generated by constantizing the following elements:
///
/// - The name of the crate (e.g. `TEST_CRATE`)
/// - The id of the message, zero padded to 5 digits (e.g. `00001`)
/// - The message in the catalogue (e.g. `USER_LOGIN`)
///
/// The final result is a constant like this that maps to a compile-time string literal:
///
/// ```ignore
/// ///User successfully logged in
/// #[deny(dead_code)]
/// pub(crate) const TEST_CRATE_00001_USER_LOGIN: &str = "user login (TEST_CRATE_00001)";
/// ```
///
/// When using the optional _objects_ feature, a `Message` struct is also generated:
///
/// ```ignore
/// /// A Message denotes a message from a message catalogue (defined as Manifest.toml) of immutable messages for audit or business intelligence logging.
/// #[derive(Debug, Eq, PartialEq)]
/// pub struct Message {
///     pub id: u16,
///     pub message: &'static str,
///     _private: (),
/// }
/// ```
///
/// Static instance of such Messages can be obtained by calling `Message::lookup` and passing it the constant. Passing
/// an unknown constant value will result in a panic:
///
/// ```ignore
/// pub(crate) const fn lookup(constant: &'static str) -> &'static Self
/// ```
///
/// Such instances can be used to pass an instance of any message constant around for use cases beyond logging such as e.g.
/// passing them to a database layer.
///
/// In contrast to the constants the message field in a `Message` struct is exactly the message defined in the manifest. The
/// equivalent to the constant value is available through a [Display](std::fmt::Display) implementation.
#[macro_export]
macro_rules! include_manifest {
    () => {
        include!(concat!(env!("OUT_DIR"), "/manifest.rs"));
    };
}

/// Functionality for build scripts using message catalogues. Requires the `build` feature.
#[cfg(feature = "build")]
pub mod build {
    use std::fmt;
    use std::fs;
    use std::marker::PhantomData;
    use std::path::PathBuf;

    use indexmap::IndexMap;
    use proc_macro2::{Span, TokenStream};
    use quote::quote;
    use serde::{
        Deserialize,
        de::{Deserializer, MapAccess, Visitor},
    };
    use syn::{self, Ident};

    macro_rules! message_const_format {
        () => {
            "{}_{:05}_{}"
        };
    }

    macro_rules! message_display_format {
        () => {
            "{} ({}_{:05})"
        };
    }

    #[derive(Debug)]
    struct Catalog<T>(IndexMap<u16, T>);

    #[derive(Deserialize)]
    struct Message {
        #[serde(default)]
        comment: Option<String>,
        #[serde(default)]
        deprecated: Option<String>,
        message: String,
    }

    impl<T> AsRef<IndexMap<u16, T>> for Catalog<T> {
        fn as_ref(&self) -> &IndexMap<u16, T> {
            &self.0
        }
    }

    impl<'de, T: Deserialize<'de>> Deserialize<'de> for Catalog<T> {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            struct MapVisitor<T>(PhantomData<T>);

            impl<'de, T: Deserialize<'de>> Visitor<'de> for MapVisitor<T> {
                type Value = Catalog<T>;

                fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                    f.write_str("a map with unique u16 keys")
                }

                fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
                    let mut res = IndexMap::new();

                    while let Some(key) = map.next_key::<String>()? {
                        let key: u16 = key.parse().map_err(|_| {
                            serde::de::Error::custom(format!("invalid key: expected u16"))
                        })?;

                        if res.insert(key, map.next_value()?).is_some() {
                            return Err(serde::de::Error::custom(format!(
                                "duplicate key: {}",
                                key
                            )));
                        }
                    }

                    Ok(Catalog(res))
                }
            }

            deserializer.deserialize_map(MapVisitor(PhantomData))
        }
    }

    /// Generate a constant name from a prefix, id, and message
    ///
    /// # Arguments
    /// * `prefix` - The prefix to use (e.g., "MANIFEST")
    /// * `id` - The message ID (u16, 0-65535)
    /// * `message` - The message text
    ///
    /// # Returns
    /// A constant name in the format `{PREFIX}_{ID:05}_{MESSAGE_UPPERCASE_ALPHANUMERIC}`
    ///
    /// # Examples
    /// ```
    /// # use manifest::build::constantize;
    /// assert_eq!(constantize("APP", 1, "user login"), "APP_00001_USER_LOGIN");
    /// assert_eq!(constantize("APP", 42, "login-failed!"), "APP_00042_LOGIN_FAILED_");
    /// ```
    #[cfg_attr(feature = "docs-test", visibility::make(pub))]
    fn constantize(prefix: &str, id: u16, message: &str) -> String {
        let message_part = message
            .to_uppercase()
            .chars()
            .map(|c| if c.is_alphanumeric() { c } else { '_' })
            .collect::<String>();

        format!(message_const_format!(), prefix, id, message_part)
    }

    /// Generate constants and optionally objects associated with the Manifest.toml file.
    ///
    /// See [include_manifest!] macro for usage details and the generated data structure.
    pub fn generate() {
        println!("cargo::rustc-check-cfg=cfg(no_inline_lookup)");

        let prefix = std::env::var("CARGO_PKG_NAME")
            .expect("CARGO_PKG_NAME not set")
            .to_uppercase();

        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set");
        let input = PathBuf::from(manifest_dir).join("Manifest.toml");

        let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR not set");
        let output = PathBuf::from(out_dir).join("manifest.rs");

        generate_at(&prefix, input, output);
    }

    #[cfg(feature = "objects")]
    fn generate_objects(
        prefix: &str,
        const_map: &IndexMap<String, (&u16, &Message)>,
    ) -> TokenStream {
        let constants = const_map
            .iter()
            .map(|(constant, (id, message))| {
                let ident = Ident::new(constant, Span::call_site());
                let id = *id;
                let message = &message.message;

                quote! {
                    static #ident: Message = Message { id: #id, message: #message, _private: () };
                }
            })
            .collect::<TokenStream>();

        let lookup_chain = const_map
            .iter()
            .map(|(constant, (id, message))| {
                let ident = Ident::new(constant, Span::call_site());
                let message = &message.message;

                let display = format!(message_display_format!(), message, prefix, id);

                quote! {
                    if equal!(constant, #display) {
                        return &#ident
                    }
                }
            })
            .collect::<TokenStream>();

        let message_display_format = message_display_format!();

        quote! {

            /// Prefix for all messages (which is a constantized version of the crate name).
            const PREFIX: &'static str = #prefix;

            /// A Message denotes a message from a message catalogue (defined as Manifest.toml) of immutable messages for audit or business intelligence logging.
            #[derive(Debug, Eq, PartialEq)]
            pub struct Message {
                pub id: u16,
                pub message: &'static str,
                _private: (),
            }

            impl Message {

                /// Lookup and return a static Message struct reference from its constant equivalent.
                ///
                /// # Panics
                ///
                /// This function will panic if the constant parameter is not defined in the message catalogue.
                #[cfg_attr(not(no_inline_lookup), inline(always))]
                pub(crate) const fn lookup(constant: &'static str) -> &'static Self {

                    use manifest::equal;

                    #constants

                    #lookup_chain

                    panic!("unknown constant");
                }
            }

            impl manifest::Message for &'static Message {
                fn id(&self) -> u16 {
                    self.id
                }

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

            impl std::fmt::Display for Message {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    write!(f, #message_display_format, self.message, PREFIX, self.id)
                }
            }

        }
    }

    #[cfg(not(feature = "objects"))]
    fn generate_objects(
        _prefix: &str,
        _const_map: &IndexMap<String, (&u16, &Message)>,
    ) -> TokenStream {
        quote! {}
    }

    fn generate_at(prefix: &str, input: PathBuf, output: PathBuf) {
        println!("cargo:rerun-if-changed={}", input.display());

        let content = fs::read_to_string(&input)
            .unwrap_or_else(|err| panic!("failed to read {:?}: {}", input, err));
        let messages: Catalog<Message> = toml::from_str(&content)
            .unwrap_or_else(|err| panic!("failed to parse {:?}: {}", input, err));

        let const_map: IndexMap<String, (&u16, &Message)> = messages
            .as_ref()
            .iter()
            .map(|(id, message)| {
                let key = constantize(prefix, *id, &message.message);
                let value = (id, message);
                (key, value)
            })
            .collect();

        let constants = const_map.iter().map(|(constant, (id, message))| {
            let ident = Ident::new(constant, Span::call_site());

            let attribute = if let Some(reason) = &message.deprecated {
                quote! {
                    #[allow(dead_code)]
                    #[deprecated(note = #reason)]
                }
            } else {
                quote! {
                    #[deny(dead_code)]
                }
            };

            let comment = message.comment.as_ref().map(|comment| {
                quote! {
                    #[doc = #comment]
                }
            });

            let message = format!(message_display_format!(), &message.message, prefix, *id);

            quote! {
                #comment
                #attribute
                pub(crate) const #ident: &str = #message;

            }
        });

        let objects = generate_objects(prefix, &const_map);

        let output_code = quote! {

            #(#constants)*

            #objects

        };

        let ast = syn::parse2(output_code).unwrap();
        let formatted = prettyplease::unparse(&ast);

        fs::write(&output, formatted)
            .unwrap_or_else(|err| panic!("failed to write to {:?}: {}", output, err));
    }

    #[cfg(test)]
    mod tests {
        use std::collections::HashMap;

        use proptest::prelude::*;

        use super::*;

        #[test]
        fn test_deserialize_keep_order() {
            let toml = r#"
        [items]
        2 = "second"
        3 = "third"
        1 = "first"
        "#;

            let data: HashMap<String, Catalog<String>> = toml::from_str(toml).unwrap();
            let map = data.get("items").unwrap().as_ref();

            assert_eq!(map.len(), 3);
            assert_eq!(map.get(&1), Some(&"first".to_string()));
            assert_eq!(map.get(&2), Some(&"second".to_string()));
            assert_eq!(map.get(&3), Some(&"third".to_string()));

            let keys: Vec<_> = map.iter().map(|(k, _)| *k).collect();
            assert_eq!(keys, vec![2, 3, 1]);
        }

        #[test]
        fn test_deserialize_fail_duplicate_keys() {
            let toml = r#"
        [items]
        1 = "first"
        2 = "second"
        1 = "duplicate"
        "#;
            let res: Result<HashMap<String, Catalog<String>>, _> = toml::from_str(toml);

            assert!(res.is_err());
            let err_msg = res.unwrap_err().to_string();
            assert!(
                err_msg.contains("duplicate key") || err_msg.contains("duplicate"),
                "Error was: {}",
                err_msg
            );
        }

        #[test]
        fn test_make_constant_name_basic() {
            assert_eq!(constantize("APP", 1, "user login"), "APP_00001_USER_LOGIN");
        }

        #[test]
        fn test_make_constant_name_with_special_chars() {
            assert_eq!(
                constantize("APP", 42, "login-failed!"),
                "APP_00042_LOGIN_FAILED_"
            );
        }

        #[test]
        fn test_make_constant_name_with_numbers() {
            assert_eq!(
                constantize("DOMAIN", 123, "error 404 not found"),
                "DOMAIN_00123_ERROR_404_NOT_FOUND"
            );
        }

        #[test]
        fn test_make_constant_name_max_u16() {
            assert_eq!(constantize("X", 65535, "test"), "X_65535_TEST");
        }

        #[test]
        fn test_make_constant_name_empty_message() {
            assert_eq!(constantize("PREFIX", 1, ""), "PREFIX_00001_");
        }

        proptest! {
            #[test]
            fn prop_never_panics(prefix in "\\PC*", id: u16, message in "\\PC*") {
                let _ = constantize(&prefix, id, &message);
            }

            #[test]
            fn prop_contains_padded_id(prefix in "[a-zA-Z_]+", id: u16, message in "\\PC*") {
                let res = constantize(&prefix, id, &message);
                let expected_id = format!("{:05}", id);
                assert!(res.contains(&expected_id),
                    "res '{}' should contain ID '{}'", res, expected_id);
            }

            #[test]
            fn prop_starts_with_prefix(prefix in "[a-zA-Z_][a-zA-Z0-9_]*", id: u16, message in "\\PC*") {
                let res = constantize(&prefix, id, &message);
                assert!(res.starts_with(&prefix),
                    "res '{}' should start with prefix '{}'", res, prefix);
            }

            #[test]
            fn prop_only_valid_identifier_chars(prefix in "[a-zA-Z_]+", id: u16, message in "\\PC*") {
                let res = constantize(&prefix, id, &message);
                assert!(res.chars().all(|c| c.is_alphanumeric() || c == '_'),
                    "res '{}' contains invalid identifier characters", res);
            }

            #[test]
            fn prop_pure(prefix in "\\PC*", id: u16, message in "\\PC*") {
                let res1 = constantize(&prefix, id, &message);
                let res2 = constantize(&prefix, id, &message);
                assert_eq!(res1, res2, "function should be pure");
            }

            #[test]
            fn prop_message_uppercased(prefix in "[a-zA-Z_]+", id: u16, message in "[a-z ]+") {
                let res = constantize(&prefix, id, &message);
                let message_upper = message.to_uppercase();
                let expected_message = message_upper.replace(' ', "_");
                assert!(res.ends_with(&expected_message),
                    "res '{}' should end with uppercased message '{}'", res, expected_message);
            }
        }
    }
}