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
use codemap::{CodeMap, Span, Spanned};
use codemap_diagnostic::{Diagnostic, Level, SpanLabel, SpanStyle};
use environment::Environment;
use linked_hash_map::LinkedHashMap;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use syntax::ast::*;
use syntax::errors::SyntaxError;
use syntax::lexer::{LexerIntoIter, LexerItem};
use syntax::parser::{parse, parse_file, parse_lexer};
use values::function::FunctionParameter;
use values::*;
macro_rules! eval_vector {
($v:expr, $ctx:expr) => {{
let mut r = Vec::new();
for s in $v.iter() {
r.push(s.eval($ctx)?)
}
r
}};
}
#[doc(hidden)]
pub const BREAK_ERROR_CODE: &'static str = "CE00";
#[doc(hidden)]
pub const CONTINUE_ERROR_CODE: &'static str = "CE01";
#[doc(hidden)]
pub const RETURN_ERROR_CODE: &'static str = "CE02";
#[doc(hidden)]
pub const INCORRECT_LEFT_VALUE_ERROR_CODE: &'static str = "CE03";
#[doc(hidden)]
pub const INCORRECT_UNPACK_ERROR_CODE: &'static str = "CE04";
#[doc(hidden)]
pub const RECURSION_ERROR_CODE: &'static str = "CE05";
#[doc(hidden)]
#[derive(Debug, Clone)]
pub enum EvalException {
Break(Span),
Continue(Span),
Return(Span, Value),
DiagnosedError(Diagnostic),
IncorrectLeftValue(Span),
IncorrectNumberOfValueToUnpack(Span, i64, i64),
Recursion(Span, String, Vec<(String, String)>),
}
type EvalResult = Result<Value, EvalException>;
macro_rules! t {
($v:expr,span $el:expr) => {{
match $v {
Err(e) => Err(EvalException::DiagnosedError(e.to_diagnostic($el))),
Ok(v) => Ok(v),
}
}};
($v:expr, $el:expr) => {{
match $v {
Err(e) => Err(EvalException::DiagnosedError(e.to_diagnostic($el.span))),
Ok(v) => Ok(v),
}
}};
}
impl Into<Diagnostic> for EvalException {
fn into(self) -> Diagnostic {
match self {
EvalException::DiagnosedError(e) => e,
EvalException::Break(s) => Diagnostic {
level: Level::Error,
message: "Break statement used outside of a loop".to_owned(),
code: Some(BREAK_ERROR_CODE.to_owned()),
spans: vec![SpanLabel {
span: s,
style: SpanStyle::Primary,
label: None,
}],
},
EvalException::Continue(s) => Diagnostic {
level: Level::Error,
message: "Continue statement used outside of a loop".to_owned(),
code: Some(CONTINUE_ERROR_CODE.to_owned()),
spans: vec![SpanLabel {
span: s,
style: SpanStyle::Primary,
label: None,
}],
},
EvalException::Return(s, ..) => Diagnostic {
level: Level::Error,
message: "Return statement used outside of a function call".to_owned(),
code: Some(RETURN_ERROR_CODE.to_owned()),
spans: vec![SpanLabel {
span: s,
style: SpanStyle::Primary,
label: None,
}],
},
EvalException::IncorrectLeftValue(s) => Diagnostic {
level: Level::Error,
message: "Incorrect expression as left value".to_owned(),
code: Some(INCORRECT_LEFT_VALUE_ERROR_CODE.to_owned()),
spans: vec![SpanLabel {
span: s,
style: SpanStyle::Primary,
label: None,
}],
},
EvalException::IncorrectNumberOfValueToUnpack(s, expected, got) => Diagnostic {
level: Level::Error,
message: format!("Unpacked {} values but expected {}", got, expected),
code: Some(INCORRECT_UNPACK_ERROR_CODE.to_owned()),
spans: vec![SpanLabel {
span: s,
style: SpanStyle::Primary,
label: None,
}],
},
EvalException::Recursion(s, f, stack) => Diagnostic {
level: Level::Error,
message: format!(
"Function {} recursed, call stack:{}",
f,
stack
.iter()
.rev()
.fold(String::new(), |a, s| format!("{}\n {}", a, s.1))
),
code: Some(RECURSION_ERROR_CODE.to_owned()),
spans: vec![SpanLabel {
span: s,
style: SpanStyle::Primary,
label: Some("Recursive call".to_owned()),
}],
},
}
}
}
pub trait FileLoader: Clone {
fn load(&self, path: &str) -> Result<Environment, EvalException>;
}
pub struct EvaluationContext<T: FileLoader> {
env: Environment,
loader: T,
call_stack: Vec<(String, String)>,
map: Arc<Mutex<CodeMap>>,
}
impl<T: FileLoader> EvaluationContext<T> {
fn new(env: Environment, loader: T, map: Arc<Mutex<CodeMap>>) -> Self {
EvaluationContext {
call_stack: Vec::new(),
env,
loader,
map,
}
}
fn child(&self, name: &str) -> EvaluationContext<()> {
EvaluationContext {
env: self.env.child(name),
call_stack: self.call_stack.clone(),
loader: (),
map: self.map.clone(),
}
}
}
impl FileLoader for () {
fn load(&self, _path: &str) -> Result<Environment, EvalException> {
unreachable!();
}
}
trait Evaluate<T: FileLoader> {
fn eval(&self, context: &mut EvaluationContext<T>) -> EvalResult;
fn transform(
&self,
context: &mut EvaluationContext<T>,
) -> Result<Box<Evaluate<T>>, EvalException>;
fn set(&self, context: &mut EvaluationContext<T>, new_value: Value) -> EvalResult;
}
impl<T: FileLoader> Evaluate<T> for AstString {
fn eval(&self, _context: &mut EvaluationContext<T>) -> EvalResult {
Ok(Value::new(self.node.clone()))
}
fn transform(
&self,
_context: &mut EvaluationContext<T>,
) -> Result<Box<Evaluate<T>>, EvalException> {
Ok(Box::new(self.clone()))
}
fn set(&self, _context: &mut EvaluationContext<T>, _new_value: Value) -> EvalResult {
Err(EvalException::IncorrectLeftValue(self.span))
}
}
impl<T: FileLoader> Evaluate<T> for AstInt {
fn eval(&self, _context: &mut EvaluationContext<T>) -> EvalResult {
Ok(Value::new(self.node.clone()))
}
fn transform(
&self,
_context: &mut EvaluationContext<T>,
) -> Result<Box<Evaluate<T>>, EvalException> {
Ok(Box::new(self.clone()))
}
fn set(&self, _context: &mut EvaluationContext<T>, _new_value: Value) -> EvalResult {
Err(EvalException::IncorrectLeftValue(self.span))
}
}
fn eval_comprehension_clause<'a, T: FileLoader + 'static>(
context: &mut EvaluationContext<T>,
e: &AstExpr,
clauses: &[AstClause],
) -> Result<Vec<Value>, EvalException> {
let mut result = Vec::new();
if let Some((c, tl)) = clauses.split_first() {
match c.node {
Clause::If(ref cond) => {
if cond.eval(context)?.to_bool() {
if tl.is_empty() {
result.push(e.eval(context)?);
} else {
let mut other = eval_comprehension_clause(context, e, tl)?;
result.append(&mut other);
}
};
}
Clause::For(ref k, ref v) => {
let mut iterable = v.eval(context)?;
iterable.freeze_for_iteration();
for i in t!(iterable.into_iter(), c)? {
k.set(context, i)?;
if tl.is_empty() {
result.push(e.eval(context)?);
} else {
let mut other = eval_comprehension_clause(context, e, tl)?;
result.append(&mut other);
}
}
iterable.unfreeze_for_iteration();
}
}
}
Ok(result)
}
enum TransformedExpr<T: FileLoader> {
Dot(Value, String, Span),
ArrayIndirection(Value, Value, Span),
List(Vec<Box<Evaluate<T>>>, Span),
Tuple(Vec<Box<Evaluate<T>>>, Span),
}
impl<T: FileLoader + 'static> Evaluate<T> for TransformedExpr<T> {
fn transform(
&self,
_context: &mut EvaluationContext<T>,
) -> Result<Box<Evaluate<T>>, EvalException> {
panic!("Transform should not be called on an already transformed object");
}
fn set(&self, context: &mut EvaluationContext<T>, new_value: Value) -> EvalResult {
let ok = Ok(Value::new(None));
match self {
&TransformedExpr::List(ref v, ref span) | &TransformedExpr::Tuple(ref v, ref span) => {
let span = span.clone();
let l = v.len() as i64;
let nvl = t!(new_value.length(), span span)?;
if nvl != l {
Err(EvalException::IncorrectNumberOfValueToUnpack(span, l, nvl))
} else {
let mut r = Vec::new();
let mut it1 = v.iter();
let mut it2 = t!(new_value.into_iter(), span span)?;
for _ in 0..l {
r.push(it1.next().unwrap().set(context, it2.next().unwrap())?)
}
ok
}
}
&TransformedExpr::Dot(ref e, ref s, ref span) => {
let span = span.clone();
t!(e.clone().set_attr(&s, new_value), span span)?;
ok
}
&TransformedExpr::ArrayIndirection(ref e, ref idx, ref span) => {
let span = span.clone();
t!(e.clone().set_at(idx.clone(), new_value), span span)?;
ok
}
}
}
fn eval(&self, context: &mut EvaluationContext<T>) -> EvalResult {
match self {
&TransformedExpr::Tuple(ref v, ..) => {
let r = eval_vector!(v, context);
Ok(Value::new(tuple::Tuple::new(r.as_slice())))
}
&TransformedExpr::List(ref v, ..) => {
let r = eval_vector!(v, context);
Ok(Value::from(r))
}
&TransformedExpr::Dot(ref left, ref s, ref span) => {
if let Some(v) = context.env.get_type_value(left, &s) {
if v.get_type() == "function" {
Ok(function::Function::new_self_call(left.clone(), v))
} else {
Ok(v)
}
} else {
t!(left.get_attr(&s), span span.clone())
}
}
&TransformedExpr::ArrayIndirection(ref e, ref idx, ref span) => {
t!(e.at(idx.clone()), span span.clone())
}
}
}
}
impl<T: FileLoader + 'static> Evaluate<T> for AstExpr {
fn transform(
&self,
context: &mut EvaluationContext<T>,
) -> Result<Box<Evaluate<T>>, EvalException> {
match self.node {
Expr::Dot(ref e, ref s) => Ok(Box::new(TransformedExpr::Dot(
e.eval(context)?,
s.node.clone(),
self.span,
))),
Expr::ArrayIndirection(ref e, ref idx) => Ok(Box::new(
TransformedExpr::ArrayIndirection(e.eval(context)?, idx.eval(context)?, self.span),
)),
Expr::List(ref v) => {
let mut r = Vec::new();
for val in v.iter() {
r.push(val.transform(context)?)
}
Ok(Box::new(TransformedExpr::List(r, self.span)))
}
Expr::Tuple(ref v) => {
let mut r = Vec::new();
for val in v.iter() {
r.push(val.transform(context)?)
}
Ok(Box::new(TransformedExpr::Tuple(r, self.span)))
}
_ => Ok(Box::new(self.clone())),
}
}
#[allow(unconditional_recursion)]
fn eval(&self, context: &mut EvaluationContext<T>) -> EvalResult {
match self.node {
Expr::Tuple(ref v) => {
let r = eval_vector!(v, context);
Ok(Value::new(tuple::Tuple::new(r.as_slice())))
}
Expr::Dot(ref e, ref s) => {
let left = e.eval(context)?;
if let Some(v) = context.env.get_type_value(&left, &s.node) {
if v.get_type() == "function" {
Ok(function::Function::new_self_call(left.clone(), v))
} else {
Ok(v)
}
} else {
t!(left.get_attr(&s.node), self)
}
}
Expr::Call(ref e, ref pos, ref named, ref args, ref kwargs) => {
let npos = eval_vector!(pos, context);
let mut nnamed = HashMap::new();
for &(ref k, ref v) in named.iter() {
nnamed.insert(k.eval(context)?.to_str(), v.eval(context)?);
}
let nargs = if let &Some(ref x) = args {
Some(x.eval(context)?)
} else {
None
};
let nkwargs = if let &Some(ref x) = kwargs {
Some(x.eval(context)?)
} else {
None
};
let f = e.eval(context)?;
let fname = f.to_repr();
let descr = f.to_str();
let mut new_stack = context.call_stack.clone();
if context.call_stack.iter().any(|x| x.0 == fname) {
Err(EvalException::Recursion(self.span, fname, new_stack))
} else {
let loc = { context.map.lock().unwrap().look_up_pos(self.span.low()) };
new_stack.push((
fname,
format!(
"call to {} at {}:{}",
descr,
loc.file.name(),
loc.position.line + 1, ),
));
t!(
e.eval(context,)?.call(
&new_stack,
context.env.clone(),
npos,
nnamed,
nargs,
nkwargs,
),
self
)
}
}
Expr::ArrayIndirection(ref e, ref idx) => {
let idx = idx.eval(context)?;
t!(e.eval(context)?.at(idx), self)
}
Expr::Slice(ref a, ref start, ref stop, ref stride) => {
let a = a.eval(context)?;
let start = match start {
&Some(ref e) => Some(e.eval(context)?),
&None => None,
};
let stop = match stop {
&Some(ref e) => Some(e.eval(context)?),
&None => None,
};
let stride = match stride {
&Some(ref e) => Some(e.eval(context)?),
&None => None,
};
t!(a.slice(start, stop, stride), self)
}
Expr::Identifier(ref i) => t!(context.env.get(&i.node), i),
Expr::IntLiteral(ref i) => Ok(Value::new(i.node)),
Expr::StringLiteral(ref s) => Ok(Value::new(s.node.clone())),
Expr::Not(ref s) => Ok(Value::new(!s.eval(context)?.to_bool())),
Expr::Minus(ref s) => t!(s.eval(context)?.minus(), self),
Expr::Plus(ref s) => t!(s.eval(context)?.plus(), self),
Expr::Op(BinOp::Or, ref l, ref r) => {
let l = l.eval(context)?;
Ok(if l.to_bool() { l } else { r.eval(context)? })
}
Expr::Op(BinOp::And, ref l, ref r) => {
let l = l.eval(context)?;
Ok(if !l.to_bool() { l } else { r.eval(context)? })
}
Expr::Op(BinOp::EqualsTo, ref l, ref r) => {
let l = l.eval(context)?;
let r = r.eval(context)?;
Ok(Value::new(t!(l.compare(&r, 0), self)? == Ordering::Equal))
}
Expr::Op(BinOp::Different, ref l, ref r) => {
let l = l.eval(context)?;
let r = r.eval(context)?;
Ok(Value::new(t!(l.compare(&r, 0), self)? != Ordering::Equal))
}
Expr::Op(BinOp::LowerThan, ref l, ref r) => {
let l = l.eval(context)?;
let r = r.eval(context)?;
Ok(Value::new(t!(l.compare(&r, 0), self)? == Ordering::Less))
}
Expr::Op(BinOp::GreaterThan, ref l, ref r) => {
let l = l.eval(context)?;
let r = r.eval(context)?;
Ok(Value::new(t!(l.compare(&r, 0), self)? == Ordering::Greater))
}
Expr::Op(BinOp::LowerOrEqual, ref l, ref r) => {
let l = l.eval(context)?;
let r = r.eval(context)?;
Ok(Value::new(t!(l.compare(&r, 0), self)? != Ordering::Greater))
}
Expr::Op(BinOp::GreaterOrEqual, ref l, ref r) => {
let l = l.eval(context)?;
let r = r.eval(context)?;
Ok(Value::new(t!(l.compare(&r, 0), self)? != Ordering::Less))
}
Expr::Op(BinOp::In, ref l, ref r) => {
t!(r.eval(context)?.is_in(&l.eval(context)?), self)
}
Expr::Op(BinOp::NotIn, ref l, ref r) => Ok(Value::new(
!t!(r.eval(context)?.is_in(&l.eval(context)?), self)?.to_bool(),
)),
Expr::Op(BinOp::Substraction, ref l, ref r) => {
t!(l.eval(context)?.sub(r.eval(context)?), self)
}
Expr::Op(BinOp::Addition, ref l, ref r) => {
t!(l.eval(context)?.add(r.eval(context)?), self)
}
Expr::Op(BinOp::Multiplication, ref l, ref r) => {
t!(l.eval(context)?.mul(r.eval(context)?), self)
}
Expr::Op(BinOp::Percent, ref l, ref r) => {
t!(l.eval(context)?.percent(r.eval(context)?), self)
}
Expr::Op(BinOp::Division, ref l, ref r) => {
t!(l.eval(context)?.div(r.eval(context)?), self)
}
Expr::Op(BinOp::FloorDivision, ref l, ref r) => {
t!(l.eval(context)?.floor_div(r.eval(context)?), self)
}
Expr::Op(BinOp::Pipe, ref l, ref r) => {
t!(l.eval(context)?.pipe(r.eval(context)?), self)
}
Expr::If(ref cond, ref v1, ref v2) => {
if cond.eval(context)?.to_bool() {
v1.eval(context)
} else {
v2.eval(context)
}
}
Expr::List(ref v) => {
let r = eval_vector!(v, context);
Ok(Value::from(r))
}
Expr::Dict(ref v) => {
let mut r = dict::Dictionary::new();
for s in v.iter() {
t!(r.set_at(s.0.eval(context)?, s.1.eval(context)?), self)?
}
Ok(r)
}
Expr::ListComprehension(ref e, ref clauses) => {
let mut r = Vec::new();
let mut context = context.child("list_comprehension");
for v in eval_comprehension_clause(&mut context, e, clauses.as_slice())? {
r.push(v.clone());
}
Ok(Value::from(r))
}
Expr::DictComprehension((ref k, ref v), ref clauses) => {
let mut r = LinkedHashMap::new();
let tuple = Box::new(Spanned {
span: k.span.merge(v.span),
node: Expr::Tuple(vec![k.clone(), v.clone()]),
});
let mut context = context.child("dict_comprehension");
for e in eval_comprehension_clause(&mut context, &tuple, clauses.as_slice())? {
let k = t!(e.at(Value::from(0)), tuple)?;
let v = t!(e.at(Value::from(1)), tuple)?;
r.insert(k, v);
}
Ok(Value::from(r))
}
}
}
fn set(&self, context: &mut EvaluationContext<T>, new_value: Value) -> EvalResult {
let ok = Ok(Value::new(None));
match self.node {
Expr::Tuple(ref v) | Expr::List(ref v) => {
let l = v.len() as i64;
let nvl = t!(new_value.length(), self)?;
if nvl != l {
Err(EvalException::IncorrectNumberOfValueToUnpack(
self.span, l, nvl,
))
} else {
let mut r = Vec::new();
let mut it1 = v.iter();
let mut it2 = t!(new_value.into_iter(), self)?;
for _ in 0..l {
r.push(it1.next().unwrap().set(context, it2.next().unwrap())?)
}
ok
}
}
Expr::Dot(ref e, ref s) => {
t!(e.eval(context)?.set_attr(&(s.node), new_value), self)?;
ok
}
Expr::Identifier(ref i) => {
t!(context.env.set(&i.node, new_value), self)?;
ok
}
Expr::ArrayIndirection(ref e, ref idx) => {
t!(e.eval(context)?.set_at(idx.eval(context)?, new_value), self)?;
ok
}
_ => Err(EvalException::IncorrectLeftValue(self.span)),
}
}
}
impl<T: FileLoader + 'static> Evaluate<T> for AstStatement {
fn eval(&self, context: &mut EvaluationContext<T>) -> EvalResult {
match self.node {
Statement::Break => Err(EvalException::Break(self.span)),
Statement::Continue => Err(EvalException::Continue(self.span)),
Statement::Pass => Ok(Value::new(None)),
Statement::Return(Some(ref e)) => {
Err(EvalException::Return(self.span, e.eval(context)?))
}
Statement::Return(None) => Err(EvalException::Return(self.span, Value::new(None))),
Statement::Expression(ref e) => e.eval(context),
Statement::Assign(ref lhs, AssignOp::Assign, ref rhs) => {
let rhs = rhs.eval(context)?;
lhs.set(context, rhs)
}
Statement::Assign(ref lhs, AssignOp::Increment, ref rhs) => {
let lhs = lhs.transform(context)?;
let l = lhs.eval(context)?;
let r = rhs.eval(context)?;
lhs.set(context, t!(l.add(r), self)?)
}
Statement::Assign(ref lhs, AssignOp::Decrement, ref rhs) => {
let lhs = lhs.transform(context)?;
let l = lhs.eval(context)?;
let r = rhs.eval(context)?;
lhs.set(context, t!(l.sub(r), self)?)
}
Statement::Assign(ref lhs, AssignOp::Multiplier, ref rhs) => {
let lhs = lhs.transform(context)?;
let l = lhs.eval(context)?;
let r = rhs.eval(context)?;
lhs.set(context, t!(l.mul(r), self)?)
}
Statement::Assign(ref lhs, AssignOp::Divider, ref rhs) => {
let lhs = lhs.transform(context)?;
let l = lhs.eval(context)?;
let r = rhs.eval(context)?;
lhs.set(context, t!(l.div(r), self)?)
}
Statement::Assign(ref lhs, AssignOp::FloorDivider, ref rhs) => {
let lhs = lhs.transform(context)?;
let l = lhs.eval(context)?;
let r = rhs.eval(context)?;
lhs.set(context, t!(l.floor_div(r), self)?)
}
Statement::Assign(ref lhs, AssignOp::Percent, ref rhs) => {
let lhs = lhs.transform(context)?;
let l = lhs.eval(context)?;
let r = rhs.eval(context)?;
lhs.set(context, t!(l.percent(r), self)?)
}
Statement::If(ref cond, ref st) => {
if cond.eval(context)?.to_bool() {
st.eval(context)
} else {
Ok(Value::new(None))
}
}
Statement::IfElse(ref cond, ref st1, ref st2) => {
if cond.eval(context)?.to_bool() {
st1.eval(context)
} else {
st2.eval(context)
}
}
Statement::For(
AstClause {
ref span,
node: Clause::For(ref e1, ref e2),
},
ref st,
) => {
let mut iterable = e2.eval(context)?;
let mut result = Ok(Value::new(None));
iterable.freeze_for_iteration();
for v in t!(iterable.into_iter(), span * span)? {
e1.set(context, v)?;
match st.eval(context) {
Err(EvalException::Break(..)) => break,
Err(EvalException::Continue(..)) => (),
Err(x) => {
result = Err(x);
break;
}
_ => (),
}
}
iterable.unfreeze_for_iteration();
result
}
Statement::For(
AstClause {
span: ref _s,
ref node,
},
..
) => panic!("The parser returned an invalid for clause: {:?}", node),
Statement::Def(ref name, ref params, ref stmts) => {
let mut p = Vec::new();
for ref x in params.iter() {
p.push(match x.node {
Parameter::Normal(ref n) => FunctionParameter::Normal(n.node.clone()),
Parameter::WithDefaultValue(ref n, ref v) => {
FunctionParameter::WithDefaultValue(n.node.clone(), v.eval(context)?)
}
Parameter::Args(ref n) => FunctionParameter::ArgsArray(n.node.clone()),
Parameter::KWArgs(ref n) => FunctionParameter::KWArgsDict(n.node.clone()),
})
}
let f = function::Function::new_def(
name.node.clone(),
context.env.name(),
p,
stmts.clone(),
context.map.clone(),
);
t!(context.env.set(&name.node, f.clone()), name)?;
Ok(f)
}
Statement::Load(ref name, ref v) => {
let loadenv = context.loader.load(name)?;
for &(ref new_name, ref orig_name) in v.iter() {
t!(context.env.import_symbol(&loadenv, &orig_name.node, &new_name.node),
span new_name.span.merge(orig_name.span))?
}
Ok(Value::new(None))
}
Statement::Statements(ref v) => {
let r = eval_vector!(v, context);
match r.len() {
0 => Ok(Value::new(None)),
_ => Ok(r.last().unwrap().clone()),
}
}
}
}
fn transform(
&self,
_context: &mut EvaluationContext<T>,
) -> Result<Box<Evaluate<T>>, EvalException> {
Ok(Box::new(self.clone()))
}
fn set(&self, _context: &mut EvaluationContext<T>, _new_value: Value) -> EvalResult {
Err(EvalException::IncorrectLeftValue(self.span))
}
}
#[doc(hidden)]
pub fn eval_def(
call_stack: &Vec<(String, String)>,
signature: &Vec<FunctionParameter>,
stmts: &AstStatement,
env: Environment,
args: Vec<Value>,
map: Arc<Mutex<CodeMap>>,
) -> ValueResult {
let mut it2 = args.iter();
for s in signature.iter() {
match s {
&FunctionParameter::Normal(ref v)
| &FunctionParameter::WithDefaultValue(ref v, ..)
| &FunctionParameter::ArgsArray(ref v)
| &FunctionParameter::KWArgsDict(ref v) => {
match env.set(v, it2.next().unwrap().clone()) {
Err(x) => return Err(x.into()),
_ => (),
}
}
}
}
let mut ctx = EvaluationContext {
call_stack: call_stack.clone(),
env,
loader: (),
map: map.clone(),
};
match stmts.eval(&mut ctx) {
Err(EvalException::Return(_s, ret)) => Ok(ret),
Err(x) => Err(ValueError::DiagnosedError(x.into())),
Ok(..) => Ok(Value::new(None)),
}
}
pub fn eval_lexer<
T1: Iterator<Item = LexerItem>,
T2: LexerIntoIter<T1>,
T3: FileLoader + 'static,
>(
map: &Arc<Mutex<CodeMap>>,
filename: &str,
content: &str,
build: bool,
lexer: T2,
env: &mut Environment,
file_loader: T3,
) -> Result<Value, Diagnostic> {
let mut context = EvaluationContext::new(env.clone(), file_loader, map.clone());
match parse_lexer(map, filename, content, build, lexer)?.eval(&mut context) {
Ok(v) => Ok(v),
Err(p) => Err(p.into()),
}
}
pub fn eval<T: FileLoader + 'static>(
map: &Arc<Mutex<CodeMap>>,
path: &str,
content: &str,
build: bool,
env: &mut Environment,
file_loader: T,
) -> Result<Value, Diagnostic> {
let mut context = EvaluationContext::new(env.clone(), file_loader, map.clone());
match parse(map, path, content, build)?.eval(&mut context) {
Ok(v) => Ok(v),
Err(p) => Err(p.into()),
}
}
pub fn eval_file<T: FileLoader + 'static>(
map: &Arc<Mutex<CodeMap>>,
path: &str,
build: bool,
env: &mut Environment,
file_loader: T,
) -> Result<Value, Diagnostic> {
let mut context = EvaluationContext::new(env.clone(), file_loader, map.clone());
match parse_file(map, path, build)?.eval(&mut context) {
Ok(v) => Ok(v),
Err(p) => Err(p.into()),
}
}
pub mod interactive;
pub mod simple;
#[cfg(test)]
#[macro_use]
pub mod testutil;
#[cfg(test)]
mod tests;