difftreelog
feature: non-static builtins
in: master
1 file changed
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth1use quote::quote;2use syn::{3 parse_macro_input, FnArg, GenericArgument, ItemFn, Pat, PatType, Path, PathArguments, Type,4};56fn is_location_arg(t: &PatType) -> bool {7 t.attrs.iter().any(|a| a.path.is_ident("location"))8}910trait RetainHad<T> {11 fn retain_had(&mut self, h: impl FnMut(&T) -> bool) -> bool;12}13impl<T> RetainHad<T> for Vec<T> {14 fn retain_had(&mut self, h: impl FnMut(&T) -> bool) -> bool {15 let before = self.len();16 self.retain(h);17 let after = self.len();18 before != after19 }20}2122fn extract_type_from_option(ty: &Type) -> Option<&Type> {23 fn path_is_option(path: &Path) -> bool {24 path.leading_colon.is_none()25 && path.segments.len() == 126 && path.segments.iter().next().unwrap().ident == "Option"27 }2829 match ty {30 Type::Path(typepath) if typepath.qself.is_none() && path_is_option(&typepath.path) => {31 // Get the first segment of the path (there is only one, in fact: "Option"):32 let type_params = &typepath.path.segments.iter().next().unwrap().arguments;33 // It should have only on angle-bracketed param ("<String>"):34 let generic_arg = match type_params {35 PathArguments::AngleBracketed(params) => params.args.iter().next().unwrap(),36 _ => panic!("missing option generic"),37 };38 // This argument must be a type:39 match generic_arg {40 GenericArgument::Type(ty) => Some(ty),41 _ => panic!("option generic should be a type"),42 }43 }44 _ => None,45 }46}4748#[proc_macro_attribute]49pub fn builtin(50 _attr: proc_macro::TokenStream,51 item: proc_macro::TokenStream,52) -> proc_macro::TokenStream {53 // syn::ItemFn::parse(input)54 let mut fun: ItemFn = parse_macro_input!(item);5556 let result = match fun.sig.output {57 syn::ReturnType::Default => panic!("builtin should return something"),58 syn::ReturnType::Type(_, ref ty) => ty.clone(),59 };6061 let params = fun62 .sig63 .inputs64 .iter()65 .map(|i| match i {66 FnArg::Receiver(_) => unreachable!(),67 FnArg::Typed(t) => t,68 })69 .filter(|a| !is_location_arg(a))70 .map(|t| {71 let ident = match &t.pat as &Pat {72 Pat::Ident(i) => i.ident.to_string(),73 _ => panic!("only idents supported yet"),74 };75 let optional = extract_type_from_option(&t.ty).is_some();76 quote! {77 BuiltinParam {78 name: std::borrow::Cow::Borrowed(#ident),79 has_default: #optional,80 }81 }82 })83 .collect::<Vec<_>>();8485 let args = fun86 .sig87 .inputs88 .iter_mut()89 .map(|i| match i {90 FnArg::Receiver(_) => unreachable!(),91 FnArg::Typed(t) => t,92 })93 .map(|t| {94 let is_location = t.attrs.retain_had(|a| !a.path.is_ident("location"));95 if is_location {96 quote! {{97 loc98 }}99 } else {100 let ident = match &t.pat as &Pat {101 Pat::Ident(i) => i.ident.to_string(),102 _ => panic!("only idents supported yet"),103 };104 let ty = &t.ty;105 if let Some(opt_ty) = extract_type_from_option(&t.ty) {106 quote! {{107 if let Some(value) = parsed.get(#ident) {108 Some(::jrsonnet_evaluator::push_description_frame(109 || format!("argument <{}> evaluation", #ident),110 || <#opt_ty>::try_from(value.evaluate()?),111 )?)112 } else {113 None114 }115 }}116 } else {117 quote! {{118 let value = parsed.get(#ident).unwrap();119120 ::jrsonnet_evaluator::push_description_frame(121 || format!("argument <{}> evaluation", #ident),122 || <#ty>::try_from(value.evaluate()?),123 )?124 }}125 }126 }127 })128 .collect::<Vec<_>>();129130 let name = &fun.sig.ident;131 let vis = &fun.vis;132 (quote! {133 #fun134 #[doc(hidden)]135 #[allow(non_camel_case_types)]136 #[derive(Clone, Copy, gcmodule::Trace)]137 #vis struct #name {}138 const _: () = {139 use ::jrsonnet_evaluator::{140 function::{Builtin, StaticBuiltin, BuiltinParam, ArgsLike, parse_builtin_call},141 error::Result, Context,142 parser::ExprLocation,143 };144 const PARAMS: &'static [BuiltinParam] = &[145 #(#params),*146 ];147148 impl #name {149 pub const INST: &'static dyn StaticBuiltin = &#name {};150 }151 impl StaticBuiltin for #name {}152 impl Builtin for #name153 where154 Self: 'static155 {156 fn name(&self) -> &str {157 stringify!(#name)158 }159 fn params(&self) -> &[BuiltinParam] {160 PARAMS161 }162 fn call(&self, context: Context, loc: Option<&ExprLocation>, args: &dyn ArgsLike) -> Result<Val> {163 let parsed = parse_builtin_call(context, &PARAMS, args, false)?;164165 let result: #result = #name(#(#args),*);166 let result = result?;167 result.try_into()168 }169 }170 };171 })172 .into()173}