egglog-add-primitive 3.0.0

egglog is a language that combines the benefits of equality saturation and datalog. It can be used for analysis, optimization, and synthesis of programs. It is the successor to the popular rust library egg.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
use proc_macro::{Span, TokenStream};
use quote::quote;
use syn::parse::{Parse, ParseStream, Result};
use syn::punctuated::Punctuated;
use syn::{Expr, Ident, LitStr, Token, braced, bracketed, parenthesized, parse_macro_input};

/// This macro lets the user declare custom egglog primitives with explicit validators.
/// It combines primitive registration with a custom validator function.
///
/// # Example
/// ```rust,ignore
/// add_primitive_with_validator!(
///     eg,
///     "custom-op" = |a: Value| -> Value { a },
///     |termdag, lhs| {
///         // Custom validation logic
///         None
///     }
/// );
/// ```
#[proc_macro]
pub fn add_primitive_with_validator(input: TokenStream) -> TokenStream {
    let parsed = parse_macro_input!(input as AddPrimitiveWithValidator);
    build_add_primitive_impl(parsed.primitive, Some(parsed.validator))
}

/// Parses an `AddPrimitive` followed by a comma and a validator expression.
struct AddPrimitiveWithValidator {
    primitive: AddPrimitive,
    validator: Expr,
}

impl Parse for AddPrimitiveWithValidator {
    fn parse(input: ParseStream) -> Result<Self> {
        let primitive = input.parse()?;
        input.parse::<Token![,]>()?;
        let validator = input.parse()?;
        Ok(AddPrimitiveWithValidator {
            primitive,
            validator,
        })
    }
}

/// This macro lets the user declare custom egglog primitives.
/// It supports a few special features:
///
/// - Failure: using `-?>` instead of `->` before the return type will
///   make the primitive fallible, requiring the body to return an
///   `Option<T>` instead of just `T`.
///
/// - Varargs: using `[xs: T]` as the argument list will cause the
///   primitive to take a variable number of arguments, which will be
///   passed to be body as an `Iterator<Item=T>`.
///
/// - Polymorphism: using `#` as a type will allow any type during
///   typechecking. These will be given type `Value` in the body.
///
/// - Containers: you must put an `@` in front of container types.
///
/// - Specialized Constraints: using `T (E)` as a type will use
///   `(E:expr).clone()` in the type constraint but `T:ty` in the body.
///   This is necessary because the relationship between Rust types
///   and egglog sorts is not 1-to-1.
///
/// - Context: sometimes you want your primitive to reference
///   information from the scope of the `add_primitive!` call.
///   Putting `{x: T}` between the `=` and the argument list
///   will let you access the expression `x` of type `T` from inside
///   the body as `self.ctx`. `T` must be the real Rust type of `x`.
///   `T` must be `Clone` and `'static`.
#[proc_macro]
pub fn add_primitive(input: TokenStream) -> TokenStream {
    build_add_primitive_impl(parse_macro_input!(input), None)
}

