Skip to main content

xbrlkit_derive/
lib.rs

1//! `#[derive(FromXbrl)]` for [xbrlkit](https://docs.rs/xbrlkit).
2//!
3//! Binds the fields of a struct to XBRL concepts. The binding lives in
4//! `#[xbrl(..)]` attributes and nowhere else, so the struct's serde names stay
5//! its Rust names — which is what reaches JSON, Arrow and Parquet.
6//!
7//! Depend on `xbrlkit` and use the derive it re-exports; this crate is not
8//! meant to be used on its own, and the code it generates refers to
9//! `::xbrlkit`.
10//!
11//! ```ignore
12//! use xbrlkit::FromXbrl;
13//!
14//! #[derive(Default, FromXbrl)]
15//! #[xbrl(instant)]
16//! pub struct BalanceSheet {
17//!     /// The date the figures are as of.
18//!     #[xbrl(period_end)]
19//!     pub as_of: Option<String>,
20//!
21//!     #[xbrl(concept = "us-gaap:Assets")]
22//!     pub assets: Option<f64>,
23//!
24//!     /// The first concept the filing reports wins.
25//!     #[xbrl(concept = "us-gaap:Liabilities", alias = "us-gaap:LiabilitiesNoncurrent")]
26//!     pub liabilities: Option<f64>,
27//! }
28//! ```
29//!
30//! ## Field attributes
31//!
32//! | Attribute                            | The field is                                             |
33//! | ------------------------------------ | -------------------------------------------------------- |
34//! | `concept = ".."` [, `alias = ".."`]… | read from these concepts, in order of preference         |
35//! | `nested`                             | another `FromXbrl` struct, read in the same scope        |
36//! | `each_period`                        | a `Vec` of a `FromXbrl` struct, one per reported period  |
37//! | `period_start` / `period_end`        | the dates of the period the struct was read for          |
38//! | *(none)*                             | left at its `Default`                                    |
39//!
40//! What a `concept` field holds is decided by its type — see
41//! `xbrlkit::bind::FromFacts`.
42//!
43//! ## Struct attributes
44//!
45//! `#[xbrl(instant)]` or `#[xbrl(duration)]` says which kind of period the
46//! struct's concepts are reported for, so that `each_period` does not produce
47//! a balance sheet for a quarter or an income statement for a date.
48
49use proc_macro::TokenStream;
50use proc_macro2::TokenStream as TokenStream2;
51use quote::quote;
52use syn::{Data, DeriveInput, Error, Field, Fields, LitStr, parse_macro_input, spanned::Spanned};
53
54/// What one field is bound to.
55enum Binding {
56    Concepts(Vec<LitStr>),
57    Nested,
58    EachPeriod,
59    PeriodStart,
60    PeriodEnd,
61    Unbound,
62}
63
64/// Derives `xbrlkit::FromXbrl` for a struct with named fields. See the crate docs.
65#[proc_macro_derive(FromXbrl, attributes(xbrl))]
66pub fn derive_from_xbrl(input: TokenStream) -> TokenStream {
67    let input = parse_macro_input!(input as DeriveInput);
68    expand(&input)
69        .unwrap_or_else(Error::into_compile_error)
70        .into()
71}
72
73fn expand(input: &DeriveInput) -> syn::Result<TokenStream2> {
74    let name = &input.ident;
75    let Data::Struct(data) = &input.data else {
76        return Err(Error::new(
77            input.span(),
78            "FromXbrl can only be derived for a struct",
79        ));
80    };
81    let Fields::Named(fields) = &data.fields else {
82        return Err(Error::new(
83            input.span(),
84            "FromXbrl needs a struct with named fields",
85        ));
86    };
87
88    let period_kind = container_period_kind(input)?;
89
90    let mut field_values = Vec::with_capacity(fields.named.len());
91    let mut concept_lists = Vec::new();
92
93    for field in &fields.named {
94        let ident = field.ident.as_ref().expect("named field");
95        let ty = &field.ty;
96        let field_name = ident.to_string();
97
98        let value = match field_binding(field)? {
99            Binding::Concepts(concepts) => {
100                concept_lists.push(quote! { out.extend_from_slice(&[#(#concepts),*]); });
101                quote! {
102                    <#ty as ::xbrlkit::bind::FromFacts>::from_facts(scope, &[#(#concepts),*], #field_name)
103                }
104            }
105            Binding::Nested => {
106                concept_lists.push(quote! { <#ty as ::xbrlkit::bind::FromXbrl>::concepts(out); });
107                quote! { <#ty as ::xbrlkit::bind::FromXbrl>::from_xbrl(scope) }
108            }
109            Binding::EachPeriod => quote! { ::xbrlkit::bind::each_period(scope) },
110            Binding::PeriodStart => quote! { scope.period_start() },
111            Binding::PeriodEnd => quote! { scope.period_end() },
112            Binding::Unbound => quote! { ::core::default::Default::default() },
113        };
114        field_values.push(quote! { #ident: #value });
115    }
116
117    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
118
119    Ok(quote! {
120        impl #impl_generics ::xbrlkit::bind::FromXbrl for #name #ty_generics #where_clause {
121            const PERIOD_KIND: ::xbrlkit::bind::PeriodKind = #period_kind;
122
123            fn concepts(out: &mut ::std::vec::Vec<&'static str>) {
124                #(#concept_lists)*
125            }
126
127            fn from_xbrl(scope: &::xbrlkit::bind::Scope<'_>) -> Self {
128                Self { #(#field_values),* }
129            }
130        }
131    })
132}
133
134fn container_period_kind(input: &DeriveInput) -> syn::Result<TokenStream2> {
135    let mut kind = quote! { ::xbrlkit::bind::PeriodKind::Any };
136    for attr in input.attrs.iter().filter(|a| a.path().is_ident("xbrl")) {
137        attr.parse_nested_meta(|meta| {
138            if meta.path.is_ident("instant") {
139                kind = quote! { ::xbrlkit::bind::PeriodKind::Instant };
140            } else if meta.path.is_ident("duration") {
141                kind = quote! { ::xbrlkit::bind::PeriodKind::Duration };
142            } else {
143                return Err(meta.error("expected `instant` or `duration`"));
144            }
145            Ok(())
146        })?;
147    }
148    Ok(kind)
149}
150
151fn field_binding(field: &Field) -> syn::Result<Binding> {
152    let mut binding = Binding::Unbound;
153    let mut aliases: Vec<LitStr> = Vec::new();
154
155    for attr in field.attrs.iter().filter(|a| a.path().is_ident("xbrl")) {
156        attr.parse_nested_meta(|meta| {
157            let path = &meta.path;
158            if path.is_ident("alias") {
159                aliases.push(meta.value()?.parse()?);
160                return Ok(());
161            }
162
163            let next = if path.is_ident("concept") {
164                Binding::Concepts(vec![meta.value()?.parse()?])
165            } else if path.is_ident("nested") {
166                Binding::Nested
167            } else if path.is_ident("each_period") {
168                Binding::EachPeriod
169            } else if path.is_ident("period_start") {
170                Binding::PeriodStart
171            } else if path.is_ident("period_end") {
172                Binding::PeriodEnd
173            } else {
174                return Err(meta.error(
175                    "expected `concept = \"..\"`, `alias = \"..\"`, `nested`, `each_period`, \
176                     `period_start` or `period_end`",
177                ));
178            };
179
180            if !matches!(binding, Binding::Unbound) {
181                return Err(meta.error("a field can be bound only once"));
182            }
183            binding = next;
184            Ok(())
185        })?;
186    }
187
188    match &mut binding {
189        Binding::Concepts(concepts) => concepts.append(&mut aliases),
190        _ if !aliases.is_empty() => {
191            return Err(Error::new(
192                field.span(),
193                "`alias` names a fallback for `concept`, which this field does not have",
194            ));
195        }
196        _ => {}
197    }
198    Ok(binding)
199}