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#[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
27struct 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#[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 let AddPrimitive {
85 eg,
86 name,
87 context,
88 is_varargs,
89 args,
90 is_fallible,
91 ret,
92 body,
93 } = parsed;
94
95 let y = Ident::new("__y", Span::mixed_site().into());
98 let value_type = syn::Type::Verbatim(quote!(Value));
100
101 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 let prim_def = quote!(struct Prim { #(#field_defs,)* });
118 let prim_use = quote!( Prim { #(#field_uses,)* });
119
120 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 !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 let Arg {
140 x,
141 t,
142 is_mutable: _,
143 } = &args[0];
144 for arg in &args {
145 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 let apply = {
172 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 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 let fail = if is_fallible { quote!(?) } else { quote!() };
216 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 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#[proc_macro]
473pub fn add_literal_prim(input: TokenStream) -> TokenStream {
474 let parsed = parse_macro_input!(input as AddPrimitive);
476
477 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 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 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 let validator_body =
520 generate_literal_validator(&parsed.args, &parsed.ret, &parsed.body, parsed.is_fallible);
521
522 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 build_add_primitive_impl(parsed, Some(validator_expr))
536}
537
538fn generate_literal_validator(
540 args: &[Arg],
541 ret: &Type,
542 body: &Expr,
543 is_fallible: bool,
544) -> quote::__private::TokenStream {
545 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 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 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 quote! {
593 #(#arg_extracts)*
594 #body_exec
595 }
596}