-
Notifications
You must be signed in to change notification settings - Fork 12.1k
/
method.rs
1712 lines (1509 loc) · 65.5 KB
/
method.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
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
# Method lookup
Method lookup can be rather complex due to the interaction of a number
of factors, such as self types, autoderef, trait lookup, etc. The
algorithm is divided into two parts: candidate collection and
candidate selection.
## Candidate collection
A `Candidate` is a method item that might plausibly be the method
being invoked. Candidates are grouped into two kinds, inherent and
extension. Inherent candidates are those that are derived from the
type of the receiver itself. So, if you have a receiver of some
nominal type `Foo` (e.g., a struct), any methods defined within an
impl like `impl Foo` are inherent methods. Nothing needs to be
imported to use an inherent method, they are associated with the type
itself (note that inherent impls can only be defined in the same
module as the type itself).
Inherent candidates are not always derived from impls. If you have a
trait instance, such as a value of type `Box<ToString>`, then the trait
methods (`to_string()`, in this case) are inherently associated with it.
Another case is type parameters, in which case the methods of their
bounds are inherent.
Extension candidates are derived from imported traits. If I have the
trait `ToString` imported, and I call `to_string()` on a value of type `T`,
then we will go off to find out whether there is an impl of `ToString`
for `T`. These kinds of method calls are called "extension methods".
They can be defined in any module, not only the one that defined `T`.
Furthermore, you must import the trait to call such a method.
For better or worse, we currently give weight to inherent methods over
extension methods during candidate selection (below).
## Candidate selection
Once we know the set of candidates, we can go off and try to select
which one is actually being called. We do this by taking the type of
the receiver, let's call it R, and checking whether it matches against
the expected receiver type for each of the collected candidates. We
first check for inherent candidates and see whether we get exactly one
match (zero means keep searching, more than one is an error). If so,
we return that as the candidate. Otherwise we search the extension
candidates in the same way.
If find no matching candidate at all, we proceed to auto-deref the
receiver type and search again. We keep doing that until we cannot
auto-deref any longer. At each step, we also check for candidates
based on "autoptr", which if the current type is `T`, checks for `&mut
T`, `&const T`, and `&T` receivers. Finally, at the very end, we will
also try autoslice, which converts `~[]` to `&[]` (there is no point
at trying autoslice earlier, because no autoderefable type is also
sliceable).
## Why two phases?
You might wonder why we first collect the candidates and then select.
Both the inherent candidate collection and the candidate selection
proceed by progressively deref'ing the receiver type, after all. The
answer is that two phases are needed to elegantly deal with explicit
self. After all, if there is an impl for the type `Foo`, it can
define a method with the type `Box<self>`, which means that it expects a
receiver of type `Box<Foo>`. If we have a receiver of type `Box<Foo>`, but we
waited to search for that impl until we have deref'd the `Box` away and
obtained the type `Foo`, we would never match this method.
*/
use middle::subst;
use middle::subst::{Subst, SelfSpace};
use middle::traits;
use middle::ty::*;
use middle::ty;
use middle::typeck::astconv::AstConv;
use middle::typeck::check::{FnCtxt, NoPreference, PreferMutLvalue};
use middle::typeck::check::{impl_self_ty};
use middle::typeck::check::vtable::select_new_fcx_obligations;
use middle::typeck::check;
use middle::typeck::infer;
use middle::typeck::{MethodCall, MethodCallee};
use middle::typeck::{MethodOrigin, MethodParam, MethodTypeParam};
use middle::typeck::{MethodStatic, MethodStaticUnboxedClosure, MethodObject, MethodTraitObject};
use middle::typeck::check::regionmanip::replace_late_bound_regions;
use middle::typeck::TypeAndSubsts;
use middle::ty_fold::TypeFoldable;
use util::common::indenter;
use util::ppaux;
use util::ppaux::{Repr, UserString};
use std::collections::HashSet;
use std::rc::Rc;
use syntax::ast::{DefId, MutImmutable, MutMutable};
use syntax::ast;
use syntax::codemap::Span;
#[deriving(PartialEq)]
pub enum CheckTraitsFlag {
CheckTraitsOnly,
CheckTraitsAndInherentMethods,
}
#[deriving(PartialEq)]
pub enum AutoderefReceiverFlag {
AutoderefReceiver,
DontAutoderefReceiver,
}
pub enum MethodError {
// Did not find an applicable method, but we did find various
// static methods that may apply.
NoMatch(Vec<CandidateSource>),
// Multiple methods might apply.
Ambiguity(Vec<CandidateSource>),
}
pub type MethodResult = Result<MethodCallee, MethodError>;
pub fn lookup<'a, 'tcx>(
fcx: &'a FnCtxt<'a, 'tcx>,
// In a call `a.b::<X, Y, ...>(...)`:
expr: &ast::Expr, // The expression `a.b(...)`.
self_expr: &'a ast::Expr, // The expression `a`.
m_name: ast::Name, // The name `b`.
self_ty: ty::t, // The type of `a`.
supplied_tps: &'a [ty::t], // The list of types X, Y, ... .
deref_args: check::DerefArgs, // Whether we autopointer first.
check_traits: CheckTraitsFlag, // Whether we check traits only.
autoderef_receiver: AutoderefReceiverFlag)
-> MethodResult
{
let mut lcx = LookupContext {
fcx: fcx,
span: expr.span,
self_expr: Some(self_expr),
m_name: m_name,
supplied_tps: supplied_tps,
impl_dups: HashSet::new(),
inherent_candidates: Vec::new(),
extension_candidates: Vec::new(),
static_candidates: Vec::new(),
deref_args: deref_args,
check_traits: check_traits,
autoderef_receiver: autoderef_receiver,
};
debug!("method lookup(self_ty={}, expr={}, self_expr={})",
self_ty.repr(fcx.tcx()), expr.repr(fcx.tcx()),
self_expr.repr(fcx.tcx()));
debug!("searching inherent candidates");
lcx.push_inherent_candidates(self_ty);
debug!("searching extension candidates");
lcx.push_bound_candidates(self_ty, None);
lcx.push_extension_candidates(expr.id);
lcx.search(self_ty)
}
pub fn lookup_in_trait<'a, 'tcx>(
fcx: &'a FnCtxt<'a, 'tcx>,
// In a call `a.b::<X, Y, ...>(...)`:
span: Span, // The expression `a.b(...)`'s span.
self_expr: Option<&'a ast::Expr>, // The expression `a`, if available.
m_name: ast::Name, // The name `b`.
trait_did: DefId, // The trait to limit the lookup to.
self_ty: ty::t, // The type of `a`.
supplied_tps: &'a [ty::t]) // The list of types X, Y, ... .
-> Option<MethodCallee>
{
let mut lcx = LookupContext {
fcx: fcx,
span: span,
self_expr: self_expr,
m_name: m_name,
supplied_tps: supplied_tps,
impl_dups: HashSet::new(),
inherent_candidates: Vec::new(),
extension_candidates: Vec::new(),
static_candidates: Vec::new(),
deref_args: check::DoDerefArgs,
check_traits: CheckTraitsOnly,
autoderef_receiver: DontAutoderefReceiver,
};
debug!("method lookup_in_trait(self_ty={}, self_expr={}, m_name={}, trait_did={})",
self_ty.repr(fcx.tcx()),
self_expr.repr(fcx.tcx()),
m_name.repr(fcx.tcx()),
trait_did.repr(fcx.tcx()));
lcx.push_bound_candidates(self_ty, Some(trait_did));
lcx.push_extension_candidate(trait_did);
// when doing a trait search, ambiguity can't really happen except
// as part of the trait-lookup in general
match lcx.search(self_ty) {
Ok(callee) => Some(callee),
Err(_) => None
}
}
pub fn report_error(fcx: &FnCtxt,
span: Span,
rcvr_ty: ty::t,
method_name: ast::Name,
error: MethodError)
{
match error {
NoMatch(static_sources) => {
let cx = fcx.tcx();
let method_ustring = method_name.user_string(cx);
// True if the type is a struct and contains a field with
// the same name as the not-found method
let is_field = match ty::get(rcvr_ty).sty {
ty_struct(did, _) =>
ty::lookup_struct_fields(cx, did)
.iter()
.any(|f| f.name.user_string(cx) == method_ustring),
_ => false
};
fcx.type_error_message(
span,
|actual| {
format!("type `{}` does not implement any \
method in scope named `{}`",
actual,
method_ustring)
},
rcvr_ty,
None);
// If the method has the name of a field, give a help note
if is_field {
cx.sess.span_note(span,
format!("use `(s.{0})(...)` if you meant to call the \
function stored in the `{0}` field", method_ustring).as_slice());
}
if static_sources.len() > 0 {
fcx.tcx().sess.fileline_note(
span,
"found defined static methods, maybe a `self` is missing?");
report_candidates(fcx, span, method_name, static_sources);
}
}
Ambiguity(sources) => {
span_err!(fcx.sess(), span, E0034,
"multiple applicable methods in scope");
report_candidates(fcx, span, method_name, sources);
}
}
fn report_candidates(fcx: &FnCtxt,
span: Span,
method_name: ast::Name,
mut sources: Vec<CandidateSource>) {
sources.sort();
sources.dedup();
for (idx, source) in sources.iter().enumerate() {
match *source {
ImplSource(impl_did) => {
// Provide the best span we can. Use the method, if local to crate, else
// the impl, if local to crate (method may be defaulted), else the call site.
let method = impl_method(fcx.tcx(), impl_did, method_name).unwrap();
let impl_span = fcx.tcx().map.def_id_span(impl_did, span);
let method_span = fcx.tcx().map.def_id_span(method.def_id, impl_span);
let impl_ty = impl_self_ty(fcx, span, impl_did).ty;
let insertion = match impl_trait_ref(fcx.tcx(), impl_did) {
None => format!(""),
Some(trait_ref) => format!(" of the trait `{}`",
ty::item_path_str(fcx.tcx(),
trait_ref.def_id)),
};
span_note!(fcx.sess(), method_span,
"candidate #{} is defined in an impl{} for the type `{}`",
idx + 1u,
insertion,
impl_ty.user_string(fcx.tcx()));
}
TraitSource(trait_did) => {
let (_, method) = trait_method(fcx.tcx(), trait_did, method_name).unwrap();
let method_span = fcx.tcx().map.def_id_span(method.def_id, span);
span_note!(fcx.sess(), method_span,
"candidate #{} is defined in the trait `{}`",
idx + 1u,
ty::item_path_str(fcx.tcx(), trait_did));
}
}
}
}
}
// Determine the index of a method in the list of all methods belonging
// to a trait and its supertraits.
fn get_method_index(tcx: &ty::ctxt,
trait_ref: &TraitRef,
subtrait: Rc<TraitRef>,
n_method: uint) -> uint {
// We need to figure the "real index" of the method in a
// listing of all the methods of an object. We do this by
// iterating down the supertraits of the object's trait until
// we find the trait the method came from, counting up the
// methods from them.
let mut method_count = 0;
ty::each_bound_trait_and_supertraits(tcx, &[subtrait], |bound_ref| {
if bound_ref.def_id == trait_ref.def_id {
false
} else {
let trait_items = ty::trait_items(tcx, bound_ref.def_id);
for trait_item in trait_items.iter() {
match *trait_item {
ty::MethodTraitItem(_) => method_count += 1,
ty::TypeTraitItem(_) => {}
}
}
true
}
});
method_count + n_method
}
struct LookupContext<'a, 'tcx: 'a> {
fcx: &'a FnCtxt<'a, 'tcx>,
span: Span,
// The receiver to the method call. Only `None` in the case of
// an overloaded autoderef, where the receiver may be an intermediate
// state like "the expression `x` when it has been autoderef'd
// twice already".
self_expr: Option<&'a ast::Expr>,
m_name: ast::Name,
supplied_tps: &'a [ty::t],
impl_dups: HashSet<DefId>,
inherent_candidates: Vec<Candidate>,
extension_candidates: Vec<ExtensionCandidate>,
static_candidates: Vec<CandidateSource>,
deref_args: check::DerefArgs,
check_traits: CheckTraitsFlag,
autoderef_receiver: AutoderefReceiverFlag,
}
// A method that the user may be trying to invoke. Initially, we
// construct candidates only for inherent methods; for extension
// traits, we use an ExtensionCandidate.
#[deriving(Clone)]
struct Candidate {
xform_self_ty: ty::t,
rcvr_substs: subst::Substs,
method_ty: Rc<ty::Method>,
origin: MethodOrigin,
}
// A variation on a candidate that just stores the data needed
// extension trait matching. Once we pick the trait that matches,
// we'll construct a normal candidate from that. There is no deep
// reason for this, the code just worked out a bit cleaner.
struct ExtensionCandidate {
obligation: traits::Obligation,
xform_self_ty: ty::t,
method_ty: Rc<ty::Method>,
method_num: uint,
}
// A pared down enum describing just the places from which a method
// candidate can arise. Used for error reporting only.
#[deriving(PartialOrd, Ord, PartialEq, Eq)]
pub enum CandidateSource {
ImplSource(ast::DefId),
TraitSource(/* trait id */ ast::DefId),
}
impl<'a, 'tcx> LookupContext<'a, 'tcx> {
fn search(self, self_ty: ty::t) -> MethodResult {
let span = self.self_expr.map_or(self.span, |e| e.span);
let self_expr_id = self.self_expr.map(|e| e.id);
let (_, _, result) =
check::autoderef(
self.fcx, span, self_ty, self_expr_id, NoPreference,
|self_ty, autoderefs| self.search_step(self_ty, autoderefs));
match result {
Some(Some(Ok(result))) => {
self.fixup_derefs_on_method_receiver_if_necessary(&result);
Ok(result)
}
Some(Some(Err(err))) => {
Err(err)
}
None | Some(None) => {
Err(NoMatch(self.static_candidates))
}
}
}
fn search_step(&self,
self_ty: ty::t,
autoderefs: uint)
-> Option<Option<MethodResult>>
{
// Oh my, what a return type!
//
// Returning:
// - `None` => autoderef more, keep searching
// - `Some(None)` => stop searching, found nothing
// - `Some(Some(_))` => stop searching, found either callee/error
// - `Some(Some(Ok(_)))` => found a callee
// - `Some(Some(Err(_)))` => found an error (ambiguity, etc)
debug!("search_step: self_ty={} autoderefs={}",
self.ty_to_string(self_ty), autoderefs);
match self.deref_args {
check::DontDerefArgs => {
match self.search_for_autoderefd_method(self_ty, autoderefs) {
Some(result) => return Some(Some(result)),
None => {}
}
match self.search_for_autoptrd_method(self_ty, autoderefs) {
Some(result) => return Some(Some(result)),
None => {}
}
}
check::DoDerefArgs => {
match self.search_for_autoptrd_method(self_ty, autoderefs) {
Some(result) => return Some(Some(result)),
None => {}
}
match self.search_for_autoderefd_method(self_ty, autoderefs) {
Some(result) => return Some(Some(result)),
None => {}
}
}
}
// If we are searching for an overloaded deref, no
// need to try coercing a `~[T]` to an `&[T]` and
// searching for an overloaded deref on *that*.
if !self.is_overloaded_deref() {
match self.search_for_autofatptrd_method(self_ty, autoderefs) {
Some(result) => return Some(Some(result)),
None => {}
}
}
// Don't autoderef if we aren't supposed to.
if self.autoderef_receiver == DontAutoderefReceiver {
Some(None)
} else {
None
}
}
fn is_overloaded_deref(&self) -> bool {
self.self_expr.is_none()
}
///////////////////////////////////////////////////////////////////////////
// Candidate collection (see comment at start of file)
fn push_inherent_candidates(&mut self, self_ty: ty::t) {
/*!
* Collect all inherent candidates into
* `self.inherent_candidates`. See comment at the start of
* the file. To find the inherent candidates, we repeatedly
* deref the self-ty to find the "base-type". So, for
* example, if the receiver is Box<Box<C>> where `C` is a struct type,
* we'll want to find the inherent impls for `C`.
*/
let span = self.self_expr.map_or(self.span, |e| e.span);
check::autoderef(self.fcx, span, self_ty, None, NoPreference, |self_ty, _| {
match get(self_ty).sty {
ty_trait(box TyTrait { def_id, ref substs, bounds, .. }) => {
self.push_inherent_candidates_from_object(self_ty, def_id, substs, bounds);
self.push_inherent_impl_candidates_for_type(def_id);
}
ty_enum(did, _) |
ty_struct(did, _) |
ty_unboxed_closure(did, _, _) => {
if self.check_traits == CheckTraitsAndInherentMethods {
self.push_inherent_impl_candidates_for_type(did);
}
}
_ => { /* No inherent methods in these types */ }
}
// Don't autoderef if we aren't supposed to.
if self.autoderef_receiver == DontAutoderefReceiver {
Some(())
} else {
None
}
});
}
fn push_bound_candidates(&mut self, self_ty: ty::t, restrict_to: Option<DefId>) {
let span = self.self_expr.map_or(self.span, |e| e.span);
check::autoderef(self.fcx, span, self_ty, None, NoPreference, |self_ty, _| {
match get(self_ty).sty {
ty_param(p) => {
self.push_inherent_candidates_from_param(self_ty, restrict_to, p);
}
_ => { /* No bound methods in these types */ }
}
// Don't autoderef if we aren't supposed to.
if self.autoderef_receiver == DontAutoderefReceiver {
Some(())
} else {
None
}
});
}
fn push_extension_candidates(&mut self, expr_id: ast::NodeId) {
debug!("push_extension_candidates(expr_id={})", expr_id);
let mut duplicates = HashSet::new();
let opt_applicable_traits = self.fcx.ccx.trait_map.find(&expr_id);
for applicable_traits in opt_applicable_traits.into_iter() {
for &trait_did in applicable_traits.iter() {
if duplicates.insert(trait_did) {
self.push_extension_candidate(trait_did);
}
}
}
}
fn push_extension_candidate(&mut self, trait_def_id: DefId) {
debug!("push_extension_candidates: trait_def_id={}", trait_def_id);
// Check whether `trait_def_id` defines a method with suitable name:
let trait_items =
ty::trait_items(self.tcx(), trait_def_id);
let matching_index =
trait_items.iter()
.position(|item| item.name() == self.m_name);
let matching_index = match matching_index {
Some(i) => i,
None => { return; }
};
let method = match (&*trait_items)[matching_index].as_opt_method() {
Some(m) => m,
None => { return; }
};
// Check whether `trait_def_id` defines a method with suitable name:
if !self.has_applicable_self(&*method) {
debug!("method has inapplicable self");
return self.record_static_candidate(TraitSource(trait_def_id));
}
// Otherwise, construct the receiver type.
let self_ty =
self.fcx.infcx().next_ty_var();
let trait_def =
ty::lookup_trait_def(self.tcx(), trait_def_id);
let substs =
self.fcx.infcx().fresh_substs_for_trait(self.span,
&trait_def.generics,
self_ty);
let xform_self_ty =
self.xform_self_ty(&method, &substs);
// Construct the obligation which must match.
let trait_ref =
Rc::new(ty::TraitRef::new(trait_def_id, substs));
let obligation =
traits::Obligation::misc(self.span, trait_ref);
debug!("extension-candidate(xform_self_ty={} obligation={})",
self.infcx().ty_to_string(xform_self_ty),
obligation.repr(self.tcx()));
self.extension_candidates.push(ExtensionCandidate {
obligation: obligation,
xform_self_ty: xform_self_ty,
method_ty: method,
method_num: matching_index,
});
}
fn push_inherent_candidates_from_object(&mut self,
self_ty: ty::t,
did: DefId,
substs: &subst::Substs,
_bounds: ty::ExistentialBounds) {
debug!("push_inherent_candidates_from_object(self_ty={})",
self_ty.repr(self.tcx()));
let tcx = self.tcx();
// It is illegal to create a trait object with methods which includes
// the Self type. An error will be reported when we coerce to a trait
// object if the method refers to the `Self` type. Substituting ty_err
// here allows compiler to soldier on.
//
// `confirm_candidate()` also relies upon this substitution
// for Self. (fix)
let rcvr_substs = substs.with_self_ty(ty::mk_err());
let trait_ref = Rc::new(TraitRef {
def_id: did,
substs: rcvr_substs.clone()
});
self.push_inherent_candidates_from_bounds_inner(
&[trait_ref.clone()],
|this, new_trait_ref, m, method_num| {
let vtable_index =
get_method_index(tcx, &*new_trait_ref,
trait_ref.clone(), method_num);
// FIXME Hacky. By-value `self` methods in objects ought to be
// just a special case of passing ownership of a DST value
// as a parameter. *But* we currently hack them in and tie them to
// the particulars of the `Box` type. So basically for a `fn foo(self,...)`
// method invoked on an object, we don't want the receiver type to be
// `TheTrait`, but rather `Box<TheTrait>`. Yuck.
let mut m = m;
match m.explicit_self {
ByValueExplicitSelfCategory => {
let mut n = (*m).clone();
let self_ty = n.fty.sig.inputs[0];
*n.fty.sig.inputs.get_mut(0) = ty::mk_uniq(tcx, self_ty);
m = Rc::new(n);
}
_ => { }
}
let xform_self_ty =
this.xform_self_ty(&m, &new_trait_ref.substs);
Some(Candidate {
xform_self_ty: xform_self_ty,
rcvr_substs: new_trait_ref.substs.clone(),
method_ty: m,
origin: MethodTraitObject(MethodObject {
trait_ref: new_trait_ref,
object_trait_id: did,
method_num: method_num,
real_index: vtable_index
})
})
});
}
fn push_inherent_candidates_from_param(&mut self,
rcvr_ty: ty::t,
restrict_to: Option<DefId>,
param_ty: ParamTy) {
debug!("push_inherent_candidates_from_param(param_ty={})",
param_ty);
self.push_inherent_candidates_from_bounds(
rcvr_ty,
param_ty.space,
param_ty.idx,
restrict_to);
}
fn push_inherent_candidates_from_bounds(&mut self,
_self_ty: ty::t,
space: subst::ParamSpace,
index: uint,
restrict_to: Option<DefId>) {
let bounds =
self.fcx.inh.param_env.bounds.get(space, index).trait_bounds
.as_slice();
self.push_inherent_candidates_from_bounds_inner(bounds,
|this, trait_ref, m, method_num| {
match restrict_to {
Some(trait_did) => {
if trait_did != trait_ref.def_id {
return None;
}
}
_ => {}
}
let xform_self_ty =
this.xform_self_ty(&m, &trait_ref.substs);
debug!("found match: trait_ref={} substs={} m={}",
trait_ref.repr(this.tcx()),
trait_ref.substs.repr(this.tcx()),
m.repr(this.tcx()));
assert_eq!(m.generics.types.get_slice(subst::TypeSpace).len(),
trait_ref.substs.types.get_slice(subst::TypeSpace).len());
assert_eq!(m.generics.regions.get_slice(subst::TypeSpace).len(),
trait_ref.substs.regions().get_slice(subst::TypeSpace).len());
assert_eq!(m.generics.types.get_slice(subst::SelfSpace).len(),
trait_ref.substs.types.get_slice(subst::SelfSpace).len());
assert_eq!(m.generics.regions.get_slice(subst::SelfSpace).len(),
trait_ref.substs.regions().get_slice(subst::SelfSpace).len());
Some(Candidate {
xform_self_ty: xform_self_ty,
rcvr_substs: trait_ref.substs.clone(),
method_ty: m,
origin: MethodTypeParam(MethodParam {
trait_ref: trait_ref,
method_num: method_num,
})
})
})
}
// Do a search through a list of bounds, using a callback to actually
// create the candidates.
fn push_inherent_candidates_from_bounds_inner(
&mut self,
bounds: &[Rc<TraitRef>],
mk_cand: |this: &mut LookupContext,
tr: Rc<TraitRef>,
m: Rc<ty::Method>,
method_num: uint|
-> Option<Candidate>)
{
let tcx = self.tcx();
let mut cache = HashSet::new();
for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
// Already visited this trait, skip it.
if !cache.insert(bound_trait_ref.def_id) {
continue;
}
let (pos, method) = match trait_method(tcx, bound_trait_ref.def_id, self.m_name) {
Some(v) => v,
None => { continue; }
};
if !self.has_applicable_self(&*method) {
self.record_static_candidate(TraitSource(bound_trait_ref.def_id));
} else {
match mk_cand(self,
bound_trait_ref,
method,
pos) {
Some(cand) => {
debug!("pushing inherent candidate for param: {}",
cand.repr(self.tcx()));
self.inherent_candidates.push(cand);
}
None => {}
}
}
}
}
fn push_inherent_impl_candidates_for_type(&mut self, did: DefId) {
// Read the inherent implementation candidates for this type from the
// metadata if necessary.
ty::populate_implementations_for_type_if_necessary(self.tcx(), did);
for impl_infos in self.tcx().inherent_impls.borrow().find(&did).iter() {
for impl_did in impl_infos.iter() {
self.push_candidates_from_inherent_impl(*impl_did);
}
}
}
fn push_candidates_from_inherent_impl(&mut self,
impl_did: DefId) {
if !self.impl_dups.insert(impl_did) {
return; // already visited
}
let method = match impl_method(self.tcx(), impl_did, self.m_name) {
Some(m) => m,
None => { return; } // No method with correct name on this impl
};
debug!("push_candidates_from_inherent_impl: impl_did={} method={}",
impl_did.repr(self.tcx()),
method.repr(self.tcx()));
if !self.has_applicable_self(&*method) {
// No receiver declared. Not a candidate.
return self.record_static_candidate(ImplSource(impl_did));
}
// Determine the `self` of the impl with fresh
// variables for each parameter.
let span = self.self_expr.map_or(self.span, |e| e.span);
let TypeAndSubsts {
substs: impl_substs,
ty: _impl_ty
} = impl_self_ty(self.fcx, span, impl_did);
// Determine the receiver type that the method itself expects.
let xform_self_ty =
self.xform_self_ty(&method, &impl_substs);
self.inherent_candidates.push(Candidate {
xform_self_ty: xform_self_ty,
rcvr_substs: impl_substs,
origin: MethodStatic(method.def_id),
method_ty: method,
});
}
// ______________________________________________________________________
// Candidate selection (see comment at start of file)
fn search_for_autoderefd_method(&self,
self_ty: ty::t,
autoderefs: uint)
-> Option<MethodResult> {
// Hacky. For overloaded derefs, there may be an adjustment
// added to the expression from the outside context, so we do not store
// an explicit adjustment, but rather we hardwire the single deref
// that occurs in trans and mem_categorization.
if self.self_expr.is_none() {
return None;
}
let (self_ty, auto_deref_ref) = self.consider_reborrow(self_ty, autoderefs);
let adjustment = Some((self.self_expr.unwrap().id, ty::AdjustDerefRef(auto_deref_ref)));
match self.search_for_method(self_ty) {
None => {
None
}
Some(Ok(method)) => {
debug!("(searching for autoderef'd method) writing \
adjustment {} for {}", adjustment, self.ty_to_string(self_ty));
match adjustment {
Some((self_expr_id, adj)) => {
self.fcx.write_adjustment(self_expr_id, self.span, adj);
}
None => {}
}
Some(Ok(method))
}
Some(Err(error)) => {
Some(Err(error))
}
}
}
fn consider_reborrow(&self,
self_ty: ty::t,
autoderefs: uint)
-> (ty::t, ty::AutoDerefRef) {
/*!
* In the event that we are invoking a method with a receiver
* of a borrowed type like `&T`, `&mut T`, or `&mut [T]`,
* we will "reborrow" the receiver implicitly. For example, if
* you have a call `r.inc()` and where `r` has type `&mut T`,
* then we treat that like `(&mut *r).inc()`. This avoids
* consuming the original pointer.
*
* You might think that this would be a natural byproduct of
* the auto-deref/auto-ref process. This is true for `Box<T>`
* but not for an `&mut T` receiver. With `Box<T>`, we would
* begin by testing for methods with a self type `Box<T>`,
* then autoderef to `T`, then autoref to `&mut T`. But with
* an `&mut T` receiver the process begins with `&mut T`, only
* without any autoadjustments.
*/
let tcx = self.tcx();
return match ty::get(self_ty).sty {
ty::ty_rptr(_, self_mt) if default_method_hack(self_mt) => {
(self_ty,
ty::AutoDerefRef {
autoderefs: autoderefs,
autoref: None})
}
ty::ty_rptr(_, self_mt) => {
let region =
self.infcx().next_region_var(infer::Autoref(self.span));
(ty::mk_rptr(tcx, region, self_mt),
ty::AutoDerefRef {
autoderefs: autoderefs + 1,
autoref: Some(ty::AutoPtr(region, self_mt.mutbl, None))})
}
_ => {
(self_ty,
ty::AutoDerefRef {
autoderefs: autoderefs,
autoref: None})
}
};
fn default_method_hack(self_mt: ty::mt) -> bool {
// FIXME(#6129). Default methods can't deal with autoref.
//
// I am a horrible monster and I pray for death. Currently
// the default method code panics when you try to reborrow
// because it is not handling types correctly. In lieu of
// fixing that, I am introducing this horrible hack. - ndm
self_mt.mutbl == MutImmutable && ty::type_is_self(self_mt.ty)
}
}
// Takes an [T] - an unwrapped DST pointer (either ~ or &)
// [T] to &[T] or &&[T] (note that we started with a &[T] or ~[T] which has
// been implicitly derefed).
fn auto_slice_vec(&self, ty: ty::t, autoderefs: uint)
-> Option<MethodResult>
{
let tcx = self.tcx();
debug!("auto_slice_vec {}", ppaux::ty_to_string(tcx, ty));
// First try to borrow to a slice
let entry = self.search_for_some_kind_of_autorefd_method(
|r, m| AutoPtr(r, m, None), autoderefs, [MutImmutable, MutMutable],
|m,r| ty::mk_slice(tcx, r,
ty::mt {ty:ty, mutbl:m}));
if entry.is_some() {
return entry;
}
// Then try to borrow to a slice *and* borrow a pointer.
self.search_for_some_kind_of_autorefd_method(
|r, m| AutoPtr(r, ast::MutImmutable, Some( box AutoPtr(r, m, None))),
autoderefs, [MutImmutable, MutMutable],
|m, r| {
let slice_ty = ty::mk_slice(tcx, r,
ty::mt {ty:ty, mutbl:m});
// NB: we do not try to autoref to a mutable
// pointer. That would be creating a pointer
// to a temporary pointer (the borrowed
// slice), so any update the callee makes to
// it can't be observed.
ty::mk_rptr(tcx, r, ty::mt {ty:slice_ty, mutbl:MutImmutable})
})
}
// [T, ..len] -> [T] or &[T] or &&[T]
fn auto_unsize_vec(&self, ty: ty::t, autoderefs: uint, len: uint) -> Option<MethodResult> {
let tcx = self.tcx();
debug!("auto_unsize_vec {}", ppaux::ty_to_string(tcx, ty));
// First try to borrow to an unsized vec.
let entry = self.search_for_some_kind_of_autorefd_method(
|_r, _m| AutoUnsize(ty::UnsizeLength(len)),
autoderefs, [MutImmutable, MutMutable],
|_m, _r| ty::mk_vec(tcx, ty, None));
if entry.is_some() {
return entry;
}
// Then try to borrow to a slice.
let entry = self.search_for_some_kind_of_autorefd_method(
|r, m| AutoPtr(r, m, Some(box AutoUnsize(ty::UnsizeLength(len)))),
autoderefs, [MutImmutable, MutMutable],
|m, r| ty::mk_slice(tcx, r, ty::mt {ty:ty, mutbl:m}));
if entry.is_some() {
return entry;
}
// Then try to borrow to a slice *and* borrow a pointer.
self.search_for_some_kind_of_autorefd_method(
|r, m| AutoPtr(r, m,
Some(box AutoPtr(r, m,
Some(box AutoUnsize(ty::UnsizeLength(len)))))),
autoderefs, [MutImmutable, MutMutable],
|m, r| {
let slice_ty = ty::mk_slice(tcx, r, ty::mt {ty:ty, mutbl:m});
ty::mk_rptr(tcx, r, ty::mt {ty:slice_ty, mutbl:MutImmutable})
})
}
fn auto_slice_str(&self, autoderefs: uint) -> Option<MethodResult> {
let tcx = self.tcx();