forked from zksecurity/noname
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
1504 lines (1293 loc) · 51.1 KB
/
Copy pathmod.rs
File metadata and controls
1504 lines (1293 loc) · 51.1 KB
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
use num_bigint::BigUint;
use num_traits::ToPrimitive;
use serde::Serialize;
use std::collections::HashMap;
use crate::{
backends::Backend,
constants::Span,
error::{Error, ErrorKind, Result},
imports::FnKind,
parser::{
types::{
FnSig, ForLoopArgument, GenericParameters, Ident, Range, Stmt, StmtKind, Symbolic, Ty,
TyKind,
},
CustomType, Expr, ExprKind, FunctionDef, Op2,
},
syntax::{is_generic_parameter, is_type},
type_checker::{ConstInfo, FnInfo, FullyQualified, StructInfo, TypeChecker},
};
pub mod ast;
/// ExprMonoInfo holds the monomorphized expression node and its resolved type.
#[derive(Debug, Clone)]
pub struct ExprMonoInfo {
/// The monomorphized expression node.
pub expr: Expr,
/// The resolved type of the expression node.
/// The generic types shouldn't be presented in this field.
pub typ: Option<TyKind>,
/// Propagated constant value
pub constant: Option<PropagatedConstant>,
}
#[derive(Debug, Clone)]
pub enum PropagatedConstant {
Single(BigUint),
Array(Vec<PropagatedConstant>),
Custom(HashMap<Ident, PropagatedConstant>),
}
impl PropagatedConstant {
pub fn as_single(&self) -> BigUint {
match self {
PropagatedConstant::Single(v) => v.clone(),
_ => panic!("expected single value"),
}
}
pub fn as_array(&self) -> Vec<BigUint> {
match self {
PropagatedConstant::Array(v) => v.iter().map(|c| c.as_single()).collect(),
_ => panic!("expected array value"),
}
}
pub fn as_custom(&self) -> HashMap<Ident, BigUint> {
match self {
PropagatedConstant::Custom(v) => {
v.iter().map(|(k, c)| (k.clone(), c.as_single())).collect()
}
_ => panic!("expected custom value"),
}
}
}
/// impl From trait for single value
impl From<BigUint> for PropagatedConstant {
fn from(v: BigUint) -> Self {
PropagatedConstant::Single(v)
}
}
impl ExprMonoInfo {
pub fn new(expr: Expr, typ: Option<TyKind>, value: Option<PropagatedConstant>) -> Self {
Self {
expr,
typ,
constant: value,
}
}
/// There can be case expression node doesn't have a type.
/// For example, the ExprKind::Assignment won't return a type.
pub fn new_notype(expr: Expr) -> Self {
Self {
expr,
typ: None,
constant: None,
}
}
}
/// MTypeInfo holds the resolved type info to pass within a function scope.
/// It is stored in the scope context environment [MonomorphizedFnEnv].
#[derive(Debug, Clone)]
pub struct MTypeInfo {
/// Some type information.
pub typ: TyKind,
/// Store constant value
pub constant: Option<PropagatedConstant>,
/// The span of the variable declaration.
pub span: Span,
}
impl MTypeInfo {
pub fn new(typ: &TyKind, span: Span, value: Option<PropagatedConstant>) -> Self {
Self {
typ: typ.clone(),
span,
constant: value,
}
}
}
/// A storage to manage the variables in function scopes.
#[derive(Default, Debug, Clone)]
pub struct MonomorphizedFnEnv {
current_scope: usize,
vars: HashMap<String, (usize, MTypeInfo)>,
}
impl MonomorphizedFnEnv {
/// Creates a new TypeEnv
pub fn new() -> Self {
Self::default()
}
/// Enters a scoped block.
pub fn nest(&mut self) {
self.current_scope += 1;
}
/// Exits a scoped block.
pub fn pop(&mut self) {
self.current_scope = self.current_scope.checked_sub(1).expect("scope bug");
self.vars
.retain(|_, (scope, _)| *scope <= self.current_scope);
}
/// Returns true if a scope is a prefix of our scope.
pub fn is_in_scope(&self, prefix_scope: usize) -> bool {
self.current_scope >= prefix_scope
}
/// Stores type information about a local variable.
pub fn store_type(&mut self, ident: &str, type_info: &MTypeInfo) -> Result<()> {
match self
.vars
.insert(ident.to_string(), (self.current_scope, type_info.clone()))
{
Some(_) => Err(Error::new(
"mast",
ErrorKind::DuplicateDefinition(ident.to_string()),
type_info.span,
)),
None => Ok(()),
}
}
/// Retrieves type information on a variable, given a name.
/// If the variable is not in scope, return None.
pub fn get_type_info(&self, ident: &str) -> Option<&MTypeInfo> {
if let Some((scope, type_info)) = self.vars.get(ident) {
if self.is_in_scope(*scope) {
Some(type_info)
} else {
None
}
} else {
None
}
}
}
impl<B: Backend> FnInfo<B> {
/// Resolves the generic values based on observed arguments.
pub fn resolve_generic_signature(
&mut self,
observed_args: &[ExprMonoInfo],
ctx: &mut MastCtx<B>,
) -> Result<FnSig> {
match self.kind {
FnKind::BuiltIn(ref mut sig, _, _) => {
sig.resolve_generic_values(observed_args, ctx)?;
}
FnKind::Native(ref mut func) => {
func.sig.resolve_generic_values(observed_args, ctx)?;
}
};
Ok(self.resolved_sig())
}
/// Returns the resolved signature of the function.
pub fn resolved_sig(&self) -> FnSig {
let fn_sig = self.sig();
let (ret_typed, fn_args_typed) = if let Some(resolved) = &fn_sig.generics.resolved_sig {
(resolved.return_type.clone(), resolved.arguments.clone())
} else {
(fn_sig.return_type.clone(), fn_sig.arguments.clone())
};
FnSig {
name: fn_sig.monomorphized_name(),
arguments: fn_args_typed,
return_type: ret_typed,
..fn_sig.clone()
}
}
}
impl FnSig {
/// Recursively resolve a type based on generic values
pub fn resolve_type<B: Backend>(&self, typ: &TyKind, ctx: &mut MastCtx<B>) -> TyKind {
match typ {
TyKind::Array(ty, size) => TyKind::Array(Box::new(self.resolve_type(ty, ctx)), *size),
TyKind::GenericSizedArray(ty, sym) => {
let val = sym.eval(&self.generics, &ctx.tast);
TyKind::Array(
Box::new(self.resolve_type(ty, ctx)),
val.to_u32().expect("array size exceeded u32"),
)
}
TyKind::Tuple(typs) => {
let typs: Vec<TyKind> = typs.iter().map(|ty| self.resolve_type(ty, ctx)).collect();
TyKind::Tuple(typs)
}
_ => typ.clone(),
}
}
/// Resolve generic values for each generic parameter
pub fn resolve_generic_values<B: Backend>(
&mut self,
observed: &[ExprMonoInfo],
ctx: &mut MastCtx<B>,
) -> Result<()> {
for (sig_arg, observed_arg) in self.arguments.clone().iter().zip(observed) {
let observed_ty = observed_arg.typ.clone().expect("expected type");
match (&sig_arg.typ.kind, &observed_ty) {
(TyKind::GenericSizedArray(_, _), TyKind::Array(_, _))
| (TyKind::Array(_, _), TyKind::Array(_, _)) => {
self.resolve_generic_array(
&sig_arg.typ.kind,
&observed_ty,
observed_arg.expr.span,
)?;
}
// if generics in tuple
(TyKind::Tuple(sig_arg_typs), TyKind::Tuple(observed_arg_typs)) => {
for (sig_arg_typ, observed_arg_typ) in
sig_arg_typs.iter().zip(observed_arg_typs)
{
self.resolve_generic_array(
&sig_arg_typ,
&observed_arg_typ,
observed_arg.expr.span,
)?;
}
}
// const NN: Field
_ => {
let cst = observed_arg.constant.clone();
if is_generic_parameter(sig_arg.name.value.as_str()) && cst.is_some() {
self.generics.assign(
&sig_arg.name.value,
cst.unwrap().as_single(),
observed_arg.expr.span,
)?;
}
}
}
}
// resolve the argument types
let mut resolved_args = vec![];
for arg in &self.arguments {
let resolved_arg_typ = self.resolve_type(&arg.typ.kind, ctx);
let mut resolved_arg = arg.clone();
resolved_arg.typ = Ty {
kind: resolved_arg_typ,
span: arg.typ.span,
};
resolved_args.push(resolved_arg);
}
// resolve the return type
let mut return_type: Option<Ty> = None;
if let Some(ty) = &self.return_type {
let ret_typed = self.resolve_type(&ty.kind, ctx);
return_type = Some(Ty {
kind: ret_typed,
span: ty.span,
});
}
// store the resolved types in arguments and return
self.generics.resolve_sig(resolved_args, return_type);
Ok(())
}
}
/// A context to store the last node id for the monomorphized AST.
#[derive(Debug)]
pub struct MastCtx<B>
where
B: Backend,
{
tast: TypeChecker<B>,
generic_func_scope: Option<usize>,
// new fully qualified function name as the key, old fully qualified function name as the value
functions_instantiated: HashMap<FullyQualified, FullyQualified>,
// new method name as the key, old method name as the value
methods_instantiated: HashMap<(FullyQualified, String), String>,
// cache for [PropagatedConstant] values from instantiated methods
cst_method_cache: HashMap<(FullyQualified, String), PropagatedConstant>,
// cache for [PropagatedConstant] values from instantiated functions
cst_fn_cache: HashMap<FullyQualified, PropagatedConstant>,
}
impl<B: Backend> MastCtx<B> {
pub fn new(tast: TypeChecker<B>) -> Self {
Self {
tast,
generic_func_scope: Some(0),
functions_instantiated: HashMap::new(),
methods_instantiated: HashMap::new(),
cst_method_cache: HashMap::new(),
cst_fn_cache: HashMap::new(),
}
}
pub fn next_node_id(&mut self) -> usize {
let new_node_id = self.tast.last_node_id() + 1;
self.tast.update_node_id(new_node_id);
new_node_id
}
pub fn start_monomorphize_func(&mut self) {
self.generic_func_scope = Some(self.generic_func_scope.unwrap() + 1);
}
pub fn finish_monomorphize_func(&mut self) {
self.generic_func_scope = Some(self.generic_func_scope.unwrap() - 1);
}
pub fn add_monomorphized_fn(
&mut self,
old_qualified: FullyQualified,
new_qualified: FullyQualified,
fn_info: FnInfo<B>,
) {
self.tast
.add_monomorphized_fn(new_qualified.clone(), fn_info);
self.functions_instantiated
.insert(new_qualified, old_qualified);
}
pub fn add_monomorphized_method(
&mut self,
struct_qualified: FullyQualified,
old_method_name: &str,
method_name: &str,
fn_info: &FunctionDef,
) {
self.tast
.add_monomorphized_method(struct_qualified.clone(), method_name, fn_info);
self.methods_instantiated.insert(
(struct_qualified, method_name.to_string()),
old_method_name.to_string(),
);
}
pub fn clear_generic_fns(&mut self) {
for (new, old) in &self.functions_instantiated {
// don't remove the instantiated function with no generic arguments
if new != old {
self.tast.remove_fn(old);
}
}
for ((struct_qualified, new), old) in &self.methods_instantiated {
// don't remove the instantiated method with no generic arguments
if new != old {
self.tast.remove_method(struct_qualified, old);
}
}
}
}
impl Symbolic {
/// Evaluate symbolic size to an integer.
pub fn eval<B: Backend>(&self, gens: &GenericParameters, tast: &TypeChecker<B>) -> BigUint {
match self {
Symbolic::Concrete(v) => v.clone(),
Symbolic::Constant(var) => {
let qualified = FullyQualified::local(var.value.clone());
let cst = tast.const_info(&qualified).expect("constant not found");
// convert to u32
let bigint: BigUint = cst.value[0].into();
bigint.try_into().expect("biguint too large")
}
Symbolic::Generic(g) => gens.get(&g.value),
Symbolic::Add(a, b) => a.eval(gens, tast) + b.eval(gens, tast),
Symbolic::Sub(a, b) => a.eval(gens, tast) - b.eval(gens, tast),
Symbolic::Mul(a, b) => a.eval(gens, tast) * b.eval(gens, tast),
}
}
}
#[derive(Debug, Clone, Serialize)]
/// Mast relies on the TAST for the information about the "unresolved" types to monomorphize.
/// Things such as loading the function AST and struct AST from fully qualified names.
/// After monomorphization process, the following data will be updated:
/// - Resolved types. This can be used to determine the size of a type.
/// - Instantiated functions. The circuit writer will load the instantiated function AST by node id.
/// - Monomorphized AST is generated for the circuit writer to walk through and compute.
pub struct Mast<B: Backend>(#[serde(bound = "TypeChecker<B>: Serialize")] pub TypeChecker<B>);
impl<B: Backend> Mast<B> {
/// Returns the concrete type for the given expression node.
pub fn expr_type(&self, expr: &Expr) -> Option<&TyKind> {
self.0.expr_type(expr)
}
/// Returns the struct info for the given fully qualified name.
pub fn struct_info(&self, qualified: &FullyQualified) -> Option<&StructInfo> {
self.0.struct_info(qualified)
}
/// Returns the constant variable info for the given fully qualified name.
pub fn const_info(&self, qualified: &FullyQualified) -> Option<&ConstInfo<B::Field>> {
self.0.const_info(qualified)
}
/// Returns the function info by fully qualified name.
pub fn fn_info(&self, qualified: &FullyQualified) -> Option<&FnInfo<B>> {
self.0.fn_info(qualified)
}
// TODO: might want to memoize that at some point
/// Returns the number of field elements contained in the given type.
pub(crate) fn size_of(&self, typ: &TyKind) -> usize {
match typ {
TyKind::Field { .. } => 1,
TyKind::Custom { module, name } => {
let qualified = FullyQualified::new(module, name);
let struct_info = self
.struct_info(&qualified)
.expect("bug in the mast: cannot find struct info");
let mut sum = 0;
for (_, t, _) in &struct_info.fields {
sum += self.size_of(t);
}
sum
}
TyKind::Array(typ, len) => (*len as usize) * self.size_of(typ),
TyKind::GenericSizedArray(_, _) => {
unreachable!("generic arrays should have been resolved")
}
TyKind::Bool => 1,
TyKind::String(s) => s.len(),
TyKind::Tuple(typs) => typs.iter().map(|ty| self.size_of(ty)).sum(),
}
}
}
/// Monomorphize the main function.
/// This is the entry point of the monomorphization process.
/// It stores the monomorphized AST at the end.
pub fn monomorphize<B: Backend>(tast: TypeChecker<B>) -> Result<Mast<B>> {
let mut ctx = MastCtx::new(tast);
let qualified = FullyQualified::local("main".to_string());
let mut main_fn = ctx
.tast
.fn_info(&qualified)
.expect("main function not found")
.clone();
let mut func_def = match &main_fn.kind {
// `fn main() { ... }`
FnKind::Native(function) => function.clone(),
_ => Err(Error::new(
"Backend - Monomorphize",
ErrorKind::UnexpectedError("Main function must be native"),
Span::default(),
))?,
};
// create a new typed fn environment to type check the function
let mut mono_fn_env = MonomorphizedFnEnv::default();
// store variables and their types in the fn_env
for arg in &func_def.sig.arguments {
// store the args' type in the fn environment
mono_fn_env.store_type(
&arg.name.value,
&MTypeInfo::new(&arg.typ.kind, arg.span, None),
)?;
}
// monomorphize main function body
let (stmts, _) = monomorphize_block(
&mut ctx,
&mut mono_fn_env,
&func_def.body,
func_def.sig.return_type.as_ref(),
)?;
// override the main function AST with the monomorphized version
func_def.body = stmts;
main_fn.kind = FnKind::Native(func_def);
ctx.tast.add_monomorphized_fn(qualified, main_fn.clone());
ctx.clear_generic_fns();
Ok(Mast(ctx.tast))
}
/// Recursively monomorphize an expression node.
/// It does two things:
/// - Monomorphize the expression node with the inferred generic values.
/// - Typecheck the resolved type.
fn monomorphize_expr<B: Backend>(
ctx: &mut MastCtx<B>,
expr: &Expr,
mono_fn_env: &mut MonomorphizedFnEnv,
) -> Result<ExprMonoInfo> {
let expr_mono: ExprMonoInfo = match &expr.kind {
ExprKind::FieldAccess { lhs, rhs } => {
let lhs_mono = monomorphize_expr(ctx, lhs, mono_fn_env)?;
// obtain the type of the field
let (module, struct_name) = match lhs_mono.typ {
Some(TyKind::Custom { module, name }) => (module, name),
_ => Err(Error::new(
"Monomorphize Expr",
ErrorKind::UnexpectedError("field access must be done on a custom struct"),
expr.span,
))?,
};
// get struct info
let qualified = FullyQualified::new(&module, &struct_name);
let struct_info = ctx
.tast
.struct_info(&qualified)
.expect("this struct is not defined, or you're trying to access a field of a struct defined in a third-party library");
// find field type
let typ = struct_info
.fields
.iter()
.find(|(name, _, _)| name == &rhs.value)
.map(|(_, typ, _)| typ.clone());
let mexpr = expr.to_mast(
ctx,
&ExprKind::FieldAccess {
lhs: Box::new(lhs_mono.expr),
rhs: rhs.clone(),
},
);
// propagate the constant value
let cst = lhs_mono.constant.and_then(|c| match c {
PropagatedConstant::Custom(map) => map.get(rhs).cloned(),
_ => None,
});
ExprMonoInfo::new(mexpr, typ, cst)
}
// `module::fn_name(args)`
ExprKind::FnCall {
module,
fn_name,
args,
unsafe_attr,
} => {
// compute the observed arguments types
let mut observed = Vec::with_capacity(args.len());
for arg in args {
let node = monomorphize_expr(ctx, arg, mono_fn_env)?;
observed.push(node);
}
// retrieve the function signature
let old_qualified = FullyQualified::new(module, &fn_name.value);
let mut fn_info = ctx
.tast
.fn_info(&old_qualified)
.expect("function not found")
.to_owned();
let args_mono = observed.clone().into_iter().map(|e| e.expr).collect();
let resolved_sig = fn_info.resolve_generic_signature(&observed, ctx)?;
let mono_qualified = FullyQualified::new(module, &resolved_sig.name.value);
// check if this function is already monomorphized
if ctx.functions_instantiated.contains_key(&mono_qualified) {
let mexpr = expr.to_mast(
ctx,
&ExprKind::FnCall {
module: module.clone(),
fn_name: resolved_sig.name,
args: args_mono,
unsafe_attr: *unsafe_attr,
},
);
let resolved_sig = &fn_info.sig().generics.resolved_sig;
let typ = resolved_sig
.as_ref()
.and_then(|sig| sig.return_type.clone().map(|t| t.kind));
// retrieve the constant value from the cache
let cst = ctx.cst_fn_cache.get(&mono_qualified).cloned();
ExprMonoInfo::new(mexpr, typ, cst)
} else {
// monomorphize the function call
let (fn_info_mono, typ, cst) =
instantiate_fn_call(ctx, fn_info, &observed, expr.span)?;
// cache the constant value
if let Some(cst) = cst.clone() {
ctx.cst_fn_cache.insert(mono_qualified.clone(), cst);
}
let fn_name_mono = &fn_info_mono.sig().name;
let mexpr = expr.to_mast(
ctx,
&ExprKind::FnCall {
module: module.clone(),
fn_name: fn_name_mono.clone(),
args: args_mono,
unsafe_attr: *unsafe_attr,
},
);
let new_qualified = FullyQualified::new(module, &fn_name_mono.value);
ctx.add_monomorphized_fn(old_qualified, new_qualified, fn_info_mono);
ExprMonoInfo::new(mexpr, typ, cst)
}
}
// `lhs.method_name(args)`
ExprKind::MethodCall {
lhs,
method_name,
args,
} => {
// retrieve struct name on the lhs
let lhs_mono = monomorphize_expr(ctx, lhs, mono_fn_env)?;
let (module, struct_name) = match lhs_mono.clone().typ {
Some(TyKind::Custom { module, name }) => (module, name),
_ => return Err(error(ErrorKind::MethodCallOnNonCustomStruct, expr.span)),
};
// get struct info
let struct_qualified = FullyQualified::new(&module, &struct_name);
let struct_info = ctx
.tast
.struct_info(&struct_qualified)
.ok_or(error(
ErrorKind::UndefinedStruct(struct_name.clone()),
lhs.span,
))?
.clone();
// get method info
let method_type = struct_info
.methods
.get(&method_name.value)
.expect("method not found on custom struct (TODO: better error)");
let fn_kind = FnKind::Native(method_type.clone());
let mut fn_info = FnInfo {
kind: fn_kind,
is_hint: false,
span: method_type.span,
};
// compute the observed arguments types
let mut observed = Vec::with_capacity(args.len());
if let Some(self_arg) = fn_info.sig().arguments.first() {
if self_arg.name.value == "self" {
observed.push(monomorphize_expr(ctx, lhs, mono_fn_env)?);
}
}
let mut args_mono = vec![];
for arg in args {
let expr_mono = monomorphize_expr(ctx, arg, mono_fn_env)?;
observed.push(expr_mono.clone());
args_mono.push(expr_mono.expr);
}
let resolved_sig = fn_info.resolve_generic_signature(&observed, ctx)?;
// check if this function is already monomorphized
if ctx
.methods_instantiated
.contains_key(&(struct_qualified.clone(), resolved_sig.name.value.clone()))
{
let mexpr = expr.to_mast(
ctx,
&ExprKind::MethodCall {
lhs: Box::new(lhs_mono.expr),
method_name: resolved_sig.name,
args: args_mono,
},
);
let typ = resolved_sig.return_type.clone().map(|t| t.kind);
// retrieve the constant value from the cache
let cst = ctx
.cst_method_cache
.get(&(struct_qualified.clone(), method_name.value.clone()))
.cloned();
ExprMonoInfo::new(mexpr, typ, cst)
} else {
// monomorphize the function call
let (fn_info_mono, typ, cst) =
instantiate_fn_call(ctx, fn_info, &observed, expr.span)?;
// cache the constant value
if let Some(cst) = cst.clone() {
ctx.cst_method_cache
.insert((struct_qualified.clone(), method_name.value.clone()), cst);
}
let fn_name_mono = &fn_info_mono.sig().name;
let mexpr = expr.to_mast(
ctx,
&ExprKind::MethodCall {
lhs: Box::new(lhs_mono.expr),
method_name: fn_name_mono.clone(),
args: args_mono,
},
);
let fn_def = fn_info_mono.native().ok_or_else(|| {
Error::new(
"monomorphize-expr-MethodCall",
ErrorKind::UnexpectedError("Function kind is not native"),
fn_info_mono.span,
)
})?;
ctx.tast
.add_monomorphized_method(struct_qualified, &fn_name_mono.value, fn_def);
ExprMonoInfo::new(mexpr, typ, cst)
}
}
ExprKind::Assignment { lhs, rhs } => {
// compute type of lhs
let lhs_mono = monomorphize_expr(ctx, lhs, mono_fn_env)?;
// and is of the same type as the rhs
let rhs_mono = monomorphize_expr(ctx, rhs, mono_fn_env)?;
let lhs_typ = lhs_mono.typ.unwrap();
let rhs_typ = rhs_mono.typ.unwrap();
if !lhs_typ.match_expected(&rhs_typ, true) {
return Err(error(
ErrorKind::AssignmentTypeMismatch(lhs_typ, rhs_typ),
expr.span,
));
}
let mexpr = expr.to_mast(
ctx,
&ExprKind::Assignment {
lhs: Box::new(lhs_mono.expr),
rhs: Box::new(rhs_mono.expr),
},
);
ExprMonoInfo::new_notype(mexpr)
}
ExprKind::BinaryOp {
op,
lhs,
rhs,
protected,
} => {
let lhs_mono = monomorphize_expr(ctx, lhs, mono_fn_env)?;
let rhs_mono = monomorphize_expr(ctx, rhs, mono_fn_env)?;
let typ = match op {
Op2::Equality => Some(TyKind::Bool),
Op2::Inequality => Some(TyKind::Bool),
Op2::Addition
| Op2::Subtraction
| Op2::Multiplication
| Op2::Division
| Op2::BoolAnd
| Op2::BoolOr => lhs_mono.typ,
};
let ExprMonoInfo { expr: lhs_expr, .. } = lhs_mono;
let ExprMonoInfo { expr: rhs_expr, .. } = rhs_mono;
// fold constants
let cst = match (&lhs_mono.constant, &rhs_mono.constant) {
(Some(PropagatedConstant::Single(lhs)), Some(PropagatedConstant::Single(rhs))) => {
match op {
Op2::Addition => Some(lhs + rhs),
Op2::Subtraction => {
if lhs < rhs {
// throw error
return Err(error(
ErrorKind::NegativeLhsLessThanRhs(
lhs.to_string(),
rhs.to_string(),
),
expr.span,
));
}
Some(lhs - rhs)
}
Op2::Multiplication => Some(lhs * rhs),
Op2::Division => Some(lhs / rhs),
_ => None,
}
}
_ => None,
};
match cst {
Some(v) => {
let mexpr = expr.to_mast(
ctx,
&ExprKind::BinaryOp {
op: op.clone(),
protected: *protected,
lhs: Box::new(lhs_expr),
rhs: Box::new(rhs_expr),
},
);
ExprMonoInfo::new(mexpr, typ, Some(PropagatedConstant::from(v)))
}
// keep as is
_ => {
let mexpr = expr.to_mast(
ctx,
&ExprKind::BinaryOp {
op: op.clone(),
protected: *protected,
lhs: Box::new(lhs_expr),
rhs: Box::new(rhs_expr),
},
);
ExprMonoInfo::new(mexpr, typ, None)
}
}
}
ExprKind::Negated(inner) => {
// todo: can constant be negative?
let inner_mono = monomorphize_expr(ctx, inner, mono_fn_env)?;
let mexpr = expr.to_mast(ctx, &ExprKind::Negated(Box::new(inner_mono.expr)));
ExprMonoInfo::new(mexpr, inner_mono.typ, None)
}
ExprKind::Not(inner) => {
let inner_mono = monomorphize_expr(ctx, inner, mono_fn_env)?;
let mexpr = expr.to_mast(ctx, &ExprKind::Not(Box::new(inner_mono.expr)));
ExprMonoInfo::new(mexpr, Some(TyKind::Bool), None)
}
ExprKind::BigUInt(inner) => {
let mexpr = expr.to_mast(ctx, &ExprKind::BigUInt(inner.clone()));
ExprMonoInfo::new(
mexpr,
Some(TyKind::Field { constant: true }),
Some(PropagatedConstant::from(inner.clone())),
)
}
ExprKind::Bool(inner) => {
let mexpr = expr.to_mast(ctx, &ExprKind::Bool(*inner));
ExprMonoInfo::new(mexpr, Some(TyKind::Bool), None)
}
ExprKind::StringLiteral(inner) => {
let mexpr = expr.to_mast(ctx, &ExprKind::StringLiteral(inner.clone()));
let string_literal_val: Vec<PropagatedConstant> = inner
.chars()
.map(|char| PropagatedConstant::Single(BigUint::from(char as u8)))
.collect();
ExprMonoInfo::new(
mexpr,
Some(TyKind::String(inner.clone())),
Some(PropagatedConstant::Array(string_literal_val)),
)
}
// mod::path.of.var
// it could be also a generic variable
ExprKind::Variable { module, name } => {
let qualified = FullyQualified::new(module, &name.value);
let res = if is_generic_parameter(&name.value) {
let mtype = mono_fn_env.get_type_info(&name.value).unwrap();
let cst = mtype.constant.clone().unwrap().as_single();
let mexpr = expr.to_mast(ctx, &ExprKind::BigUInt(BigUint::from(cst)));
ExprMonoInfo::new(mexpr, Some(mtype.typ.clone()), mtype.constant.clone())
} else if is_type(&name.value) {
let mtype = TyKind::Custom {
module: module.clone(),
name: name.value.clone(),
};
let mexpr = expr.to_mast(
ctx,
&ExprKind::Variable {
module: module.clone(),
name: name.clone(),
},
);
ExprMonoInfo::new(mexpr, Some(mtype), None)
} else if let Some(cst) = ctx.tast.const_info(&qualified) {
// if it's a variable,
// check if it's a constant first
let bigint: BigUint = cst.value[0].into();
let mexpr = expr.to_mast(ctx, &ExprKind::BigUInt(bigint.clone()));
ExprMonoInfo::new(
mexpr,
Some(TyKind::Field { constant: true }),
Some(PropagatedConstant::from(bigint)),
)
} else {
// otherwise it's a local variable
let mexpr = expr.to_mast(
ctx,
&ExprKind::Variable {
module: module.clone(),
name: name.clone(),
},
);
let mtype = mono_fn_env.get_type_info(&name.value).unwrap().clone();
ExprMonoInfo::new(mexpr, Some(mtype.typ), mtype.constant)
};
res
}
ExprKind::ArrayOrTupleAccess { container, idx } => {
// get type of lhs
let array_mono = monomorphize_expr(ctx, container, mono_fn_env)?;
let id_mono = monomorphize_expr(ctx, idx, mono_fn_env)?;
// get type of element
let el_typ = match array_mono.typ {
Some(TyKind::Array(typkind, _)) => Some(*typkind),
Some(TyKind::Tuple(typs)) => match &idx.kind {
ExprKind::BigUInt(index) => Some(typs[index.to_usize().unwrap()].clone()),
_ => Err(Error::new(
"Non constant container access",
ErrorKind::ExpectedConstant,
expr.span,
))?,