binius_macros/lib.rs
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
// Copyright 2024-2025 Irreducible Inc.
extern crate proc_macro;
mod arith_circuit_poly;
mod arith_expr;
mod composition_poly;
use std::collections::BTreeSet;
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse_macro_input, Data, DeriveInput, Fields};
use crate::{
arith_circuit_poly::ArithCircuitPolyItem, arith_expr::ArithExprItem,
composition_poly::CompositionPolyItem,
};
/// Useful for concisely creating structs that implement CompositionPolyOS.
/// This currently only supports creating composition polynomials of tower level 0.
///
/// ```
/// use binius_macros::composition_poly;
/// use binius_math::CompositionPolyOS;
/// use binius_field::{Field, BinaryField1b as F};
///
/// // Defines named struct without any fields that implements CompositionPolyOS
/// composition_poly!(MyComposition[x, y, z] = x + y * z);
/// assert_eq!(
/// MyComposition.evaluate(&[F::ONE, F::ONE, F::ONE]).unwrap(),
/// F::ZERO
/// );
///
/// // If you omit the name you get an anonymous instance instead, which can be used inline
/// assert_eq!(
/// composition_poly!([x, y, z] = x + y * z)
/// .evaluate(&[F::ONE, F::ONE, F::ONE]).unwrap(),
/// F::ZERO
/// );
/// ```
#[proc_macro]
pub fn composition_poly(input: TokenStream) -> TokenStream {
parse_macro_input!(input as CompositionPolyItem)
.into_token_stream()
.into()
}
/// Define polynomial expressions compactly using named positional arguments
///
/// ```
/// use binius_macros::arith_expr;
/// use binius_field::{Field, BinaryField1b, BinaryField8b};
/// use binius_math::ArithExpr as Expr;
///
/// assert_eq!(
/// arith_expr!([x, y] = x + y + 1),
/// Expr::Var(0) + Expr::Var(1) + Expr::Const(BinaryField1b::ONE)
/// );
///
/// assert_eq!(
/// arith_expr!(BinaryField8b[x] = 3*x + 15),
/// Expr::Const(BinaryField8b::new(3)) * Expr::Var(0) + Expr::Const(BinaryField8b::new(15))
/// );
/// ```
#[proc_macro]
pub fn arith_expr(input: TokenStream) -> TokenStream {
parse_macro_input!(input as ArithExprItem)
.into_token_stream()
.into()
}
#[proc_macro]
pub fn arith_circuit_poly(input: TokenStream) -> TokenStream {
parse_macro_input!(input as ArithCircuitPolyItem)
.into_token_stream()
.into()
}
/// Implements `pub fn iter_oracles(&self) -> impl Iterator<Item = OracleId>`.
///
/// Detects and includes fields with type `OracleId`, `[OracleId; N]`
///
/// ```
/// use binius_macros::IterOracles;
/// type OracleId = usize;
/// type BatchId = usize;
///
/// #[derive(IterOracles)]
/// struct Oracle {
/// x: OracleId,
/// y: [OracleId; 5],
/// z: [OracleId; 5*2],
/// ignored_field1: usize,
/// ignored_field2: BatchId,
/// ignored_field3: [[OracleId; 5]; 2],
/// }
/// ```
#[proc_macro_derive(IterOracles)]
pub fn iter_oracle_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let Data::Struct(data) = &input.data else {
panic!("#[derive(IterOracles)] is only defined for structs with named fields");
};
let Fields::Named(fields) = &data.fields else {
panic!("#[derive(IterOracles)] is only defined for structs with named fields");
};
let name = &input.ident;
let (impl_generics, ty_generics, where_clause) = &input.generics.split_for_impl();
let oracles = fields
.named
.iter()
.filter_map(|f| {
let name = f.ident.clone();
match &f.ty {
syn::Type::Path(type_path) if type_path.path.is_ident("OracleId") => {
Some(quote!(std::iter::once(self.#name)))
}
syn::Type::Array(array) => {
if let syn::Type::Path(type_path) = *array.elem.clone() {
type_path
.path
.is_ident("OracleId")
.then(|| quote!(self.#name.into_iter()))
} else {
None
}
}
_ => None,
}
})
.collect::<Vec<_>>();
quote! {
impl #impl_generics #name #ty_generics #where_clause {
pub fn iter_oracles(&self) -> impl Iterator<Item = OracleId> {
std::iter::empty()
#(.chain(#oracles))*
}
}
}
.into()
}
/// Implements `pub fn iter_polys(&self) -> impl Iterator<Item = MultilinearExtension<P>>`.
///
/// Supports `Vec<P>`, `[Vec<P>; N]`. Currently doesn't filter out fields from the struct, so you can't add any other fields.
///
/// ```
/// use binius_macros::IterPolys;
/// use binius_field::PackedField;
///
/// #[derive(IterPolys)]
/// struct Witness<P: PackedField> {
/// x: Vec<P>,
/// y: [Vec<P>; 5],
/// z: [Vec<P>; 5*2],
/// }
/// ```
#[proc_macro_derive(IterPolys)]
pub fn iter_witness_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let Data::Struct(data) = &input.data else {
panic!("#[derive(IterPolys)] is only defined for structs with named fields");
};
let Fields::Named(fields) = &data.fields else {
panic!("#[derive(IterPolys)] is only defined for structs with named fields");
};
let name = &input.ident;
let witnesses = fields
.named
.iter()
.map(|f| {
let name = f.ident.clone();
match &f.ty {
syn::Type::Array(_) => quote!(self.#name.iter()),
_ => quote!(std::iter::once(&self.#name)),
}
})
.collect::<Vec<_>>();
let packed_field_vars = generic_vars_with_trait(&input.generics, "PackedField");
assert_eq!(packed_field_vars.len(), 1, "Only a single packed field is supported for now");
let p = packed_field_vars.first();
let (impl_generics, ty_generics, where_clause) = &input.generics.split_for_impl();
quote! {
impl #impl_generics #name #ty_generics #where_clause {
pub fn iter_polys(&self) -> impl Iterator<Item = binius_math::MultilinearExtension<#p, &[#p]>> {
std::iter::empty()
#(.chain(#witnesses))*
.map(|values| binius_math::MultilinearExtension::from_values_slice(values.as_slice()).unwrap())
}
}
}
.into()
}
/// This will accept the generics definition of a struct (relevant for derive macros),
/// and return all the generic vars that are constrained by a specific trait identifier.
/// ```
/// use binius_field::{PackedField, Field};
/// struct Example<A: PackedField, B: PackedField + Field, C: Field>(A, B, C);
/// ```
/// In the above example, when matching against the trait_name "PackedField",
/// the identifiers A and B will be returned, but not C
pub(crate) fn generic_vars_with_trait(
vars: &syn::Generics,
trait_name: &str,
) -> BTreeSet<syn::Ident> {
vars.params
.iter()
.filter_map(|param| match param {
syn::GenericParam::Type(type_param) => {
let is_bounded_by_trait_name = type_param.bounds.iter().any(|bound| match bound {
syn::TypeParamBound::Trait(trait_bound) => {
if let Some(last_segment) = trait_bound.path.segments.last() {
last_segment.ident == trait_name
} else {
false
}
}
_ => false,
});
is_bounded_by_trait_name.then(|| type_param.ident.clone())
}
syn::GenericParam::Const(_) | syn::GenericParam::Lifetime(_) => None,
})
.collect()
}