icydb-model-macros 0.253.2

Procedural macros for IcyDB application models
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
//! Module: node::traits
//! Responsibility: derive-side node parsing.
//! Does not own: runtime schema semantics.
//! Boundary: macro metadata to node models.

use crate::case::{Case, Casing};
use crate::prelude::*;

///
/// HasDef
///

pub trait HasDef {
    fn def(&self) -> &Def;

    fn current_name_literal(&self, name: Option<&LitStr>) -> LitStr {
        name.cloned().unwrap_or_else(|| {
            let ident = self.def().ident();
            LitStr::new(&ident.to_string(), ident.span())
        })
    }
}

///
/// ValidateNode
///
/// Runs input validation for macro arguments before code generation.
///

pub trait ValidateNode {
    fn validate(&self) -> Result<(), DarlingError>;

    /// Fatal validation errors that must short-circuit macro expansion.
    fn fatal_errors(&self) -> Vec<syn::Error> {
        Vec::new()
    }
}

///
/// TraitTokens
///
/// Result of trait resolution — combines derived traits and manual impls.
///

pub struct TraitTokens {
    pub(crate) derive: TokenStream,
    pub(crate) impls: TokenStream,
}

///
/// HasMacro
///
/// High-level entrypoint for procedural code generation.
/// Coordinates schema emission, type emission, and trait impl generation.
///

pub trait HasMacro: HasSchema + HasTraits + HasType + ToTokens {
    /// Generate all Rust tokens for this node: schema consts, derives, main type, and impls.
    fn all_tokens(&self) -> TokenStream {
        let TraitTokens { derive, impls } = self.resolve_trait_tokens();
        let schema = self.schema_tokens();
        let type_part = self.type_part();

        quote! {
            // SCHEMA CONSTANT
            #schema

            // MAIN TYPE
            #derive
            #type_part

            // IMPLEMENTATIONS
            #impls
        }
    }

