Skip to main content

layline_codegen/model/
derive.rs

1//! Derives written on generated types.
2
3use alloc::string::String;
4
5/// A derive written on a generated struct or enum.
6///
7/// A bare path derives unconditionally. [`with_cfg`](Self::with_cfg) puts the derive behind a
8/// `cfg` predicate, which is how an optional dependency reaches generated code.
9///
10/// `Module::with_derives` sets them for every item; each item's own `with_derives` adds to that.
11///
12/// ```
13/// use layline_codegen::Derive;
14///
15/// let always: Derive = "Copy".into();
16/// let gated = Derive::new("serde::Serialize").with_cfg("feature = \"serde\"");
17/// assert_eq!(always.cfg, None);
18/// assert_eq!(gated.path, "serde::Serialize");
19/// ```
20#[derive(Debug, Clone, PartialEq, Eq)]
21#[non_exhaustive]
22pub struct Derive {
23    /// The derive path, such as `serde::Serialize`.
24    pub path: String,
25    /// The `cfg` predicate the derive sits behind, such as `feature = "serde"`.
26    pub cfg: Option<String>,
27}
28
29impl Derive {
30    /// An unconditional derive of `path`.
31    #[must_use]
32    pub fn new(path: &str) -> Self {
33        Self { path: String::from(path), cfg: None }
34    }
35
36    /// Sets [`cfg`](Self::cfg).
37    #[must_use]
38    pub fn with_cfg(self, cfg: &str) -> Self {
39        Self { cfg: Some(String::from(cfg)), ..self }
40    }
41}
42
43impl From<&str> for Derive {
44    fn from(path: &str) -> Self {
45        Self::new(path)
46    }
47}
48
49impl From<String> for Derive {
50    fn from(path: String) -> Self {
51        Self { path, cfg: None }
52    }
53}