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
#![allow(non_camel_case_types)]
use middle::def;
use middle::pat_util::{PatIdMap, pat_id_map, pat_is_binding, pat_is_const};
use middle::subst;
use middle::subst::Subst;
use middle::ty;
use middle::typeck::check::demand;
use middle::typeck::check::{check_expr, check_expr_has_type, FnCtxt};
use middle::typeck::check::{instantiate_path, lookup_def};
use middle::typeck::check::{structure_of, valid_range_bounds};
use middle::typeck::infer;
use middle::typeck::require_same_types;
use std::collections::{HashMap, HashSet};
use std::gc::Gc;
use syntax::ast;
use syntax::ast_util;
use syntax::parse::token;
use syntax::codemap::Span;
use syntax::print::pprust;
pub fn check_match(fcx: &FnCtxt,
expr: &ast::Expr,
discrim: &ast::Expr,
arms: &[ast::Arm]) {
let tcx = fcx.ccx.tcx;
let discrim_ty = fcx.infcx().next_ty_var();
check_expr_has_type(fcx, discrim, discrim_ty);for arm in arms.iter() {
let mut pcx = pat_ctxt {
fcx: fcx,
map: pat_id_map(&tcx.def_map, &**arm.pats.get(0)),
};
for p in arm.pats.iter() { check_pat(&mut pcx, &**p, discrim_ty);}
}let mut result_ty = ty::mk_bot();let mut saw_err = ty::type_is_error(discrim_ty);
for arm in arms.iter() {
let mut guard_err = false;
let mut guard_bot = false;
match arm.guard {
Some(ref e) => {
check_expr_has_type(fcx, &**e, ty::mk_bool());
let e_ty = fcx.expr_ty(&**e);
if ty::type_is_error(e_ty) {
guard_err = true;
}
else if ty::type_is_bot(e_ty) {
guard_bot = true;
}
},
None => ()
}
check_expr(fcx, &*arm.body);
let bty = fcx.node_ty(arm.body.id);
saw_err = saw_err || ty::type_is_error(bty);
if guard_err {
fcx.write_error(arm.body.id);
saw_err = true;
}
else if guard_bot {
fcx.write_bot(arm.body.id);
}
result_ty =
infer::common_supertype(
fcx.infcx(),
infer::MatchExpressionArm(expr.span, arm.body.span),
true,result_ty,
bty);
}
if saw_err {
result_ty = ty::mk_err();
} else if ty::type_is_bot(discrim_ty) {
result_ty = ty::mk_bot();
}
fcx.write_ty(expr.id, result_ty);
}
pub struct pat_ctxt<'a> {
pub fcx: &'a FnCtxt<'a>,
pub map: PatIdMap,
}
pub fn check_pat_variant(pcx: &pat_ctxt, pat: &ast::Pat, path: &ast::Path,
subpats: &Option<Vec<Gc<ast::Pat>>>, expected: ty::t) {let fcx = pcx.fcx;
let tcx = pcx.fcx.ccx.tcx;
let arg_types: Vec<ty::t> ;
let kind_name;match *structure_of(pcx.fcx, pat.span, expected) {
ty::ty_enum(expected_def_id, ref expected_substs) => {let v_def = lookup_def(pcx.fcx, pat.span, pat.id);
match v_def.variant_def_ids() {
Some((enm, var)) => {let enum_pty = ty::lookup_item_type(tcx, enm);
instantiate_path(pcx.fcx,
path,
enum_pty,
v_def,
pat.span,
pat.id);let pat_ty = fcx.node_ty(pat.id);
demand::subtype(fcx, pat.span, expected, pat_ty);arg_types = {
let vinfo =
ty::enum_variant_with_id(tcx, enm, var);
if enm == expected_def_id {
vinfo.args.iter()
.map(|t| t.subst(tcx, expected_substs))
.collect()
} else {
vinfo.args.iter()
.map(|_| ty::mk_err())
.collect()
}
};
kind_name = "variant";
}
None => {fcx.infcx().type_error_message_str_with_expected(pat.span,
|expected, actual| {
expected.map_or("".to_string(), |e| {
format!("mismatched types: expected `{}` but found {}",
e, actual)
})},
Some(expected),
"a structure pattern".to_string(),
None);
fcx.write_error(pat.id);
kind_name = "[error]";
arg_types = subpats.clone()
.unwrap_or_default()
.move_iter()
.map(|_| ty::mk_err())
.collect();
}
}
}
ty::ty_struct(struct_def_id, ref expected_substs) => {let s_def = lookup_def(pcx.fcx, pat.span, pat.id);
let s_def_id = s_def.def_id();let ctor_pty = ty::lookup_item_type(tcx, s_def_id);
let struct_pty = if ty::is_fn_ty(ctor_pty.ty) {
ty::Polytype {ty: ty::ty_fn_ret(ctor_pty.ty),
..ctor_pty}
} else {
ctor_pty
};
instantiate_path(pcx.fcx,
path,
struct_pty,
s_def,
pat.span,
pat.id);let pat_ty = fcx.node_ty(pat.id);
demand::subtype(fcx, pat.span, expected, pat_ty);let class_fields = ty::struct_fields(
tcx, struct_def_id, expected_substs);
arg_types = class_fields.iter().map(|field| field.mt.ty).collect();
kind_name = "structure";
}
_ => {fcx.infcx().type_error_message_str_with_expected(pat.span,
|expected, actual| {
expected.map_or("".to_string(),
|e| {
format!("mismatched types: expected `{}` but found {}",
e, actual)
})
},
Some(expected),
"an enum or structure pattern".to_string(),
None);
fcx.write_error(pat.id);
kind_name = "[error]";
arg_types = subpats.clone()
.unwrap_or_default()
.iter()
.map(|_| ty::mk_err())
.collect();
}
}
let arg_len = arg_types.len();let subpats_len;
match *subpats {
None => subpats_len = arg_len,
Some(ref subpats) => subpats_len = subpats.len()
}
let mut error_happened = false;
if arg_len > 0 {if arg_len != subpats_len {
let s = format!("this pattern has {} field{}, \
but the corresponding {} has {} field{}",
subpats_len,
if subpats_len == 1 {""} else {"s"},
kind_name,
arg_len,
if arg_len == 1 {""} else {"s"});
tcx.sess.span_err(pat.span, s.as_slice());
error_happened = true;
}
if !error_happened {
for pats in subpats.iter() {
for (subpat, arg_ty) in pats.iter().zip(arg_types.iter()) {
check_pat(pcx, &**subpat, *arg_ty);
}
}
}
} else if subpats_len > 0 {
tcx.sess.span_err(pat.span,
format!("this pattern has {} field{}, \
but the corresponding {} has no fields",
subpats_len,
if subpats_len == 1 {""} else {"s"},
kind_name).as_slice());
error_happened = true;
}
if error_happened {
for pats in subpats.iter() {
for pat in pats.iter() {
check_pat(pcx, &**pat, ty::mk_err());
}
}
}
}
pub fn check_struct_pat_fields(pcx: &pat_ctxt,
span: Span,
fields: &[ast::FieldPat],
class_fields: Vec<ty::field_ty>,
class_id: ast::DefId,
substitutions: &subst::Substs,
etc: bool) {
let tcx = pcx.fcx.ccx.tcx;let mut field_map = HashMap::new();
for (i, class_field) in class_fields.iter().enumerate() {
field_map.insert(class_field.name, (i, false));
}let mut found_fields = HashSet::new();
for field in fields.iter() {
match field_map.find_mut(&field.ident.name) {
Some(&(_, true)) => {
tcx.sess.span_err(span,
format!("field `{}` bound twice in pattern",
token::get_ident(field.ident)).as_slice());
}
Some(&(index, ref mut used)) => {
*used = true;
let class_field = *class_fields.get(index);
let field_type = ty::lookup_field_type(tcx,
class_id,
class_field.id,
substitutions);
check_pat(pcx, &*field.pat, field_type);
found_fields.insert(index);
}
None => {check_pat(pcx, &*field.pat, ty::mk_err());
tcx.sess.span_err(span,
format!("struct `{}` does not have a field named `{}`",
ty::item_path_str(tcx, class_id),
token::get_ident(field.ident)).as_slice());
}
}
}if !etc {
for (i, field) in class_fields.iter().enumerate() {
if found_fields.contains(&i) {
continue;
}
tcx.sess
.span_err(span,
format!("pattern does not mention field `{}`",
token::get_name(field.name)).as_slice());
}
}
}
pub fn check_struct_pat(pcx: &pat_ctxt, pat_id: ast::NodeId, span: Span,
expected: ty::t, path: &ast::Path,
fields: &[ast::FieldPat], etc: bool,
struct_id: ast::DefId,
substitutions: &subst::Substs) {
let fcx = pcx.fcx;
let tcx = pcx.fcx.ccx.tcx;
let class_fields = ty::lookup_struct_fields(tcx, struct_id);match tcx.def_map.borrow().find(&pat_id) {
Some(&def::DefStruct(supplied_def_id))
if supplied_def_id == struct_id => {}
Some(&def::DefStruct(..)) | Some(&def::DefVariant(..)) => {
let name = pprust::path_to_str(path);
tcx.sess
.span_err(span,
format!("mismatched types: expected `{}` but found \
`{}`",
fcx.infcx().ty_to_str(expected),
name).as_slice());
}
_ => {
tcx.sess.span_bug(span, "resolve didn't write in struct ID");
}
}
check_struct_pat_fields(pcx, span, fields, class_fields, struct_id,
substitutions, etc);
}
pub fn check_struct_like_enum_variant_pat(pcx: &pat_ctxt,
pat_id: ast::NodeId,
span: Span,
expected: ty::t,
path: &ast::Path,
fields: &[ast::FieldPat],
etc: bool,
enum_id: ast::DefId,
substitutions: &subst::Substs) {
let fcx = pcx.fcx;
let tcx = pcx.fcx.ccx.tcx;match tcx.def_map.borrow().find(&pat_id) {
Some(&def::DefVariant(found_enum_id, variant_id, _))
if found_enum_id == enum_id => {let class_fields = ty::lookup_struct_fields(tcx, variant_id);
check_struct_pat_fields(pcx, span, fields, class_fields,
variant_id, substitutions, etc);
}
Some(&def::DefStruct(..)) | Some(&def::DefVariant(..)) => {
let name = pprust::path_to_str(path);
tcx.sess.span_err(span,
format!("mismatched types: expected `{}` but \
found `{}`",
fcx.infcx().ty_to_str(expected),
name).as_slice());
}
_ => {
tcx.sess.span_bug(span, "resolve didn't write in variant");
}
}
}pub fn check_pat(pcx: &pat_ctxt, pat: &ast::Pat, expected: ty::t) {
let fcx = pcx.fcx;
let tcx = pcx.fcx.ccx.tcx;
match pat.node {
ast::PatWild | ast::PatWildMulti => {
fcx.write_ty(pat.id, expected);
}
ast::PatLit(ref lt) => {
check_expr_has_type(fcx, &**lt, expected);
fcx.write_ty(pat.id, fcx.expr_ty(&**lt));
}
ast::PatRange(ref begin, ref end) => {
check_expr_has_type(fcx, &**begin, expected);
check_expr_has_type(fcx, &**end, expected);
let b_ty =
fcx.infcx().resolve_type_vars_if_possible(fcx.expr_ty(&**begin));
let e_ty =
fcx.infcx().resolve_type_vars_if_possible(fcx.expr_ty(&**end));
debug!("pat_range beginning type: {:?}", b_ty);
debug!("pat_range ending type: {:?}", e_ty);
if !require_same_types(
tcx, Some(fcx.infcx()), false, pat.span, b_ty, e_ty,
|| "mismatched types in range".to_string())
{} else if !ty::type_is_numeric(b_ty) && !ty::type_is_char(b_ty) {
tcx.sess.span_err(pat.span,
"only char and numeric types are allowed in range");
} else {
match valid_range_bounds(fcx.ccx, &**begin, &**end) {
Some(false) => {
tcx.sess.span_err(begin.span,
"lower range bound must be less than upper");
},
None => {
tcx.sess.span_err(begin.span,
"mismatched types in range");
},
_ => { },
}
}
fcx.write_ty(pat.id, b_ty);
}
ast::PatEnum(..) |
ast::PatIdent(..) if pat_is_const(&tcx.def_map, pat) => {
let const_did = tcx.def_map.borrow().get_copy(&pat.id).def_id();
let const_pty = ty::lookup_item_type(tcx, const_did);
demand::suptype(fcx, pat.span, expected, const_pty.ty);
fcx.write_ty(pat.id, const_pty.ty);
}
ast::PatIdent(bm, ref name, sub) if pat_is_binding(&tcx.def_map, pat) => {
let typ = fcx.local_ty(pat.span, pat.id);
match bm {
ast::BindByRef(mutbl) => {let region_var =
fcx.infcx().next_region_var(
infer::PatternRegion(pat.span));
let mt = ty::mt {ty: expected, mutbl: mutbl};
let region_ty = ty::mk_rptr(tcx, region_var, mt);
demand::eqtype(fcx, pat.span, region_ty, typ);
}ast::BindByValue(_) => {
demand::eqtype(fcx, pat.span, expected, typ);
}
}
let canon_id = *pcx.map.get(&ast_util::path_to_ident(name));
if canon_id != pat.id {
let ct = fcx.local_ty(pat.span, canon_id);
demand::eqtype(fcx, pat.span, ct, typ);
}
fcx.write_ty(pat.id, typ);
debug!("(checking match) writing type for pat id {}", pat.id);
match sub {
Some(ref p) => check_pat(pcx, &**p, expected),
_ => ()
}
}
ast::PatIdent(_, ref path, _) => {
check_pat_variant(pcx, pat, path, &Some(Vec::new()), expected);
}
ast::PatEnum(ref path, ref subpats) => {
check_pat_variant(pcx, pat, path, subpats, expected);
}
ast::PatStruct(ref path, ref fields, etc) => {let structure = structure_of(fcx, pat.span, expected);
let mut error_happened = false;
match *structure {
ty::ty_struct(cid, ref substs) => {
check_struct_pat(pcx, pat.id, pat.span, expected, path,
fields.as_slice(), etc, cid, substs);
}
ty::ty_enum(eid, ref substs) => {
check_struct_like_enum_variant_pat(pcx,
pat.id,
pat.span,
expected,
path,
fields.as_slice(),
etc,
eid,
substs);
}
_ => {fcx.infcx().type_error_message_str_with_expected(pat.span,
|expected, actual| {
expected.map_or("".to_string(),
|e| {
format!("mismatched types: expected \
`{}` but found {}", e, actual)
})},
Some(expected),
"a structure pattern".to_string(),
None);
match tcx.def_map.borrow().find(&pat.id) {
Some(&def::DefStruct(supplied_def_id)) => {
check_struct_pat(pcx,
pat.id,
pat.span,
ty::mk_err(),
path,
fields.as_slice(),
etc,
supplied_def_id,
&subst::Substs::empty());
}
_ => ()}
error_happened = true;
}
}if error_happened {
fcx.write_error(pat.id);
} else {
fcx.write_ty(pat.id, expected);
}
}
ast::PatTup(ref elts) => {
let s = structure_of(fcx, pat.span, expected);
let e_count = elts.len();
match *s {
ty::ty_tup(ref ex_elts) if e_count == ex_elts.len() => {
for (i, elt) in elts.iter().enumerate() {
check_pat(pcx, &**elt, *ex_elts.get(i));
}
fcx.write_ty(pat.id, expected);
}
_ => {
for elt in elts.iter() {
check_pat(pcx, &**elt, ty::mk_err());
}let type_error = match *s {
ty::ty_tup(ref ex_elts) => {
ty::terr_tuple_size(ty::expected_found {
expected: ex_elts.len(),
found: e_count
})
}
_ => ty::terr_mismatch
};fcx.infcx().type_error_message_str_with_expected(pat.span,
|expected,
actual| {
expected.map_or("".to_string(), |e| {
format!("mismatched types: expected `{}` \
but found {}", e, actual)
}
)},
Some(expected),
"tuple".to_string(),
Some(&type_error));
fcx.write_error(pat.id);
}
}
}
ast::PatBox(ref inner) => {
check_pointer_pat(pcx, Send, &**inner, pat.id, pat.span, expected);
}
ast::PatRegion(ref inner) => {
check_pointer_pat(pcx, Borrowed, &**inner, pat.id, pat.span, expected);
}
ast::PatVec(ref before, slice, ref after) => {
let default_region_var =
fcx.infcx().next_region_var(
infer::PatternRegion(pat.span));
let check_err = |found: String| {
for &elt in before.iter() {
check_pat(pcx, &*elt, ty::mk_err());
}
for elt in slice.iter() {
check_pat(pcx, &**elt, ty::mk_err());
}
for elt in after.iter() {
check_pat(pcx, &**elt, ty::mk_err());
}fcx.infcx().type_error_message_str_with_expected(
pat.span,
|expected, actual| {
expected.map_or("".to_string(),
|e| {
format!("mismatched types: expected `{}` but found {}",
e, actual)
})
},
Some(expected),
found,
None);
fcx.write_error(pat.id);
};
let (elt_type, region_var, mutbl, fixed) = match *structure_of(fcx,
pat.span,
expected) {
ty::ty_vec(mt, Some(fixed)) =>
(mt.ty, default_region_var, ast::MutImmutable, Some(fixed)),
ty::ty_uniq(t) => match ty::get(t).sty {
ty::ty_vec(mt, None) => {
fcx.type_error_message(pat.span,
|_| {
"unique vector patterns are no \
longer supported".to_string()
},
expected,
None);
(mt.ty, default_region_var, ast::MutImmutable, None)
}
_ => {
check_err("a vector pattern".to_string());
return;
}
},
ty::ty_rptr(r, mt) => match ty::get(mt.ty).sty {
ty::ty_vec(mt, None) => (mt.ty, r, mt.mutbl, None),
_ => {
check_err("a vector pattern".to_string());
return;
}
},
_ => {
check_err("a vector pattern".to_string());
return;
}
};
let min_len = before.len() + after.len();
fixed.and_then(|count| match slice {
Some(_) if count < min_len =>
Some(format!("a fixed vector pattern of size at least {}", min_len)),
None if count != min_len =>
Some(format!("a fixed vector pattern of size {}", min_len)),
_ => None
}).map(check_err);
for elt in before.iter() {
check_pat(pcx, &**elt, elt_type);
}
match slice {
Some(ref slice_pat) => {
let slice_ty = ty::mk_slice(tcx,
region_var,
ty::mt {ty: elt_type, mutbl: mutbl});
check_pat(pcx, &**slice_pat, slice_ty);
}
None => ()
}
for elt in after.iter() {
check_pat(pcx, &**elt, elt_type);
}
fcx.write_ty(pat.id, expected);
}
ast::PatMac(_) => tcx.sess.bug("unexpanded macro"),
}
}fn check_pointer_pat(pcx: &pat_ctxt,
pointer_kind: PointerKind,
inner: &ast::Pat,
pat_id: ast::NodeId,
span: Span,
expected: ty::t) {
let fcx = pcx.fcx;
let tcx = fcx.ccx.tcx;
let check_inner: |ty::t| = |e_inner| {
match ty::get(e_inner).sty {
ty::ty_trait(_) if pat_is_binding(&tcx.def_map, inner) => {check_pat(pcx, inner, ty::mk_err());
tcx.sess.span_err(
span,
format!("type `{}` cannot be dereferenced",
fcx.infcx().ty_to_str(expected)).as_slice());
fcx.write_error(pat_id);
}
_ => {
check_pat(pcx, inner, e_inner);
fcx.write_ty(pat_id, expected);
}
}
};
match *structure_of(fcx, span, expected) {
ty::ty_uniq(e_inner) if pointer_kind == Send => {
check_inner(e_inner);
}
ty::ty_rptr(_, e_inner) if pointer_kind == Borrowed => {
check_inner(e_inner.ty);
}
_ => {
check_pat(pcx, inner, ty::mk_err());fcx.infcx().type_error_message_str_with_expected(
span,
|expected, actual| {
expected.map_or("".to_string(), |e| {
format!("mismatched types: expected `{}` but found {}",
e, actual)
})
},
Some(expected),
format!("{} pattern", match pointer_kind {
Send => "a box",
Borrowed => "an `&`-pointer",
}),
None);
fcx.write_error(pat_id);
}
}
}
#[deriving(PartialEq)]
pub enum PointerKind {
Send,
Borrowed,
}