fn build_add_primitive_impl(parsed: AddPrimitive, validator: Option<Expr>) -> TokenStream {
    // If you're trying to read this code, you should read the big
    // `quote!` block at the bottom of this function first. Trying
    // to parse all the intermediate gobbledygook is going to be
    // hard without that context.

    // Parse the input by implementing `syn::Parse` for our data types.
    let AddPrimitive {
        eg,
        name,
        context,
        is_varargs,
        args,
        is_fallible,
        ret,
        body,
    } = parsed;

    // Create a new field name for the `Prim` struct to hold the return sort.
    // (We reuse the closure argument names for the argument sorts.)
    let y = Ident::new("__y", Span::mixed_site().into());
    // Create a type that refers to whichever `Value` import is closer.
    let value_type = syn::Type::Verbatim(quote!(Value));

    // List out the sorts that we need to store.
    let (field_defs, field_uses): (Vec<_>, Vec<_>) = args
        .iter()
        .map(|arg| (&arg.x, &arg.t))
        .chain([(&y, &ret)])
        .filter_map(|(x, t)| {
            t.field
                .as_ref()
                .map(|(d, u)| (quote!(#x: #d), quote!(#x: #u.clone())))
        })
        .chain(match context.0 {
            Some((e, t)) => vec![(quote!(ctx: #t), quote!(ctx: #e))],
            None => vec![],
        })
        .unzip();
    // Bundle up the defs and uses into structs.
    let prim_def = quote!(struct Prim { #(#field_defs,)* });
    let prim_use = quote!(       Prim { #(#field_uses,)* });

    // Create the type constraint for the `egglog` typechecker.
    // TODO: add a new type constraint that supports all possible combinations
    // of features that this macro supports. Right now `|a: #, b: i64|` is
    // impossible to express with the current type constraints.
    let type_constraint = {
        let has_type = |t: &Type| t.field.is_some();
        let args_have_types = args.iter().all(|arg| has_type(&arg.t));
        let ret_has_type = has_type(&ret);

        // If we're in the simple case, we can use the `SimpleTypeConstraint`.
        // However, use of either `#` or varargs makes this impossible.
        if !is_varargs && args_have_types && ret_has_type {
            let x = args.iter().map(|arg| &arg.x);
            quote! {
                let sorts: Vec<ArcSort> = vec![#(self.#x.clone() as ArcSort,)* self.#y.clone()];
                SimpleTypeConstraint::new(self.name(), sorts, span.clone()).into_box()
            }
        } else {
            // As a fallback, try to use `AllEqualTypeConstraint` for everything else.
            let Arg {
                x,
                t,
                is_mutable: _,
            } = &args[0];
            for arg in &args {
                // NOTE: this is a conservative (incomplete!) check, as `syn::Type`
                // is not `PartialEq`. See the TODO on `type_constraint`.
                assert_eq!(
                    has_type(t),
                    has_type(&arg.t),
                    "AllEqualTypeConstraint doesn't support multiple argument types"
                )
            }

            let new = quote!(AllEqualTypeConstraint::new(self.name(), span.clone()));

            let len = args.len() + 1;
            let len = quote!(.with_exact_length(#len));
            let len = if is_varargs { quote!() } else { len };

            let args = quote!(.with_all_arguments_sort(self.#x.clone()));
            let args = if args_have_types { args } else { quote!() };

            let ret = quote!(.with_output_sort(self.#y.clone()));
            let ret = if ret_has_type { ret } else { quote!() };

            quote!(#new #len #args #ret .into_box())
        }
    };

    // Create the function body for `apply`.
    let apply = {
        // Bind the argument names that were passed in to this macro.
        let bind = if is_varargs {
            let x = &args[0].x;
            quote!(let #x = args.iter();)
        } else {
            let x = args.iter().map(|arg| &arg.x);
            quote!(let [#(#x),*] = args else { panic!("wrong number of arguments") };)
        };

        // Cast the arguments to the desired type. `state` is a
        // `PureState<'a, 'db>` whose `base_values()` and
        // `container_values()` come from the `Core` trait (re-exported
        // via the `egglog::*` glob below).
        let cast1 = |x, t: &syn::Type, is_container| match is_container {
            false => quote!(state.base_values().unwrap::<#t>(*#x)),
            true => quote!(state.container_values().get_val::<#t>(*#x).unwrap().clone()),
        };
        let cast = if is_varargs {
            let Arg { x, t, is_mutable } = &args[0];
            let mutable = if *is_mutable { quote!(mut) } else { quote!() };
            match &t.cast {
                None => quote!(let #mutable #x = #x.copied();),
                Some((t, is_container)) => {
                    let cast = cast1(x, t, *is_container);
                    quote!(let #mutable #x = #x.map(|#x| #cast);)
                }
            }
        } else {
            args.iter()
                .map(|Arg { x, t, is_mutable }| {
                    let mutable = if *is_mutable { quote!(mut) } else { quote!() };
                    match &t.cast {
                        None => quote!(let #mutable #x: Value = *#x;),
                        Some((t, is_container)) => {
                            let cast = cast1(x, t, *is_container);
                            quote!(let #mutable #x: #t = #cast;)
                        }
                    }
                })
                .collect()
        };

        // If the primitive is fallible, put a `?` after the body.
        let fail = if is_fallible { quote!(?) } else { quote!() };
        // Cast the result back to an interned value. For container
        // returns we go through `state.register_container`, which is a
        // `Core` method and (per #772) safe in every context since
        // container interning is idempotent.
        let (yt, ret) = match &ret.cast {
            None => (&value_type, quote!(#y)),
            Some((t, is_container)) => (
                t,
                match is_container {
                    false => quote!(state.base_values().get::<#t>(#y)),
                    true => quote!(state.register_container::<#t>(#y)),
                },
            ),
        };

        quote! {
            #bind
            #cast
            let #y: #yt = (#body)#fail;
            Some(#ret)
        }
    };

    // This is the big `quote!` block that ties everything together.
    //
    // Macro-generated primitives are registered as `PurePrim` (valid
    // in all four contexts) because every code path the macro emits
    // is pure: it reads base / container values and registers
    // containers, which are all safe everywhere per the `Core` trait.
    // If a future extension of the macro introduces a non-pure
    // emission path, the declared kind would need to narrow accordingly.
    let add_call = match validator {
        None => quote!(eg.add_pure_primitive(#prim_use, None);),
        Some(validator_expr) => quote!(eg.add_pure_primitive(
            #prim_use,
            Some(::std::sync::Arc::new(#validator_expr))
        );),
    };

    quote! {{
        #[allow(unused_imports)] use ::egglog::{*, ast::*, constraint::*};
        #[allow(unused_imports)] use ::std::{any::TypeId, sync::Arc};

        #[derive(Clone)]
        #prim_def

        impl Primitive for Prim {
            fn name(&self) -> &str {
                #name
            }

            fn get_type_constraints(&self, span: &Span) -> Box<dyn TypeConstraint> {
                #type_constraint
            }
        }

        impl PurePrim for Prim {
            fn apply<'a, 'db>(
                &self,
                #[allow(unused_mut)] mut state: PureState<'a, 'db>,
                args: &[Value],
            ) -> Option<Value> {
                #apply
            }
        }

        let eg: &mut EGraph = #eg;
        #add_call
    }}
    .into()
}

struct AddPrimitive {
    eg: Expr,
    name: LitStr,
    context: Context,
    args: Vec<Arg>,
    ret: Type,
    body: Expr,
    is_varargs: bool,
    is_fallible: bool,
}

impl Parse for AddPrimitive {
    fn parse(input: ParseStream) -> Result<Self> {
        let eg = input.parse()?;
        input.parse::<Token![,]>()?;
        let name = input.parse()?;
        input.parse::<Token![=]>()?;
        let context = input.parse()?;
        let Args { is_varargs, args } = input.parse()?;
        let Arrow { is_fallible } = input.parse()?;
        let ret = input.parse()?;

        let body;
        braced!(body in input);
        let body = body.parse()?;

        Ok(AddPrimitive {
            eg,
            name,
            context,
            args,
            ret,
            body,
            is_varargs,
            is_fallible,
        })
    }
}

struct Context(Option<(Expr, syn::Type)>);

impl Parse for Context {
    fn parse(input: ParseStream) -> Result<Self> {
        if let Ok(context) = (|| {
            let context;
            braced!(context in input);
            Ok(context)
        })() {
            let e = context.parse()?;
            context.parse::<Token![:]>()?;
            let t = context.parse()?;
            Ok(Context(Some((e, t))))
        } else {
            Ok(Context(None))
        }
    }
}

struct Args {
    is_varargs: bool,
    args: Vec<Arg>,
}

impl Parse for Args {
    fn parse(input: ParseStream) -> Result<Self> {
        fn var(input: ParseStream) -> Result<Args> {
            let arg;
            bracketed!(arg in input);
            Ok(Args {
                is_varargs: true,
                args: vec![arg.parse()?],
            })
        }

        fn fix(input: ParseStream) -> Result<Args> {
            let mut args = Punctuated::<Arg, Token![,]>::new();

            input.parse::<Token![|]>()?;
            loop {
                if input.peek(Token![|]) {
                    break;
                }
                args.push_value(input.parse()?);
                if input.peek(Token![|]) {
                    break;
                }
                args.push_punct(input.parse()?);
            }
            input.parse::<Token![|]>()?;

            Ok(Args {
                is_varargs: false,
                args: args.into_iter().collect(),
            })
        }

        var(input).or_else(|a| {
            fix(input).map_err(|b| {
                let mut e = a;
                e.combine(b);
                e
            })
        })
    }
}

struct Arg {
    x: Ident,
    t: Type,
    is_mutable: bool,
}

impl Parse for Arg {
    fn parse(input: ParseStream) -> Result<Self> {
        let is_mutable = input.parse::<Token![mut]>().is_ok();
        let x = input.parse()?;
        input.parse::<Token![:]>()?;
        let t = input.parse()?;
        Ok(Arg { x, t, is_mutable })
    }
}

struct Type {
    cast: Option<(syn::Type, bool)>,
    field: Option<(syn::Type, Expr)>,
}

impl Parse for Type {
    fn parse(input: ParseStream) -> Result<Self> {
        let is_container = input.parse::<Token![@]>().is_ok();
        let cast = match input.parse::<Token![#]>() {
            Ok(_) => None,
            Err(_) => Some((input.parse()?, is_container)),
        };

        let field_def = syn::Type::Verbatim(quote!(ArcSort));

        let field = if input.peek(syn::token::Paren) {
            let inner;
            parenthesized!(inner in input);
            let field_use = inner.parse()?;

            Some((field_def, field_use))
        } else if let Some((t, _)) = &cast {
            let field_use = Expr::Verbatim(quote! {
                eg.get_arcsort_for_value_type::<#t>()
            });

            Some((field_def, field_use))
        } else {
            None
        };

        Ok(Type { cast, field })
    }
}

struct Arrow {
    is_fallible: bool,
}

impl Parse for Arrow {
    fn parse(input: ParseStream) -> Result<Self> {
        syn::custom_punctuation!(FailArrow, -?>);

        if input.parse::<Token![->]>().is_ok() {
            Ok(Arrow { is_fallible: false })
        } else if input.parse::<FailArrow>().is_ok() {
            Ok(Arrow { is_fallible: true })
        } else {
            Err(input.error("expected -> or -?>"))
        }
    }
}

/// This macro lets the user declare literal primitives with automatic validator generation.
/// It automatically generates validators by converting between Rust values and Literal types.
///
/// # Example
/// ```rust,ignore
/// add_literal_prim!(eg, "not" = |a: bool| -> bool { !a });
/// add_literal_prim!(eg, "+" = |a: i64, b: i64| -> i64 { a + b });
/// add_literal_prim!(eg, "<" = |a: i64, b: i64| -> bool { a < b });
/// ```
#[proc_macro]
pub fn add_literal_prim(input: TokenStream) -> TokenStream {
    // Parse the input using the same structure as add_primitive
    let parsed = parse_macro_input!(input as AddPrimitive);

    // Varargs not supported for literal primitives
    if parsed.is_varargs {
        return syn::Error::new_spanned(
            &parsed.name,
            "varargs not supported for literal primitives",
        )
        .to_compile_error()
        .into();
    }

    // Context not supported for literal primitives
    if parsed.context.0.is_some() {
        return syn::Error::new_spanned(
            &parsed.name,
            "context not supported for literal primitives",
        )
        .to_compile_error()
        .into();
    }

    // Check for polymorphic types
    for arg in &parsed.args {
        if arg.t.cast.is_none() {
            return syn::Error::new_spanned(
                &arg.x,
                "polymorphic types not supported for literal primitives",
            )
            .to_compile_error()
            .into();
        }
    }

    if parsed.ret.cast.is_none() {
        return syn::Error::new_spanned(
            &parsed.name,
            "polymorphic return type not supported for literal primitives",
        )
        .to_compile_error()
        .into();
    }

    // Generate the validator body
    let validator_body =
        generate_literal_validator(&parsed.args, &parsed.ret, &parsed.body, parsed.is_fallible);

    // Create the validator expression
    let validator_expr = syn::parse2::<Expr>(quote! {
        |termdag: &mut ::egglog::TermDag, args: &[::egglog::TermId]| -> Option<::egglog::TermId> {
            use egglog::termdag::Term;
            use egglog_ast::generic_ast::Literal;
            Some({
                #validator_body
            })
        }
    })
    .unwrap();

    // Use the shared implementation with the validator
    build_add_primitive_impl(parsed, Some(validator_expr))
}

// Helper function to generate literal validator that computes results
fn generate_literal_validator(
    args: &[Arg],
    ret: &Type,
    body: &Expr,
    is_fallible: bool,
) -> quote::__private::TokenStream {
    // Generate extraction code for arguments
    let arg_extracts = args.iter().enumerate().map(|(i, arg)| {
        let x = &arg.x;
        if let Some((ty, _)) = &arg.t.cast {
            quote! {
                let #x = if let Term::Lit(lit) = termdag.get(args[#i]) {
                    match <#ty as egglog::prelude::LiteralConvertible>::from_literal(&lit) {
                        Some(val) => val,
                        None => return None,
                    }
                } else {
                    return None;
                };
            }
        } else {
            quote!(panic!("Polymorphic arguments not supported for literal primitives");)
        }
    });

    // Generate converter for return value
    let ret_conv = if let Some((ty, _)) = &ret.cast {
        quote!(<#ty as egglog::prelude::LiteralConvertible>::to_literal)
    } else {
        quote!(|_| panic!("Polymorphic types not supported for literal primitives"))
    };

    // Generate the body execution and result creation
    let body_exec = if is_fallible {
        quote! {
            let result: Option<_> = #body;
            match result {
                Some(result) => {
                    let result_lit = #ret_conv(result);
                    termdag.lit(result_lit)
                }
                None => return None,
            }
        }
    } else {
        quote! {
            let result = #body;
            let result_lit = #ret_conv(result);
            termdag.lit(result_lit)
        }
    };

    // Put it all together
    quote! {
        #(#arg_extracts)*
        #body_exec
    }
}