Skip to main content

rp_supabase_client_macros/
lib.rs

1#![cfg_attr(doc, doc = include_str!("../README.md"))]
2use proc_macro::TokenStream;
3use proc_macro2::TokenStream as Tokens;
4use quote::{quote, quote_spanned};
5use syn::{
6    Ident, Path, Token, Type, braced,
7    ext::IdentExt as _,
8    parenthesized,
9    parse::{Parse, ParseStream},
10    parse_macro_input,
11};
12
13mod named;
14mod projection;
15
16/// Version-owned support for the runtime's `$crate`-preserving `projection!` adapter.
17#[doc(hidden)]
18#[proc_macro]
19pub fn __projection(input: TokenStream) -> TokenStream {
20    let names = Names::new(input.clone().into());
21    let input = parse_macro_input!(input as named::Input);
22    named::expand(&names, &input).into()
23}
24
25struct Input {
26    runtime: Path,
27    root: Type,
28    fields: Vec<Field>,
29}
30struct Field {
31    alias: Ident,
32    kind: Kind,
33}
34enum Kind {
35    Scalar,
36    Nested(Ident, Vec<Field>, bool),
37    Shared(Ident, Box<Type>, bool),
38    Empty(Ident, bool),
39}
40fn fields(input: ParseStream) -> syn::Result<Vec<Field>> {
41    let body;
42    braced!(body in input);
43    let mut out = Vec::<Field>::new();
44    while !body.is_empty() {
45        let alias: Ident = body.parse()?;
46        let normalized = alias.to_string().trim_start_matches("r#").to_owned();
47        if out
48            .iter()
49            .any(|field| field.alias.to_string().trim_start_matches("r#") == normalized)
50        {
51            return Err(syn::Error::new(alias.span(), "duplicate selected alias"));
52        }
53        let kind = if body.peek(Token![:]) {
54            body.parse::<Token![:]>()?;
55            let edge: Ident = body.parse()?;
56            if edge == "embed" || edge == "empty" || edge == "inner" {
57                let args;
58                parenthesized!(args in body);
59                let key = args.parse()?;
60                if edge == "inner" {
61                    if !args.is_empty() {
62                        return Err(args.error("expected inner(relationship)"));
63                    }
64                    Kind::Nested(key, fields(&body)?, true)
65                } else {
66                    let dto = if edge == "embed" {
67                        args.parse::<Token![,]>()?;
68                        Some(args.parse::<Type>()?)
69                    } else {
70                        None
71                    };
72                    let inner = if args.peek(Token![,]) {
73                        args.parse::<Token![,]>()?;
74                        let flag: Ident = args.parse()?;
75                        if flag != "inner" {
76                            return Err(syn::Error::new(flag.span(), "expected inner"));
77                        }
78                        true
79                    } else {
80                        false
81                    };
82                    if !args.is_empty() {
83                        return Err(args.error("unexpected embed arguments"));
84                    }
85                    match dto {
86                        Some(dto) => Kind::Shared(key, Box::new(dto), inner),
87                        None => Kind::Empty(key, inner),
88                    }
89                }
90            } else {
91                Kind::Nested(edge, fields(&body)?, false)
92            }
93        } else {
94            Kind::Scalar
95        };
96        out.push(Field { alias, kind });
97        if body.is_empty() {
98            break;
99        }
100        body.parse::<Token![,]>()?;
101    }
102    if out.is_empty() {
103        return Err(body.error("select at least one field"));
104    }
105    Ok(out)
106}
107impl Parse for Input {
108    fn parse(input: ParseStream) -> syn::Result<Self> {
109        let runtime = if input.peek(Ident) && input.peek2(Token![=]) && !input.peek2(Token![=>]) {
110            let keyword: Ident = input.parse()?;
111            if keyword != "runtime" {
112                return Err(syn::Error::new(
113                    keyword.span(),
114                    "expected runtime = crate_path;",
115                ));
116            }
117            input.parse::<Token![=]>()?;
118            let path = input.parse()?;
119            input.parse::<Token![;]>()?;
120            path
121        } else {
122            syn::parse_quote!(::rp_supabase_client)
123        };
124        let root = input.parse()?;
125        input.parse::<Token![=>]>()?;
126        let fields = fields(input)?;
127        Ok(Self {
128            runtime,
129            root,
130            fields,
131        })
132    }
133}
134/// Construct a typed query-local selection from a relation and selected fields.
135#[proc_macro]
136pub fn select(input: TokenStream) -> TokenStream {
137    let names = Names::new(input.clone().into());
138    let Input {
139        runtime,
140        root,
141        fields,
142    } = parse_macro_input!(input as Input);
143    node(
144        &names,
145        &runtime,
146        &fields,
147        &quote!(#runtime::schema::selection::RelationToken::<#root>::new()),
148    )
149    .into()
150}
151// Every generated spelling is outside the entire caller token identifier set.
152// Growing a prefix (rather than hashing) also covers nested paths and generic arguments.
153struct Names {
154    prefix: String,
155}
156
157impl Names {
158    fn new(tokens: Tokens) -> Self {
159        fn collect(tokens: Tokens, names: &mut Vec<String>) {
160            for token in tokens {
161                match token {
162                    proc_macro2::TokenTree::Ident(ident) => names.push(ident.unraw().to_string()),
163                    proc_macro2::TokenTree::Group(group) => collect(group.stream(), names),
164                    proc_macro2::TokenTree::Punct(_) | proc_macro2::TokenTree::Literal(_) => {}
165                }
166            }
167        }
168        let mut identifiers = Vec::new();
169        collect(tokens, &mut identifiers);
170        let mut prefix = String::from("__selection_");
171        while identifiers.iter().any(|name| name.starts_with(&prefix)) {
172            prefix.push('_');
173        }
174        Self { prefix }
175    }
176
177    fn ident(&self, suffix: &str) -> Ident {
178        self.ident_at(suffix, proc_macro2::Span::mixed_site())
179    }
180
181    fn ident_at(&self, suffix: &str, span: proc_macro2::Span) -> Ident {
182        Ident::new(&format!("{}{suffix}", self.prefix), span)
183    }
184}
185
186struct EmissionField<'a> {
187    field: &'a Field,
188    index: usize,
189    ty: Ident,
190    argument: Ident,
191    slot: Ident,
192}
193
194struct Emission<'a> {
195    names: &'a Names,
196    runtime: &'a Path,
197    fields: Vec<EmissionField<'a>>,
198    marker: Ident,
199}
200
201impl<'a> Emission<'a> {
202    fn new(names: &'a Names, runtime: &'a Path, fields: &'a [Field]) -> Self {
203        let marker = names.ident("marker");
204        let fields = fields
205            .iter()
206            .enumerate()
207            .map(|(index, field)| EmissionField {
208                field,
209                index,
210                ty: names.ident(&format!("F{index}")),
211                argument: names.ident(&format!("arg{index}")),
212                slot: names.ident(&format!("slot{index}")),
213            })
214            .collect();
215        Self {
216            names,
217            runtime,
218            fields,
219            marker,
220        }
221    }
222
223    fn types(&self) -> impl Iterator<Item = &Ident> {
224        self.fields.iter().map(|field| &field.ty)
225    }
226
227    fn decoded(&self) -> impl Iterator<Item = &EmissionField<'a>> {
228        self.fields
229            .iter()
230            .filter(|field| !matches!(field.field.kind, Kind::Empty(..)))
231    }
232
233    fn embedded(&self) -> impl Iterator<Item = &EmissionField<'a>> {
234        self.fields
235            .iter()
236            .filter(|field| !matches!(field.field.kind, Kind::Scalar))
237    }
238
239    fn bound(&self) -> Tokens {
240        let r_ident = self.names.ident("R");
241        let rt = self.runtime;
242        let types = self.types();
243        quote!(#r_ident: #rt::schema::Relation + #rt::schema::Projection<#r_ident>, #(#types: #rt::schema::selection::SelectionField<#r_ident>),*)
244    }
245}
246
247fn node(names: &Names, rt: &Path, fields: &[Field], relation: &Tokens) -> Tokens {
248    let construct_ident = names.ident("construct");
249    let relation_ident = names.ident("relation");
250    let emission = Emission::new(names, rt, fields);
251    let record = record(&emission);
252    let decoder = local_decoder(&emission);
253    let projection = projection(&emission);
254    let descriptor = descriptor(&emission);
255    let values = emission
256        .fields
257        .iter()
258        .map(|field| field_value(names, rt, field));
259    quote!({
260        #record
261        #decoder
262        #projection
263        #descriptor
264        let #relation_ident = #relation;
265        #construct_ident(#relation_ident, #(#values),*)
266    })
267}
268
269fn field_value(names: &Names, rt: &Path, field: &EmissionField<'_>) -> Tokens {
270    let edge_ident = names.ident("edge");
271    let alias = &field.field.alias;
272    match &field.field.kind {
273        Kind::Scalar => lookup(names, rt, "column", alias),
274        Kind::Nested(edge, child, inner) => {
275            let child = node(names, rt, child, &quote!(#edge_ident.target()));
276            embedded_value(names, rt, field, edge, *inner, &child)
277        }
278        Kind::Shared(edge, dto, inner) => {
279            let child = quote_spanned!(alias.span()=> #rt::schema::selection::shared::<_, #dto>(#edge_ident));
280            embedded_value(names, rt, field, edge, *inner, &child)
281        }
282        Kind::Empty(edge, inner) => {
283            let child = quote!(#rt::schema::selection::empty(#edge_ident));
284            embedded_value(names, rt, field, edge, *inner, &child)
285        }
286    }
287}
288
289fn embedded_value(
290    names: &Names,
291    rt: &Path,
292    field: &EmissionField<'_>,
293    edge: &Ident,
294    inner: bool,
295    child: &Tokens,
296) -> Tokens {
297    let child_ident = names.ident("child");
298    let edge_ident = names.ident("edge");
299    let alias = &field.field.alias;
300    let index = field.index;
301    let alias_ty = names.ident(&format!("Alias{index}"));
302    let alias_name = alias.unraw().to_string();
303    let lookup = lookup(names, rt, "edge", edge);
304    quote!({
305        struct #alias_ty;
306        impl #rt::schema::selection::Alias for #alias_ty { const NAME: &'static ::core::primitive::str = #alias_name; }
307        let #edge_ident = #lookup;
308        let #child_ident = #child;
309        #rt::schema::selection::embed::<_, _, _, #inner>(#edge_ident, #child_ident, #alias_ty)
310    })
311}
312
313// Generic items know only resolved Field descriptors; lookup constraints never enter decoder/rendering.
314#[expect(
315    clippy::cognitive_complexity,
316    reason = "quote emits record trait implementations; the emitter has no branches"
317)]
318fn record(emission: &Emission<'_>) -> Tokens {
319    let r_ident = emission.names.ident("R");
320    let record_ident = emission.names.ident("Record");
321    let s_ident = emission.names.ident("S");
322    let rt = emission.runtime;
323    let fs: Vec<_> = emission.types().collect();
324    let bound = emission.bound();
325    let dfs: Vec<_> = emission.decoded().map(|field| &field.ty).collect();
326    let dnames: Vec<_> = emission.decoded().map(|field| &field.field.alias).collect();
327    let module = emission.names.ident("record");
328    let value_types: Vec<_> = emission
329        .decoded()
330        .map(|field| emission.names.ident(&format!("V{}", field.index)))
331        .collect();
332    let marker_type = emission.names.ident("Marker");
333    let marker = &emission.marker;
334    let count = dfs.len();
335    quote! {
336        mod #module {
337            pub struct Record<#(#value_types,)* #marker_type> {
338                #(pub #dnames: #value_types,)*
339                #marker: ::core::marker::PhantomData<fn() -> #marker_type>,
340            }
341            impl<#(#value_types,)* #marker_type> Record<#(#value_types,)* #marker_type> {
342                pub fn new(#(#dnames: #value_types),*) -> Self {
343                    Self { #(#dnames,)* #marker: ::core::marker::PhantomData }
344                }
345            }
346        }
347        #[allow(type_alias_bounds)]
348        type #record_ident<#r_ident,#(#fs),*> where #bound = #module::Record<
349            #(<#dfs as #rt::schema::selection::SelectionField<#r_ident>>::Value,)*
350            (#r_ident,#(#fs),*)
351        >;
352        impl<#r_ident,#(#fs),*> ::core::fmt::Debug for #record_ident<#r_ident,#(#fs),*> where #bound, #(<#dfs as #rt::schema::selection::SelectionField<#r_ident>>::Value: ::core::fmt::Debug,)* {
353            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
354                let mut d = f.debug_struct("Record"); #(d.field(::core::stringify!(#dnames), &self.#dnames);)* d.finish()
355            }
356        }
357        impl<#r_ident,#(#fs),*> #rt::schema::__private::serde::Serialize for #record_ident<#r_ident,#(#fs),*> where #bound, #(<#dfs as #rt::schema::selection::SelectionField<#r_ident>>::Value: #rt::schema::__private::serde::Serialize,)* {
358            fn serialize<#s_ident: #rt::schema::__private::serde::Serializer>(&self, s: #s_ident) -> ::core::result::Result<#s_ident::Ok,#s_ident::Error> {
359                let mut m = s.serialize_map(::core::option::Option::Some(#count))?;
360                #(#rt::schema::__private::serde::ser::SerializeMap::serialize_entry(&mut m, <#dfs as #rt::schema::selection::SelectionField<#r_ident>>::KEY, &self.#dnames)?;)* #rt::schema::__private::serde::ser::SerializeMap::end(m)
361            }
362        }
363    }
364}
365
366fn local_generics(emission: &Emission<'_>) -> syn::Generics {
367    let relation_ident = emission.names.ident("R");
368    let fields = emission.types();
369    let bound = emission.bound();
370    let mut generics: syn::Generics = syn::parse_quote!(<#relation_ident, #(#fields),*>);
371    generics.where_clause = Some(syn::parse_quote!(where #bound));
372    generics
373}
374
375fn local_decoder(emission: &Emission<'_>) -> Tokens {
376    let rt = emission.runtime;
377    let relation_ident = emission.names.ident("R");
378    let record = emission.names.ident("Record");
379    let fields: Vec<_> = emission
380        .decoded()
381        .map(|field| {
382            let ty = &field.ty;
383            projection::DecodedField {
384                name: field.field.alias.clone(),
385                ty: quote!(<#ty as #rt::schema::selection::SelectionField<#relation_ident>>::Value),
386                key: quote!(<#ty as #rt::schema::selection::SelectionField<#relation_ident>>::KEY),
387                slot: field.slot.clone(),
388            }
389        })
390        .collect();
391    projection::decoder(
392        emission.names,
393        &quote!(#rt),
394        &record,
395        &local_generics(emission),
396        &fields,
397        Some(&emission.marker),
398        ("a selected object", "a selected object field"),
399    )
400}
401
402fn projection(emission: &Emission<'_>) -> Tokens {
403    let rt = emission.runtime;
404    let relation_ident = emission.names.ident("R");
405    let record = emission.names.ident("Record");
406    let fields = emission.types().map(|ty| quote!(#ty)).collect::<Vec<_>>();
407    projection::rendering(
408        &quote!(#rt),
409        &record,
410        &quote!(#relation_ident),
411        &local_generics(emission),
412        &fields,
413    )
414}
415
416#[expect(
417    clippy::cognitive_complexity,
418    reason = "quote emits descriptor trait bounds; the emitter has no branches"
419)]
420fn descriptor(emission: &Emission<'_>) -> Tokens {
421    let descriptor_ident = emission.names.ident("Descriptor");
422    let r_ident = emission.names.ident("R");
423    let record_ident = emission.names.ident("Record");
424    let construct_ident = emission.names.ident("construct");
425    let rt = emission.runtime;
426    let fs: Vec<_> = emission.types().collect();
427    let args: Vec<_> = emission
428        .fields
429        .iter()
430        .map(|field| &field.argument)
431        .collect();
432    let bound = emission.bound();
433    let marker = &emission.marker;
434    let ebounds: Vec<_> = emission
435        .embedded()
436        .map(|field| {
437            let ty = &field.ty;
438            quote!(#ty: #rt::schema::selection::Embedded<#r_ident>)
439        })
440        .collect();
441    let descfields: Vec<_> = emission.embedded().map(|field| {
442        let ty = &field.ty;
443        let alias = &field.field.alias;
444        quote!(pub #alias: #rt::schema::selection::Handle<#record_ident<#r_ident,#(#fs),*>, <<#ty as #rt::schema::selection::Embedded<#r_ident>>::Child as #rt::schema::selection::Selection>::Record, <#ty as #rt::schema::selection::Embedded<#r_ident>>::Edge, <#ty as #rt::schema::selection::Embedded<#r_ident>>::Alias, <#ty as #rt::schema::selection::Embedded<#r_ident>>::Child>)
445    }).collect();
446    let descinit: Vec<_> = emission.embedded().map(|field| {
447        let argument = &field.argument;
448        let alias = &field.field.alias;
449        quote!(#alias: #rt::schema::selection::Handle::new(#rt::schema::selection::Embedded::child(#argument)))
450    }).collect();
451    quote! {
452        struct #descriptor_ident<#r_ident,#(#fs),*> where #bound, #(#ebounds,)* {
453            #(#descfields,)*
454            #marker: ::core::marker::PhantomData<fn() -> (#r_ident,#(#fs),*)>,
455        }
456        impl<#r_ident,#(#fs),*> ::core::marker::Copy for #descriptor_ident<#r_ident,#(#fs),*> where #bound, #(#ebounds,)* {}
457        impl<#r_ident,#(#fs),*> ::core::clone::Clone for #descriptor_ident<#r_ident,#(#fs),*> where #bound, #(#ebounds,)* { fn clone(&self) -> Self { *self } }
458        impl<#r_ident,#(#fs),*> #rt::schema::selection::Selection for #descriptor_ident<#r_ident,#(#fs),*> where #bound, #(#ebounds,)* {
459            type Relation = #r_ident;
460            type Record = #record_ident<#r_ident,#(#fs),*>;
461        }
462        fn #construct_ident<#r_ident,#(#fs),*>(_: #rt::schema::selection::RelationToken<#r_ident>, #(#args: #fs),*) -> #descriptor_ident<#r_ident,#(#fs),*> where #bound, #(#ebounds,)* {
463            #descriptor_ident { #(#descinit,)* #marker: ::core::marker::PhantomData }
464        }
465    }
466}
467
468fn key_type(rt: &Path, name: &Ident) -> Tokens {
469    let text = name.unraw().to_string();
470    let characters = text.chars();
471    quote!((#(#rt::schema::Character<#characters>,)*))
472}
473// Resolve `name` on the relation in scope with `selection::column` or `selection::edge`.
474// The argument is a block-local unit struct named after the identifier the user wrote:
475// lookup diagnostics print that type, so an unknown name appears as a word, not a key.
476// Every token is located at `name`, so rustc points at the name, not the whole macro call.
477// Only prefixed identifiers are in scope inside the struct block, so it shadows nothing.
478fn lookup(names: &Names, rt: &Path, function: &str, name: &Ident) -> Tokens {
479    let span = proc_macro2::Span::mixed_site().located_at(name.span());
480    let relation = names.ident_at("relation", span);
481    let key_type = key_type(rt, name);
482    let name_trait = names.ident_at("KeyName", span);
483    let encoded = names.ident_at("EncodedKey", span);
484    let edge_lookup = names.ident_at("lookup_edge", span);
485    let mut local = name.clone();
486    local.set_span(span);
487    let value = quote_spanned!(span=> {
488        use #rt::schema::KeyName as #name_trait;
489        type #encoded = #key_type;
490        {
491            #[allow(non_camel_case_types)]
492            struct #local;
493            impl #name_trait for #local { type Key = #encoded; }
494            #local
495        }
496    });
497    if function == "column" {
498        quote_spanned!(span=> {
499            #[allow(unused_imports)]
500            use #rt::schema::selection::ColumnLookup as _;
501            #relation.columns().column(#value)
502        })
503    } else {
504        quote_spanned!(span=> {
505            use #rt::schema::selection::edge as #edge_lookup;
506            #edge_lookup(#relation, #value)
507        })
508    }
509}
510struct KeyInput {
511    runtime: Path,
512    name: Ident,
513    ty: bool,
514}
515impl Parse for KeyInput {
516    fn parse(input: ParseStream) -> syn::Result<Self> {
517        let runtime = if input.peek(Ident) && input.peek2(Token![=]) {
518            let word: Ident = input.parse()?;
519            if word != "runtime" {
520                return Err(syn::Error::new(word.span(), "expected runtime"));
521            }
522            input.parse::<Token![=]>()?;
523            let path = input.parse()?;
524            input.parse::<Token![;]>()?;
525            path
526        } else {
527            syn::parse_quote!(::rp_supabase_client)
528        };
529        let ty = input.peek(Token![type]);
530        if ty {
531            input.parse::<Token![type]>()?;
532        }
533        let name = input.parse()?;
534        Ok(Self { runtime, name, ty })
535    }
536}
537/// Construct a lossless schema key, or its name type with `key!(type identifier)`.
538#[proc_macro]
539pub fn key(input: TokenStream) -> TokenStream {
540    let names = Names::new(input.clone().into());
541    let KeyInput { runtime, name, ty } = parse_macro_input!(input as KeyInput);
542    let key = key_type(&runtime, &name);
543    if ty {
544        key.into()
545    } else {
546        let span = proc_macro2::Span::mixed_site().located_at(name.span());
547        let name_trait = names.ident_at("KeyName", span);
548        let encoded = names.ident_at("EncodedKey", span);
549        let constructor = names.ident_at("Key", span);
550        quote_spanned!(span=> {
551            use #runtime::schema::{KeyName as #name_trait, Key as #constructor};
552            type #encoded = #key;
553            {
554                #[allow(non_camel_case_types)]
555                struct #name;
556                impl #name_trait for #name { type Key = #encoded; }
557                #constructor::<#encoded, #name>::new()
558            }
559        })
560        .into()
561    }
562}