/
probe.rs
1663 lines (1502 loc) · 68.3 KB
/
probe.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
use super::MethodError;
use super::NoMatchData;
use super::{CandidateSource, ImplSource, TraitSource};
use super::suggest;
use crate::check::autoderef::{self, Autoderef};
use crate::check::FnCtxt;
use crate::hir::def_id::DefId;
use crate::hir::def::DefKind;
use crate::namespace::Namespace;
use rustc_data_structures::sync::Lrc;
use rustc::hir;
use rustc::lint;
use rustc::session::config::nightly_options;
use rustc::ty::subst::{Subst, InternalSubsts, SubstsRef};
use rustc::traits::{self, ObligationCause};
use rustc::traits::query::{CanonicalTyGoal};
use rustc::traits::query::method_autoderef::{CandidateStep, MethodAutoderefStepsResult};
use rustc::traits::query::method_autoderef::{MethodAutoderefBadTy};
use rustc::ty::{self, ParamEnvAnd, Ty, TyCtxt, ToPolyTraitRef, ToPredicate, TraitRef, TypeFoldable};
use rustc::ty::GenericParamDefKind;
use rustc::infer::type_variable::TypeVariableOrigin;
use rustc::infer::unify_key::ConstVariableOrigin;
use rustc::util::nodemap::FxHashSet;
use rustc::infer::{self, InferOk};
use rustc::infer::canonical::{Canonical, QueryResponse};
use rustc::infer::canonical::{OriginalQueryValues};
use rustc::middle::stability;
use syntax::ast;
use syntax::util::lev_distance::{lev_distance, find_best_match_for_name};
use syntax_pos::{DUMMY_SP, Span, symbol::Symbol};
use std::iter;
use std::mem;
use std::ops::Deref;
use std::cmp::max;
use smallvec::{smallvec, SmallVec};
use self::CandidateKind::*;
pub use self::PickKind::*;
/// Boolean flag used to indicate if this search is for a suggestion
/// or not. If true, we can allow ambiguity and so forth.
#[derive(Clone, Copy)]
pub struct IsSuggestion(pub bool);
struct ProbeContext<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
span: Span,
mode: Mode,
method_name: Option<ast::Ident>,
return_type: Option<Ty<'tcx>>,
/// This is the OriginalQueryValues for the steps queries
/// that are answered in steps.
orig_steps_var_values: OriginalQueryValues<'tcx>,
steps: Lrc<Vec<CandidateStep<'gcx>>>,
inherent_candidates: Vec<Candidate<'tcx>>,
extension_candidates: Vec<Candidate<'tcx>>,
impl_dups: FxHashSet<DefId>,
/// Collects near misses when the candidate functions are missing a `self` keyword and is only
/// used for error reporting
static_candidates: Vec<CandidateSource>,
/// When probing for names, include names that are close to the
/// requested name (by Levensthein distance)
allow_similar_names: bool,
/// Some(candidate) if there is a private candidate
private_candidate: Option<(DefKind, DefId)>,
/// Collects near misses when trait bounds for type parameters are unsatisfied and is only used
/// for error reporting
unsatisfied_predicates: Vec<TraitRef<'tcx>>,
is_suggestion: IsSuggestion,
}
impl<'a, 'gcx, 'tcx> Deref for ProbeContext<'a, 'gcx, 'tcx> {
type Target = FnCtxt<'a, 'gcx, 'tcx>;
fn deref(&self) -> &Self::Target {
&self.fcx
}
}
#[derive(Debug)]
struct Candidate<'tcx> {
// Candidates are (I'm not quite sure, but they are mostly) basically
// some metadata on top of a `ty::AssociatedItem` (without substs).
//
// However, method probing wants to be able to evaluate the predicates
// for a function with the substs applied - for example, if a function
// has `where Self: Sized`, we don't want to consider it unless `Self`
// is actually `Sized`, and similarly, return-type suggestions want
// to consider the "actual" return type.
//
// The way this is handled is through `xform_self_ty`. It contains
// the receiver type of this candidate, but `xform_self_ty`,
// `xform_ret_ty` and `kind` (which contains the predicates) have the
// generic parameters of this candidate substituted with the *same set*
// of inference variables, which acts as some weird sort of "query".
//
// When we check out a candidate, we require `xform_self_ty` to be
// a subtype of the passed-in self-type, and this equates the type
// variables in the rest of the fields.
//
// For example, if we have this candidate:
// ```
// trait Foo {
// fn foo(&self) where Self: Sized;
// }
// ```
//
// Then `xform_self_ty` will be `&'erased ?X` and `kind` will contain
// the predicate `?X: Sized`, so if we are evaluating `Foo` for a
// the receiver `&T`, we'll do the subtyping which will make `?X`
// get the right value, then when we evaluate the predicate we'll check
// if `T: Sized`.
xform_self_ty: Ty<'tcx>,
xform_ret_ty: Option<Ty<'tcx>>,
item: ty::AssociatedItem,
kind: CandidateKind<'tcx>,
import_ids: SmallVec<[hir::HirId; 1]>,
}
#[derive(Debug)]
enum CandidateKind<'tcx> {
InherentImplCandidate(SubstsRef<'tcx>,
// Normalize obligations
Vec<traits::PredicateObligation<'tcx>>),
ObjectCandidate,
TraitCandidate(ty::TraitRef<'tcx>),
WhereClauseCandidate(// Trait
ty::PolyTraitRef<'tcx>),
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
enum ProbeResult {
NoMatch,
BadReturnType,
Match,
}
#[derive(Debug, PartialEq, Clone)]
pub struct Pick<'tcx> {
pub item: ty::AssociatedItem,
pub kind: PickKind<'tcx>,
pub import_ids: SmallVec<[hir::HirId; 1]>,
// Indicates that the source expression should be autoderef'd N times
//
// A = expr | *expr | **expr | ...
pub autoderefs: usize,
// Indicates that an autoref is applied after the optional autoderefs
//
// B = A | &A | &mut A
pub autoref: Option<hir::Mutability>,
// Indicates that the source expression should be "unsized" to a
// target type. This should probably eventually go away in favor
// of just coercing method receivers.
//
// C = B | unsize(B)
pub unsize: Option<Ty<'tcx>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PickKind<'tcx> {
InherentImplPick,
ObjectPick,
TraitPick,
WhereClausePick(// Trait
ty::PolyTraitRef<'tcx>),
}
pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>;
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum Mode {
// An expression of the form `receiver.method_name(...)`.
// Autoderefs are performed on `receiver`, lookup is done based on the
// `self` argument of the method, and static methods aren't considered.
MethodCall,
// An expression of the form `Type::item` or `<T>::item`.
// No autoderefs are performed, lookup is done based on the type each
// implementation is for, and static methods are included.
Path,
}
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum ProbeScope {
// Assemble candidates coming only from traits in scope.
TraitsInScope,
// Assemble candidates coming from all traits.
AllTraits,
}
impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
/// This is used to offer suggestions to users. It returns methods
/// that could have been called which have the desired return
/// type. Some effort is made to rule out methods that, if called,
/// would result in an error (basically, the same criteria we
/// would use to decide if a method is a plausible fit for
/// ambiguity purposes).
pub fn probe_for_return_type(&self,
span: Span,
mode: Mode,
return_type: Ty<'tcx>,
self_ty: Ty<'tcx>,
scope_expr_id: hir::HirId)
-> Vec<ty::AssociatedItem> {
debug!("probe(self_ty={:?}, return_type={}, scope_expr_id={})",
self_ty,
return_type,
scope_expr_id);
let method_names =
self.probe_op(span, mode, None, Some(return_type), IsSuggestion(true),
self_ty, scope_expr_id, ProbeScope::AllTraits,
|probe_cx| Ok(probe_cx.candidate_method_names()))
.unwrap_or(vec![]);
method_names
.iter()
.flat_map(|&method_name| {
self.probe_op(
span, mode, Some(method_name), Some(return_type),
IsSuggestion(true), self_ty, scope_expr_id,
ProbeScope::AllTraits, |probe_cx| probe_cx.pick()
).ok().map(|pick| pick.item)
})
.collect()
}
pub fn probe_for_name(&self,
span: Span,
mode: Mode,
item_name: ast::Ident,
is_suggestion: IsSuggestion,
self_ty: Ty<'tcx>,
scope_expr_id: hir::HirId,
scope: ProbeScope)
-> PickResult<'tcx> {
debug!("probe(self_ty={:?}, item_name={}, scope_expr_id={})",
self_ty,
item_name,
scope_expr_id);
self.probe_op(span,
mode,
Some(item_name),
None,
is_suggestion,
self_ty,
scope_expr_id,
scope,
|probe_cx| probe_cx.pick())
}
fn probe_op<OP,R>(&'a self,
span: Span,
mode: Mode,
method_name: Option<ast::Ident>,
return_type: Option<Ty<'tcx>>,
is_suggestion: IsSuggestion,
self_ty: Ty<'tcx>,
scope_expr_id: hir::HirId,
scope: ProbeScope,
op: OP)
-> Result<R, MethodError<'tcx>>
where OP: FnOnce(ProbeContext<'a, 'gcx, 'tcx>) -> Result<R, MethodError<'tcx>>
{
let mut orig_values = OriginalQueryValues::default();
let param_env_and_self_ty =
self.infcx.canonicalize_query(
&ParamEnvAnd {
param_env: self.param_env,
value: self_ty
}, &mut orig_values);
let steps = if mode == Mode::MethodCall {
self.tcx.method_autoderef_steps(param_env_and_self_ty)
} else {
self.infcx.probe(|_| {
// Mode::Path - the deref steps is "trivial". This turns
// our CanonicalQuery into a "trivial" QueryResponse. This
// is a bit inefficient, but I don't think that writing
// special handling for this "trivial case" is a good idea.
let infcx = &self.infcx;
let (ParamEnvAnd {
param_env: _,
value: self_ty
}, canonical_inference_vars) =
infcx.instantiate_canonical_with_fresh_inference_vars(
span, ¶m_env_and_self_ty);
debug!("probe_op: Mode::Path, param_env_and_self_ty={:?} self_ty={:?}",
param_env_and_self_ty, self_ty);
MethodAutoderefStepsResult {
steps: Lrc::new(vec![CandidateStep {
self_ty: self.make_query_response_ignoring_pending_obligations(
canonical_inference_vars, self_ty),
autoderefs: 0,
from_unsafe_deref: false,
unsize: false,
}]),
opt_bad_ty: None,
reached_recursion_limit: false
}
})
};
// If our autoderef loop had reached the recursion limit,
// report an overflow error, but continue going on with
// the truncated autoderef list.
if steps.reached_recursion_limit {
self.probe(|_| {
let ty = &steps.steps.last().unwrap_or_else(|| {
span_bug!(span, "reached the recursion limit in 0 steps?")
}).self_ty;
let ty = self.probe_instantiate_query_response(span, &orig_values, ty)
.unwrap_or_else(|_| span_bug!(span, "instantiating {:?} failed?", ty));
autoderef::report_autoderef_recursion_limit_error(self.tcx, span,
ty.value);
});
}
// If we encountered an `_` type or an error type during autoderef, this is
// ambiguous.
if let Some(bad_ty) = &steps.opt_bad_ty {
if is_suggestion.0 {
// Ambiguity was encountered during a suggestion. Just keep going.
debug!("ProbeContext: encountered ambiguity in suggestion");
} else if bad_ty.reached_raw_pointer && !self.tcx.features().arbitrary_self_types {
// this case used to be allowed by the compiler,
// so we do a future-compat lint here for the 2015 edition
// (see https://github.com/rust-lang/rust/issues/46906)
if self.tcx.sess.rust_2018() {
span_err!(self.tcx.sess, span, E0699,
"the type of this value must be known \
to call a method on a raw pointer on it");
} else {
self.tcx.lint_hir(
lint::builtin::TYVAR_BEHIND_RAW_POINTER,
scope_expr_id,
span,
"type annotations needed");
}
} else {
// Encountered a real ambiguity, so abort the lookup. If `ty` is not
// an `Err`, report the right "type annotations needed" error pointing
// to it.
let ty = &bad_ty.ty;
let ty = self.probe_instantiate_query_response(span, &orig_values, ty)
.unwrap_or_else(|_| span_bug!(span, "instantiating {:?} failed?", ty));
let ty = self.structurally_resolved_type(span, ty.value);
assert_eq!(ty, self.tcx.types.err);
return Err(MethodError::NoMatch(NoMatchData::new(Vec::new(),
Vec::new(),
Vec::new(),
None,
mode)));
}
}
debug!("ProbeContext: steps for self_ty={:?} are {:?}",
self_ty,
steps);
// this creates one big transaction so that all type variables etc
// that we create during the probe process are removed later
self.probe(|_| {
let mut probe_cx = ProbeContext::new(
self, span, mode, method_name, return_type, orig_values,
steps.steps, is_suggestion,
);
probe_cx.assemble_inherent_candidates();
match scope {
ProbeScope::TraitsInScope =>
probe_cx.assemble_extension_candidates_for_traits_in_scope(scope_expr_id)?,
ProbeScope::AllTraits =>
probe_cx.assemble_extension_candidates_for_all_traits()?,
};
op(probe_cx)
})
}
}
pub fn provide(providers: &mut ty::query::Providers<'_>) {
providers.method_autoderef_steps = method_autoderef_steps;
}
fn method_autoderef_steps<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
goal: CanonicalTyGoal<'tcx>)
-> MethodAutoderefStepsResult<'gcx>
{
debug!("method_autoderef_steps({:?})", goal);
tcx.infer_ctxt().enter_with_canonical(DUMMY_SP, &goal, |ref infcx, goal, inference_vars| {
let ParamEnvAnd { param_env, value: self_ty } = goal;
let mut autoderef = Autoderef::new(infcx, param_env, hir::DUMMY_HIR_ID, DUMMY_SP, self_ty)
.include_raw_pointers()
.silence_errors();
let mut reached_raw_pointer = false;
let mut steps: Vec<_> = autoderef.by_ref()
.map(|(ty, d)| {
let step = CandidateStep {
self_ty: infcx.make_query_response_ignoring_pending_obligations(
inference_vars.clone(), ty),
autoderefs: d,
from_unsafe_deref: reached_raw_pointer,
unsize: false,
};
if let ty::RawPtr(_) = ty.sty {
// all the subsequent steps will be from_unsafe_deref
reached_raw_pointer = true;
}
step
})
.collect();
let final_ty = autoderef.maybe_ambiguous_final_ty();
let opt_bad_ty = match final_ty.sty {
ty::Infer(ty::TyVar(_)) |
ty::Error => {
Some(MethodAutoderefBadTy {
reached_raw_pointer,
ty: infcx.make_query_response_ignoring_pending_obligations(
inference_vars, final_ty)
})
}
ty::Array(elem_ty, _) => {
let dereferences = steps.len() - 1;
steps.push(CandidateStep {
self_ty: infcx.make_query_response_ignoring_pending_obligations(
inference_vars, infcx.tcx.mk_slice(elem_ty)),
autoderefs: dereferences,
// this could be from an unsafe deref if we had
// a *mut/const [T; N]
from_unsafe_deref: reached_raw_pointer,
unsize: true,
});
None
}
_ => None
};
debug!("method_autoderef_steps: steps={:?} opt_bad_ty={:?}", steps, opt_bad_ty);
MethodAutoderefStepsResult {
steps: Lrc::new(steps),
opt_bad_ty: opt_bad_ty.map(Lrc::new),
reached_recursion_limit: autoderef.reached_recursion_limit()
}
})
}
impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
span: Span,
mode: Mode,
method_name: Option<ast::Ident>,
return_type: Option<Ty<'tcx>>,
orig_steps_var_values: OriginalQueryValues<'tcx>,
steps: Lrc<Vec<CandidateStep<'gcx>>>,
is_suggestion: IsSuggestion)
-> ProbeContext<'a, 'gcx, 'tcx> {
ProbeContext {
fcx,
span,
mode,
method_name,
return_type,
inherent_candidates: Vec::new(),
extension_candidates: Vec::new(),
impl_dups: FxHashSet::default(),
orig_steps_var_values,
steps,
static_candidates: Vec::new(),
allow_similar_names: false,
private_candidate: None,
unsatisfied_predicates: Vec::new(),
is_suggestion,
}
}
fn reset(&mut self) {
self.inherent_candidates.clear();
self.extension_candidates.clear();
self.impl_dups.clear();
self.static_candidates.clear();
self.private_candidate = None;
}
///////////////////////////////////////////////////////////////////////////
// CANDIDATE ASSEMBLY
fn push_candidate(&mut self,
candidate: Candidate<'tcx>,
is_inherent: bool)
{
let is_accessible = if let Some(name) = self.method_name {
let item = candidate.item;
let def_scope = self.tcx.adjust_ident(name, item.container.id(), self.body_id).1;
item.vis.is_accessible_from(def_scope, self.tcx)
} else {
true
};
if is_accessible {
if is_inherent {
self.inherent_candidates.push(candidate);
} else {
self.extension_candidates.push(candidate);
}
} else if self.private_candidate.is_none() {
self.private_candidate =
Some((candidate.item.def_kind(), candidate.item.def_id));
}
}
fn assemble_inherent_candidates(&mut self) {
let steps = self.steps.clone();
for step in steps.iter() {
self.assemble_probe(&step.self_ty);
}
}
fn assemble_probe(&mut self, self_ty: &Canonical<'gcx, QueryResponse<'gcx, Ty<'gcx>>>) {
debug!("assemble_probe: self_ty={:?}", self_ty);
let lang_items = self.tcx.lang_items();
match self_ty.value.value.sty {
ty::Dynamic(ref data, ..) => {
if let Some(p) = data.principal() {
// Subtle: we can't use `instantiate_query_response` here: using it will
// commit to all of the type equalities assumed by inference going through
// autoderef (see the `method-probe-no-guessing` test).
//
// However, in this code, it is OK if we end up with an object type that is
// "more general" than the object type that we are evaluating. For *every*
// object type `MY_OBJECT`, a function call that goes through a trait-ref
// of the form `<MY_OBJECT as SuperTraitOf(MY_OBJECT)>::func` is a valid
// `ObjectCandidate`, and it should be discoverable "exactly" through one
// of the iterations in the autoderef loop, so there is no problem with it
// being discoverable in another one of these iterations.
//
// Using `instantiate_canonical_with_fresh_inference_vars` on our
// `Canonical<QueryResponse<Ty<'tcx>>>` and then *throwing away* the
// `CanonicalVarValues` will exactly give us such a generalization - it
// will still match the original object type, but it won't pollute our
// type variables in any form, so just do that!
let (QueryResponse { value: generalized_self_ty, .. }, _ignored_var_values) =
self.fcx.instantiate_canonical_with_fresh_inference_vars(
self.span, &self_ty);
self.assemble_inherent_candidates_from_object(generalized_self_ty);
self.assemble_inherent_impl_candidates_for_type(p.def_id());
}
}
ty::Adt(def, _) => {
self.assemble_inherent_impl_candidates_for_type(def.did);
}
ty::Foreign(did) => {
self.assemble_inherent_impl_candidates_for_type(did);
}
ty::Param(p) => {
self.assemble_inherent_candidates_from_param(p);
}
ty::Char => {
let lang_def_id = lang_items.char_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Str => {
let lang_def_id = lang_items.str_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
let lang_def_id = lang_items.str_alloc_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Slice(_) => {
let lang_def_id = lang_items.slice_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
let lang_def_id = lang_items.slice_u8_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
let lang_def_id = lang_items.slice_alloc_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
let lang_def_id = lang_items.slice_u8_alloc_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::RawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutImmutable }) => {
let lang_def_id = lang_items.const_ptr_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::RawPtr(ty::TypeAndMut { ty: _, mutbl: hir::MutMutable }) => {
let lang_def_id = lang_items.mut_ptr_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Int(ast::IntTy::I8) => {
let lang_def_id = lang_items.i8_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Int(ast::IntTy::I16) => {
let lang_def_id = lang_items.i16_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Int(ast::IntTy::I32) => {
let lang_def_id = lang_items.i32_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Int(ast::IntTy::I64) => {
let lang_def_id = lang_items.i64_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Int(ast::IntTy::I128) => {
let lang_def_id = lang_items.i128_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Int(ast::IntTy::Isize) => {
let lang_def_id = lang_items.isize_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Uint(ast::UintTy::U8) => {
let lang_def_id = lang_items.u8_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Uint(ast::UintTy::U16) => {
let lang_def_id = lang_items.u16_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Uint(ast::UintTy::U32) => {
let lang_def_id = lang_items.u32_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Uint(ast::UintTy::U64) => {
let lang_def_id = lang_items.u64_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Uint(ast::UintTy::U128) => {
let lang_def_id = lang_items.u128_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Uint(ast::UintTy::Usize) => {
let lang_def_id = lang_items.usize_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Float(ast::FloatTy::F32) => {
let lang_def_id = lang_items.f32_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
let lang_def_id = lang_items.f32_runtime_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::Float(ast::FloatTy::F64) => {
let lang_def_id = lang_items.f64_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
let lang_def_id = lang_items.f64_runtime_impl();
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
_ => {}
}
}
fn assemble_inherent_impl_for_primitive(&mut self, lang_def_id: Option<DefId>) {
if let Some(impl_def_id) = lang_def_id {
self.assemble_inherent_impl_probe(impl_def_id);
}
}
fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId) {
let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id);
for &impl_def_id in impl_def_ids.iter() {
self.assemble_inherent_impl_probe(impl_def_id);
}
}
fn assemble_inherent_impl_probe(&mut self, impl_def_id: DefId) {
if !self.impl_dups.insert(impl_def_id) {
return; // already visited
}
debug!("assemble_inherent_impl_probe {:?}", impl_def_id);
for item in self.impl_or_trait_item(impl_def_id) {
if !self.has_applicable_self(&item) {
// No receiver declared. Not a candidate.
self.record_static_candidate(ImplSource(impl_def_id));
continue
}
let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id);
let impl_ty = impl_ty.subst(self.tcx, impl_substs);
// Determine the receiver type that the method itself expects.
let xform_tys = self.xform_self_ty(&item, impl_ty, impl_substs);
// We can't use normalize_associated_types_in as it will pollute the
// fcx's fulfillment context after this probe is over.
let cause = traits::ObligationCause::misc(self.span, self.body_id);
let selcx = &mut traits::SelectionContext::new(self.fcx);
let traits::Normalized { value: (xform_self_ty, xform_ret_ty), obligations } =
traits::normalize(selcx, self.param_env, cause, &xform_tys);
debug!("assemble_inherent_impl_probe: xform_self_ty = {:?}/{:?}",
xform_self_ty, xform_ret_ty);
self.push_candidate(Candidate {
xform_self_ty, xform_ret_ty, item,
kind: InherentImplCandidate(impl_substs, obligations),
import_ids: smallvec![]
}, true);
}
}
fn assemble_inherent_candidates_from_object(&mut self,
self_ty: Ty<'tcx>) {
debug!("assemble_inherent_candidates_from_object(self_ty={:?})",
self_ty);
let principal = match self_ty.sty {
ty::Dynamic(ref data, ..) => Some(data),
_ => None
}.and_then(|data| data.principal()).unwrap_or_else(|| {
span_bug!(self.span, "non-object {:?} in assemble_inherent_candidates_from_object",
self_ty)
});
// It is illegal to invoke a method on a trait instance that
// refers to the `Self` type. An error will be reported by
// `enforce_object_limitations()` if the method refers to the
// `Self` type anywhere other than the receiver. Here, we use
// a substitution that replaces `Self` with the object type
// itself. Hence, a `&self` method will wind up with an
// argument type like `&Trait`.
let trait_ref = principal.with_self_ty(self.tcx, self_ty);
self.elaborate_bounds(iter::once(trait_ref), |this, new_trait_ref, item| {
let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref);
let (xform_self_ty, xform_ret_ty) =
this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
this.push_candidate(Candidate {
xform_self_ty, xform_ret_ty, item,
kind: ObjectCandidate,
import_ids: smallvec![]
}, true);
});
}
fn assemble_inherent_candidates_from_param(&mut self, param_ty: ty::ParamTy) {
// FIXME -- Do we want to commit to this behavior for param bounds?
let bounds = self.param_env
.caller_bounds
.iter()
.filter_map(|predicate| {
match *predicate {
ty::Predicate::Trait(ref trait_predicate) => {
match trait_predicate.skip_binder().trait_ref.self_ty().sty {
ty::Param(ref p) if *p == param_ty => {
Some(trait_predicate.to_poly_trait_ref())
}
_ => None,
}
}
ty::Predicate::Subtype(..) |
ty::Predicate::Projection(..) |
ty::Predicate::RegionOutlives(..) |
ty::Predicate::WellFormed(..) |
ty::Predicate::ObjectSafe(..) |
ty::Predicate::ClosureKind(..) |
ty::Predicate::TypeOutlives(..) |
ty::Predicate::ConstEvaluatable(..) => None,
}
});
self.elaborate_bounds(bounds, |this, poly_trait_ref, item| {
let trait_ref = this.erase_late_bound_regions(&poly_trait_ref);
let (xform_self_ty, xform_ret_ty) =
this.xform_self_ty(&item, trait_ref.self_ty(), trait_ref.substs);
// Because this trait derives from a where-clause, it
// should not contain any inference variables or other
// artifacts. This means it is safe to put into the
// `WhereClauseCandidate` and (eventually) into the
// `WhereClausePick`.
assert!(!trait_ref.substs.needs_infer());
this.push_candidate(Candidate {
xform_self_ty, xform_ret_ty, item,
kind: WhereClauseCandidate(poly_trait_ref),
import_ids: smallvec![]
}, true);
});
}
// Do a search through a list of bounds, using a callback to actually
// create the candidates.
fn elaborate_bounds<F>(&mut self,
bounds: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
mut mk_cand: F)
where F: for<'b> FnMut(&mut ProbeContext<'b, 'gcx, 'tcx>,
ty::PolyTraitRef<'tcx>,
ty::AssociatedItem)
{
let tcx = self.tcx;
for bound_trait_ref in traits::transitive_bounds(tcx, bounds) {
debug!("elaborate_bounds(bound_trait_ref={:?})", bound_trait_ref);
for item in self.impl_or_trait_item(bound_trait_ref.def_id()) {
if !self.has_applicable_self(&item) {
self.record_static_candidate(TraitSource(bound_trait_ref.def_id()));
} else {
mk_cand(self, bound_trait_ref, item);
}
}
}
}
fn assemble_extension_candidates_for_traits_in_scope(&mut self,
expr_hir_id: hir::HirId)
-> Result<(), MethodError<'tcx>> {
if expr_hir_id == hir::DUMMY_HIR_ID {
return Ok(())
}
let mut duplicates = FxHashSet::default();
let opt_applicable_traits = self.tcx.in_scope_traits(expr_hir_id);
if let Some(applicable_traits) = opt_applicable_traits {
for trait_candidate in applicable_traits.iter() {
let trait_did = trait_candidate.def_id;
if duplicates.insert(trait_did) {
let import_ids = trait_candidate.import_ids.iter().map(|node_id|
self.fcx.tcx.hir().node_to_hir_id(*node_id)).collect();
let result = self.assemble_extension_candidates_for_trait(import_ids,
trait_did);
result?;
}
}
}
Ok(())
}
fn assemble_extension_candidates_for_all_traits(&mut self) -> Result<(), MethodError<'tcx>> {
let mut duplicates = FxHashSet::default();
for trait_info in suggest::all_traits(self.tcx) {
if duplicates.insert(trait_info.def_id) {
self.assemble_extension_candidates_for_trait(smallvec![], trait_info.def_id)?;
}
}
Ok(())
}
pub fn matches_return_type(&self,
method: &ty::AssociatedItem,
self_ty: Option<Ty<'tcx>>,
expected: Ty<'tcx>) -> bool {
match method.kind {
ty::AssociatedKind::Method => {
let fty = self.tcx.fn_sig(method.def_id);
self.probe(|_| {
let substs = self.fresh_substs_for_item(self.span, method.def_id);
let fty = fty.subst(self.tcx, substs);
let (fty, _) = self.replace_bound_vars_with_fresh_vars(
self.span,
infer::FnCall,
&fty
);
if let Some(self_ty) = self_ty {
if self.at(&ObligationCause::dummy(), self.param_env)
.sup(fty.inputs()[0], self_ty)
.is_err()
{
return false
}
}
self.can_sub(self.param_env, fty.output(), expected).is_ok()
})
}
_ => false,
}
}
fn assemble_extension_candidates_for_trait(&mut self,
import_ids: SmallVec<[hir::HirId; 1]>,
trait_def_id: DefId)
-> Result<(), MethodError<'tcx>> {
debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})",
trait_def_id);
let trait_substs = self.fresh_item_substs(trait_def_id);
let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
if self.tcx.is_trait_alias(trait_def_id) {
// For trait aliases, assume all super-traits are relevant.
let bounds = iter::once(trait_ref.to_poly_trait_ref());
self.elaborate_bounds(bounds, |this, new_trait_ref, item| {
let new_trait_ref = this.erase_late_bound_regions(&new_trait_ref);
let (xform_self_ty, xform_ret_ty) =
this.xform_self_ty(&item, new_trait_ref.self_ty(), new_trait_ref.substs);
this.push_candidate(Candidate {
xform_self_ty, xform_ret_ty, item, import_ids: import_ids.clone(),
kind: TraitCandidate(new_trait_ref),
}, true);
});
} else {
debug_assert!(self.tcx.is_trait(trait_def_id));
for item in self.impl_or_trait_item(trait_def_id) {
// Check whether `trait_def_id` defines a method with suitable name.
if !self.has_applicable_self(&item) {
debug!("method has inapplicable self");
self.record_static_candidate(TraitSource(trait_def_id));
continue;
}
let (xform_self_ty, xform_ret_ty) =
self.xform_self_ty(&item, trait_ref.self_ty(), trait_substs);
self.push_candidate(Candidate {
xform_self_ty, xform_ret_ty, item, import_ids: import_ids.clone(),
kind: TraitCandidate(trait_ref),
}, false);
}
}
Ok(())
}
fn candidate_method_names(&self) -> Vec<ast::Ident> {
let mut set = FxHashSet::default();
let mut names: Vec<_> = self.inherent_candidates
.iter()
.chain(&self.extension_candidates)
.filter(|candidate| {
if let Some(return_ty) = self.return_type {
self.matches_return_type(&candidate.item, None, return_ty)
} else {
true
}
})
.map(|candidate| candidate.item.ident)
.filter(|&name| set.insert(name))
.collect();
// Sort them by the name so we have a stable result.
names.sort_by_cached_key(|n| n.as_str());
names
}
///////////////////////////////////////////////////////////////////////////
// THE ACTUAL SEARCH
fn pick(mut self) -> PickResult<'tcx> {
assert!(self.method_name.is_some());
if let Some(r) = self.pick_core() {
return r;
}
debug!("pick: actual search failed, assemble diagnotics");
let static_candidates = mem::replace(&mut self.static_candidates, vec![]);
let private_candidate = self.private_candidate.take();
let unsatisfied_predicates = mem::replace(&mut self.unsatisfied_predicates, vec![]);
// things failed, so lets look at all traits, for diagnostic purposes now:
self.reset();
let span = self.span;
let tcx = self.tcx;
self.assemble_extension_candidates_for_all_traits()?;
let out_of_scope_traits = match self.pick_core() {
Some(Ok(p)) => vec![p.item.container.id()],
//Some(Ok(p)) => p.iter().map(|p| p.item.container().id()).collect(),
Some(Err(MethodError::Ambiguity(v))) => {
v.into_iter()
.map(|source| {
match source {
TraitSource(id) => id,
ImplSource(impl_id) => {
match tcx.trait_id_of_impl(impl_id) {
Some(id) => id,
None => {
span_bug!(span,
"found inherent method when looking at traits")
}
}
}
}
})