|
| 1 | +use proc_macro::TokenStream; |
| 2 | +use proc_macro2::TokenStream as TokenStream2; |
| 3 | +use quote::{format_ident, quote, ToTokens}; |
| 4 | +use syn::{ |
| 5 | + parse_macro_input, FnArg, GenericParam, Generics, ItemFn, Pat, ReturnType, Type, |
| 6 | + TypeParamBound, WherePredicate, |
| 7 | +}; |
| 8 | + |
| 9 | +/// Transforms a function annotated with `#[requires(req)]` and `#[ensures(ens)]` into |
| 10 | +/// an internal multi-function representation for the Thrust analysis backend. |
| 11 | +/// |
| 12 | +/// This macro must be paired with `#[ensures(...)]` on the same function. |
| 13 | +/// |
| 14 | +/// # Generated output |
| 15 | +/// |
| 16 | +/// For `#[requires(req)] #[ensures(ens)] fn f<T>(a: A) -> R`: |
| 17 | +/// |
| 18 | +/// - The original function `f` (unchanged, minus the two thrust attrs) |
| 19 | +/// - `_thrust_requires_f<T>(a: <A as Model>::Ty) -> bool` with body `req` |
| 20 | +/// - `_thrust_ensures_f<T>(result: <R as Model>::Ty, a: <A as Model>::Ty) -> bool` with body `ens` |
| 21 | +/// - `_thrust_extern_spec_f<T>(a: A) -> R` referencing the above via path statements |
| 22 | +#[proc_macro_attribute] |
| 23 | +pub fn requires(attr: TokenStream, item: TokenStream) -> TokenStream { |
| 24 | + let req_expr = TokenStream2::from(attr); |
| 25 | + let mut func = parse_macro_input!(item as ItemFn); |
| 26 | + |
| 27 | + // Find and extract the paired #[ensures(...)] attribute |
| 28 | + let ensures_pos = func.attrs.iter().position(|a| { |
| 29 | + a.path() |
| 30 | + .segments |
| 31 | + .last() |
| 32 | + .map_or(false, |s| s.ident == "ensures") |
| 33 | + }); |
| 34 | + |
| 35 | + let ens_expr = match ensures_pos { |
| 36 | + Some(idx) => { |
| 37 | + let attr = func.attrs.remove(idx); |
| 38 | + match attr.parse_args::<TokenStream2>() { |
| 39 | + Ok(ts) => ts, |
| 40 | + Err(e) => return e.to_compile_error().into(), |
| 41 | + } |
| 42 | + } |
| 43 | + None => { |
| 44 | + return syn::Error::new_spanned( |
| 45 | + &func.sig.ident, |
| 46 | + "#[requires] must be paired with #[ensures]", |
| 47 | + ) |
| 48 | + .to_compile_error() |
| 49 | + .into(); |
| 50 | + } |
| 51 | + }; |
| 52 | + |
| 53 | + // Strip any stray requires attrs (defensive — they'd cause infinite recursion) |
| 54 | + func.attrs.retain(|a| { |
| 55 | + a.path() |
| 56 | + .segments |
| 57 | + .last() |
| 58 | + .map_or(true, |s| s.ident != "requires") |
| 59 | + }); |
| 60 | + |
| 61 | + transform(func, req_expr, ens_expr).unwrap_or_else(|e| e.to_compile_error().into()) |
| 62 | +} |
| 63 | + |
| 64 | +/// Pass-through no-op. When `#[ensures]` is consumed by `#[requires]`, this is never |
| 65 | +/// reached. It exists so that `#[ensures]` is a recognized proc macro attribute and does |
| 66 | +/// not produce an "unknown attribute" error if applied in isolation. |
| 67 | +#[proc_macro_attribute] |
| 68 | +pub fn ensures(_attr: TokenStream, item: TokenStream) -> TokenStream { |
| 69 | + item |
| 70 | +} |
| 71 | + |
| 72 | +fn transform( |
| 73 | + func: ItemFn, |
| 74 | + req_expr: TokenStream2, |
| 75 | + ens_expr: TokenStream2, |
| 76 | +) -> syn::Result<TokenStream> { |
| 77 | + let name = &func.sig.ident; |
| 78 | + let requires_name = format_ident!("_thrust_requires_{}", name); |
| 79 | + let ensures_name = format_ident!("_thrust_ensures_{}", name); |
| 80 | + let extern_spec_name = format_ident!("_thrust_extern_spec_{}", name); |
| 81 | + |
| 82 | + let generics = &func.sig.generics; |
| 83 | + |
| 84 | + // <T, U, 'a, ...> for function definitions (params only, no where clause) |
| 85 | + let def_generics = generic_params_tokens(generics); |
| 86 | + |
| 87 | + // ::<T, U, 'a, ...> for turbofish (empty if no params) |
| 88 | + let turbofish = generic_turbofish(generics); |
| 89 | + |
| 90 | + // Additional where predicates: T: thrust_models::Model for qualifying type params |
| 91 | + let model_preds = model_where_predicates(generics); |
| 92 | + |
| 93 | + // Full where clause combining original predicates and model predicates |
| 94 | + let extended_where = extended_where_clause(generics, &model_preds); |
| 95 | + |
| 96 | + // Parameters with types replaced by <T as thrust_models::Model>::Ty |
| 97 | + let model_ty_params = fn_params_with_model_ty(&func.sig.inputs); |
| 98 | + |
| 99 | + // Argument idents for function call expressions |
| 100 | + let call_args = fn_arg_idents(&func.sig.inputs); |
| 101 | + |
| 102 | + // Return type for requires/ensures helper (wrapped in ::Ty) |
| 103 | + let ret_model_ty: Type = match &func.sig.output { |
| 104 | + ReturnType::Default => syn::parse_quote!(<() as thrust_models::Model>::Ty), |
| 105 | + ReturnType::Type(_, ty) => syn::parse_quote!(<#ty as thrust_models::Model>::Ty), |
| 106 | + }; |
| 107 | + |
| 108 | + let orig_inputs = &func.sig.inputs; |
| 109 | + let orig_output = &func.sig.output; |
| 110 | + |
| 111 | + let output = quote! { |
| 112 | + #func |
| 113 | + |
| 114 | + #[allow(unused_variables)] |
| 115 | + #[thrust::formula_fn] |
| 116 | + fn #requires_name #def_generics(#model_ty_params) -> bool #extended_where { |
| 117 | + #req_expr |
| 118 | + } |
| 119 | + |
| 120 | + #[allow(unused_variables)] |
| 121 | + #[thrust::formula_fn] |
| 122 | + fn #ensures_name #def_generics(result: #ret_model_ty, #model_ty_params) -> bool #extended_where { |
| 123 | + #ens_expr |
| 124 | + } |
| 125 | + |
| 126 | + #[thrust::extern_spec_fn] |
| 127 | + #[allow(path_statements)] |
| 128 | + fn #extern_spec_name #def_generics(#orig_inputs) #orig_output #extended_where { |
| 129 | + #[thrust::requires_path] |
| 130 | + #requires_name #turbofish; |
| 131 | + |
| 132 | + #[thrust::ensures_path] |
| 133 | + #ensures_name #turbofish; |
| 134 | + |
| 135 | + #name #turbofish(#call_args) |
| 136 | + } |
| 137 | + }; |
| 138 | + |
| 139 | + Ok(output.into()) |
| 140 | +} |
| 141 | + |
| 142 | +/// Returns `<T: Bound, U, 'a>` — the generic param list for function definitions, |
| 143 | +/// without a where clause. |
| 144 | +fn generic_params_tokens(generics: &Generics) -> TokenStream2 { |
| 145 | + if generics.params.is_empty() { |
| 146 | + return quote!(); |
| 147 | + } |
| 148 | + let params = &generics.params; |
| 149 | + quote!(<#params>) |
| 150 | +} |
| 151 | + |
| 152 | +/// Returns `::<T, U, 'a>` for turbofish use, or nothing if no generic params. |
| 153 | +fn generic_turbofish(generics: &Generics) -> TokenStream2 { |
| 154 | + if generics.params.is_empty() { |
| 155 | + return quote!(); |
| 156 | + } |
| 157 | + let args: Vec<TokenStream2> = generics |
| 158 | + .params |
| 159 | + .iter() |
| 160 | + .map(|p| match p { |
| 161 | + GenericParam::Type(tp) => tp.ident.to_token_stream(), |
| 162 | + GenericParam::Lifetime(lp) => lp.lifetime.to_token_stream(), |
| 163 | + GenericParam::Const(cp) => cp.ident.to_token_stream(), |
| 164 | + }) |
| 165 | + .collect(); |
| 166 | + quote!(::<#(#args),*>) |
| 167 | +} |
| 168 | + |
| 169 | +/// Returns `T: thrust_models::Model` predicates for every type param that does not |
| 170 | +/// already carry an `Fn`, `FnOnce`, or `FnMut` bound. |
| 171 | +fn model_where_predicates(generics: &Generics) -> Vec<WherePredicate> { |
| 172 | + generics |
| 173 | + .params |
| 174 | + .iter() |
| 175 | + .filter_map(|p| { |
| 176 | + let GenericParam::Type(tp) = p else { |
| 177 | + return None; |
| 178 | + }; |
| 179 | + let has_fn_bound = tp.bounds.iter().any(|b| { |
| 180 | + let TypeParamBound::Trait(tb) = b else { |
| 181 | + return false; |
| 182 | + }; |
| 183 | + tb.path.segments.last().map_or(false, |s| { |
| 184 | + matches!(s.ident.to_string().as_str(), "Fn" | "FnOnce" | "FnMut") |
| 185 | + }) |
| 186 | + }); |
| 187 | + if has_fn_bound { |
| 188 | + return None; |
| 189 | + } |
| 190 | + let ident = &tp.ident; |
| 191 | + Some(syn::parse_quote!(#ident: thrust_models::Model)) |
| 192 | + }) |
| 193 | + .collect() |
| 194 | +} |
| 195 | + |
| 196 | +/// Builds `where <original predicates>, <model predicates>`. |
| 197 | +/// Returns an empty token stream when both sets are empty. |
| 198 | +fn extended_where_clause(generics: &Generics, model_preds: &[WherePredicate]) -> TokenStream2 { |
| 199 | + let existing: Vec<&WherePredicate> = generics |
| 200 | + .where_clause |
| 201 | + .as_ref() |
| 202 | + .map(|wc| wc.predicates.iter().collect()) |
| 203 | + .unwrap_or_default(); |
| 204 | + |
| 205 | + if existing.is_empty() && model_preds.is_empty() { |
| 206 | + return quote!(); |
| 207 | + } |
| 208 | + |
| 209 | + quote! { where #(#existing,)* #(#model_preds),* } |
| 210 | +} |
| 211 | + |
| 212 | +/// Maps each typed function parameter `x: T` to `x: <T as thrust_models::Model>::Ty`. |
| 213 | +/// Receiver (`self`) parameters are skipped. |
| 214 | +fn fn_params_with_model_ty( |
| 215 | + inputs: &syn::punctuated::Punctuated<FnArg, syn::token::Comma>, |
| 216 | +) -> TokenStream2 { |
| 217 | + let params: Vec<TokenStream2> = inputs |
| 218 | + .iter() |
| 219 | + .filter_map(|arg| { |
| 220 | + let FnArg::Typed(pt) = arg else { return None }; |
| 221 | + let pat = &pt.pat; |
| 222 | + let ty = &pt.ty; |
| 223 | + let model_ty: Type = syn::parse_quote!(<#ty as thrust_models::Model>::Ty); |
| 224 | + Some(quote!(#pat: #model_ty)) |
| 225 | + }) |
| 226 | + .collect(); |
| 227 | + quote!(#(#params),*) |
| 228 | +} |
| 229 | + |
| 230 | +/// Extracts argument identifiers from function parameters for use in a call expression. |
| 231 | +fn fn_arg_idents(inputs: &syn::punctuated::Punctuated<FnArg, syn::token::Comma>) -> TokenStream2 { |
| 232 | + let args: Vec<TokenStream2> = inputs |
| 233 | + .iter() |
| 234 | + .filter_map(|arg| match arg { |
| 235 | + FnArg::Typed(pt) => { |
| 236 | + if let Pat::Ident(pi) = &*pt.pat { |
| 237 | + Some(pi.ident.to_token_stream()) |
| 238 | + } else { |
| 239 | + None |
| 240 | + } |
| 241 | + } |
| 242 | + FnArg::Receiver(_) => Some(quote!(self)), |
| 243 | + }) |
| 244 | + .collect(); |
| 245 | + quote!(#(#args),*) |
| 246 | +} |
0 commit comments