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};
#[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))
}
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,
})
}
}
#[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 {
let AddPrimitive {
eg,
name,
context,
is_varargs,
args,
is_fallible,
ret,
body,
} = parsed;
let y = Ident::new("__y", Span::mixed_site().into());
let value_type = syn::Type::Verbatim(quote!(Value));
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();
let prim_def = quote!(struct Prim { #(#field_defs,)* });
let prim_use = quote!( Prim { #(#field_uses,)* });
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 !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 {
let Arg {
x,
t,
is_mutable: _,
} = &args[0];
for arg in &args {
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())
}
};
let apply = {
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") };)
};
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()
};
let fail = if is_fallible { quote!(?) } else { quote!() };
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)
}
};
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 -?>"))
}
}
}
#[proc_macro]
pub fn add_literal_prim(input: TokenStream) -> TokenStream {
let parsed = parse_macro_input!(input as AddPrimitive);
if parsed.is_varargs {
return syn::Error::new_spanned(
&parsed.name,
"varargs not supported for literal primitives",
)
.to_compile_error()
.into();
}
if parsed.context.0.is_some() {
return syn::Error::new_spanned(
&parsed.name,
"context not supported for literal primitives",
)
.to_compile_error()
.into();
}
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();
}
let validator_body =
generate_literal_validator(&parsed.args, &parsed.ret, &parsed.body, parsed.is_fallible);
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();
build_add_primitive_impl(parsed, Some(validator_expr))
}
fn generate_literal_validator(
args: &[Arg],
ret: &Type,
body: &Expr,
is_fallible: bool,
) -> quote::__private::TokenStream {
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");)
}
});
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"))
};
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)
}
};
quote! {
#(#arg_extracts)*
#body_exec
}
}