-
Notifications
You must be signed in to change notification settings - Fork 72
/
mod.rs
1397 lines (1263 loc) · 47.8 KB
/
mod.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
mod display;
pub mod visitor;
use std::cmp::max;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt::Display;
use std::hash::{Hash, Hasher};
use std::iter::{self, empty};
use std::ops::{self, ControlFlow};
use std::sync::Arc;
use itertools::Itertools;
use powdr_number::{DegreeType, FieldElement};
use powdr_parser_util::SourceRef;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::parsed::types::{ArrayType, Type, TypeBounds, TypeScheme};
use crate::parsed::visitor::{Children, ExpressionVisitable};
pub use crate::parsed::BinaryOperator;
pub use crate::parsed::UnaryOperator;
use crate::parsed::{
self, ArrayExpression, ArrayLiteral, EnumDeclaration, EnumVariant, TraitDeclaration,
TraitFunction,
};
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub enum StatementIdentifier {
/// Either an intermediate column or a definition.
Definition(String),
PublicDeclaration(String),
/// Index into the vector of identities.
Identity(usize),
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct Analyzed<T> {
pub definitions: HashMap<String, (Symbol, Option<FunctionValueDefinition>)>,
pub public_declarations: HashMap<String, PublicDeclaration>,
pub intermediate_columns: HashMap<String, (Symbol, Vec<AlgebraicExpression<T>>)>,
pub identities: Vec<Identity<SelectedExpressions<AlgebraicExpression<T>>>>,
/// The order in which definitions and identities
/// appear in the source.
pub source_order: Vec<StatementIdentifier>,
/// Symbols from the core that were added automatically but will not be printed.
pub auto_added_symbols: HashSet<String>,
}
impl<T> Analyzed<T> {
/// Returns the degree common among all symbols that have an explicit degree.
///
/// # Panics
///
/// Panics if there is no common degree or if there are no symbols
pub fn degree(&self) -> DegreeType {
self.definitions
.values()
.filter_map(|(symbol, _)| symbol.degree)
.unique()
.exactly_one()
.unwrap()
}
/// Returns the set of all explicit degrees in this [`Analyzed<T>`].
pub fn degrees(&self) -> HashSet<DegreeType> {
self.definitions
.values()
.filter_map(|(symbol, _)| symbol.degree)
.collect::<HashSet<_>>()
}
/// @returns the number of committed polynomials (with multiplicities for arrays)
pub fn commitment_count(&self) -> usize {
self.declaration_type_count(PolynomialType::Committed)
}
/// @returns the number of intermediate polynomials (with multiplicities for arrays)
pub fn intermediate_count(&self) -> usize {
self.intermediate_columns
.iter()
.map(|(_, (sym, _))| sym.length.unwrap_or(1) as usize)
.sum()
}
/// @returns the number of constant polynomials (with multiplicities for arrays)
pub fn constant_count(&self) -> usize {
self.declaration_type_count(PolynomialType::Constant)
}
/// @returns the number of public inputs
pub fn publics_count(&self) -> usize {
self.public_declarations.len()
}
pub fn constant_polys_in_source_order(
&self,
) -> Vec<&(Symbol, Option<FunctionValueDefinition>)> {
self.definitions_in_source_order(PolynomialType::Constant)
}
pub fn committed_polys_in_source_order(
&self,
) -> Vec<&(Symbol, Option<FunctionValueDefinition>)> {
self.definitions_in_source_order(PolynomialType::Committed)
}
pub fn intermediate_polys_in_source_order(
&self,
) -> Vec<&(Symbol, Vec<AlgebraicExpression<T>>)> {
self.source_order
.iter()
.filter_map(move |statement| {
if let StatementIdentifier::Definition(name) = statement {
if let Some(definition) = self.intermediate_columns.get(name) {
return Some(definition);
}
}
None
})
.collect()
}
pub fn definitions_in_source_order(
&self,
poly_type: PolynomialType,
) -> Vec<&(Symbol, Option<FunctionValueDefinition>)> {
assert!(
poly_type != PolynomialType::Intermediate,
"Use intermediate_polys_in_source_order to get intermediate polys."
);
self.source_order
.iter()
.filter_map(move |statement| {
if let StatementIdentifier::Definition(name) = statement {
if let Some(definition) = self.definitions.get(name) {
match definition.0.kind {
SymbolKind::Poly(ptype) if ptype == poly_type => {
return Some(definition);
}
_ => {}
}
}
}
None
})
.collect()
}
pub fn public_declarations_in_source_order(&self) -> Vec<(&String, &PublicDeclaration)> {
self.source_order
.iter()
.filter_map(move |statement| {
if let StatementIdentifier::PublicDeclaration(name) = statement {
if let Some(public_declaration) = self.public_declarations.get(name) {
return Some((name, public_declaration));
}
}
None
})
.collect()
}
fn declaration_type_count(&self, poly_type: PolynomialType) -> usize {
self.definitions
.iter()
.filter_map(move |(_name, (symbol, _))| match symbol.kind {
SymbolKind::Poly(ptype) if ptype == poly_type => {
Some(symbol.length.unwrap_or(1) as usize)
}
_ => None,
})
.sum()
}
/// Returns the type (scheme) of a symbol with the given name.
pub fn type_of_symbol(&self, name: &str) -> TypeScheme {
let (sym, value) = &self.definitions[name];
type_from_definition(sym, value).unwrap()
}
/// Adds a polynomial identity and returns the ID.
pub fn append_polynomial_identity(
&mut self,
identity: AlgebraicExpression<T>,
source: SourceRef,
) -> u64 {
let id = self
.identities
.iter()
.map(|identity| identity.id)
.max()
.unwrap_or_default()
+ 1;
self.identities.push(
Identity::<SelectedExpressions<AlgebraicExpression<T>>>::from_polynomial_identity(
id, source, identity,
),
);
self.source_order
.push(StatementIdentifier::Identity(self.identities.len() - 1));
id
}
/// Remove some identities by their index (not their ID).
/// Does not re-allocate IDs.
pub fn remove_identities(&mut self, to_remove: &BTreeSet<usize>) {
let mut shift = 0;
self.source_order.retain_mut(|s| {
if let StatementIdentifier::Identity(index) = s {
if to_remove.contains(index) {
shift += 1;
return false;
}
*index -= shift;
}
true
});
let mut index = 0;
self.identities.retain(|_| {
let retain = !to_remove.contains(&index);
index += 1;
retain
})
}
/// Removes the given definitions and intermediate columns by name. Those must not be referenced
/// by any remaining definitions, identities or public declarations.
pub fn remove_definitions(&mut self, to_remove: &BTreeSet<String>) {
self.definitions.retain(|name, _| !to_remove.contains(name));
self.intermediate_columns
.retain(|name, _| !to_remove.contains(name));
self.source_order.retain_mut(|s| {
if let StatementIdentifier::Definition(name) = s {
!to_remove.contains(name)
} else {
true
}
});
// Now re-assign the IDs to be contiguous and in source order again.
let mut replacements: BTreeMap<PolyID, PolyID> = Default::default();
let mut handle_symbol = |new_id: u64, symbol: &Symbol| -> u64 {
let length = symbol.length.unwrap_or(1);
// Empty arrays still need ID replacement
for i in 0..max(length, 1) {
let old_poly_id = PolyID {
id: symbol.id + i,
..PolyID::from(symbol)
};
let new_poly_id = PolyID {
id: new_id + i,
..PolyID::from(symbol)
};
replacements.insert(old_poly_id, new_poly_id);
}
new_id + length
};
// Create and update the replacement map for all polys.
self.committed_polys_in_source_order()
.iter()
.fold(0, |new_id, (poly, _def)| handle_symbol(new_id, poly));
self.constant_polys_in_source_order()
.iter()
.fold(0, |new_id, (poly, _def)| handle_symbol(new_id, poly));
self.intermediate_polys_in_source_order()
.iter()
.fold(0, |new_id, (poly, _def)| handle_symbol(new_id, poly));
self.definitions.values_mut().for_each(|(poly, _def)| {
if matches!(poly.kind, SymbolKind::Poly(_)) {
let poly_id = PolyID::from(poly as &Symbol);
poly.id = replacements[&poly_id].id;
}
});
self.intermediate_columns
.values_mut()
.for_each(|(poly, _def)| {
let poly_id = PolyID::from(poly as &Symbol);
poly.id = replacements[&poly_id].id;
});
let visitor = &mut |expr: &mut Expression| {
if let Expression::Reference(_, Reference::Poly(poly)) = expr {
poly.poly_id = poly.poly_id.map(|poly_id| replacements[&poly_id]);
}
};
self.post_visit_expressions_in_definitions_mut(visitor);
let algebraic_visitor = &mut |expr: &mut AlgebraicExpression<_>| {
if let AlgebraicExpression::Reference(poly) = expr {
poly.poly_id = replacements[&poly.poly_id];
}
};
self.post_visit_expressions_in_identities_mut(algebraic_visitor);
self.public_declarations
.values_mut()
.for_each(|public_decl| {
let poly_id = public_decl.polynomial.poly_id.unwrap();
public_decl.polynomial.poly_id = Some(replacements[&poly_id]);
});
}
pub fn post_visit_expressions_in_identities_mut<F>(&mut self, f: &mut F)
where
F: FnMut(&mut AlgebraicExpression<T>),
{
self.identities
.iter_mut()
.for_each(|i| i.post_visit_expressions_mut(f));
self.intermediate_columns
.values_mut()
.for_each(|(_sym, value)| {
value
.iter_mut()
.for_each(|v| v.post_visit_expressions_mut(f))
});
}
pub fn post_visit_expressions_in_definitions_mut<F>(&mut self, f: &mut F)
where
F: FnMut(&mut Expression),
{
// TODO add public inputs if we change them to expressions at some point.
self.definitions
.values_mut()
.filter_map(|(_poly, definition)| definition.as_mut())
.for_each(|definition| definition.post_visit_expressions_mut(f))
}
/// Retrieves (col_name, col_idx, offset) of each public witness in the trace.
pub fn get_publics(&self) -> Vec<(String, usize, usize)> {
let mut publics = self
.public_declarations
.values()
.map(|public_declaration| {
let column_name = public_declaration.referenced_poly_name();
let column_idx = {
let base = public_declaration.polynomial.poly_id.unwrap().id as usize;
match public_declaration.array_index {
Some(array_idx) => base + array_idx,
None => base,
}
};
let row_offset = public_declaration.index as usize;
(column_name, column_idx, row_offset)
})
.collect::<Vec<_>>();
// Sort, so that the order is deterministic
publics.sort();
publics
}
}
impl<T: FieldElement> Analyzed<T> {
/// @returns all identities with intermediate polynomials inlined.
pub fn identities_with_inlined_intermediate_polynomials(
&self,
) -> Vec<Identity<SelectedExpressions<AlgebraicExpression<T>>>> {
let intermediates = &self
.intermediate_polys_in_source_order()
.iter()
.flat_map(|(symbol, def)| {
symbol
.array_elements()
.zip(def)
.map(|((_, poly_id), def)| (poly_id, def))
})
.collect();
substitute_intermediate(self.identities.clone(), intermediates)
}
pub fn get_struct_schema() -> schemars::schema::RootSchema {
schemars::schema_for!(Self)
}
pub fn serialize(&self) -> Result<Vec<u8>, String> {
serde_cbor::to_vec(self).map_err(|e| format!("Failed to serialize analyzed: {e}"))
}
pub fn deserialize(bytes: &[u8]) -> Result<Self, String> {
serde_cbor::from_slice(bytes).map_err(|e| format!("Failed to deserialize analyzed: {e}"))
}
}
/// Takes identities as values and inlines intermediate polynomials everywhere, returning a vector of the updated identities
/// TODO: this could return an iterator
fn substitute_intermediate<T: Copy + Display>(
identities: impl IntoIterator<Item = Identity<SelectedExpressions<AlgebraicExpression<T>>>>,
intermediate_polynomials: &HashMap<PolyID, &AlgebraicExpression<T>>,
) -> Vec<Identity<SelectedExpressions<AlgebraicExpression<T>>>> {
identities
.into_iter()
.scan(HashMap::default(), |cache, mut identity| {
identity.post_visit_expressions_mut(&mut |e| {
if let AlgebraicExpression::Reference(poly) = e {
match poly.poly_id.ptype {
PolynomialType::Committed => {}
PolynomialType::Constant => {}
PolynomialType::Intermediate => {
// recursively inline intermediate polynomials, updating the cache
*e = inlined_expression_from_intermediate_poly_id(
poly.clone(),
intermediate_polynomials,
cache,
);
}
}
}
});
Some(identity)
})
.collect()
}
/// Recursively inlines intermediate polynomials inside an expression and returns the new expression
/// This uses a cache to avoid resolving an intermediate polynomial twice
///
/// poly_to_replace can be a "next" reference, but then its value cannot contain any next references.
fn inlined_expression_from_intermediate_poly_id<T: Copy + Display>(
poly_to_replace: AlgebraicReference,
intermediate_polynomials: &HashMap<PolyID, &AlgebraicExpression<T>>,
cache: &mut HashMap<AlgebraicReference, AlgebraicExpression<T>>,
) -> AlgebraicExpression<T> {
assert_eq!(poly_to_replace.poly_id.ptype, PolynomialType::Intermediate);
if let Some(e) = cache.get(&poly_to_replace) {
return e.clone();
}
let mut expr = intermediate_polynomials[&poly_to_replace.poly_id].clone();
expr.post_visit_expressions_mut(&mut |e| {
let AlgebraicExpression::Reference(r) = e else { return; };
// "forward" the next operator from the polynomial to be replaced.
if poly_to_replace.next && r.next {
let value = intermediate_polynomials[&poly_to_replace.poly_id];
panic!(
"Error inlining intermediate polynomial {poly_to_replace} = ({value})':\nNext operator already applied to {} and then again to {} - cannot apply it twice!",
r.name,
poly_to_replace.name
);
}
r.next = r.next || poly_to_replace.next;
match r.poly_id.ptype {
PolynomialType::Committed | PolynomialType::Constant => {}
PolynomialType::Intermediate => {
*e = inlined_expression_from_intermediate_poly_id(
r.clone(),
intermediate_polynomials,
cache,
);
}
}
});
cache.insert(poly_to_replace, expr.clone());
expr
}
/// Extracts the declared (or implicit) type from a definition.
pub fn type_from_definition(
symbol: &Symbol,
value: &Option<FunctionValueDefinition>,
) -> Option<TypeScheme> {
if let Some(value) = value {
match value {
FunctionValueDefinition::Array(_) => Some(Type::Col.into()),
FunctionValueDefinition::Expression(TypedExpression { e: _, type_scheme }) => {
type_scheme.clone()
}
FunctionValueDefinition::TypeDeclaration(_) => {
panic!("Requested type of type declaration.")
}
FunctionValueDefinition::TypeConstructor(enum_decl, variant) => {
Some(variant.constructor_type(enum_decl))
}
FunctionValueDefinition::TraitDeclaration(_) => {
panic!("Requested type of trait declaration.")
}
FunctionValueDefinition::TraitFunction(trait_decl, trait_func) => {
let vars = trait_decl
.type_vars
.iter()
.map(|var| {
let bounds = BTreeSet::new();
(var.clone(), bounds)
})
.collect::<Vec<_>>();
Some(TypeScheme {
vars: TypeBounds::new(vars.into_iter()),
ty: trait_func.ty.clone(),
})
}
}
} else {
assert!(
symbol.kind == SymbolKind::Poly(PolynomialType::Committed)
|| symbol.kind == SymbolKind::Poly(PolynomialType::Constant)
);
if symbol.length.is_some() {
Some(
Type::Array(ArrayType {
base: Box::new(Type::Col),
length: None,
})
.into(),
)
} else {
Some(Type::Col.into())
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Symbol {
pub id: u64,
pub source: SourceRef,
pub absolute_name: String,
pub stage: Option<u32>,
pub kind: SymbolKind,
pub length: Option<DegreeType>,
pub degree: Option<DegreeType>,
}
impl Symbol {
pub fn is_array(&self) -> bool {
self.length.is_some()
}
/// Returns an iterator producing either just the symbol (if it is not an array),
/// or all the elements of the array with their names in the form `array[index]`.
pub fn array_elements(&self) -> impl Iterator<Item = (String, PolyID)> + '_ {
let SymbolKind::Poly(ptype) = self.kind else {
panic!("Expected polynomial.");
};
let length = self.length.unwrap_or(1);
(0..length).map(move |i| {
(
self.array_element_name(i),
PolyID {
id: self.id + i,
ptype,
},
)
})
}
/// Returns "name[index]" if this is an array or just "name" otherwise.
/// In the second case, requires index to be zero and otherwise
/// requires index to be less than length.
pub fn array_element_name(&self, index: u64) -> String {
match self.length {
Some(length) => {
assert!(index < length);
format!("{}[{index}]", self.absolute_name)
}
None => self.absolute_name.to_string(),
}
}
/// Returns "name[length]" if this is an array or just "name" otherwise.
pub fn array_name(&self) -> String {
match self.length {
Some(length) => {
format!("{}[{length}]", self.absolute_name)
}
None => self.absolute_name.to_string(),
}
}
}
/// The "kind" of a symbol. In the future, this will be mostly
/// replaced by its type.
#[derive(
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
pub enum SymbolKind {
/// Fixed, witness or intermediate polynomial
Poly(PolynomialType),
/// Other symbol, depends on the type.
/// Examples include functions not of the type "int -> fe".
Other(),
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub enum FunctionValueDefinition {
Array(ArrayExpression<Reference>),
Expression(TypedExpression),
TypeDeclaration(EnumDeclaration),
TypeConstructor(Arc<EnumDeclaration>, EnumVariant),
TraitDeclaration(TraitDeclaration),
TraitFunction(Arc<TraitDeclaration>, TraitFunction),
}
impl Children<Expression> for FunctionValueDefinition {
fn children(&self) -> Box<dyn Iterator<Item = &Expression> + '_> {
match self {
FunctionValueDefinition::Expression(TypedExpression { e, type_scheme: _ }) => {
Box::new(iter::once(e))
}
FunctionValueDefinition::Array(e) => e.children(),
FunctionValueDefinition::TypeDeclaration(enum_declaration) => {
enum_declaration.children()
}
FunctionValueDefinition::TypeConstructor(_, variant) => variant.children(),
FunctionValueDefinition::TraitDeclaration(trait_decl) => trait_decl.children(),
FunctionValueDefinition::TraitFunction(_, trait_func) => trait_func.children(),
}
}
fn children_mut(&mut self) -> Box<dyn Iterator<Item = &mut Expression> + '_> {
match self {
FunctionValueDefinition::Expression(TypedExpression { e, type_scheme: _ }) => {
Box::new(iter::once(e))
}
FunctionValueDefinition::Array(e) => e.children_mut(),
FunctionValueDefinition::TypeDeclaration(enum_declaration) => {
enum_declaration.children_mut()
}
FunctionValueDefinition::TypeConstructor(_, variant) => variant.children_mut(),
FunctionValueDefinition::TraitDeclaration(trait_decl) => trait_decl.children_mut(),
FunctionValueDefinition::TraitFunction(_, trait_func) => trait_func.children_mut(),
}
}
}
impl Children<Expression> for TraitDeclaration {
fn children(&self) -> Box<dyn Iterator<Item = &Expression> + '_> {
Box::new(empty())
}
fn children_mut(&mut self) -> Box<dyn Iterator<Item = &mut Expression> + '_> {
Box::new(empty())
}
}
impl Children<Expression> for TraitFunction {
fn children(&self) -> Box<dyn Iterator<Item = &Expression> + '_> {
Box::new(empty())
}
fn children_mut(&mut self) -> Box<dyn Iterator<Item = &mut Expression> + '_> {
Box::new(empty())
}
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PublicDeclaration {
pub id: u64,
pub source: SourceRef,
pub name: String,
pub polynomial: PolynomialReference,
pub array_index: Option<usize>,
/// The evaluation point of the polynomial, not the array index.
pub index: DegreeType,
}
impl PublicDeclaration {
pub fn referenced_poly_name(&self) -> String {
match self.array_index {
Some(index) => format!("{}[{}]", self.polynomial.name, index),
None => self.polynomial.name.clone(),
}
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SelectedExpressions<Expr> {
pub selector: Option<Expr>,
pub expressions: Vec<Expr>,
}
impl<Expr> Default for SelectedExpressions<Expr> {
fn default() -> Self {
Self {
selector: Default::default(),
expressions: vec![],
}
}
}
impl<Expr> Children<Expr> for SelectedExpressions<Expr> {
/// Returns an iterator over all (top-level) expressions in this SelectedExpressions.
fn children(&self) -> Box<dyn Iterator<Item = &Expr> + '_> {
Box::new(self.selector.iter().chain(self.expressions.iter()))
}
/// Returns an iterator over all (top-level) expressions in this SelectedExpressions.
fn children_mut(&mut self) -> Box<dyn Iterator<Item = &mut Expr> + '_> {
Box::new(self.selector.iter_mut().chain(self.expressions.iter_mut()))
}
}
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Identity<SelectedExpressions> {
/// The ID is globally unique among identities.
pub id: u64,
pub kind: IdentityKind,
pub source: SourceRef,
/// For a simple polynomial identity, the selector contains
/// the actual expression (see expression_for_poly_id).
pub left: SelectedExpressions,
pub right: SelectedExpressions,
}
impl<T> Identity<SelectedExpressions<AlgebraicExpression<T>>> {
/// Constructs an Identity from a polynomial identity (expression assumed to be identical zero).
pub fn from_polynomial_identity(
id: u64,
source: SourceRef,
identity: AlgebraicExpression<T>,
) -> Self {
Identity {
id,
kind: IdentityKind::Polynomial,
source,
left: SelectedExpressions {
selector: Some(identity),
expressions: vec![],
},
right: SelectedExpressions {
selector: Default::default(),
expressions: vec![],
},
}
}
/// Returns the expression in case this is a polynomial identity.
pub fn expression_for_poly_id(&self) -> &AlgebraicExpression<T> {
assert_eq!(self.kind, IdentityKind::Polynomial);
self.left.selector.as_ref().unwrap()
}
/// Returns the expression in case this is a polynomial identity.
pub fn expression_for_poly_id_mut(&mut self) -> &mut AlgebraicExpression<T> {
assert_eq!(self.kind, IdentityKind::Polynomial);
self.left.selector.as_mut().unwrap()
}
pub fn contains_next_ref(&self) -> bool {
self.left.contains_next_ref() || self.right.contains_next_ref()
}
/// Either returns (a, Some(b)) if this is a - b or (a, None)
/// if it is a polynomial identity of a different structure.
/// Panics if it is a different kind of constraint.
pub fn as_polynomial_identity(
&self,
) -> (&AlgebraicExpression<T>, Option<&AlgebraicExpression<T>>) {
assert_eq!(self.kind, IdentityKind::Polynomial);
match self.expression_for_poly_id() {
AlgebraicExpression::BinaryOperation(AlgebraicBinaryOperation {
left: a,
op: AlgebraicBinaryOperator::Sub,
right: b,
}) => (a.as_ref(), Some(b.as_ref())),
a => (a, None),
}
}
pub fn degree(&self) -> usize {
self.children().map(|e| e.degree()).max().unwrap_or(0)
}
}
impl<R> Identity<parsed::SelectedExpressions<parsed::Expression<R>>> {
/// Constructs an Identity from a polynomial identity (expression assumed to be identical zero).
pub fn from_polynomial_identity(
id: u64,
source: SourceRef,
identity: parsed::Expression<R>,
) -> Self {
Identity {
id,
kind: IdentityKind::Polynomial,
source,
left: parsed::SelectedExpressions {
selector: Some(identity),
expressions: Box::new(ArrayLiteral { items: vec![] }.into()),
},
right: Default::default(),
}
}
/// Returns the expression in case this is a polynomial identity.
pub fn expression_for_poly_id(&self) -> &parsed::Expression<R> {
assert_eq!(self.kind, IdentityKind::Polynomial);
self.left.selector.as_ref().unwrap()
}
/// Returns the expression in case this is a polynomial identity.
pub fn expression_for_poly_id_mut(&mut self) -> &mut parsed::Expression<R> {
assert_eq!(self.kind, IdentityKind::Polynomial);
self.left.selector.as_mut().unwrap()
}
/// Either returns (a, Some(b)) if this is a - b or (a, None)
/// if it is a polynomial identity of a different structure.
/// Panics if it is a different kind of constraint.
pub fn as_polynomial_identity(
&self,
) -> (&parsed::Expression<R>, Option<&parsed::Expression<R>>) {
assert_eq!(self.kind, IdentityKind::Polynomial);
match self.expression_for_poly_id() {
parsed::Expression::BinaryOperation(
_,
parsed::BinaryOperation {
left,
op: BinaryOperator::Sub,
right,
},
) => (left.as_ref(), Some(right.as_ref())),
a => (a, None),
}
}
}
impl<T> Children<AlgebraicExpression<T>> for Identity<SelectedExpressions<AlgebraicExpression<T>>> {
fn children_mut(&mut self) -> Box<dyn Iterator<Item = &mut AlgebraicExpression<T>> + '_> {
Box::new(self.left.children_mut().chain(self.right.children_mut()))
}
fn children(&self) -> Box<dyn Iterator<Item = &AlgebraicExpression<T>> + '_> {
Box::new(self.left.children().chain(self.right.children()))
}
}
impl<R> Children<parsed::Expression<R>>
for Identity<parsed::SelectedExpressions<parsed::Expression<R>>>
{
fn children_mut(&mut self) -> Box<dyn Iterator<Item = &mut parsed::Expression<R>> + '_> {
Box::new(self.left.children_mut().chain(self.right.children_mut()))
}
fn children(&self) -> Box<dyn Iterator<Item = &parsed::Expression<R>> + '_> {
Box::new(self.left.children().chain(self.right.children()))
}
}
#[derive(
Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash, Serialize, Deserialize, JsonSchema,
)]
pub enum IdentityKind {
Polynomial,
Plookup,
Permutation,
Connect,
}
impl<T> SelectedExpressions<AlgebraicExpression<T>> {
/// @returns true if the expression contains a reference to a next value of a
/// (witness or fixed) column
pub fn contains_next_ref(&self) -> bool {
self.selector
.iter()
.chain(self.expressions.iter())
.any(|e| e.contains_next_ref())
}
}
pub type Expression = parsed::Expression<Reference>;
pub type TypedExpression = crate::parsed::TypedExpression<Reference, u64>;
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub enum Reference {
LocalVar(u64, String),
Poly(PolynomialReference),
}
#[derive(Debug, Clone, Eq, Serialize, Deserialize, JsonSchema)]
pub struct AlgebraicReference {
/// Name of the polynomial - just for informational purposes.
/// Comparisons are based on polynomial ID.
/// In case of an array element, this ends in `[i]`.
pub name: String,
/// Identifier for a polynomial reference, already contains
/// the element offset in case of an array element.
pub poly_id: PolyID,
pub next: bool,
}
impl AlgebraicReference {
#[inline]
pub fn is_witness(&self) -> bool {
self.poly_id.ptype == PolynomialType::Committed
}
#[inline]
pub fn is_fixed(&self) -> bool {
self.poly_id.ptype == PolynomialType::Constant
}
}
impl PartialOrd for AlgebraicReference {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for AlgebraicReference {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
(&self.poly_id, &self.next).cmp(&(&other.poly_id, &other.next))
}
}
impl PartialEq for AlgebraicReference {
fn eq(&self, other: &Self) -> bool {
self.poly_id == other.poly_id && self.next == other.next
}
}
impl Hash for AlgebraicReference {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.poly_id.hash(state);
self.next.hash(state);
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize, JsonSchema)]
pub enum AlgebraicExpression<T> {
Reference(AlgebraicReference),
PublicReference(String),
Challenge(Challenge),
Number(T),
BinaryOperation(AlgebraicBinaryOperation<T>),
UnaryOperation(AlgebraicUnaryOperation<T>),
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AlgebraicBinaryOperation<T> {
pub left: Box<AlgebraicExpression<T>>,
pub op: AlgebraicBinaryOperator,
pub right: Box<AlgebraicExpression<T>>,
}
impl<T> AlgebraicBinaryOperation<T> {
fn new(
left: AlgebraicExpression<T>,
op: AlgebraicBinaryOperator,
right: AlgebraicExpression<T>,
) -> Self {
Self {
left: Box::new(left),
op,
right: Box::new(right),
}
}
}
impl<T> From<AlgebraicBinaryOperation<T>> for AlgebraicExpression<T> {
fn from(value: AlgebraicBinaryOperation<T>) -> Self {
Self::BinaryOperation(value)
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AlgebraicUnaryOperation<T> {
pub op: AlgebraicUnaryOperator,
pub expr: Box<AlgebraicExpression<T>>,
}
impl<T> AlgebraicUnaryOperation<T> {
fn new(op: AlgebraicUnaryOperator, expr: AlgebraicExpression<T>) -> Self {
Self {
op,
expr: Box::new(expr),
}
}
}
impl<T> From<AlgebraicUnaryOperation<T>> for AlgebraicExpression<T> {
fn from(value: AlgebraicUnaryOperation<T>) -> Self {
Self::UnaryOperation(value)
}
}
pub type ExpressionPrecedence = u64;
trait Precedence {
fn precedence(&self) -> Option<ExpressionPrecedence>;
}
impl Precedence for AlgebraicUnaryOperator {
fn precedence(&self) -> Option<ExpressionPrecedence> {
use AlgebraicUnaryOperator::*;
let precedence = match self {
// NOTE: Any modification must be done with care to not overlap with BinaryOperator's precedence
Minus => 1,
};
Some(precedence)
}
}
impl Precedence for AlgebraicBinaryOperator {
fn precedence(&self) -> Option<ExpressionPrecedence> {
use AlgebraicBinaryOperator::*;
let precedence = match self {
// NOTE: Any modification must be done with care to not overlap with LambdaExpression's precedence
// Unary Oprators
// **
Pow => 2,
// * / %
Mul => 3,
// + -
Add | Sub => 4,
};
Some(precedence)
}
}
impl<E> Precedence for AlgebraicExpression<E> {
fn precedence(&self) -> Option<ExpressionPrecedence> {
match self {