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
// Copyright 2024 Ulvetanna Inc.

use crate::{
	oracle::OracleId,
	polynomial::{
		Error as PolynomialError, MultilinearExtension, MultilinearExtensionBorrowed,
		MultilinearPoly,
	},
	util::PackingDeref,
};
use binius_field::{
	as_packed_field::{PackScalar, PackedType},
	underlier::{UnderlierType, WithUnderlier},
	ExtensionField, Field, TowerField,
};
use binius_utils::bail;
use std::{fmt::Debug, sync::Arc};

pub type MultilinearWitness<'a, P> = Arc<dyn MultilinearPoly<P> + Send + Sync + 'a>;

#[derive(Debug)]
struct MultilinearExtensionBacking<'a, U: UnderlierType> {
	underliers: ArcOrRef<'a, [U]>,
	tower_level: usize,
}

#[derive(Debug)]
struct MultilinearExtensionIndexEntry<'a, U: UnderlierType, F>
where
	U: UnderlierType + PackScalar<F>,
	F: Field,
{
	type_erased: MultilinearWitness<'a, PackedType<U, F>>,
	backing: Option<MultilinearExtensionBacking<'a, U>>,
}

/// Data structure that indexes multilinear extensions by oracle ID.
///
/// A [`crate::oracle::MultilinearOracleSet`] indexes multilinear polynomial oracles by assigning
/// unique, sequential oracle IDs. The caller can get the [`MultilinearExtension`] defined natively
/// over a subfield. This is possible because the [`MultilinearExtensionIndex::get`] method is
/// generic over the subfield type and the struct itself only stores the underlying data.
#[derive(Default, Debug)]
pub struct MultilinearExtensionIndex<'a, U: UnderlierType, FW>
where
	U: UnderlierType + PackScalar<FW>,
	FW: Field,
{
	entries: Vec<Option<MultilinearExtensionIndexEntry<'a, U, FW>>>,
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
	#[error("witness not found for oracle {id}")]
	MissingWitness { id: OracleId },
	#[error("witness for oracle id {id} does not have an explicit backing multilinear")]
	NoExplicitBackingMultilinearExtension { id: OracleId },
	#[error("oracle tower height does not match field parameter")]
	OracleTowerHeightMismatch {
		oracle_id: OracleId,
		oracle_level: usize,
		field_level: usize,
	},
	#[error("polynomial error: {0}")]
	Polynomial(#[from] PolynomialError),
}

impl<'a, U, FW> MultilinearExtensionIndex<'a, U, FW>
where
	U: UnderlierType + PackScalar<FW>,
	FW: Field,
{
	pub fn new() -> Self {
		Self::default()
	}

	pub fn get<FS>(
		&self,
		id: OracleId,
	) -> Result<MultilinearExtensionBorrowed<PackedType<U, FS>>, Error>
	where
		FS: TowerField,
		FW: ExtensionField<FS>,
		U: PackScalar<FS>,
	{
		let entry = self
			.entries
			.get(id)
			.ok_or(Error::MissingWitness { id })?
			.as_ref()
			.ok_or(Error::MissingWitness { id })?;

		let backing = entry
			.backing
			.as_ref()
			.ok_or(Error::NoExplicitBackingMultilinearExtension { id })?;

		if backing.tower_level != FS::TOWER_LEVEL {
			bail!(Error::OracleTowerHeightMismatch {
				oracle_id: id,
				oracle_level: backing.tower_level,
				field_level: FS::TOWER_LEVEL,
			});
		}

		let underliers_ref = backing.underliers.as_ref();

		let mle = MultilinearExtension::from_values_slice(
			PackedType::<U, FS>::from_underliers_ref(underliers_ref),
		)?;
		Ok(mle)
	}

	pub fn get_multilin_poly(
		&self,
		id: OracleId,
	) -> Result<MultilinearWitness<'a, PackedType<U, FW>>, Error> {
		let entry = self
			.entries
			.get(id)
			.ok_or(Error::MissingWitness { id })?
			.as_ref()
			.ok_or(Error::MissingWitness { id })?;
		Ok(entry.type_erased.clone())
	}

	/// Whether has data for the given oracle id.
	pub fn has(&self, id: OracleId) -> bool {
		self.entries.get(id).map_or(false, Option::is_some)
	}

	pub fn update_owned<FS, Data>(
		self,
		witnesses: impl IntoIterator<Item = (OracleId, Data)>,
	) -> Result<MultilinearExtensionIndex<'a, U, FW>, Error>
	where
		FS: TowerField,
		FW: ExtensionField<FS>,
		U: PackScalar<FS> + Debug,
		Data: Into<Arc<[U]>>,
	{
		let MultilinearExtensionIndex { mut entries } = self;
		for (id, witness) in witnesses {
			if id >= entries.len() {
				entries.resize_with(id + 1, || None);
			}

			let witness = witness.into();
			let mle = MultilinearExtension::<_, PackingDeref<U, FS, _>>::from_underliers(
				witness.clone(),
			)?;
			let backing = MultilinearExtensionBacking {
				underliers: ArcOrRef::Arc(witness),
				tower_level: FS::TOWER_LEVEL,
			};
			entries[id] = Some(MultilinearExtensionIndexEntry {
				type_erased: mle.specialize_arc_dyn(),
				backing: Some(backing),
			});
		}
		Ok(MultilinearExtensionIndex { entries })
	}

	pub fn update_borrowed<'new, FS>(
		self,
		witnesses: impl IntoIterator<Item = (OracleId, &'new [U])>,
	) -> Result<MultilinearExtensionIndex<'new, U, FW>, Error>
	where
		'a: 'new,
		FS: TowerField,
		FW: ExtensionField<FS>,
		U: PackScalar<FS>,
	{
		let MultilinearExtensionIndex { mut entries } = self;
		for (id, witness) in witnesses {
			if id >= entries.len() {
				entries.resize_with(id + 1, || None);
			}

			let mle = MultilinearExtension::from_values_slice(
				PackedType::<U, FS>::from_underliers_ref(witness),
			)?;
			let backing = MultilinearExtensionBacking {
				underliers: ArcOrRef::Ref(witness),
				tower_level: FS::TOWER_LEVEL,
			};
			entries[id] = Some(MultilinearExtensionIndexEntry {
				type_erased: mle.specialize_arc_dyn(),
				backing: Some(backing),
			});
		}
		Ok(MultilinearExtensionIndex { entries })
	}

	pub fn update_multilin_poly(
		&mut self,
		witnesses: impl IntoIterator<Item = (OracleId, MultilinearWitness<'a, PackedType<U, FW>>)>,
	) -> Result<(), Error> {
		for (id, witness) in witnesses {
			if id >= self.entries.len() {
				self.entries.resize_with(id + 1, || None);
			}

			self.entries[id] = Some(MultilinearExtensionIndexEntry {
				type_erased: witness,
				backing: None,
			});
		}
		Ok(())
	}

	pub fn update_packed<'new, FS>(
		self,
		witnesses: impl IntoIterator<Item = (OracleId, &'new [PackedType<U, FS>])>,
	) -> Result<MultilinearExtensionIndex<'new, U, FW>, Error>
	where
		'a: 'new,
		FS: TowerField,
		FW: ExtensionField<FS>,
		U: PackScalar<FS>,
	{
		self.update_borrowed(
			witnesses.into_iter().map(|(oracle_id, packed)| {
				(oracle_id, <PackedType<U, FS>>::to_underliers_ref(packed))
			}),
		)
	}
}

#[derive(Debug)]
enum ArcOrRef<'a, T: ?Sized> {
	Arc(Arc<T>),
	Ref(&'a T),
}

impl<'a, T: ?Sized> AsRef<T> for ArcOrRef<'a, T> {
	fn as_ref(&self) -> &T {
		match self {
			Self::Arc(owned) => owned,
			Self::Ref(borrowed) => borrowed,
		}
	}
}