darling_core\codegen/
default_expr.rs1use proc_macro2::{Span, TokenStream};
2use quote::{quote, quote_spanned, ToTokens, TokenStreamExt};
3use syn::{spanned::Spanned, Ident, Path};
4
5const DEFAULT_STRUCT_NAME: &str = "__default";
7
8#[derive(Debug, Clone)]
10pub enum DefaultExpression<'a> {
11 Inherit(&'a Ident),
14 Explicit(&'a Path),
15 Trait {
16 span: Span,
17 },
18}
19
20impl<'a> DefaultExpression<'a> {
21 pub fn as_declaration(&'a self) -> DefaultDeclaration<'a> {
22 DefaultDeclaration(self)
23 }
24}
25
26impl<'a> ToTokens for DefaultExpression<'a> {
27 fn to_tokens(&self, tokens: &mut TokenStream) {
28 tokens.append_all(match *self {
29 DefaultExpression::Inherit(ident) => {
30 let dsn = Ident::new(DEFAULT_STRUCT_NAME, ::proc_macro2::Span::call_site());
31 quote!(#dsn.#ident)
32 }
33 DefaultExpression::Explicit(path) => {
34 quote_spanned!(path.span()=>#path())
36 }
37 DefaultExpression::Trait { span } => {
38 quote_spanned!(span=> ::darling::export::Default::default())
39 }
40 });
41 }
42}
43
44pub struct DefaultDeclaration<'a>(&'a DefaultExpression<'a>);
46
47impl<'a> ToTokens for DefaultDeclaration<'a> {
48 fn to_tokens(&self, tokens: &mut TokenStream) {
49 let name = Ident::new(DEFAULT_STRUCT_NAME, ::proc_macro2::Span::call_site());
50 let expr = self.0;
51 tokens.append_all(quote!(let #name: Self = #expr;));
52 }
53}