forked from tweag/nickel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperation.rs
1119 lines (1082 loc) · 39 KB
/
operation.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
//! Implementation of primitive operations.
//!
//! Define functions which perform the evaluation of primitive operators. The machinery required
//! for the strict evaluation of the operands is mainly handled by [`eval`](../eval/index.html),
//! and marginally in [`continuate_operation`](fn.continuate_operation.html). On the other hand,
//! the functions [`process_unary_operation`](fn.process_unary_operation.html) and
//! [`process_binary_operation`](fn.process_binary_operation.html) receive evaluated operands and
//! implement the actual semantics of operators.
use crate::error::EvalError;
use crate::eval::Environment;
use crate::eval::{CallStack, Closure};
use crate::identifier::Ident;
use crate::label::ty_path;
use crate::merge;
use crate::merge::merge;
use crate::position::RawSpan;
use crate::stack::Stack;
use crate::term::{BinaryOp, RichTerm, StrChunk, Term, UnaryOp};
use crate::transformations::Closurizable;
use simple_counter::*;
use std::collections::HashMap;
generate_counter!(FreshVariableCounter, usize);
/// An operation continuation as stored on the stack.
#[derive(Debug, PartialEq)]
pub enum OperationCont {
Op1(
/* unary operation */ UnaryOp<Closure>,
/* original position of the argument before evaluation */ Option<RawSpan>,
),
// The last parameter saves the strictness mode before the evaluation of the operator
Op2First(
/* the binary operation */ BinaryOp<Closure>,
/* second argument, to evaluate next */ Closure,
/* original position of the first argument */ Option<RawSpan>,
/* previous value of enriched_strict */ bool,
),
Op2Second(
/* binary operation */ BinaryOp<Closure>,
/* first argument, evaluated */ Closure,
/* original position of the first argument before evaluation */ Option<RawSpan>,
/* original position of the second argument before evaluation */ Option<RawSpan>,
/* previous value of enriched_strict */ bool,
),
}
/// Process to the next step of the evaluation of an operation.
///
/// Depending on the content of the stack, it either starts the evaluation of the first argument,
/// starts the evaluation of the second argument, or finally process with the operation if both
/// arguments are evaluated (for binary operators).
pub fn continuate_operation(
mut clos: Closure,
stack: &mut Stack,
call_stack: &mut CallStack,
enriched_strict: &mut bool,
) -> Result<Closure, EvalError> {
let (cont, cs_len, pos) = stack.pop_op_cont().expect("Condition already checked");
call_stack.truncate(cs_len);
match cont {
OperationCont::Op1(u_op, arg_pos) => {
process_unary_operation(u_op, clos, arg_pos, stack, pos)
}
OperationCont::Op2First(b_op, mut snd_clos, fst_pos, prev_strict) => {
std::mem::swap(&mut clos, &mut snd_clos);
stack.push_op_cont(
OperationCont::Op2Second(
b_op,
snd_clos,
fst_pos,
clos.body.pos.clone(),
prev_strict,
),
cs_len,
pos,
);
Ok(clos)
}
OperationCont::Op2Second(b_op, fst_clos, fst_pos, snd_pos, prev_strict) => {
let result =
process_binary_operation(b_op, fst_clos, fst_pos, clos, snd_pos, stack, pos);
*enriched_strict = prev_strict;
result
}
}
}
/// Evaluate a unary operation.
///
/// The argument is expected to be evaluated (in WHNF). `pos_op` corresponds to the whole
/// operation position, that may be needed for error reporting.
fn process_unary_operation(
u_op: UnaryOp<Closure>,
clos: Closure,
arg_pos: Option<RawSpan>,
stack: &mut Stack,
pos_op: Option<RawSpan>,
) -> Result<Closure, EvalError> {
let Closure {
body: RichTerm { term: t, pos },
mut env,
} = clos;
match u_op {
UnaryOp::Ite() => {
if let Term::Bool(b) = *t {
if stack.count_args() >= 2 {
let (fst, _) = stack.pop_arg().expect("Condition already checked.");
let (snd, _) = stack.pop_arg().expect("Condition already checked.");
Ok(if b { fst } else { snd })
} else {
panic!("An If-Then-Else wasn't saturated")
}
} else {
Err(EvalError::TypeError(
String::from("Bool"),
String::from("if"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::IsZero() => {
if let Term::Num(n) = *t {
// TODO Discuss and decide on this comparison for 0 on f64
Ok(Closure::atomic_closure(Term::Bool(n == 0.).into()))
} else {
Err(EvalError::TypeError(
String::from("Num"),
String::from("isZero"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::IsNum() => {
if let Term::Num(_) = *t {
Ok(Closure::atomic_closure(Term::Bool(true).into()))
} else {
Ok(Closure::atomic_closure(Term::Bool(false).into()))
}
}
UnaryOp::IsBool() => {
if let Term::Bool(_) = *t {
Ok(Closure::atomic_closure(Term::Bool(true).into()))
} else {
Ok(Closure::atomic_closure(Term::Bool(false).into()))
}
}
UnaryOp::IsStr() => {
if let Term::Str(_) = *t {
Ok(Closure::atomic_closure(Term::Bool(true).into()))
} else {
Ok(Closure::atomic_closure(Term::Bool(false).into()))
}
}
UnaryOp::IsFun() => {
if let Term::Fun(_, _) = *t {
Ok(Closure::atomic_closure(Term::Bool(true).into()))
} else {
Ok(Closure::atomic_closure(Term::Bool(false).into()))
}
}
UnaryOp::IsList() => {
if let Term::List(_) = *t {
Ok(Closure::atomic_closure(Term::Bool(true).into()))
} else {
Ok(Closure::atomic_closure(Term::Bool(false).into()))
}
}
UnaryOp::IsRecord() => match *t {
Term::Record(_) | Term::RecRecord(_) => {
Ok(Closure::atomic_closure(Term::Bool(true).into()))
}
_ => Ok(Closure::atomic_closure(Term::Bool(false).into())),
},
UnaryOp::Blame() => {
if let Term::Lbl(l) = *t {
Err(EvalError::BlameError(l, None))
} else {
Err(EvalError::TypeError(
String::from("Label"),
String::from("blame"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::Embed(_id) => {
if let en @ Term::Enum(_) = *t {
Ok(Closure::atomic_closure(en.into()))
} else {
Err(EvalError::TypeError(
String::from("Enum"),
String::from("embed"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::Switch(mut m, d) => {
if let Term::Enum(en) = *t {
match m.remove(&en) {
Some(clos) => Ok(clos),
None => match d {
Some(clos) => Ok(clos),
None => Err(EvalError::TypeError(
String::from("Enum"),
String::from("switch"),
arg_pos,
RichTerm {
term: Box::new(Term::Enum(en)),
pos,
},
)),
},
}
} else {
match d {
Some(clos) => Ok(clos),
None => Err(EvalError::TypeError(
String::from("Enum"),
String::from("switch"),
arg_pos,
RichTerm { term: t, pos },
)),
}
}
}
UnaryOp::ChangePolarity() => {
if let Term::Lbl(mut l) = *t {
l.polarity = !l.polarity;
Ok(Closure::atomic_closure(Term::Lbl(l).into()))
} else {
Err(EvalError::TypeError(
String::from("Label"),
String::from("changePolarity"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::Pol() => {
if let Term::Lbl(l) = *t {
Ok(Closure::atomic_closure(Term::Bool(l.polarity).into()))
} else {
Err(EvalError::TypeError(
String::from("Label"),
String::from("polarity"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::GoDom() => {
if let Term::Lbl(mut l) = *t {
l.path.push(ty_path::Elem::Domain);
Ok(Closure::atomic_closure(Term::Lbl(l).into()))
} else {
Err(EvalError::TypeError(
String::from("Label"),
String::from("goDom"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::GoCodom() => {
if let Term::Lbl(mut l) = *t {
l.path.push(ty_path::Elem::Codomain);
Ok(Closure::atomic_closure(Term::Lbl(l).into()))
} else {
Err(EvalError::TypeError(
String::from("Label"),
String::from("goCodom"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::Tag(s) => {
if let Term::Lbl(mut l) = *t {
l.tag = String::from(&s);
Ok(Closure::atomic_closure(Term::Lbl(l).into()))
} else {
Err(EvalError::TypeError(
String::from("Label"),
String::from("tag"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::Wrap() => {
if let Term::Sym(s) = *t {
Ok(Closure::atomic_closure(
Term::Fun(
Ident("x".to_string()),
Term::Wrapped(s, RichTerm::var("x".to_string())).into(),
)
.into(),
))
} else {
Err(EvalError::TypeError(
String::from("Sym"),
String::from("wrap"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::StaticAccess(id) => {
if let Term::Record(mut static_map) = *t {
match static_map.remove(&id) {
Some(e) => Ok(Closure { body: e, env }),
None => Err(EvalError::FieldMissing(
id.0,
String::from("(.)"),
RichTerm {
term: Box::new(Term::Record(static_map)),
pos,
},
pos_op,
)), //TODO include the position of operators on the stack
}
} else {
Err(EvalError::TypeError(
String::from("Record"),
String::from("field access"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::FieldsOf() => {
if let Term::Record(map) = *t {
let mut fields: Vec<String> = map.keys().map(|Ident(id)| id.clone()).collect();
fields.sort();
let terms = fields.into_iter().map(|id| Term::Str(id).into()).collect();
Ok(Closure::atomic_closure(Term::List(terms).into()))
} else {
Err(EvalError::TypeError(
String::from("Record"),
String::from("fieldsOf"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::MapRec(f) => {
if let Term::Record(rec) = *t {
let f_as_var = f.body.closurize(&mut env, f.env);
let rec = rec
.into_iter()
.map(|e| {
let (Ident(s), t) = e;
(
Ident(s.clone()),
Term::App(
Term::App(f_as_var.clone(), Term::Str(s.clone()).into()).into(),
t.clone(),
)
.into(),
)
})
.collect();
Ok(Closure {
body: Term::Record(rec).into(),
env,
})
} else {
Err(EvalError::TypeError(
String::from("Record"),
String::from("map on record"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::Seq() => {
if stack.count_args() >= 1 {
let (next, _) = stack.pop_arg().expect("Condition already checked.");
Ok(next)
} else {
Err(EvalError::NotEnoughArgs(2, String::from("seq"), pos_op))
}
}
UnaryOp::DeepSeq() => {
/// Build a closure that forces a given list of terms, and at the end resumes the
/// evaluation of the argument on the top of the stack.
///
/// Requires its first argument to be non-empty.
fn seq_terms<I>(mut terms: I, env: Environment) -> Result<Closure, EvalError>
where
I: Iterator<Item = RichTerm>,
{
let first = terms
.next()
.expect("expected the argument to be a non-empty iterator");
let body = terms.fold(Term::Op1(UnaryOp::DeepSeq(), first).into(), |acc, t| {
Term::App(Term::Op1(UnaryOp::DeepSeq(), t).into(), acc).into()
});
Ok(Closure { body, env })
};
match *t {
Term::Record(map) if !map.is_empty() => {
let terms = map.into_iter().map(|(_, t)| t);
seq_terms(terms, env)
}
Term::List(ts) if !ts.is_empty() => seq_terms(ts.into_iter(), env),
_ => {
if stack.count_args() >= 1 {
let (next, _) = stack.pop_arg().expect("Condition already checked.");
Ok(next)
} else {
Err(EvalError::NotEnoughArgs(2, String::from("deepSeq"), pos_op))
}
}
}
}
UnaryOp::ListHead() => {
if let Term::List(ts) = *t {
let mut ts_it = ts.into_iter();
if let Some(head) = ts_it.next() {
Ok(Closure { body: head, env })
} else {
Err(EvalError::Other(String::from("head: empty list"), pos_op))
}
} else {
Err(EvalError::TypeError(
String::from("List"),
String::from("head"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::ListTail() => {
if let Term::List(ts) = *t {
let mut ts_it = ts.into_iter();
if let Some(_) = ts_it.next() {
Ok(Closure {
body: Term::List(ts_it.collect()).into(),
env,
})
} else {
Err(EvalError::Other(String::from("tail: empty list"), pos_op))
}
} else {
Err(EvalError::TypeError(
String::from("List"),
String::from("tail"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::ListLength() => {
if let Term::List(ts) = *t {
// A num does not have any free variable so we can drop the environment
Ok(Closure {
body: Term::Num(ts.len() as f64).into(),
env: HashMap::new(),
})
} else {
Err(EvalError::TypeError(
String::from("List"),
String::from("length"),
arg_pos,
RichTerm { term: t, pos },
))
}
}
UnaryOp::ChunksConcat(mut acc, mut tail) => {
if let Term::Str(s) = *t {
acc.push_str(&s);
let mut next_opt = tail.pop();
// Pop consecutive string literals to find the next expression to evaluate
while let Some(StrChunk::Literal(s)) = next_opt {
acc.push_str(&s);
next_opt = tail.pop();
}
if let Some(StrChunk::Expr(e)) = next_opt {
let arg_closure = e.body.closurize(&mut env, e.env);
let tail_closure = tail
.into_iter()
.map(|chunk| match chunk {
StrChunk::Literal(s) => StrChunk::Literal(s),
StrChunk::Expr(c) => StrChunk::Expr(c.body.closurize(&mut env, c.env)),
})
.collect();
Ok(Closure {
body: RichTerm {
term: Box::new(Term::Op1(
UnaryOp::ChunksConcat(acc, tail_closure),
arg_closure,
)),
pos: pos_op,
},
env,
})
} else {
Ok(Closure {
body: RichTerm {
term: Box::new(Term::Str(acc)),
pos: pos_op,
},
env: HashMap::new(),
})
}
} else {
Err(EvalError::TypeError(
String::from("String"),
String::from("interpolated string"),
pos_op,
RichTerm { term: t, pos },
))
}
}
}
}
/// Evaluate a binary operation.
///
/// Both arguments are expected to be evaluated (in WHNF). `pos_op` corresponds to the whole
/// operation position, that may be needed for error reporting.
fn process_binary_operation(
b_op: BinaryOp<Closure>,
fst_clos: Closure,
fst_pos: Option<RawSpan>,
clos: Closure,
snd_pos: Option<RawSpan>,
_stack: &mut Stack,
pos_op: Option<RawSpan>,
) -> Result<Closure, EvalError> {
let Closure {
body: RichTerm {
term: t1,
pos: pos1,
},
env: env1,
} = fst_clos;
let Closure {
body: RichTerm {
term: t2,
pos: pos2,
},
env: mut env2,
} = clos;
match b_op {
BinaryOp::Plus() => {
if let Term::Num(n1) = *t1 {
if let Term::Num(n2) = *t2 {
Ok(Closure::atomic_closure(Term::Num(n1 + n2).into()))
} else {
Err(EvalError::TypeError(
String::from("Num"),
String::from("+, 2nd argument"),
snd_pos,
RichTerm {
term: t2,
pos: pos2,
},
))
}
} else {
Err(EvalError::TypeError(
String::from("Num"),
String::from("+, 1st argument"),
fst_pos,
RichTerm {
term: t1,
pos: pos1,
},
))
}
}
BinaryOp::PlusStr() => {
if let Term::Str(s1) = *t1 {
if let Term::Str(s2) = *t2 {
Ok(Closure::atomic_closure(Term::Str(s1 + &s2).into()))
} else {
Err(EvalError::TypeError(
String::from("Str"),
String::from("++, 2nd argument"),
snd_pos,
RichTerm {
term: t2,
pos: pos2,
},
))
}
} else {
Err(EvalError::TypeError(
String::from("Str"),
String::from("++, 1st argument"),
fst_pos,
RichTerm {
term: t1,
pos: pos1,
},
))
}
}
BinaryOp::Unwrap() => {
if let Term::Sym(s1) = *t1 {
// Return a function that either behaves like the identity or
// const unwrapped_term
Ok(if let Term::Wrapped(s2, t) = *t2 {
if s1 == s2 {
Closure {
body: Term::Fun(Ident("-invld".to_string()), t).into(),
env: env2,
}
} else {
Closure::atomic_closure(
Term::Fun(Ident("x".to_string()), RichTerm::var("x".to_string()))
.into(),
)
}
} else {
Closure::atomic_closure(
Term::Fun(Ident("x".to_string()), RichTerm::var("x".to_string())).into(),
)
})
} else {
Err(EvalError::TypeError(
String::from("Sym"),
String::from("unwrap, 1st argument"),
fst_pos,
RichTerm {
term: t1,
pos: pos1,
},
))
}
}
BinaryOp::Eq() => {
/// Take an iterator of pairs of RichTerm, the common environments of all left
/// components of these pairs and all right components, the final environment,
/// and build a Term which evaluates to `Bool(true)` if and only if all the pairs are
/// equals
fn eq_all<T>(
it: T,
env1: &Environment,
env2: &Environment,
env: &mut Environment,
) -> Term
where
T: Iterator<Item = (RichTerm, RichTerm)>,
{
let subeqs: Vec<RichTerm> = it
.map(|(t1, t2)| {
let t1_var = t1.closurize(env, env1.clone());
let t2_var = t2.closurize(env, env2.clone());
Term::Op2(BinaryOp::Eq(), t1_var, t2_var).into()
})
.collect();
// lists.all (fun x => x) subeqs
Term::App(
RichTerm::app(
// lists.all
Term::Op1(
UnaryOp::StaticAccess(Ident::from("all")),
RichTerm::var(String::from("lists")),
)
.into(),
// identity (we should probably have it in the stdlib at some point)
RichTerm::fun(String::from("x"), RichTerm::var(String::from("x"))),
),
Term::List(subeqs).into(),
)
}
let mut env: Environment = HashMap::new();
let res = match (*t1, *t2) {
(Term::Bool(b1), Term::Bool(b2)) => Term::Bool(b1 == b2),
(Term::Num(n1), Term::Num(n2)) => Term::Bool(n1 == n2),
(Term::Str(s1), Term::Str(s2)) => Term::Bool(s1 == s2),
(Term::Lbl(l1), Term::Lbl(l2)) => Term::Bool(l1 == l2),
(Term::Sym(s1), Term::Sym(s2)) => Term::Bool(s1 == s2),
(Term::Record(m1), Term::Record(m2)) => {
let (left, center, right) = merge::hashmap::split(m1, m2);
if !left.is_empty() || !right.is_empty() {
Term::Bool(false)
} else {
eq_all(
center.into_iter().map(|(_, (t1, t2))| (t1, t2)),
&env1,
&env2,
&mut env,
)
}
}
(Term::List(l1), Term::List(l2)) if l1.len() == l2.len() => {
eq_all(l1.into_iter().zip(l2.into_iter()), &env1, &env2, &mut env)
}
(_, _) => Term::Bool(false),
};
Ok(Closure {
body: res.into(),
env,
})
}
BinaryOp::GoField() => {
if let Term::Str(field) = *t1 {
if let Term::Lbl(mut l) = *t2 {
l.path.push(ty_path::Elem::Field(Ident(field)));
Ok(Closure::atomic_closure(Term::Lbl(l).into()))
} else {
Err(EvalError::TypeError(
String::from("Label"),
String::from("goField, 2nd argument"),
snd_pos,
RichTerm {
term: t2,
pos: pos2,
},
))
}
} else {
Err(EvalError::TypeError(
String::from("Str"),
String::from("goField, 1st argument"),
fst_pos,
RichTerm {
term: t1,
pos: pos1,
},
))
}
}
BinaryOp::DynAccess() => {
if let Term::Str(id) = *t1 {
if let Term::Record(mut static_map) = *t2 {
match static_map.remove(&Ident(id.clone())) {
Some(e) => Ok(Closure { body: e, env: env2 }),
None => Err(EvalError::FieldMissing(
format!("{}", id),
String::from("(.$)"),
RichTerm {
term: Box::new(Term::Record(static_map)),
pos: pos2,
},
pos_op,
)),
}
} else {
Err(EvalError::TypeError(
String::from("Record"),
String::from(".$"),
snd_pos,
RichTerm {
term: t2,
pos: pos2,
},
))
}
} else {
Err(EvalError::TypeError(
String::from("Str"),
String::from(".$"),
fst_pos,
RichTerm {
term: t1,
pos: pos1,
},
))
}
}
BinaryOp::DynExtend(clos) => {
if let Term::Str(id) = *t1 {
if let Term::Record(mut static_map) = *t2 {
let as_var = clos.body.closurize(&mut env2, clos.env);
match static_map.insert(Ident(id.clone()), as_var) {
Some(_) => Err(EvalError::Other(format!("$[ .. ]: tried to extend record with the field {}, but it already exists", id), pos_op)),
None => Ok(Closure {
body: Term::Record(static_map).into(),
env: env2,
}),
}
} else {
Err(EvalError::TypeError(
String::from("Record"),
String::from("$[ .. ]"),
snd_pos,
RichTerm {
term: t2,
pos: pos2,
},
))
}
} else {
Err(EvalError::TypeError(
String::from("Str"),
String::from("$[ .. ]"),
fst_pos,
RichTerm {
term: t1,
pos: pos1,
},
))
}
}
BinaryOp::DynRemove() => {
if let Term::Str(id) = *t1 {
if let Term::Record(mut static_map) = *t2 {
match static_map.remove(&Ident(id.clone())) {
None => Err(EvalError::FieldMissing(
format!("{}", id),
String::from("(-$)"),
RichTerm {
term: Box::new(Term::Record(static_map)),
pos: pos2,
},
pos_op,
)),
Some(_) => Ok(Closure {
body: Term::Record(static_map).into(),
env: env2,
}),
}
} else {
Err(EvalError::TypeError(
String::from("Record"),
String::from("-$"),
snd_pos,
RichTerm {
term: t2,
pos: pos2,
},
))
}
} else {
Err(EvalError::TypeError(
String::from("Str"),
String::from("-$"),
fst_pos,
RichTerm {
term: t1,
pos: pos1,
},
))
}
}
BinaryOp::HasField() => {
if let Term::Str(id) = *t1 {
if let Term::Record(static_map) = *t2 {
Ok(Closure::atomic_closure(
Term::Bool(static_map.contains_key(&Ident(id))).into(),
))
} else {
Err(EvalError::TypeError(
String::from("Record"),
String::from("hasField, 2nd argument"),
snd_pos,
RichTerm {
term: t2,
pos: pos2,
},
))
}
} else {
Err(EvalError::TypeError(
String::from("Str"),
String::from("hasField, 1st argument"),
fst_pos,
RichTerm {
term: t1,
pos: pos1,
},
))
}
}
BinaryOp::ListConcat() => match (*t1, *t2) {
(Term::List(ts1), Term::List(ts2)) => {
let mut env = Environment::new();
let mut ts: Vec<RichTerm> = ts1
.into_iter()
.map(|t| t.closurize(&mut env, env1.clone()))
.collect();
ts.extend(ts2.into_iter().map(|t| t.closurize(&mut env, env2.clone())));
Ok(Closure {
body: Term::List(ts).into(),
env,
})
}
(Term::List(_), t2) => Err(EvalError::TypeError(
String::from("List"),
String::from("@, 2nd operand"),
snd_pos,
RichTerm {
term: Box::new(t2),
pos: pos2,
},
)),
(t1, _) => Err(EvalError::TypeError(
String::from("List"),
String::from("@, 1st operand"),
fst_pos,
RichTerm {
term: Box::new(t1),
pos: pos1,
},
)),
},
// This one should not be strict in the first argument (f)
BinaryOp::ListMap() => {
if let Term::List(ts) = *t2 {
let f = RichTerm {
term: t1,
pos: pos1,
};
let f_as_var = f.closurize(&mut env2, env1);
let ts = ts
.into_iter()
.map(|t| Term::App(f_as_var.clone(), t).into())
.collect();
Ok(Closure {
body: Term::List(ts).into(),
env: env2,
})
} else {
Err(EvalError::TypeError(
String::from("List"),
String::from("map, 2nd argument"),
snd_pos,
RichTerm {
term: t2,
pos: pos2,
},
))
}
}
BinaryOp::ListElemAt() => match (*t1, *t2) {
(Term::List(mut ts), Term::Num(n)) => {
let n_int = n as usize;
if n.fract() != 0.0 {
Err(EvalError::Other(format!("elemAt: expected the 2nd agument to be an integer, got the floating-point value {}", n), pos_op))
} else if n_int >= ts.len() {
Err(EvalError::Other(format!("elemAt: index out of bounds. Expected a value between 0 and {}, got {})", ts.len(), n_int), pos_op))
} else {
Ok(Closure {
body: ts.swap_remove(n_int),
env: env1,
})
}
}
(Term::List(_), t2) => Err(EvalError::TypeError(
String::from("Num"),
String::from("elemAt, 2nd argument"),
snd_pos,
RichTerm {
term: Box::new(t2),
pos: pos2,
},
)),
(t1, _) => Err(EvalError::TypeError(
String::from("List"),
String::from("elemAt, 1st argument"),
fst_pos,
RichTerm {
term: Box::new(t1),
pos: pos1,
},
)),
},
BinaryOp::Merge() => merge(
RichTerm {
term: t1,
pos: pos1,
},
env1,
RichTerm {
term: t2,
pos: pos2,
},
env2,
pos_op,
),
}
}
#[cfg(test)]