Skip to main content

spacetimedb_bindings_macro/
lib.rs

1//! Defines procedural macros like `#[spacetimedb::table]`,
2//! simplifying writing SpacetimeDB modules in Rust.
3
4// DO NOT WRITE (public) DOCS IN THIS MODULE.
5// Docs should be written in the `spacetimedb` crate (i.e. `bindings/`) at reexport sites
6// using `#[doc(inline)]`.
7// We do this so that links to library traits, structs, etc can resolve correctly.
8//
9// (private documentation for the macro authors is totally fine here and you SHOULD write that!)
10
11mod procedure;
12mod reducer;
13mod sats;
14mod table;
15mod util;
16mod view;
17
18use proc_macro::TokenStream as StdTokenStream;
19use proc_macro2::TokenStream;
20use quote::quote;
21use std::time::Duration;
22use syn::{parse::ParseStream, Attribute};
23use syn::{ItemConst, ItemFn};
24use util::{cvt_attr, ok_or_compile_error};
25
26mod sym {
27    /// A symbol known at compile-time against
28    /// which identifiers and paths may be matched.
29    pub struct Symbol(&'static str);
30
31    macro_rules! symbol {
32        ($ident:ident) => {
33            symbol!($ident, $ident);
34        };
35        ($const:ident, $ident:ident) => {
36            #[allow(non_upper_case_globals)]
37            #[doc = concat!("Matches `", stringify!($ident), "`.")]
38            pub const $const: Symbol = Symbol(stringify!($ident));
39        };
40    }
41
42    symbol!(accessor);
43    symbol!(at);
44    symbol!(auto_inc);
45    symbol!(btree);
46    symbol!(client_connected);
47    symbol!(client_disconnected);
48    symbol!(column);
49    symbol!(columns);
50    symbol!(crate_, crate);
51    symbol!(direct);
52    symbol!(hash);
53    symbol!(index);
54    symbol!(init);
55    symbol!(name);
56    symbol!(primary_key);
57    symbol!(private);
58    symbol!(public);
59    symbol!(repr);
60    symbol!(sats);
61    symbol!(scheduled);
62    symbol!(unique);
63    symbol!(update);
64    symbol!(default);
65    symbol!(event);
66
67    symbol!(u8);
68    symbol!(i8);
69    symbol!(u16);
70    symbol!(i16);
71    symbol!(u32);
72    symbol!(i32);
73    symbol!(u64);
74    symbol!(i64);
75    symbol!(u128);
76    symbol!(i128);
77    symbol!(f32);
78    symbol!(f64);
79
80    impl PartialEq<Symbol> for syn::Ident {
81        fn eq(&self, sym: &Symbol) -> bool {
82            self == sym.0
83        }
84    }
85    impl PartialEq<Symbol> for &syn::Ident {
86        fn eq(&self, sym: &Symbol) -> bool {
87            *self == sym.0
88        }
89    }
90    impl PartialEq<Symbol> for syn::Path {
91        fn eq(&self, sym: &Symbol) -> bool {
92            self.is_ident(sym)
93        }
94    }
95    impl PartialEq<Symbol> for &syn::Path {
96        fn eq(&self, sym: &Symbol) -> bool {
97            self.is_ident(sym)
98        }
99    }
100    impl std::fmt::Display for Symbol {
101        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102            f.write_str(self.0)
103        }
104    }
105    impl std::borrow::Borrow<str> for Symbol {
106        fn borrow(&self) -> &str {
107            self.0
108        }
109    }
110}
111
112#[proc_macro_attribute]
113pub fn procedure(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream {
114    cvt_attr::<ItemFn>(args, item, quote!(), |args, original_function| {
115        let args = procedure::ProcedureArgs::parse(args)?;
116        procedure::procedure_impl(args, original_function)
117    })
118}
119
120#[proc_macro_attribute]
121pub fn reducer(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream {
122    cvt_attr::<ItemFn>(args, item, quote!(), |args, original_function| {
123        let args = reducer::ReducerArgs::parse(args)?;
124        reducer::reducer_impl(args, original_function)
125    })
126}
127
128#[proc_macro_attribute]
129pub fn view(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream {
130    let item_ts: TokenStream = item.into();
131    let original_function = match syn::parse2::<ItemFn>(item_ts.clone()) {
132        Ok(f) => f,
133        Err(e) => return TokenStream::from_iter([item_ts, e.into_compile_error()]).into(),
134    };
135    let args = match view::ViewArgs::parse(args.into(), &original_function.sig.ident) {
136        Ok(a) => a,
137        Err(e) => return TokenStream::from_iter([item_ts, e.into_compile_error()]).into(),
138    };
139    match view::view_impl(args, &original_function) {
140        Ok(ts) => ts.into(),
141        Err(e) => TokenStream::from_iter([item_ts, e.into_compile_error()]).into(),
142    }
143}
144
145/// It turns out to be shockingly difficult to construct an [`Attribute`].
146/// That type is not [`Parse`], instead having two distinct methods
147/// for parsing "inner" vs "outer" attributes.
148///
149/// We need this [`Attribute`] in [`table`] so that we can "pushnew" it
150/// onto the end of a list of attributes. See comments within [`table`].
151fn derive_table_helper_attr() -> Attribute {
152    let source = quote!(#[derive(spacetimedb::__TableHelper)]);
153
154    syn::parse::Parser::parse2(Attribute::parse_outer, source)
155        .unwrap()
156        .into_iter()
157        .next()
158        .unwrap()
159}
160
161#[proc_macro_attribute]
162pub fn table(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream {
163    // put this on the struct so we don't get unknown attribute errors
164    let derive_table_helper: syn::Attribute = derive_table_helper_attr();
165
166    ok_or_compile_error(|| {
167        let item = TokenStream::from(item);
168        let mut derive_input: syn::DeriveInput = syn::parse2(item.clone())?;
169
170        // Add `derive(__TableHelper)` only if it's not already in the attributes of the `derive_input.`
171        // If multiple `#[table]` attributes are applied to the same `struct` item,
172        // this will ensure that we don't emit multiple conflicting implementations
173        // for traits like `SpacetimeType`, `Serialize` and `Deserialize`.
174        //
175        // We need to push at the end, rather than the beginning,
176        // because rustc expands attribute macros (including derives) top-to-bottom,
177        // and we need *all* `#[table]` attributes *before* the `derive(__TableHelper)`.
178        // This way, the first `table` will insert a `derive(__TableHelper)`,
179        // and all subsequent `#[table]`s on the same `struct` will see it,
180        // and not add another.
181        //
182        // Note, thank goodness, that `syn`'s `PartialEq` impls (provided with the `extra-traits` feature)
183        // skip any [`Span`]s contained in the items,
184        // thereby comparing for syntactic rather than structural equality. This shouldn't matter,
185        // since we expect that the `derive_table_helper` will always have the same [`Span`]s,
186        // but it's nice to know.
187        if !derive_input.attrs.contains(&derive_table_helper) {
188            derive_input.attrs.push(derive_table_helper);
189        }
190
191        let args = table::TableArgs::parse(args.into(), &derive_input.ident)?;
192        let generated = table::table_impl(args, &derive_input)?;
193        Ok(TokenStream::from_iter([quote!(#derive_input), generated]))
194    })
195}
196
197/// Special alias for `derive(SpacetimeType)`, aka [`schema_type`], for use by [`table`].
198///
199/// Provides helper attributes for `#[spacetimedb::table]`, so that we don't get unknown attribute errors.
200#[doc(hidden)]
201#[proc_macro_derive(__TableHelper, attributes(sats, unique, auto_inc, primary_key, index, default))]
202pub fn table_helper(input: StdTokenStream) -> StdTokenStream {
203    schema_type(input)
204}
205
206#[proc_macro]
207pub fn duration(input: StdTokenStream) -> StdTokenStream {
208    let dur = syn::parse_macro_input!(input with parse_duration);
209    let (secs, nanos) = (dur.as_secs(), dur.subsec_nanos());
210    quote!({
211        const DUR: ::core::time::Duration = ::core::time::Duration::new(#secs, #nanos);
212        DUR
213    })
214    .into()
215}
216
217fn parse_duration(input: ParseStream) -> syn::Result<Duration> {
218    let lookahead = input.lookahead1();
219    let (s, span) = if lookahead.peek(syn::LitStr) {
220        let s = input.parse::<syn::LitStr>()?;
221        (s.value(), s.span())
222    } else if lookahead.peek(syn::LitInt) {
223        let i = input.parse::<syn::LitInt>()?;
224        (i.to_string(), i.span())
225    } else {
226        return Err(lookahead.error());
227    };
228    humantime::parse_duration(&s).map_err(|e| syn::Error::new(span, format_args!("can't parse as duration: {e}")))
229}
230
231/// A helper for the common bits of the derive macros.
232fn sats_derive(
233    input: StdTokenStream,
234    assume_in_module: bool,
235    logic: impl FnOnce(&sats::SatsType) -> TokenStream,
236) -> StdTokenStream {
237    let input = syn::parse_macro_input!(input as syn::DeriveInput);
238    let crate_fallback = if assume_in_module {
239        quote!(spacetimedb::spacetimedb_lib)
240    } else {
241        quote!(spacetimedb_lib)
242    };
243    sats::sats_type_from_derive(&input, crate_fallback)
244        .map(|ty| logic(&ty))
245        .unwrap_or_else(syn::Error::into_compile_error)
246        .into()
247}
248
249#[proc_macro_derive(Deserialize, attributes(sats))]
250pub fn deserialize(input: StdTokenStream) -> StdTokenStream {
251    sats_derive(input, false, sats::derive_deserialize)
252}
253
254#[proc_macro_derive(Serialize, attributes(sats))]
255pub fn serialize(input: StdTokenStream) -> StdTokenStream {
256    sats_derive(input, false, sats::derive_serialize)
257}
258
259#[proc_macro_derive(SpacetimeType, attributes(sats))]
260pub fn schema_type(input: StdTokenStream) -> StdTokenStream {
261    sats_derive(input, true, |ty| {
262        let ident = ty.ident;
263        let name = &ty.name;
264
265        let krate = &ty.krate;
266        TokenStream::from_iter([
267            sats::derive_satstype(ty),
268            sats::derive_deserialize(ty),
269            sats::derive_serialize(ty),
270            // unfortunately, generic types don't work in modules at the moment.
271            quote!(#krate::__make_register_reftype!(#ident, #name);),
272        ])
273    })
274}
275
276#[proc_macro_attribute]
277pub fn client_visibility_filter(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream {
278    ok_or_compile_error(|| {
279        if !args.is_empty() {
280            return Err(syn::Error::new_spanned(
281                TokenStream::from(args),
282                "The `client_visibility_filter` attribute does not accept arguments",
283            ));
284        }
285
286        let item: ItemConst = syn::parse(item)?;
287        let rls_ident = item.ident.clone();
288        let register_rls_symbol = format!("__preinit__20_register_row_level_security_{rls_ident}");
289
290        Ok(quote! {
291            #item
292
293            const _: () = {
294                #[export_name = #register_rls_symbol]
295                extern "C" fn __register_client_visibility_filter() {
296                    spacetimedb::rt::register_row_level_security(#rls_ident.sql_text())
297                }
298            };
299        })
300    })
301}
302
303/// Known setting names and their registration code generators.
304const KNOWN_SETTINGS: &[&str] = &["CASE_CONVERSION_POLICY"];
305
306#[proc_macro_attribute]
307pub fn settings(args: StdTokenStream, item: StdTokenStream) -> StdTokenStream {
308    ok_or_compile_error(|| {
309        if !args.is_empty() {
310            return Err(syn::Error::new_spanned(
311                TokenStream::from(args),
312                "The `settings` attribute does not accept arguments",
313            ));
314        }
315
316        let item: ItemConst = syn::parse(item)?;
317        let ident = &item.ident;
318        let ident_str = ident.to_string();
319
320        if !KNOWN_SETTINGS.contains(&ident_str.as_str()) {
321            return Err(syn::Error::new_spanned(
322                ident,
323                format!(
324                    "unknown setting `{ident_str}`. Known settings: {}",
325                    KNOWN_SETTINGS.join(", ")
326                ),
327            ));
328        }
329
330        // Use a fixed export name so that two `#[spacetimedb::settings]` consts
331        // for the same setting produce a linker error (duplicate symbol).
332        let register_symbol = format!("__preinit__05_setting_{ident_str}");
333
334        // Generate the registration call based on the setting name.
335        let register_call = match ident_str.as_str() {
336            "CASE_CONVERSION_POLICY" => quote! {
337                spacetimedb::rt::register_case_conversion_policy(#ident)
338            },
339            _ => unreachable!("validated above"),
340        };
341
342        Ok(quote! {
343            #item
344
345            const _: () = {
346                #[export_name = #register_symbol]
347                extern "C" fn __register_setting() {
348                    #register_call
349                }
350            };
351        })
352    })
353}