binius_macros/
composition_poly.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Copyright 2024-2025 Irreducible Inc.

use quote::{quote, ToTokens};
use syn::{bracketed, parse::Parse, parse_quote, spanned::Spanned, Token};

#[derive(Debug)]
pub(crate) struct CompositionPolyItem {
	pub is_anonymous: bool,
	pub name: syn::Ident,
	pub vars: Vec<syn::Ident>,
	pub poly_packed: syn::Expr,
	pub expr: syn::Expr,
	pub scalar_type: syn::Type,
	pub degree: usize,
}

impl ToTokens for CompositionPolyItem {
	fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
		let Self {
			is_anonymous,
			name,
			vars,
			poly_packed,
			expr,
			scalar_type,
			degree,
		} = self;
		let n_vars = vars.len();

		let mut eval_single = poly_packed.clone();
		subst_vars(&mut eval_single, vars, &|i| parse_quote!(unsafe {*query.get_unchecked(#i)}))
			.expect("Failed to substitute vars");

		let mut eval_batch = poly_packed.clone();
		subst_vars(
			&mut eval_batch,
			vars,
			&|i| parse_quote!(unsafe {*batch_query.get_unchecked(#i).get_unchecked(row)}),
		)
		.expect("Failed to substitute vars");

		let result = quote! {
			#[derive(Debug, Clone, Copy)]
			struct #name;

			impl binius_math::CompositionPoly<#scalar_type> for #name {
				fn n_vars(&self) -> usize {
					#n_vars
				}

				fn degree(&self) -> usize {
					#degree
				}

				fn binary_tower_level(&self) -> usize {
					0
				}

				fn expression<FE: binius_field::ExtensionField<#scalar_type>>(&self) -> binius_math::ArithExpr<FE> {
					(#expr).convert_field()
				}

				fn evaluate<P: binius_field::PackedField<Scalar: binius_field::ExtensionField<#scalar_type>>>(&self, query: &[P]) -> Result<P, binius_math::Error> {
					if query.len() != #n_vars {
						return Err(binius_math::Error::IncorrectQuerySize { expected: #n_vars });
					}
					Ok(#eval_single)
				}

				fn batch_evaluate<P: binius_field::PackedField<Scalar: binius_field::ExtensionField<#scalar_type>>>(
					&self,
					batch_query: &[&[P]],
					evals: &mut [P],
				) -> Result<(), binius_math::Error> {
					if batch_query.len() != #n_vars {
						return Err(binius_math::Error::IncorrectQuerySize { expected: #n_vars });
					}

					for col in 1..batch_query.len() {
						if batch_query[col].len() != batch_query[0].len() {
							return Err(binius_math::Error::BatchEvaluateSizeMismatch);
						}
					}

					for row in 0..batch_query[0].len() {
						evals[row] = #eval_batch;
					}

					Ok(())
				}
			}

			impl<P> binius_math::CompositionPolyOS<P> for #name
			where
				P: binius_field::PackedField<Scalar: binius_field::ExtensionField<#scalar_type>>,
			{
				fn n_vars(&self) -> usize {
					<Self as binius_math::CompositionPoly<_>>::n_vars(self)
				}

				fn degree(&self) -> usize {
					<Self as binius_math::CompositionPoly<_>>::degree(self)
				}

				fn binary_tower_level(&self) -> usize {
					<Self as binius_math::CompositionPoly<_>>::binary_tower_level(self)
				}

				fn expression(&self) -> binius_math::ArithExpr<P::Scalar> {
					<Self as binius_math::CompositionPoly<_>>::expression(self)
				}

				fn evaluate(&self, query: &[P]) -> Result<P, binius_math::Error> {
					<Self as binius_math::CompositionPoly<_>>::evaluate(self, query)
				}

				fn batch_evaluate(&self, batch_query: &[&[P]], evals: &mut [P]) -> Result<(), binius_math::Error> {
					<Self as binius_math::CompositionPoly<_>>::batch_evaluate(self, batch_query, evals)
				}
			}

		};

		if *is_anonymous {
			// In this case we return an instance of our struct rather
			// than defining the struct within the current scope
			tokens.extend(quote! {
				{
					#result
					#name
				}
			});
		} else {
			tokens.extend(result);
		}
	}
}

impl Parse for CompositionPolyItem {
	fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
		let name = input.parse::<syn::Ident>();
		let is_anonymous = name.is_err();
		let name = name.unwrap_or_else(|_| parse_quote!(UnnamedCompositionPoly));
		let vars = {
			let content;
			bracketed!(content in input);
			let vars = content.parse_terminated(syn::Ident::parse, Token![,])?;
			vars.into_iter().collect::<Vec<_>>()
		};
		input.parse::<Token![=]>()?;
		let mut poly_packed = input.parse::<syn::Expr>()?;
		let mut expr = poly_packed.clone();

		let degree = poly_degree(&poly_packed)?;
		rewrite_literals(&mut poly_packed, &replace_packed_literals)?;

		subst_vars(&mut expr, &vars, &|i| parse_quote!(binius_math::ArithExpr::Var(#i)))?;
		rewrite_literals(&mut expr, &replace_expr_literals)?;

		let scalar_type = if input.is_empty() {
			parse_quote!(binius_field::BinaryField1b)
		} else {
			input.parse::<Token![,]>()?;

			input.parse()?
		};

		Ok(Self {
			is_anonymous,
			name,
			vars,
			poly_packed,
			expr,
			scalar_type,
			degree,
		})
	}
}

/// Make sure to run this before rewrite_literals as it will rewrite Lit to Path,
/// which will mess up the degree
fn poly_degree(expr: &syn::Expr) -> Result<usize, syn::Error> {
	Ok(match expr.clone() {
		syn::Expr::Lit(_) => 0,
		syn::Expr::Path(_) => 1,
		syn::Expr::Paren(paren) => poly_degree(&paren.expr)?,
		syn::Expr::Binary(binary) => {
			let op = binary.op;
			let left = poly_degree(&binary.left)?;
			let right = poly_degree(&binary.right)?;
			match op {
				syn::BinOp::Add(_) | syn::BinOp::Sub(_) => std::cmp::max(left, right),
				syn::BinOp::Mul(_) => left + right,
				expr => {
					return Err(syn::Error::new(expr.span(), "Unsupported binop"));
				}
			}
		}
		expr => return Err(syn::Error::new(expr.span(), "Unsupported expression")),
	})
}

/// Replace literals to P::zero() and P::one() to be used in `evaluate` and `batch_evaluate`.
fn replace_packed_literals(literal: &syn::LitInt) -> Result<syn::Expr, syn::Error> {
	Ok(match &*literal.to_string() {
		"0" => parse_quote!(P::zero()),
		"1" => parse_quote!(P::one()),
		_ => return Err(syn::Error::new(literal.span(), "Unsupported integer")),
	})
}

/// Replace literals to Expr::zero() and Expr::one() to be used in `expression` method.
fn replace_expr_literals(literal: &syn::LitInt) -> Result<syn::Expr, syn::Error> {
	Ok(match &*literal.to_string() {
		"0" => parse_quote!(binius_math::ArithExpr::zero()),
		"1" => parse_quote!(binius_math::ArithExpr::one()),
		_ => return Err(syn::Error::new(literal.span(), "Unsupported integer")),
	})
}

/// Replace literals in an expression
fn rewrite_literals(
	expr: &mut syn::Expr,
	f: &impl Fn(&syn::LitInt) -> Result<syn::Expr, syn::Error>,
) -> Result<(), syn::Error> {
	match expr {
		syn::Expr::Lit(exprlit) => {
			if let syn::Lit::Int(int) = &exprlit.lit {
				*expr = f(int)?;
			}
		}
		syn::Expr::Paren(paren) => {
			rewrite_literals(&mut paren.expr, f)?;
		}
		syn::Expr::Binary(binary) => {
			rewrite_literals(&mut binary.left, f)?;
			rewrite_literals(&mut binary.right, f)?;
		}
		_ => {}
	}
	Ok(())
}

/// Substitutes variables in an expression with a slice access
fn subst_vars(
	expr: &mut syn::Expr,
	vars: &[syn::Ident],
	f: &impl Fn(usize) -> syn::Expr,
) -> Result<(), syn::Error> {
	match expr {
		syn::Expr::Path(p) => {
			for (i, var) in vars.iter().enumerate() {
				if p.path.is_ident(var) {
					*expr = f(i);
					return Ok(());
				}
			}
			Err(syn::Error::new(p.span(), "unknown variable"))
		}
		syn::Expr::Paren(paren) => subst_vars(&mut paren.expr, vars, f),
		syn::Expr::Binary(binary) => {
			subst_vars(&mut binary.left, vars, f)?;
			subst_vars(&mut binary.right, vars, f)
		}
		_ => Ok(()),
	}
}