-
Notifications
You must be signed in to change notification settings - Fork 145
/
mod.rs
1962 lines (1801 loc) · 66.5 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
extern crate smallvec;
extern crate typed_arena;
#[macro_export]
#[cfg(test)]
macro_rules! assert_deq {
($left:expr, $right:expr) => ({
match (&$left, &$right) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
panic!("assertion failed: `(left == right)` \
(left: `{}`, right: `{}`)", left_val, right_val)
}
}
}
});
($left:expr, $right:expr, $($arg:tt)+) => ({
match (&($left), &($right)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
panic!("assertion failed: `(left == right)` \
(left: `{}`, right: `{}`): {}", left_val, right_val,
format_args!($($arg)+))
}
}
}
});
}
#[cfg(test)]
#[cfg_attr(rustfmt, rustfmt_skip)]
mod grammar;
pub mod optimize;
pub mod interpreter;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::iter::once;
use std::mem;
use itertools::Itertools;
use self::typed_arena::Arena;
use self::smallvec::SmallVec;
use pretty::{self, DocAllocator};
use base::ast::{self, Literal, SpannedExpr, SpannedPattern, Typed, TypedIdent};
use base::fnv::FnvSet;
use base::pos::{spanned, BytePos, ExpansionId, Span};
use base::resolve::remove_aliases_cow;
use base::symbol::Symbol;
use base::types::{arg_iter, ArcType, PrimitiveEnv, Type, TypeEnv};
#[derive(Clone, Debug, PartialEq)]
pub struct Closure<'a> {
pub pos: BytePos,
pub name: TypedIdent<Symbol>,
pub args: Vec<TypedIdent<Symbol>>,
pub expr: &'a Expr<'a>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Named<'a> {
Recursive(Vec<Closure<'a>>),
Expr(&'a Expr<'a>),
}
#[derive(Clone, Debug, PartialEq)]
pub struct LetBinding<'a> {
pub name: TypedIdent<Symbol>,
pub expr: Named<'a>,
pub span_start: BytePos,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Pattern {
Constructor(TypedIdent<Symbol>, Vec<TypedIdent<Symbol>>),
Record(Vec<(TypedIdent<Symbol>, Option<Symbol>)>),
Ident(TypedIdent<Symbol>),
}
#[derive(Clone, Debug, PartialEq)]
pub struct Alternative<'a> {
pub pattern: Pattern,
pub expr: &'a Expr<'a>,
}
pub type CExpr<'a> = &'a Expr<'a>;
#[derive(Clone, Debug, PartialEq)]
pub enum Expr<'a> {
Const(Literal, Span<BytePos>),
Ident(TypedIdent<Symbol>, Span<BytePos>),
Call(&'a Expr<'a>, &'a [Expr<'a>]),
Data(TypedIdent<Symbol>, &'a [Expr<'a>], BytePos, ExpansionId),
Let(LetBinding<'a>, &'a Expr<'a>),
Match(&'a Expr<'a>, &'a [Alternative<'a>]),
}
impl fmt::Display for Pattern {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let arena = pretty::Arena::new();
let mut s = Vec::new();
self.pretty(&arena).1.render(80, &mut s).unwrap();
write!(f, "{}", ::std::str::from_utf8(&s).expect("utf-8"))
}
}
impl<'a> fmt::Display for Expr<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let arena = pretty::Arena::new();
let mut s = Vec::new();
self.pretty(&arena).1.render(80, &mut s).unwrap();
write!(f, "{}", ::std::str::from_utf8(&s).expect("utf-8"))
}
}
const INDENT: usize = 4;
#[derive(Default)]
#[must_use]
struct Binder<'a> {
bindings: Vec<LetBinding<'a>>,
}
impl<'a> Binder<'a> {
fn bind(&mut self, expr: CExpr<'a>, typ: ArcType) -> Expr<'a> {
let name = TypedIdent {
name: Symbol::from(format!("bind_arg{}", self.bindings.len())),
typ,
};
self.bind_id(name, expr)
}
fn bind_id(&mut self, name: TypedIdent<Symbol>, expr: CExpr<'a>) -> Expr<'a> {
let ident_expr = Expr::Ident(name.clone(), expr.span());
self.bindings.push(LetBinding {
name,
expr: Named::Expr(expr),
span_start: ident_expr.span().start,
});
ident_expr
}
fn into_expr(self, arena: &'a Arena<Expr<'a>>, expr: Expr<'a>) -> Expr<'a> {
self.bindings
.into_iter()
.rev()
.fold(expr, |expr, bind| Expr::Let(bind, arena.alloc(expr)))
}
fn into_expr_ref(self, arena: &'a Arena<Expr<'a>>, expr: &'a Expr<'a>) -> &'a Expr<'a> {
self.bindings
.into_iter()
.rev()
.fold(expr, |expr, bind| arena.alloc(Expr::Let(bind, expr)))
}
}
impl<'a> Expr<'a> {
pub fn pretty(
&'a self,
arena: &'a pretty::Arena<'a>,
) -> pretty::DocBuilder<'a, pretty::Arena<'a>> {
match *self {
Expr::Call(f, args) => chain![arena;
f.pretty(arena),
arena.concat(args.iter().map(|arg| {
arena.space().append(arg.pretty(arena))
}))
].group(),
Expr::Const(ref literal, _) => match *literal {
Literal::Byte(b) => arena.text(format!("b{}", b)),
Literal::Char(c) => arena.text(format!("{:?}", c)),
Literal::Float(f) => arena.text(format!("{}", f)),
Literal::Int(i) => arena.text(format!("{}", i)),
Literal::String(ref s) => arena.text(format!("{:?}", s)),
},
Expr::Data(ref ctor, args, _, _) => match *ctor.typ {
Type::Record(ref record) => chain![arena;
"{",
arena.space(),
arena.concat(record.row_iter().zip(args).map(|(field, arg)| {
chain![arena;
field.name.as_ref(),
" =",
arena.space(),
arg.pretty(arena),
","
]
})),
arena.space(),
"}"
].group(),
_ => chain![arena;
ctor.as_ref(),
arena.concat(args.iter().map(|arg| {
arena.space().append(arg.pretty(arena))
}))
].group(),
},
Expr::Ident(ref id, _) => arena.text(id.as_ref()),
Expr::Let(ref bind, ref expr) => chain![arena;
"let ",
match bind.expr {
Named::Expr(ref expr) => {
chain![arena;
bind.name.as_ref(),
arena.space(),
"=",
arena.space(),
chain![arena;
expr.pretty(arena),
arena.space()
].group()
].group().nest(INDENT)
}
Named::Recursive(ref closures) => {
arena.concat(closures.iter().map(|closure| {
chain![arena;
closure.name.as_ref(),
arena.concat(closure.args.iter()
.map(|arg| arena.space().append(arena.text(arg.as_ref())))),
arena.space(),
"=",
arena.space(),
chain![arena;
closure.expr.pretty(arena),
arena.space()
].nest(INDENT).group()
].group()
}))
}
},
arena.newline(),
expr.pretty(arena)
],
Expr::Match(expr, alts) => match alts.first() {
Some(
alt @ &Alternative {
pattern: Pattern::Record(..),
..
},
) if alts.len() == 1 =>
{
chain![arena;
"match ",
expr.pretty(arena),
" with",
arena.newline(),
chain![arena;
alt.pattern.pretty(arena),
arena.space(),
"->"
].group(),
arena.newline(),
alt.expr.pretty(arena).group()
].group()
}
_ => chain![arena;
"match ",
expr.pretty(arena),
" with",
arena.newline(),
arena.concat(alts.iter().map(|alt| {
chain![arena;
alt.pattern.pretty(arena),
" ->",
arena.space(),
alt.expr.pretty(arena).nest(INDENT).group()
].nest(INDENT)
}).intersperse(arena.newline()))
].group(),
},
}
}
pub fn span(&self) -> Span<BytePos> {
match *self {
Expr::Call(expr, args) => {
let span = expr.span();
Span::with_id(
span.start,
args.last().unwrap().span().end,
span.expansion_id,
)
}
Expr::Const(_, span) => span,
Expr::Data(_, args, span_start, expansion_id) => {
let span_end = args.last().map_or(span_start, |arg| arg.span().end);
Span::with_id(span_start, span_end, expansion_id)
}
Expr::Ident(_, span) => span,
Expr::Let(ref let_binding, ref body) => {
let span_end = body.span();
Span::with_id(let_binding.span_start, span_end.end, span_end.expansion_id)
}
Expr::Match(expr, alts) => {
let span_start = expr.span();
Span::with_id(
span_start.start,
alts.last().unwrap().expr.span().end,
span_start.expansion_id,
)
}
}
}
}
impl Pattern {
pub fn pretty<'a>(
&'a self,
arena: &'a pretty::Arena<'a>,
) -> pretty::DocBuilder<'a, pretty::Arena<'a>> {
match *self {
Pattern::Constructor(ref ctor, ref args) => chain![arena;
ctor.as_ref(),
arena.concat(args.iter().map(|arg| {
arena.space().append(arg.as_ref())
}))
].group(),
Pattern::Ident(ref id) => arena.text(id.as_ref()),
Pattern::Record(ref fields) => chain![arena;
"{",
arena.concat(fields.iter().map(|&(ref field, ref value)| {
chain![arena;
arena.space(),
arena.text(field.as_ref()),
match *value {
Some(ref value) => {
chain![arena;
"=",
arena.space(),
value.as_ref()
]
}
None => arena.nil(),
}
]
}).intersperse(arena.text(","))).nest(INDENT),
arena.space(),
"}"
].group(),
}
}
}
fn is_constructor(s: &Symbol) -> bool {
s.as_ref()
.rsplit('.')
.next()
.unwrap()
.starts_with(char::is_uppercase)
}
mod internal {
use super::{Allocator, Expr};
pub struct CoreExpr {
allocator: Allocator<'static>,
expr: Expr<'static>,
}
impl CoreExpr {
pub fn new(allocator: Allocator<'static>, expr: Expr<'static>) -> CoreExpr {
CoreExpr { allocator, expr }
}
// unsafe: The lifetimes of the returned `Expr` must be bound to `&self`
pub fn expr(&self) -> &Expr {
&self.expr
}
pub fn allocator(&self) -> &Allocator {
unsafe { ::std::mem::transmute(&self.allocator) }
}
}
}
pub use self::internal::CoreExpr;
pub struct Allocator<'a> {
pub arena: Arena<Expr<'a>>,
pub alternative_arena: Arena<Alternative<'a>>,
}
impl<'a> Allocator<'a> {
pub fn new() -> Allocator<'a> {
Allocator {
arena: Arena::new(),
alternative_arena: Arena::new(),
}
}
}
pub fn translate(env: &PrimitiveEnv, expr: &SpannedExpr<Symbol>) -> CoreExpr {
// Here we temporarily forget the lifetime of `translator` so it can be moved into a
// `CoreExpr`. After we have it in `CoreExpr` the expression is then guaranteed to live as
// long as the `CoreExpr` making it safe again
unsafe {
let translator = Translator::new(env);
let core_expr = {
let core_expr = (*(&translator as *const Translator)).translate(expr);
mem::transmute::<Expr, Expr<'static>>(core_expr)
};
CoreExpr::new(
mem::transmute::<Allocator, Allocator<'static>>(translator.allocator),
core_expr,
)
}
}
pub struct Translator<'a, 'e> {
pub allocator: Allocator<'a>,
env: &'e PrimitiveEnv,
dummy_symbol: TypedIdent<Symbol>,
}
impl<'a, 'e> Translator<'a, 'e> {
pub fn new(env: &'e PrimitiveEnv) -> Translator<'a, 'e> {
Translator {
allocator: Allocator::new(),
env: env,
dummy_symbol: TypedIdent::new(Symbol::from("")),
}
}
pub fn translate_alloc(&'a self, expr: &SpannedExpr<Symbol>) -> &'a Expr<'a> {
self.allocator.arena.alloc(self.translate(expr))
}
pub fn translate(&'a self, expr: &SpannedExpr<Symbol>) -> Expr<'a> {
let mut current = expr;
let mut lets = Vec::new();
while let ast::Expr::LetBindings(ref binds, ref tail) = current.value {
lets.push((current.span.start, binds));
current = tail;
}
let tail = self.translate_(current);
lets.iter()
.rev()
.fold(tail, |result, &(span_start, ref binds)| {
self.translate_let(binds, result, span_start)
})
}
fn translate_(&'a self, expr: &SpannedExpr<Symbol>) -> Expr<'a> {
let arena = &self.allocator.arena;
match expr.value {
ast::Expr::App(ref function, ref args) => {
let new_args: SmallVec<[_; 16]> =
args.iter().map(|arg| self.translate(arg)).collect();
match function.value {
ast::Expr::Ident(ref id) if is_constructor(&id.name) => {
let typ = expr.env_type_of(&self.env);
self.new_data_constructor(typ, id, new_args, expr.span)
}
_ => Expr::Call(
self.translate_alloc(function),
arena.alloc_extend(new_args.into_iter()),
),
}
}
ast::Expr::Array(ref array) => {
let exprs: SmallVec<[_; 16]> = array
.exprs
.iter()
.map(|expr| self.translate(expr))
.collect();
Expr::Data(
TypedIdent {
name: self.dummy_symbol.name.clone(),
typ: array.typ.clone(),
},
arena.alloc_extend(exprs.into_iter()),
expr.span.start,
expr.span.expansion_id,
)
}
ast::Expr::Block(ref exprs) => {
let (last, prefix) = exprs.split_last().unwrap();
let result = self.translate(last);
prefix.iter().rev().fold(result, |result, expr| {
Expr::Let(
LetBinding {
name: self.dummy_symbol.clone(),
expr: Named::Expr(self.translate_alloc(expr)),
span_start: expr.span.start,
},
arena.alloc(result),
)
})
}
ast::Expr::Ident(ref id) => if is_constructor(&id.name) {
self.new_data_constructor(id.typ.clone(), id, SmallVec::new(), expr.span)
} else {
Expr::Ident(id.clone(), expr.span)
},
ast::Expr::IfElse(ref pred, ref if_true, ref if_false) => {
let alts: SmallVec<[_; 2]> = collect![
Alternative {
pattern: Pattern::Constructor(self.bool_constructor(true), vec![]),
expr: self.translate_alloc(if_true),
},
Alternative {
pattern: Pattern::Constructor(self.bool_constructor(false), vec![]),
expr: self.translate_alloc(if_false),
},
];
Expr::Match(
self.translate_alloc(pred),
self.allocator
.alternative_arena
.alloc_extend(alts.into_iter()),
)
}
ast::Expr::Infix(ref l, ref op, ref r) => {
let args: SmallVec<[_; 2]> = collect![self.translate(l), self.translate(r)];
Expr::Call(
arena.alloc(Expr::Ident(op.value.clone(), op.span)),
arena.alloc_extend(args.into_iter()),
)
}
ast::Expr::Lambda(ref lambda) => self.new_lambda(
expr.span.start,
lambda.id.clone(),
lambda.args.iter().map(|arg| arg.value.clone()).collect(),
self.translate_alloc(&lambda.body),
expr.span,
),
ast::Expr::LetBindings(ref binds, ref tail) => {
self.translate_let(binds, self.translate(tail), expr.span.start)
}
ast::Expr::Literal(ref literal) => Expr::Const(literal.clone(), expr.span),
ast::Expr::Match(ref expr, ref alts) => {
let expr = self.translate_alloc(expr);
let alts: Vec<_> = alts.iter()
.map(|alt| {
Equation {
patterns: vec![&alt.pattern],
result: self.translate_alloc(&alt.expr),
}
})
.collect();
PatternTranslator(self).translate_top(expr, &alts).clone()
}
// expr.projection
// =>
// match expr with
// | { projection } -> projection
ast::Expr::Projection(ref projected_expr, ref projection, ref projected_type) => {
let projected_expr = self.translate_alloc(projected_expr);
self.project_expr(expr.span, projected_expr, projection, projected_type)
}
ast::Expr::Record {
ref typ,
ref exprs,
ref base,
..
} => {
let mut binder = Binder::default();
// If `base` exists and is non-trivial we need to introduce bindings for each
// value to ensure that the expressions are evaluated in the correct order
let needs_bindings = base.as_ref().map_or(false, |base| match base.value {
ast::Expr::Ident(_) => false,
_ => true,
});
let mut last_span = expr.span;
let mut args = SmallVec::<[_; 16]>::new();
args.extend(exprs.iter().map(|field| {
let expr = match field.value {
Some(ref expr) => {
last_span = expr.span;
self.translate(expr)
}
None => Expr::Ident(TypedIdent::new(field.name.value.clone()), last_span),
};
if needs_bindings {
let typ = expr.env_type_of(&self.env);
binder.bind(arena.alloc(expr), typ)
} else {
expr
}
}));
let base_binding = base.as_ref().map(|base_expr| {
let core_base = self.translate_alloc(base_expr);
let typ = remove_aliases_cow(&self.env, &base_expr.env_type_of(&self.env))
.into_owned();
let core_base = if needs_bindings {
&*arena.alloc(binder.bind(core_base, base_expr.env_type_of(&self.env)))
} else {
core_base
};
(core_base, typ)
});
let defined_fields: FnvSet<&str> = exprs
.iter()
.map(|field| field.name.value.declared_name())
.collect();
args.extend(base_binding.as_ref().into_iter().flat_map(
|&(base_ident_expr, ref base_type)| {
base_type
.row_iter()
// Only load fields that aren't named in this record constructor
.filter(|field| !defined_fields.contains(field.name.declared_name()))
.map(move |field| {
self.project_expr(
base_ident_expr.span(),
base_ident_expr,
&field.name,
&field.typ
)
})
},
));
let record_constructor = Expr::Data(
TypedIdent {
name: self.dummy_symbol.name.clone(),
typ: typ.clone(),
},
arena.alloc_extend(args),
expr.span.start,
expr.span.expansion_id,
);
binder.into_expr(arena, record_constructor)
}
ast::Expr::Tuple { ref elems, .. } => if elems.len() == 1 {
self.translate(&elems[0])
} else {
let args: SmallVec<[_; 16]> =
elems.iter().map(|expr| self.translate(expr)).collect();
Expr::Data(
TypedIdent {
name: self.dummy_symbol.name.clone(),
typ: expr.env_type_of(&self.env),
},
arena.alloc_extend(args.into_iter()),
expr.span.start,
expr.span.expansion_id,
)
},
ast::Expr::TypeBindings(_, ref expr) => self.translate(expr),
ast::Expr::Do(ast::Do {
ref id,
ref bound,
ref body,
ref flat_map_id,
}) => {
let flat_map_id = flat_map_id
.as_ref()
.unwrap_or_else(|| ice!("flat_map_id must be set when translating to core"));
let mut binder = Binder::default();
let bound_ident =
binder.bind(self.translate_alloc(bound), bound.env_type_of(&self.env));
let lambda = self.new_lambda(
expr.span.start,
id.value.clone(),
vec![id.value.clone()],
self.translate_alloc(body),
body.span,
);
binder.into_expr(
arena,
Expr::Call(
arena.alloc(Expr::Ident(flat_map_id.clone(), expr.span)),
arena.alloc_extend(Some(lambda).into_iter().chain(Some(bound_ident))),
),
)
}
ast::Expr::Error(_) => ice!("ICE: Error expression found in the compiler"),
}
}
fn project_expr(
&'a self,
span: Span<BytePos>,
projected_expr: CExpr<'a>,
projection: &Symbol,
projected_type: &ArcType,
) -> Expr<'a> {
let arena = &self.allocator.arena;
let alt = Alternative {
pattern: Pattern::Record(vec![
(
TypedIdent {
name: projection.clone(),
typ: projected_type.clone(),
},
None,
),
]),
expr: arena.alloc(Expr::Ident(
TypedIdent {
name: projection.clone(),
typ: projected_type.clone(),
},
span,
)),
};
Expr::Match(
projected_expr,
self.allocator.alternative_arena.alloc_extend(once(alt)),
)
}
fn translate_let(
&'a self,
binds: &[ast::ValueBinding<Symbol>],
tail: Expr<'a>,
span_start: BytePos,
) -> Expr<'a> {
let arena = &self.allocator.arena;
let is_recursive = binds.iter().all(|bind| bind.args.len() > 0);
if is_recursive {
let closures = binds
.iter()
.map(|bind| {
Closure {
pos: bind.name.span.start,
name: match bind.name.value {
ast::Pattern::Ident(ref id) => id.clone(),
_ => unreachable!(),
},
args: bind.args.iter().map(|arg| arg.value.clone()).collect(),
expr: self.translate_alloc(&bind.expr),
}
})
.collect();
Expr::Let(
LetBinding {
// TODO
name: self.dummy_symbol.clone(),
expr: Named::Recursive(closures),
span_start: span_start,
},
arena.alloc(tail),
)
} else {
binds.iter().rev().fold(tail, |tail, bind| {
let name = match bind.name.value {
ast::Pattern::Ident(ref id) => id.clone(),
_ => {
let bind_expr = self.translate_alloc(&bind.expr);
let tail = &*arena.alloc(tail);
return PatternTranslator(self).translate_top(
bind_expr,
&[
Equation {
patterns: vec![&bind.name],
result: tail,
},
],
);
}
};
let named = if bind.args.is_empty() {
Named::Expr(self.translate_alloc(&bind.expr))
} else {
Named::Recursive(vec![
Closure {
pos: bind.name.span.start,
name: name.clone(),
args: bind.args.iter().map(|arg| arg.value.clone()).collect(),
expr: self.translate_alloc(&bind.expr),
},
])
};
Expr::Let(
LetBinding {
name: name,
expr: named,
span_start: bind.expr.span.start,
},
arena.alloc(tail),
)
})
}
}
fn bool_constructor(&self, variant: bool) -> TypedIdent<Symbol> {
let b = self.env.get_bool();
match **b {
Type::Alias(ref alias) => match **alias.typ() {
Type::Variant(ref variants) => TypedIdent {
name: variants
.row_iter()
.nth(variant as usize)
.unwrap()
.name
.clone(),
typ: b.clone(),
},
_ => ice!(),
},
_ => ice!(),
}
}
fn new_data_constructor(
&'a self,
expr_type: ArcType,
id: &TypedIdent<Symbol>,
mut new_args: SmallVec<[Expr<'a>; 16]>,
span: Span<BytePos>,
) -> Expr<'a> {
let arena = &self.allocator.arena;
let typ = expr_type;
let unapplied_args: Vec<_>;
// If the constructor is not fully applied we retrieve the type of the data
// by iterating through the arguments. If it is fully applied the arg_iter
// has no effect and `typ` itself will be used
let data_type;
{
let mut args = arg_iter(typ.remove_forall());
unapplied_args = args.by_ref()
.enumerate()
.map(|(i, arg)| {
TypedIdent {
name: Symbol::from(format!("#{}", i)),
typ: arg.clone(),
}
})
.collect();
data_type = args.typ.clone();
}
new_args.extend(
unapplied_args
.iter()
.map(|arg| Expr::Ident(arg.clone(), span)),
);
let data = Expr::Data(
TypedIdent {
name: id.name.clone(),
typ: data_type,
},
arena.alloc_extend(new_args.into_iter()),
span.start,
span.expansion_id,
);
if unapplied_args.is_empty() {
data
} else {
self.new_lambda(
span.start,
TypedIdent {
name: Symbol::from(format!("${}", id.name)),
typ: typ,
},
unapplied_args,
arena.alloc(data),
span,
)
}
}
fn new_lambda(
&'a self,
pos: BytePos,
name: TypedIdent<Symbol>,
args: Vec<TypedIdent<Symbol>>,
body: &'a Expr<'a>,
span: Span<BytePos>,
) -> Expr<'a> {
let arena = &self.allocator.arena;
Expr::Let(
LetBinding {
name: name.clone(),
expr: Named::Recursive(vec![
Closure {
pos,
name: name.clone(),
args: args,
expr: body,
},
]),
span_start: span.start,
},
arena.alloc(Expr::Ident(name, span)),
)
}
}
impl<'a> Typed for Expr<'a> {
type Ident = Symbol;
fn env_type_of(&self, env: &TypeEnv) -> ArcType<Self::Ident> {
match *self {
Expr::Call(expr, args) => get_return_type(env, &expr.env_type_of(env), args.len()),
Expr::Const(ref literal, _) => literal.env_type_of(env),
Expr::Data(ref id, _, _, _) => id.typ.clone(),
Expr::Ident(ref id, _) => id.typ.clone(),
Expr::Let(_, ref body) => body.env_type_of(env),
Expr::Match(_, alts) => alts[0].expr.env_type_of(env),
}
}
}
fn get_return_type(env: &TypeEnv, alias_type: &ArcType, arg_count: usize) -> ArcType {
if arg_count == 0 {
return alias_type.clone();
}
let function_type = remove_aliases_cow(env, alias_type);
let ret = function_type
.remove_forall()
.as_function()
.map(|t| Cow::Borrowed(t.1))
.unwrap_or_else(|| {
warn!(
"Call expression with a non function type `{}`",
function_type
);
Cow::Owned(Type::hole())
});
get_return_type(env, &ret, arg_count - 1)
}
pub struct PatternTranslator<'a, 'e: 'a>(&'a Translator<'a, 'e>);
#[derive(Clone, PartialEq, Debug)]
struct Equation<'a, 'p> {
patterns: Vec<&'p SpannedPattern<Symbol>>,
result: &'a Expr<'a>,
}
impl<'a, 'p> fmt::Display for Equation<'a, 'p> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"[({:?},{})]",
self.patterns.iter().format(", "),
self.result
)
}
}
#[derive(PartialEq)]
enum CType {
Constructor,
Record,
Variable,
}
use self::optimize::*;
struct ReplaceVariables<'a> {
replacements: HashMap<Symbol, Symbol>,
allocator: &'a Allocator<'a>,
}
impl<'a> Visitor<'a, 'a> for ReplaceVariables<'a> {
type Producer = SameLifetime<'a>;
fn visit_expr(&mut self, expr: &'a Expr<'a>) -> Option<&'a Expr<'a>> {
match *expr {
Expr::Ident(ref id, span) => self.replacements.get(&id.name).map(|new_name| {
&*self.allocator.arena.alloc(Expr::Ident(
TypedIdent {
name: new_name.clone(),
typ: id.typ.clone(),
},
span,
))
}),
_ => walk_expr_alloc(self, expr),
}
}
fn detach_allocator(&self) -> Option<&'a Allocator<'a>> {
Some(self.allocator)
}
}
/// `PatternTranslator` translated nested (AST) patterns into non-nested (core) patterns.
///
/// It does this this by looking at each nested pattern as part of an `Equation` to be solved.
/// Each step of the algorithm looks at the first pattern in each equation, translates it into a
/// a non-nested match and then for each alternative in this created `match` it recursively calls
/// itself with the rest of the equations plus any nested patterns from the pattern that was
/// just translated to the non-nested form.
///
/// For a more comprehensive explanation the following links are recommended
///
/// The implementation of Hob
/// http://marijnhaverbeke.nl/hob/saga/pattern_matching.html
///
/// Derivation of a Pattern-Matching Compiler
/// Geoff Barrett and Philip Wadler
/// Oxford University Computing Laboratory, Programming Research Group