Skip to main content

egglog_add_primitive/
lib.rs

1use proc_macro::{Span, TokenStream};
2use quote::quote;
3use syn::parse::{Parse, ParseStream, Result};
4use syn::punctuated::Punctuated;
5use syn::{Expr, Ident, LitStr, Token, braced, bracketed, parenthesized, parse_macro_input};
6
7/// This macro lets the user declare custom egglog primitives with explicit validators.
8/// It combines primitive registration with a custom validator function.
9///
10/// # Example
11/// ```rust,ignore
12/// add_primitive_with_validator!(
13///     eg,
14///     "custom-op" = |a: Value| -> Value { a },
15///     |termdag, lhs| {
16///         // Custom validation logic
17///         None
18///     }
19/// );
20/// ```
21#[proc_macro]
22pub fn add_primitive_with_validator(input: TokenStream) -> TokenStream {
23    let parsed = parse_macro_input!(input as AddPrimitiveWithValidator);
24    build_add_primitive_impl(parsed.primitive, Some(parsed.validator))
25}
26
27/// Parses an `AddPrimitive` followed by a comma and a validator expression.
28struct AddPrimitiveWithValidator {
29    primitive: AddPrimitive,
30    validator: Expr,
31}
32
33impl Parse for AddPrimitiveWithValidator {
34    fn parse(input: ParseStream) -> Result<Self> {
35        let primitive = input.parse()?;
36        input.parse::<Token![,]>()?;
37        let validator = input.parse()?;
38        Ok(AddPrimitiveWithValidator {
39            primitive,
40            validator,
41        })
42    }
43}
44
45/// This macro lets the user declare custom egglog primitives.
46/// It supports a few special features:
47///
48/// - Failure: using `-?>` instead of `->` before the return type will
49///   make the primitive fallible, requiring the body to return an
50///   `Option<T>` instead of just `T`.
51///
52/// - Varargs: using `[xs: T]` as the argument list will cause the
53///   primitive to take a variable number of arguments, which will be
54///   passed to be body as an `Iterator<Item=T>`.
55///
56/// - Polymorphism: using `#` as a type will allow any type during
57///   typechecking. These will be given type `Value` in the body.
58///
59/// - Containers: you must put an `@` in front of container types.
60///
61/// - Specialized Constraints: using `T (E)` as a type will use
62///   `(E:expr).clone()` in the type constraint but `T:ty` in the body.
63///   This is necessary because the relationship between Rust types
64///   and egglog sorts is not 1-to-1.
65///
66/// - Context: sometimes you want your primitive to reference
67///   information from the scope of the `add_primitive!` call.
68///   Putting `{x: T}` between the `=` and the argument list
69///   will let you access the expression `x` of type `T` from inside
70///   the body as `self.ctx`. `T` must be the real Rust type of `x`.
71///   `T` must be `Clone` and `'static`.
72#[proc_macro]
73pub fn add_primitive(input: TokenStream) -> TokenStream {
74    build_add_primitive_impl(parse_macro_input!(input), None)
75}
76
77fn build_add_primitive_impl(parsed: AddPrimitive, validator: Option<Expr>) -> TokenStream {
78    // If you're trying to read this code, you should read the big
79    // `quote!` block at the bottom of this function first. Trying
80    // to parse all the intermediate gobbledygook is going to be
81    // hard without that context.
82
83    // Parse the input by implementing `syn::Parse` for our data types.
84    let AddPrimitive {
85        eg,
86        name,
87        context,
88        is_varargs,
89        args,
90        is_fallible,
91        ret,
92        body,
93    } = parsed;
94
95    // Create a new field name for the `Prim` struct to hold the return sort.
96    // (We reuse the closure argument names for the argument sorts.)
97    let y = Ident::new("__y", Span::mixed_site().into());
98    // Create a type that refers to whichever `Value` import is closer.
99    let value_type = syn::Type::Verbatim(quote!(Value));
100
101    // List out the sorts that we need to store.
102    let (field_defs, field_uses): (Vec<_>, Vec<_>) = args
103        .iter()
104        .map(|arg| (&arg.x, &arg.t))
105        .chain([(&y, &ret)])
106        .filter_map(|(x, t)| {
107            t.field
108                .as_ref()
109                .map(|(d, u)| (quote!(#x: #d), quote!(#x: #u.clone())))
110        })
111        .chain(match context.0 {
112            Some((e, t)) => vec![(quote!(ctx: #t), quote!(ctx: #e))],
113            None => vec![],
114        })
115        .unzip();
116    // Bundle up the defs and uses into structs.
117    let prim_def = quote!(struct Prim { #(#field_defs,)* });
118    let prim_use = quote!(       Prim { #(#field_uses,)* });
119
120    // Create the type constraint for the `egglog` typechecker.
121    // TODO: add a new type constraint that supports all possible combinations
122    // of features that this macro supports. Right now `|a: #, b: i64|` is
123    // impossible to express with the current type constraints.
124    let type_constraint = {
125        let has_type = |t: &Type| t.field.is_some();
126        let args_have_types = args.iter().all(|arg| has_type(&arg.t));
127        let ret_has_type = has_type(&ret);
128
129        // If we're in the simple case, we can use the `SimpleTypeConstraint`.
130        // However, use of either `#` or varargs makes this impossible.
131        if !is_varargs && args_have_types && ret_has_type {
132            let x = args.iter().map(|arg| &arg.x);
133            quote! {
134                let sorts: Vec<ArcSort> = vec![#(self.#x.clone() as ArcSort,)* self.#y.clone()];
135                SimpleTypeConstraint::new(self.name(), sorts, span.clone()).into_box()
136            }
137        } else {
138            // As a fallback, try to use `AllEqualTypeConstraint` for everything else.
139            let Arg {
140                x,
141                t,
142                is_mutable: _,
143            } = &args[0];
144            for arg in &args {
145                // NOTE: this is a conservative (incomplete!) check, as `syn::Type`
146                // is not `PartialEq`. See the TODO on `type_constraint`.
147                assert_eq!(
148                    has_type(t),
149                    has_type(&arg.t),
150                    "AllEqualTypeConstraint doesn't support multiple argument types"
151                )
152            }
153
154            let new = quote!(AllEqualTypeConstraint::new(self.name(), span.clone()));
155
156            let len = args.len() + 1;
157            let len = quote!(.with_exact_length(#len));
158            let len = if is_varargs { quote!() } else { len };
159
160            let args = quote!(.with_all_arguments_sort(self.#x.clone()));
161            let args = if args_have_types { args } else { quote!() };
162
163            let ret = quote!(.with_output_sort(self.#y.clone()));
164            let ret = if ret_has_type { ret } else { quote!() };
165
166            quote!(#new #len #args #ret .into_box())
167        }
168    };
169
170    // Create the function body for `apply`.
171    let apply = {
172        // Bind the argument names that were passed in to this macro.
173        let bind = if is_varargs {
174            let x = &args[0].x;
175            quote!(let #x = args.iter();)
176        } else {
177            let x = args.iter().map(|arg| &arg.x);
178            quote!(let [#(#x),*] = args else { panic!("wrong number of arguments") };)
179        };
180
181        // Cast the arguments to the desired type. `state` is a
182        // `PureState<'a, 'db>` whose `base_values()` and
183        // `container_values()` come from the `Core` trait (re-exported
184        // via the `egglog::*` glob below).
185        let cast1 = |x, t: &syn::Type, is_container| match is_container {
186            false => quote!(state.base_values().unwrap::<#t>(*#x)),
187            true => quote!(state.container_values().get_val::<#t>(*#x).unwrap().clone()),
188        };
189        let cast = if is_varargs {
190            let Arg { x, t, is_mutable } = &args[0];
191            let mutable = if *is_mutable { quote!(mut) } else { quote!() };
192            match &t.cast {
193                None => quote!(let #mutable #x = #x.copied();),
194                Some((t, is_container)) => {
195                    let cast = cast1(x, t, *is_container);
196                    quote!(let #mutable #x = #x.map(|#x| #cast);)
197                }
198            }
199        } else {
200            args.iter()
201                .map(|Arg { x, t, is_mutable }| {
202                    let mutable = if *is_mutable { quote!(mut) } else { quote!() };
203                    match &t.cast {
204                        None => quote!(let #mutable #x: Value = *#x;),
205                        Some((t, is_container)) => {
206                            let cast = cast1(x, t, *is_container);
207                            quote!(let #mutable #x: #t = #cast;)
208                        }
209                    }
210                })
211                .collect()
212        };
213
214        // If the primitive is fallible, put a `?` after the body.
215        let fail = if is_fallible { quote!(?) } else { quote!() };
216        // Cast the result back to an interned value. For container
217        // returns we go through `state.register_container`, which is a
218        // `Core` method and (per #772) safe in every context since
219        // container interning is idempotent.
220        let (yt, ret) = match &ret.cast {
221            None => (&value_type, quote!(#y)),
222            Some((t, is_container)) => (
223                t,
224                match is_container {
225                    false => quote!(state.base_values().get::<#t>(#y)),
226                    true => quote!(state.register_container::<#t>(#y)),
227                },
228            ),
229        };
230
231        quote! {
232            #bind
233            #cast
234            let #y: #yt = (#body)#fail;
235            Some(#ret)
236        }
237    };
238
239    // This is the big `quote!` block that ties everything together.
240    //
241    // Macro-generated primitives are registered as `PurePrim` (valid
242    // in all four contexts) because every code path the macro emits
243    // is pure: it reads base / container values and registers
244    // containers, which are all safe everywhere per the `Core` trait.
245    // If a future extension of the macro introduces a non-pure
246    // emission path, the declared kind would need to narrow accordingly.
247    let add_call = match validator {
248        None => quote!(eg.add_pure_primitive(#prim_use, None);),
249        Some(validator_expr) => quote!(eg.add_pure_primitive(
250            #prim_use,
251            Some(::std::sync::Arc::new(#validator_expr))
252        );),
253    };
254
255    quote! {{
256        #[allow(unused_imports)] use ::egglog::{*, ast::*, constraint::*};
257        #[allow(unused_imports)] use ::std::{any::TypeId, sync::Arc};
258
259        #[derive(Clone)]
260        #prim_def
261
262        impl Primitive for Prim {
263            fn name(&self) -> &str {
264                #name
265            }
266
267            fn get_type_constraints(&self, span: &Span) -> Box<dyn TypeConstraint> {
268                #type_constraint
269            }
270        }
271
272        impl PurePrim for Prim {
273            fn apply<'a, 'db>(
274                &self,
275                #[allow(unused_mut)] mut state: PureState<'a, 'db>,
276                args: &[Value],
277            ) -> Option<Value> {
278                #apply
279            }
280        }
281
282        let eg: &mut EGraph = #eg;
283        #add_call
284    }}
285    .into()
286}
287
288struct AddPrimitive {
289    eg: Expr,
290    name: LitStr,
291    context: Context,
292    args: Vec<Arg>,
293    ret: Type,
294    body: Expr,
295    is_varargs: bool,
296    is_fallible: bool,
297}
298
299impl Parse for AddPrimitive {
300    fn parse(input: ParseStream) -> Result<Self> {
301        let eg = input.parse()?;
302        input.parse::<Token![,]>()?;
303        let name = input.parse()?;
304        input.parse::<Token![=]>()?;
305        let context = input.parse()?;
306        let Args { is_varargs, args } = input.parse()?;
307        let Arrow { is_fallible } = input.parse()?;
308        let ret = input.parse()?;
309
310        let body;
311        braced!(body in input);
312        let body = body.parse()?;
313
314        Ok(AddPrimitive {
315            eg,
316            name,
317            context,
318            args,
319            ret,
320            body,
321            is_varargs,
322            is_fallible,
323        })
324    }
325}
326
327struct Context(Option<(Expr, syn::Type)>);
328
329impl Parse for Context {
330    fn parse(input: ParseStream) -> Result<Self> {
331        if let Ok(context) = (|| {
332            let context;
333            braced!(context in input);
334            Ok(context)
335        })() {
336            let e = context.parse()?;
337            context.parse::<Token![:]>()?;
338            let t = context.parse()?;
339            Ok(Context(Some((e, t))))
340        } else {
341            Ok(Context(None))
342        }
343    }
344}
345
346struct Args {
347    is_varargs: bool,
348    args: Vec<Arg>,
349}
350
351impl Parse for Args {
352    fn parse(input: ParseStream) -> Result<Self> {
353        fn var(input: ParseStream) -> Result<Args> {
354            let arg;
355            bracketed!(arg in input);
356            Ok(Args {
357                is_varargs: true,
358                args: vec![arg.parse()?],
359            })
360        }
361
362        fn fix(input: ParseStream) -> Result<Args> {
363            let mut args = Punctuated::<Arg, Token![,]>::new();
364
365            input.parse::<Token![|]>()?;
366            loop {
367                if input.peek(Token![|]) {
368                    break;
369                }
370                args.push_value(input.parse()?);
371                if input.peek(Token![|]) {
372                    break;
373                }
374                args.push_punct(input.parse()?);
375            }
376            input.parse::<Token![|]>()?;
377
378            Ok(Args {
379                is_varargs: false,
380                args: args.into_iter().collect(),
381            })
382        }
383
384        var(input).or_else(|a| {
385            fix(input).map_err(|b| {
386                let mut e = a;
387                e.combine(b);
388                e
389            })
390        })
391    }
392}
393
394struct Arg {
395    x: Ident,
396    t: Type,
397    is_mutable: bool,
398}
399
400impl Parse for Arg {
401    fn parse(input: ParseStream) -> Result<Self> {
402        let is_mutable = input.parse::<Token![mut]>().is_ok();
403        let x = input.parse()?;
404        input.parse::<Token![:]>()?;
405        let t = input.parse()?;
406        Ok(Arg { x, t, is_mutable })
407    }
408}
409
410struct Type {
411    cast: Option<(syn::Type, bool)>,
412    field: Option<(syn::Type, Expr)>,
413}
414
415impl Parse for Type {
416    fn parse(input: ParseStream) -> Result<Self> {
417        let is_container = input.parse::<Token![@]>().is_ok();
418        let cast = match input.parse::<Token![#]>() {
419            Ok(_) => None,
420            Err(_) => Some((input.parse()?, is_container)),
421        };
422
423        let field_def = syn::Type::Verbatim(quote!(ArcSort));
424
425        let field = if input.peek(syn::token::Paren) {
426            let inner;
427            parenthesized!(inner in input);
428            let field_use = inner.parse()?;
429
430            Some((field_def, field_use))
431        } else if let Some((t, _)) = &cast {
432            let field_use = Expr::Verbatim(quote! {
433                eg.get_arcsort_for_value_type::<#t>()
434            });
435
436            Some((field_def, field_use))
437        } else {
438            None
439        };
440
441        Ok(Type { cast, field })
442    }
443}
444
445struct Arrow {
446    is_fallible: bool,
447}
448
449impl Parse for Arrow {
450    fn parse(input: ParseStream) -> Result<Self> {
451        syn::custom_punctuation!(FailArrow, -?>);
452
453        if input.parse::<Token![->]>().is_ok() {
454            Ok(Arrow { is_fallible: false })
455        } else if input.parse::<FailArrow>().is_ok() {
456            Ok(Arrow { is_fallible: true })
457        } else {
458            Err(input.error("expected -> or -?>"))
459        }
460    }
461}
462
463/// This macro lets the user declare literal primitives with automatic validator generation.
464/// It automatically generates validators by converting between Rust values and Literal types.
465///
466/// # Example
467/// ```rust,ignore
468/// add_literal_prim!(eg, "not" = |a: bool| -> bool { !a });
469/// add_literal_prim!(eg, "+" = |a: i64, b: i64| -> i64 { a + b });
470/// add_literal_prim!(eg, "<" = |a: i64, b: i64| -> bool { a < b });
471/// ```
472#[proc_macro]
473pub fn add_literal_prim(input: TokenStream) -> TokenStream {
474    // Parse the input using the same structure as add_primitive
475    let parsed = parse_macro_input!(input as AddPrimitive);
476
477    // Varargs not supported for literal primitives
478    if parsed.is_varargs {
479        return syn::Error::new_spanned(
480            &parsed.name,
481            "varargs not supported for literal primitives",
482        )
483        .to_compile_error()
484        .into();
485    }
486
487    // Context not supported for literal primitives
488    if parsed.context.0.is_some() {
489        return syn::Error::new_spanned(
490            &parsed.name,
491            "context not supported for literal primitives",
492        )
493        .to_compile_error()
494        .into();
495    }
496
497    // Check for polymorphic types
498    for arg in &parsed.args {
499        if arg.t.cast.is_none() {
500            return syn::Error::new_spanned(
501                &arg.x,
502                "polymorphic types not supported for literal primitives",
503            )
504            .to_compile_error()
505            .into();
506        }
507    }
508
509    if parsed.ret.cast.is_none() {
510        return syn::Error::new_spanned(
511            &parsed.name,
512            "polymorphic return type not supported for literal primitives",
513        )
514        .to_compile_error()
515        .into();
516    }
517
518    // Generate the validator body
519    let validator_body =
520        generate_literal_validator(&parsed.args, &parsed.ret, &parsed.body, parsed.is_fallible);
521
522    // Create the validator expression
523    let validator_expr = syn::parse2::<Expr>(quote! {
524        |termdag: &mut ::egglog::TermDag, args: &[::egglog::TermId]| -> Option<::egglog::TermId> {
525            use egglog::termdag::Term;
526            use egglog_ast::generic_ast::Literal;
527            Some({
528                #validator_body
529            })
530        }
531    })
532    .unwrap();
533
534    // Use the shared implementation with the validator
535    build_add_primitive_impl(parsed, Some(validator_expr))
536}
537
538// Helper function to generate literal validator that computes results
539fn generate_literal_validator(
540    args: &[Arg],
541    ret: &Type,
542    body: &Expr,
543    is_fallible: bool,
544) -> quote::__private::TokenStream {
545    // Generate extraction code for arguments
546    let arg_extracts = args.iter().enumerate().map(|(i, arg)| {
547        let x = &arg.x;
548        if let Some((ty, _)) = &arg.t.cast {
549            quote! {
550                let #x = if let Term::Lit(lit) = termdag.get(args[#i]) {
551                    match <#ty as egglog::prelude::LiteralConvertible>::from_literal(&lit) {
552                        Some(val) => val,
553                        None => return None,
554                    }
555                } else {
556                    return None;
557                };
558            }
559        } else {
560            quote!(panic!("Polymorphic arguments not supported for literal primitives");)
561        }
562    });
563
564    // Generate converter for return value
565    let ret_conv = if let Some((ty, _)) = &ret.cast {
566        quote!(<#ty as egglog::prelude::LiteralConvertible>::to_literal)
567    } else {
568        quote!(|_| panic!("Polymorphic types not supported for literal primitives"))
569    };
570
571    // Generate the body execution and result creation
572    let body_exec = if is_fallible {
573        quote! {
574            let result: Option<_> = #body;
575            match result {
576                Some(result) => {
577                    let result_lit = #ret_conv(result);
578                    termdag.lit(result_lit)
579                }
580                None => return None,
581            }
582        }
583    } else {
584        quote! {
585            let result = #body;
586            let result_lit = #ret_conv(result);
587            termdag.lit(result_lit)
588        }
589    };
590
591    // Put it all together
592    quote! {
593        #(#arg_extracts)*
594        #body_exec
595    }
596}