    /// Resolve all derive + impl traits for this node, returning combined code.
    fn resolve_trait_tokens(&self) -> TraitTokens {
        let mut derive_traits = Vec::new();
        let mut attrs = Vec::new();
        let mut impls = TokenStream::new();
        let mut has_serde_deserialize = false;

        for tr in self.traits() {
            let Some(strategy) = self.trait_strategy(tr) else {
                impls.extend(
                    self.missing_trait_strategy_error(self.application_type_kind(), tr)
                        .write_errors(),
                );
                continue;
            };

            if let Some(ts) = strategy.imp {
                impls.extend(ts);
            }

            if let Some(derive_tr) = strategy.derive
                && let Some(path) = derive_tr.derive_path()
            {
                if matches!(derive_tr, TraitKind::Deserialize) {
                    has_serde_deserialize = true;
                }
                if matches!(derive_tr, TraitKind::CandidType) {
                    attrs.push(quote!(
                        #[candid_path("::icydb_model::__reexports::candid")]
                    ));
                }
                derive_traits.push(path);
            }
        }

        let mut derive = if derive_traits.is_empty() {
            quote!()
        } else {
            quote!(#[derive(#(#derive_traits),*)])
        };

        if has_serde_deserialize {
            attrs.push(quote!(#[serde(crate = "::icydb_model::__reexports::serde")]));
        }

        derive.extend(attrs);

        TraitTokens { derive, impls }
    }
}

/// Blanket implementation so any node that satisfies the constraints
/// automatically gets full macro generation.
impl<T> HasMacro for T where T: HasDef + HasSchema + HasTraits + HasType + ToTokens {}

///
/// HasType
///
/// A node that emits a Rust type definition.
///

pub trait HasType: HasDef {
    /// Emit the main Rust type definition (struct, enum, etc.)
    fn type_part(&self) -> TokenStream {
        quote!()
    }
}

///
/// HasTypeExpr
///

pub trait HasTypeExpr {
    fn type_expr(&self) -> TokenStream {
        quote!()
    }
}

///
/// HasTraits
///
/// Describes which traits a schema node implements or derives,
/// and provides default strategies for common trait patterns.
///
/// This layer is responsible only for *trait selection* and *impl generation logic*,
/// not for assembling the final macro output.
///

pub trait HasTraits: HasType {
    /// Application node kind used by the node-aware trait resolver.
    fn application_type_kind(&self) -> Option<ApplicationTypeKind> {
        None
    }

    /// Authored trait directives for an application value node.
    fn trait_builder(&self) -> Option<&TraitBuilder> {
        None
    }

    /// Compiler- and shape-owned traits before authored directives are applied.
    fn trait_baseline(&self) -> TraitSet {
        application_type_trait_set()
    }

    /// List of traits this node participates in (either derived or implemented).
    fn traits(&self) -> Vec<TraitKind> {
        let Some(builder) = self.trait_builder() else {
            return Vec::new();
        };

        builder.build_for_type(self.trait_baseline()).into_vec()
    }

    /// Map a specific trait to a custom implementation.
    /// Return `None` to use the `default_strategy` fallback.
    fn map_trait(&self, _: TraitKind) -> Option<TraitStrategy> {
        None
    }

    /// Provides built-in fallback strategies for common trait types.
    ///
    /// Most schema nodes rely on these automatically unless overridden in `map_trait`.
    fn default_strategy(&self, t: TraitKind) -> Option<TraitStrategy> {
        let def = self.def();
        let ident = def.ident();

        match t {
            // ─────────────────────────────
            // Inline constant path metadata
            // ─────────────────────────────
            TraitKind::Path => {
                let q = quote! {
                    const PATH: &'static str = concat!(module_path!(), "::", stringify!(#ident));
                };
                let tokens = Implementor::new(def, t).set_tokens(q).to_token_stream();

                Some(TraitStrategy::from_impl(tokens))
            }

            // ─────────────────────────────
            // Marker traits — empty impls
            // ─────────────────────────────
            TraitKind::NormalizeAuto
            | TraitKind::NormalizeCustom
            | TraitKind::ValidateAuto
            | TraitKind::ValidateCustom
            | TraitKind::Visitable => {
                let tokens = Implementor::new(def, t).to_token_stream();
                Some(TraitStrategy::from_impl(tokens))
            }

            _ => None,
        }
    }

    /// Resolve a selected trait to its sole derive or implementation strategy.
    fn trait_strategy(&self, trait_kind: TraitKind) -> Option<TraitStrategy> {
        self.map_trait(trait_kind)
            .or_else(|| self.default_strategy(trait_kind))
            .or_else(|| {
                trait_kind
                    .derive_path()
                    .map(|_| TraitStrategy::from_derive(trait_kind))
            })
    }

    /// Validate directives against the complete node/shape baseline and prove
    /// that every selected trait has an emission strategy.
    fn validate_traits(&self) -> Result<(), DarlingError> {
        let Some(node_kind) = self.application_type_kind() else {
            return Ok(());
        };
        let Some(builder) = self.trait_builder() else {
            return Err(DarlingError::custom(format!(
                "internal {} trait resolver has no authored directive owner",
                node_kind.as_str(),
            )));
        };

        let baseline = self.trait_baseline();
        builder.validate_for_type(node_kind, baseline.clone())?;
        let selected = builder.build_for_type(baseline).into_vec();
        for trait_kind in selected {
            let Some(strategy) = self.trait_strategy(trait_kind) else {
                return Err(self.missing_trait_strategy_error(Some(node_kind), trait_kind));
            };
            let has_impl = strategy
                .imp
                .as_ref()
                .is_some_and(|tokens| !tokens.is_empty());
            let has_derive = strategy
                .derive
                .is_some_and(|derived| derived.derive_path().is_some());
            if !has_impl && !has_derive {
                return Err(self.missing_trait_strategy_error(Some(node_kind), trait_kind));
            }
        }

        Ok(())
    }

    fn missing_trait_strategy_error(
        &self,
        node_kind: Option<ApplicationTypeKind>,
        trait_kind: TraitKind,
    ) -> DarlingError {
        let node_kind = node_kind.map_or("generated node", ApplicationTypeKind::as_str);
        DarlingError::custom(format!(
            "generated trait '{trait_kind:?}' for {} {} has no derive or implementation strategy",
            node_kind,
            self.def().ident(),
        ))
        .with_span(&self.def().ident())
    }
}

// Keep the identical generated collection baseline and strategy dispatch in
// the trait owner. Each collection node supplies only its node kind; concrete
// strategy implementations remain specialized through `Imp<Node>`.
macro_rules! impl_collection_has_traits {
    ($node:ty, $kind:ident) => {
        impl HasTraits for $node {
            fn application_type_kind(&self) -> Option<ApplicationTypeKind> {
                Some(ApplicationTypeKind::$kind)
            }

            fn trait_builder(&self) -> Option<&TraitBuilder> {
                Some(&self.traits)
            }

            fn trait_baseline(&self) -> TraitSet {
                let mut traits = application_type_trait_set();
                traits.extend([
                    TraitKind::Default,
                    TraitKind::Deref,
                    TraitKind::DerefMut,
                    TraitKind::From,
                    TraitKind::FromIterator,
                    TraitKind::IntoIterator,
                ]);

                traits
            }

            fn map_trait(&self, trait_kind: TraitKind) -> Option<TraitStrategy> {
                match trait_kind {
                    TraitKind::From => FromTrait::strategy(self),
                    TraitKind::FromIterator => FromIteratorTrait::strategy(self),
                    TraitKind::IntoIterator => IntoIteratorTrait::strategy(self),
                    TraitKind::NormalizeAuto => NormalizeAutoTrait::strategy(self),
                    TraitKind::ValidateAuto => ValidateAutoTrait::strategy(self),
                    TraitKind::Visitable => VisitableTrait::strategy(self),
                    _ => None,
                }
            }
        }
    };
}

pub(crate) use impl_collection_has_traits;

///
/// HasSchema
///
/// Anything that can emit a schema constant.
///

pub trait HasSchema: HasSchemaPart + HasDef {
    /// The kind of schema node this represents (Entity, Enum, etc.)
    fn schema_node_kind() -> SchemaNodeKind;

    /// The uppercase snake-case constant name used in the generated schema file.
    fn schema_const(&self) -> Ident {
        let ident_s = self.def().ident().to_string().to_case(Case::UpperSnake);
        format_ident!("{ident_s}_CONST")
    }

    /// Emits the full schema constant + registration constructor.
    fn schema_tokens(&self) -> TokenStream {
        let schema_expr = self.schema_part();
        if schema_expr.is_empty() {
            return quote!();
        }

        let const_var = self.schema_const();
        let ctor = format_ident!(
            "__icydb_register_{}",
            const_var.to_string().to_case(Case::Snake)
        );
        let kind = Self::schema_node_kind();

        quote! {
            const #const_var: ::icydb_model::node::#kind = #schema_expr;

            #[cfg(not(target_arch = "wasm32"))]
            #[::icydb_model::__reexports::ctor::ctor(
                unsafe,
                anonymous,
                crate_path = ::icydb_model::__reexports::ctor
            )]
            fn #ctor() {
                ::icydb_model::build::register_node(
                    ::icydb_model::node::SchemaNode::#kind(#const_var)
                );
            }
        }
    }
}

#[derive(Debug)]
#[remain::sorted]
pub enum SchemaNodeKind {
    Canister,
    Entity,
    Enum,
    List,
    Map,
    Newtype,
    Normalizer,
    Record,
    Set,
    Store,
    Tuple,
    Validator,
}

impl ToTokens for SchemaNodeKind {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        format_ident!("{self:?}").to_tokens(tokens);
    }
}

///
/// HasSchemaPart
///
/// Low-level helper for schema fragments.
///

pub trait HasSchemaPart {
    fn schema_part(&self) -> TokenStream {
        quote!()
    }
}