-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathlower.rs
2298 lines (2156 loc) · 98.1 KB
/
lower.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
//! Methods for lowering the HIR to types. There are two main cases here:
//!
//! - Lowering a type reference like `&usize` or `Option<foo::bar::Baz>` to a
//! type: The entry point for this is `TyLoweringContext::lower_ty`.
//! - Building the type for an item: This happens through the `ty` query.
//!
//! This usually involves resolving names, collecting generic arguments etc.
use std::{
cell::{Cell, RefCell, RefMut},
iter,
ops::{self, Not as _},
};
use base_db::{salsa::Cycle, CrateId};
use chalk_ir::{
cast::Cast,
fold::{Shift, TypeFoldable},
interner::HasInterner,
Mutability, Safety, TypeOutlives,
};
use either::Either;
use hir_def::{
builtin_type::BuiltinType,
data::adt::StructKind,
expander::Expander,
generics::{
GenericParamDataRef, TypeOrConstParamData, TypeParamProvenance, WherePredicate,
WherePredicateTypeTarget,
},
lang_item::LangItem,
nameres::MacroSubNs,
path::{GenericArg, GenericArgs, ModPath, Path, PathKind, PathSegment, PathSegments},
resolver::{HasResolver, LifetimeNs, Resolver, TypeNs},
type_ref::{
ConstRef, LifetimeRef, TraitBoundModifier, TraitRef as HirTraitRef, TypeBound, TypeRef,
},
AdtId, AssocItemId, CallableDefId, ConstId, ConstParamId, DefWithBodyId, EnumId, EnumVariantId,
FunctionId, GenericDefId, GenericParamId, HasModule, ImplId, InTypeConstLoc, ItemContainerId,
LocalFieldId, Lookup, StaticId, StructId, TraitId, TypeAliasId, TypeOrConstParamId,
TypeOwnerId, UnionId, VariantId,
};
use hir_expand::{name::Name, ExpandResult};
use intern::Interned;
use la_arena::{Arena, ArenaMap};
use once_cell::unsync::OnceCell;
use rustc_hash::FxHashSet;
use rustc_pattern_analysis::Captures;
use smallvec::SmallVec;
use stdx::{impl_from, never};
use syntax::ast;
use triomphe::Arc;
use crate::{
all_super_traits,
consteval::{
intern_const_ref, intern_const_scalar, path_to_const, unknown_const,
unknown_const_as_generic,
},
db::HirDatabase,
error_lifetime,
generics::{generics, Generics},
make_binders,
mapping::{from_chalk_trait_id, lt_to_placeholder_idx, ToChalk},
static_lifetime, to_assoc_type_id, to_chalk_trait_id, to_placeholder_idx,
utils::{
all_super_trait_refs, associated_type_by_name_including_super_traits, InTypeConstIdMetadata,
},
AliasEq, AliasTy, Binders, BoundVar, CallableSig, Const, ConstScalar, DebruijnIndex, DynTy,
FnAbi, FnPointer, FnSig, FnSubst, ImplTrait, ImplTraitId, ImplTraits, Interner, Lifetime,
LifetimeData, LifetimeOutlives, ParamKind, PolyFnSig, ProgramClause, ProjectionTy,
QuantifiedWhereClause, QuantifiedWhereClauses, Substitution, TraitEnvironment, TraitRef,
TraitRefExt, Ty, TyBuilder, TyKind, WhereClause,
};
#[derive(Debug)]
enum ImplTraitLoweringState {
/// When turning `impl Trait` into opaque types, we have to collect the
/// bounds at the same time to get the IDs correct (without becoming too
/// complicated). I don't like using interior mutability (as for the
/// counter), but I've tried and failed to make the lifetimes work for
/// passing around a `&mut TyLoweringContext`. The core problem is that
/// we're grouping the mutable data (the counter and this field) together
/// with the immutable context (the references to the DB and resolver).
/// Splitting this up would be a possible fix.
Opaque(RefCell<Arena<ImplTrait>>),
Param(Cell<u16>),
Variable(Cell<u16>),
Disallowed,
}
impl ImplTraitLoweringState {
fn new(impl_trait_mode: ImplTraitLoweringMode) -> ImplTraitLoweringState {
match impl_trait_mode {
ImplTraitLoweringMode::Opaque => Self::Opaque(RefCell::new(Arena::new())),
ImplTraitLoweringMode::Param => Self::Param(Cell::new(0)),
ImplTraitLoweringMode::Variable => Self::Variable(Cell::new(0)),
ImplTraitLoweringMode::Disallowed => Self::Disallowed,
}
}
fn take(&self) -> Self {
match self {
Self::Opaque(x) => Self::Opaque(RefCell::new(x.take())),
Self::Param(x) => Self::Param(Cell::new(x.get())),
Self::Variable(x) => Self::Variable(Cell::new(x.get())),
Self::Disallowed => Self::Disallowed,
}
}
fn swap(&self, impl_trait_mode: &Self) {
match (self, impl_trait_mode) {
(Self::Opaque(x), Self::Opaque(y)) => x.swap(y),
(Self::Param(x), Self::Param(y)) => x.swap(y),
(Self::Variable(x), Self::Variable(y)) => x.swap(y),
(Self::Disallowed, Self::Disallowed) => (),
_ => panic!("mismatched lowering mode"),
}
}
}
#[derive(Debug)]
pub struct TyLoweringContext<'a> {
pub db: &'a dyn HirDatabase,
resolver: &'a Resolver,
generics: OnceCell<Option<Generics>>,
in_binders: DebruijnIndex,
// FIXME: Should not be an `Option` but `Resolver` currently does not return owners in all cases
// where expected
owner: Option<TypeOwnerId>,
/// Note: Conceptually, it's thinkable that we could be in a location where
/// some type params should be represented as placeholders, and others
/// should be converted to variables. I think in practice, this isn't
/// possible currently, so this should be fine for now.
pub type_param_mode: ParamLoweringMode,
impl_trait_mode: ImplTraitLoweringState,
expander: RefCell<Option<Expander>>,
/// Tracks types with explicit `?Sized` bounds.
pub(crate) unsized_types: RefCell<FxHashSet<Ty>>,
}
impl<'a> TyLoweringContext<'a> {
pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver, owner: TypeOwnerId) -> Self {
Self::new_maybe_unowned(db, resolver, Some(owner))
}
pub fn new_maybe_unowned(
db: &'a dyn HirDatabase,
resolver: &'a Resolver,
owner: Option<TypeOwnerId>,
) -> Self {
let impl_trait_mode = ImplTraitLoweringState::Disallowed;
let type_param_mode = ParamLoweringMode::Placeholder;
let in_binders = DebruijnIndex::INNERMOST;
Self {
db,
resolver,
generics: OnceCell::new(),
owner,
in_binders,
impl_trait_mode,
type_param_mode,
expander: RefCell::new(None),
unsized_types: RefCell::default(),
}
}
pub fn with_debruijn<T>(
&self,
debruijn: DebruijnIndex,
f: impl FnOnce(&TyLoweringContext<'_>) -> T,
) -> T {
let impl_trait_mode = self.impl_trait_mode.take();
let expander = self.expander.take();
let unsized_types = self.unsized_types.take();
let new_ctx = Self {
in_binders: debruijn,
impl_trait_mode,
expander: RefCell::new(expander),
unsized_types: RefCell::new(unsized_types),
generics: self.generics.clone(),
..*self
};
let result = f(&new_ctx);
self.impl_trait_mode.swap(&new_ctx.impl_trait_mode);
self.expander.replace(new_ctx.expander.into_inner());
self.unsized_types.replace(new_ctx.unsized_types.into_inner());
result
}
pub fn with_shifted_in<T>(
&self,
debruijn: DebruijnIndex,
f: impl FnOnce(&TyLoweringContext<'_>) -> T,
) -> T {
self.with_debruijn(self.in_binders.shifted_in_from(debruijn), f)
}
pub fn with_impl_trait_mode(self, impl_trait_mode: ImplTraitLoweringMode) -> Self {
Self { impl_trait_mode: ImplTraitLoweringState::new(impl_trait_mode), ..self }
}
pub fn with_type_param_mode(self, type_param_mode: ParamLoweringMode) -> Self {
Self { type_param_mode, ..self }
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ImplTraitLoweringMode {
/// `impl Trait` gets lowered into an opaque type that doesn't unify with
/// anything except itself. This is used in places where values flow 'out',
/// i.e. for arguments of the function we're currently checking, and return
/// types of functions we're calling.
Opaque,
/// `impl Trait` gets lowered into a type variable. Used for argument
/// position impl Trait when inside the respective function, since it allows
/// us to support that without Chalk.
Param,
/// `impl Trait` gets lowered into a variable that can unify with some
/// type. This is used in places where values flow 'in', i.e. for arguments
/// of functions we're calling, and the return type of the function we're
/// currently checking.
Variable,
/// `impl Trait` is disallowed and will be an error.
Disallowed,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ParamLoweringMode {
Placeholder,
Variable,
}
impl<'a> TyLoweringContext<'a> {
pub fn lower_ty(&self, type_ref: &TypeRef) -> Ty {
self.lower_ty_ext(type_ref).0
}
pub fn lower_const(&self, const_ref: &ConstRef, const_type: Ty) -> Const {
let Some(owner) = self.owner else { return unknown_const(const_type) };
const_or_path_to_chalk(
self.db,
self.resolver,
owner,
const_type,
const_ref,
self.type_param_mode,
|| self.generics(),
self.in_binders,
)
}
fn generics(&self) -> Option<&Generics> {
self.generics
.get_or_init(|| self.resolver.generic_def().map(|def| generics(self.db.upcast(), def)))
.as_ref()
}
pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option<TypeNs>) {
let mut res = None;
let ty = match type_ref {
TypeRef::Never => TyKind::Never.intern(Interner),
TypeRef::Tuple(inner) => {
let inner_tys = inner.iter().map(|tr| self.lower_ty(tr));
TyKind::Tuple(inner_tys.len(), Substitution::from_iter(Interner, inner_tys))
.intern(Interner)
}
TypeRef::Path(path) => {
let (ty, res_) = self.lower_path(path);
res = res_;
ty
}
TypeRef::RawPtr(inner, mutability) => {
let inner_ty = self.lower_ty(inner);
TyKind::Raw(lower_to_chalk_mutability(*mutability), inner_ty).intern(Interner)
}
TypeRef::Array(inner, len) => {
let inner_ty = self.lower_ty(inner);
let const_len = self.lower_const(len, TyBuilder::usize());
TyKind::Array(inner_ty, const_len).intern(Interner)
}
TypeRef::Slice(inner) => {
let inner_ty = self.lower_ty(inner);
TyKind::Slice(inner_ty).intern(Interner)
}
TypeRef::Reference(inner, lifetime, mutability) => {
let inner_ty = self.lower_ty(inner);
// FIXME: It should infer the eldided lifetimes instead of stubbing with static
let lifetime =
lifetime.as_ref().map_or_else(error_lifetime, |lr| self.lower_lifetime(lr));
TyKind::Ref(lower_to_chalk_mutability(*mutability), lifetime, inner_ty)
.intern(Interner)
}
TypeRef::Placeholder => TyKind::Error.intern(Interner),
&TypeRef::Fn(ref params, variadic, is_unsafe, ref abi) => {
let substs = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
Substitution::from_iter(Interner, params.iter().map(|(_, tr)| ctx.lower_ty(tr)))
});
TyKind::Function(FnPointer {
num_binders: 0, // FIXME lower `for<'a> fn()` correctly
sig: FnSig {
abi: abi.as_deref().map_or(FnAbi::Rust, FnAbi::from_str),
safety: if is_unsafe { Safety::Unsafe } else { Safety::Safe },
variadic,
},
substitution: FnSubst(substs),
})
.intern(Interner)
}
TypeRef::DynTrait(bounds) => self.lower_dyn_trait(bounds),
TypeRef::ImplTrait(bounds) => {
match &self.impl_trait_mode {
ImplTraitLoweringState::Opaque(opaque_type_data) => {
let origin = match self.resolver.generic_def() {
Some(GenericDefId::FunctionId(it)) => Either::Left(it),
Some(GenericDefId::TypeAliasId(it)) => Either::Right(it),
_ => panic!(
"opaque impl trait lowering must be in function or type alias"
),
};
// this dance is to make sure the data is in the right
// place even if we encounter more opaque types while
// lowering the bounds
let idx = opaque_type_data.borrow_mut().alloc(ImplTrait {
bounds: crate::make_single_type_binders(Vec::default()),
});
// We don't want to lower the bounds inside the binders
// we're currently in, because they don't end up inside
// those binders. E.g. when we have `impl Trait<impl
// OtherTrait<T>>`, the `impl OtherTrait<T>` can't refer
// to the self parameter from `impl Trait`, and the
// bounds aren't actually stored nested within each
// other, but separately. So if the `T` refers to a type
// parameter of the outer function, it's just one binder
// away instead of two.
let actual_opaque_type_data = self
.with_debruijn(DebruijnIndex::INNERMOST, |ctx| {
ctx.lower_impl_trait(bounds, self.resolver.krate())
});
opaque_type_data.borrow_mut()[idx] = actual_opaque_type_data;
let impl_trait_id = origin.either(
|f| ImplTraitId::ReturnTypeImplTrait(f, idx),
|a| ImplTraitId::AssociatedTypeImplTrait(a, idx),
);
let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
let generics =
generics(self.db.upcast(), origin.either(|f| f.into(), |a| a.into()));
let parameters = generics.bound_vars_subst(self.db, self.in_binders);
TyKind::OpaqueType(opaque_ty_id, parameters).intern(Interner)
}
ImplTraitLoweringState::Param(counter) => {
let idx = counter.get();
// Count the number of `impl Trait` things that appear within our bounds.
// Since t hose have been emitted as implicit type args already.
counter.set(idx + count_impl_traits(type_ref) as u16);
let kind = self
.generics()
.expect("param impl trait lowering must be in a generic def")
.iter()
.filter_map(|(id, data)| match (id, data) {
(
GenericParamId::TypeParamId(id),
GenericParamDataRef::TypeParamData(data),
) if data.provenance == TypeParamProvenance::ArgumentImplTrait => {
Some(id)
}
_ => None,
})
.nth(idx as usize)
.map_or(TyKind::Error, |id| {
TyKind::Placeholder(to_placeholder_idx(self.db, id.into()))
});
kind.intern(Interner)
}
ImplTraitLoweringState::Variable(counter) => {
let idx = counter.get();
// Count the number of `impl Trait` things that appear within our bounds.
// Since t hose have been emitted as implicit type args already.
counter.set(idx + count_impl_traits(type_ref) as u16);
let (
_parent_params,
self_param,
type_params,
const_params,
_impl_trait_params,
lifetime_params,
) = self
.generics()
.expect("variable impl trait lowering must be in a generic def")
.provenance_split();
TyKind::BoundVar(BoundVar::new(
self.in_binders,
idx as usize
+ self_param as usize
+ type_params
+ const_params
+ lifetime_params,
))
.intern(Interner)
}
ImplTraitLoweringState::Disallowed => {
// FIXME: report error
TyKind::Error.intern(Interner)
}
}
}
TypeRef::Macro(macro_call) => {
let (mut expander, recursion_start) = {
match RefMut::filter_map(self.expander.borrow_mut(), Option::as_mut) {
// There already is an expander here, this means we are already recursing
Ok(expander) => (expander, false),
// No expander was created yet, so we are at the start of the expansion recursion
// and therefore have to create an expander.
Err(expander) => (
RefMut::map(expander, |it| {
it.insert(Expander::new(
self.db.upcast(),
macro_call.file_id,
self.resolver.module(),
))
}),
true,
),
}
};
let ty = {
let macro_call = macro_call.to_node(self.db.upcast());
let resolver = |path: &_| {
self.resolver
.resolve_path_as_macro(self.db.upcast(), path, Some(MacroSubNs::Bang))
.map(|(it, _)| it)
};
match expander.enter_expand::<ast::Type>(self.db.upcast(), macro_call, resolver)
{
Ok(ExpandResult { value: Some((mark, expanded)), .. }) => {
let ctx = expander.ctx(self.db.upcast());
// FIXME: Report syntax errors in expansion here
let type_ref = TypeRef::from_ast(&ctx, expanded.tree());
drop(expander);
let ty = self.lower_ty(&type_ref);
self.expander.borrow_mut().as_mut().unwrap().exit(mark);
Some(ty)
}
_ => {
drop(expander);
None
}
}
};
// drop the expander, resetting it to pre-recursion state
if recursion_start {
*self.expander.borrow_mut() = None;
}
ty.unwrap_or_else(|| TyKind::Error.intern(Interner))
}
TypeRef::Error => TyKind::Error.intern(Interner),
};
(ty, res)
}
/// This is only for `generic_predicates_for_param`, where we can't just
/// lower the self types of the predicates since that could lead to cycles.
/// So we just check here if the `type_ref` resolves to a generic param, and which.
fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option<TypeOrConstParamId> {
let path = match type_ref {
TypeRef::Path(path) => path,
_ => return None,
};
if path.type_anchor().is_some() {
return None;
}
if path.segments().len() > 1 {
return None;
}
let resolution = match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path) {
Some((it, None, _)) => it,
_ => return None,
};
match resolution {
TypeNs::GenericParam(param_id) => Some(param_id.into()),
_ => None,
}
}
pub(crate) fn lower_ty_relative_path(
&self,
ty: Ty,
// We need the original resolution to lower `Self::AssocTy` correctly
res: Option<TypeNs>,
remaining_segments: PathSegments<'_>,
) -> (Ty, Option<TypeNs>) {
match remaining_segments.len() {
0 => (ty, res),
1 => {
// resolve unselected assoc types
let segment = remaining_segments.first().unwrap();
(self.select_associated_type(res, segment), None)
}
_ => {
// FIXME report error (ambiguous associated type)
(TyKind::Error.intern(Interner), None)
}
}
}
pub(crate) fn lower_partly_resolved_path(
&self,
resolution: TypeNs,
resolved_segment: PathSegment<'_>,
remaining_segments: PathSegments<'_>,
infer_args: bool,
) -> (Ty, Option<TypeNs>) {
let ty = match resolution {
TypeNs::TraitId(trait_) => {
let ty = match remaining_segments.len() {
1 => {
let trait_ref =
self.lower_trait_ref_from_resolved_path(trait_, resolved_segment, None);
let segment = remaining_segments.first().unwrap();
let found = self
.db
.trait_data(trait_ref.hir_trait_id())
.associated_type_by_name(segment.name);
match found {
Some(associated_ty) => {
// FIXME: `substs_from_path_segment()` pushes `TyKind::Error` for every parent
// generic params. It's inefficient to splice the `Substitution`s, so we may want
// that method to optionally take parent `Substitution` as we already know them at
// this point (`trait_ref.substitution`).
let substitution = self.substs_from_path_segment(
segment,
Some(associated_ty.into()),
false,
None,
);
let len_self =
generics(self.db.upcast(), associated_ty.into()).len_self();
let substitution = Substitution::from_iter(
Interner,
substitution
.iter(Interner)
.take(len_self)
.chain(trait_ref.substitution.iter(Interner)),
);
TyKind::Alias(AliasTy::Projection(ProjectionTy {
associated_ty_id: to_assoc_type_id(associated_ty),
substitution,
}))
.intern(Interner)
}
None => {
// FIXME: report error (associated type not found)
TyKind::Error.intern(Interner)
}
}
}
0 => {
// Trait object type without dyn; this should be handled in upstream. See
// `lower_path()`.
stdx::never!("unexpected fully resolved trait path");
TyKind::Error.intern(Interner)
}
_ => {
// FIXME report error (ambiguous associated type)
TyKind::Error.intern(Interner)
}
};
return (ty, None);
}
TypeNs::TraitAliasId(_) => {
// FIXME(trait_alias): Implement trait alias.
return (TyKind::Error.intern(Interner), None);
}
TypeNs::GenericParam(param_id) => match self.type_param_mode {
ParamLoweringMode::Placeholder => {
TyKind::Placeholder(to_placeholder_idx(self.db, param_id.into()))
}
ParamLoweringMode::Variable => {
let idx = match self
.generics()
.expect("generics in scope")
.type_or_const_param_idx(param_id.into())
{
None => {
never!("no matching generics");
return (TyKind::Error.intern(Interner), None);
}
Some(idx) => idx,
};
TyKind::BoundVar(BoundVar::new(self.in_binders, idx))
}
}
.intern(Interner),
TypeNs::SelfType(impl_id) => {
let generics = self.generics().expect("impl should have generic param scope");
match self.type_param_mode {
ParamLoweringMode::Placeholder => {
// `def` can be either impl itself or item within, and we need impl itself
// now.
let generics = generics.parent_or_self();
let subst = generics.placeholder_subst(self.db);
self.db.impl_self_ty(impl_id).substitute(Interner, &subst)
}
ParamLoweringMode::Variable => {
let starting_from = match generics.def() {
GenericDefId::ImplId(_) => 0,
// `def` is an item within impl. We need to substitute `BoundVar`s but
// remember that they are for parent (i.e. impl) generic params so they
// come after our own params.
_ => generics.len_self(),
};
TyBuilder::impl_self_ty(self.db, impl_id)
.fill_with_bound_vars(self.in_binders, starting_from)
.build()
}
}
}
TypeNs::AdtSelfType(adt) => {
let generics = generics(self.db.upcast(), adt.into());
let substs = match self.type_param_mode {
ParamLoweringMode::Placeholder => generics.placeholder_subst(self.db),
ParamLoweringMode::Variable => {
generics.bound_vars_subst(self.db, self.in_binders)
}
};
self.db.ty(adt.into()).substitute(Interner, &substs)
}
TypeNs::AdtId(it) => self.lower_path_inner(resolved_segment, it.into(), infer_args),
TypeNs::BuiltinType(it) => {
self.lower_path_inner(resolved_segment, it.into(), infer_args)
}
TypeNs::TypeAliasId(it) => {
self.lower_path_inner(resolved_segment, it.into(), infer_args)
}
// FIXME: report error
TypeNs::EnumVariantId(_) => return (TyKind::Error.intern(Interner), None),
};
self.lower_ty_relative_path(ty, Some(resolution), remaining_segments)
}
pub(crate) fn lower_path(&self, path: &Path) -> (Ty, Option<TypeNs>) {
// Resolve the path (in type namespace)
if let Some(type_ref) = path.type_anchor() {
let (ty, res) = self.lower_ty_ext(type_ref);
return self.lower_ty_relative_path(ty, res, path.segments());
}
let (resolution, remaining_index, _) =
match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path) {
Some(it) => it,
None => return (TyKind::Error.intern(Interner), None),
};
if matches!(resolution, TypeNs::TraitId(_)) && remaining_index.is_none() {
// trait object type without dyn
let bound = TypeBound::Path(path.clone(), TraitBoundModifier::None);
let ty = self.lower_dyn_trait(&[Interned::new(bound)]);
return (ty, None);
}
let (resolved_segment, remaining_segments) = match remaining_index {
None => (
path.segments().last().expect("resolved path has at least one element"),
PathSegments::EMPTY,
),
Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)),
};
self.lower_partly_resolved_path(resolution, resolved_segment, remaining_segments, false)
}
fn select_associated_type(&self, res: Option<TypeNs>, segment: PathSegment<'_>) -> Ty {
let Some((generics, res)) = self.generics().zip(res) else {
return TyKind::Error.intern(Interner);
};
let ty = named_associated_type_shorthand_candidates(
self.db,
generics.def(),
res,
Some(segment.name.clone()),
move |name, t, associated_ty| {
if name != segment.name {
return None;
}
let parent_subst = t.substitution.clone();
let parent_subst = match self.type_param_mode {
ParamLoweringMode::Placeholder => {
// if we're lowering to placeholders, we have to put them in now.
let s = generics.placeholder_subst(self.db);
s.apply(parent_subst, Interner)
}
ParamLoweringMode::Variable => {
// We need to shift in the bound vars, since
// `named_associated_type_shorthand_candidates` does not do that.
parent_subst.shifted_in_from(Interner, self.in_binders)
}
};
// FIXME: `substs_from_path_segment()` pushes `TyKind::Error` for every parent
// generic params. It's inefficient to splice the `Substitution`s, so we may want
// that method to optionally take parent `Substitution` as we already know them at
// this point (`t.substitution`).
let substs = self.substs_from_path_segment(
segment.clone(),
Some(associated_ty.into()),
false,
None,
);
let len_self =
crate::generics::generics(self.db.upcast(), associated_ty.into()).len_self();
let substs = Substitution::from_iter(
Interner,
substs.iter(Interner).take(len_self).chain(parent_subst.iter(Interner)),
);
Some(
TyKind::Alias(AliasTy::Projection(ProjectionTy {
associated_ty_id: to_assoc_type_id(associated_ty),
substitution: substs,
}))
.intern(Interner),
)
},
);
ty.unwrap_or_else(|| TyKind::Error.intern(Interner))
}
fn lower_path_inner(
&self,
segment: PathSegment<'_>,
typeable: TyDefId,
infer_args: bool,
) -> Ty {
let generic_def = match typeable {
TyDefId::BuiltinType(_) => None,
TyDefId::AdtId(it) => Some(it.into()),
TyDefId::TypeAliasId(it) => Some(it.into()),
};
let substs = self.substs_from_path_segment(segment, generic_def, infer_args, None);
self.db.ty(typeable).substitute(Interner, &substs)
}
/// Collect generic arguments from a path into a `Substs`. See also
/// `create_substs_for_ast_path` and `def_to_ty` in rustc.
pub(super) fn substs_from_path(
&self,
path: &Path,
// Note that we don't call `db.value_type(resolved)` here,
// `ValueTyDefId` is just a convenient way to pass generics and
// special-case enum variants
resolved: ValueTyDefId,
infer_args: bool,
) -> Substitution {
let last = path.segments().last();
let (segment, generic_def) = match resolved {
ValueTyDefId::FunctionId(it) => (last, Some(it.into())),
ValueTyDefId::StructId(it) => (last, Some(it.into())),
ValueTyDefId::UnionId(it) => (last, Some(it.into())),
ValueTyDefId::ConstId(it) => (last, Some(it.into())),
ValueTyDefId::StaticId(_) => (last, None),
ValueTyDefId::EnumVariantId(var) => {
// the generic args for an enum variant may be either specified
// on the segment referring to the enum, or on the segment
// referring to the variant. So `Option::<T>::None` and
// `Option::None::<T>` are both allowed (though the former is
// preferred). See also `def_ids_for_path_segments` in rustc.
let len = path.segments().len();
let penultimate = len.checked_sub(2).and_then(|idx| path.segments().get(idx));
let segment = match penultimate {
Some(segment) if segment.args_and_bindings.is_some() => Some(segment),
_ => last,
};
(segment, Some(var.lookup(self.db.upcast()).parent.into()))
}
};
if let Some(segment) = segment {
self.substs_from_path_segment(segment, generic_def, infer_args, None)
} else if let Some(generic_def) = generic_def {
// lang item
self.substs_from_args_and_bindings(None, Some(generic_def), infer_args, None)
} else {
Substitution::empty(Interner)
}
}
pub(super) fn substs_from_path_segment(
&self,
segment: PathSegment<'_>,
def: Option<GenericDefId>,
infer_args: bool,
explicit_self_ty: Option<Ty>,
) -> Substitution {
self.substs_from_args_and_bindings(
segment.args_and_bindings,
def,
infer_args,
explicit_self_ty,
)
}
fn substs_from_args_and_bindings(
&self,
args_and_bindings: Option<&GenericArgs>,
def: Option<GenericDefId>,
infer_args: bool,
explicit_self_ty: Option<Ty>,
) -> Substitution {
let Some(def) = def else { return Substitution::empty(Interner) };
// Order is
// - Optional Self parameter
// - Lifetime parameters
// - Type or Const parameters
// - Parent parameters
let def_generics = generics(self.db.upcast(), def);
let (
parent_params,
self_param,
type_params,
const_params,
impl_trait_params,
lifetime_params,
) = def_generics.provenance_split();
let item_len =
self_param as usize + type_params + const_params + impl_trait_params + lifetime_params;
let total_len = parent_params + item_len;
let mut substs = Vec::new();
// we need to iterate the lifetime and type/const params separately as our order of them
// differs from the supplied syntax
let ty_error = || TyKind::Error.intern(Interner).cast(Interner);
let mut def_toc_iter = def_generics.iter_self_type_or_consts_id();
let fill_self_param = || {
if self_param {
let self_ty = explicit_self_ty.map(|x| x.cast(Interner)).unwrap_or_else(ty_error);
if let Some(id) = def_toc_iter.next() {
assert!(matches!(id, GenericParamId::TypeParamId(_)));
substs.push(self_ty);
}
}
};
let mut had_explicit_args = false;
if let Some(&GenericArgs { ref args, has_self_type, .. }) = args_and_bindings {
// Fill in the self param first
if has_self_type && self_param {
had_explicit_args = true;
if let Some(id) = def_toc_iter.next() {
assert!(matches!(id, GenericParamId::TypeParamId(_)));
had_explicit_args = true;
if let GenericArg::Type(ty) = &args[0] {
substs.push(self.lower_ty(ty).cast(Interner));
}
}
} else {
fill_self_param()
};
// Then fill in the supplied lifetime args, or error lifetimes if there are too few
// (default lifetimes aren't a thing)
for arg in args
.iter()
.filter_map(|arg| match arg {
GenericArg::Lifetime(arg) => Some(self.lower_lifetime(arg)),
_ => None,
})
.chain(iter::repeat(error_lifetime()))
.take(lifetime_params)
{
substs.push(arg.cast(Interner));
}
let skip = if has_self_type { 1 } else { 0 };
// Fill in supplied type and const args
// Note if non-lifetime args are provided, it should be all of them, but we can't rely on that
for (arg, id) in args
.iter()
.filter(|arg| !matches!(arg, GenericArg::Lifetime(_)))
.skip(skip)
.take(type_params + const_params)
.zip(def_toc_iter)
{
had_explicit_args = true;
let arg = generic_arg_to_chalk(
self.db,
id,
arg,
&mut (),
|_, type_ref| self.lower_ty(type_ref),
|_, const_ref, ty| self.lower_const(const_ref, ty),
|_, lifetime_ref| self.lower_lifetime(lifetime_ref),
);
substs.push(arg);
}
} else {
fill_self_param();
}
let param_to_err = |id| match id {
GenericParamId::ConstParamId(x) => unknown_const_as_generic(self.db.const_param_ty(x)),
GenericParamId::TypeParamId(_) => ty_error(),
GenericParamId::LifetimeParamId(_) => error_lifetime().cast(Interner),
};
// handle defaults. In expression or pattern path segments without
// explicitly specified type arguments, missing type arguments are inferred
// (i.e. defaults aren't used).
// Generic parameters for associated types are not supposed to have defaults, so we just
// ignore them.
let is_assoc_ty = || match def {
GenericDefId::TypeAliasId(id) => {
matches!(id.lookup(self.db.upcast()).container, ItemContainerId::TraitId(_))
}
_ => false,
};
let fill_defaults = (!infer_args || had_explicit_args) && !is_assoc_ty();
if fill_defaults {
let defaults = &*self.db.generic_defaults(def);
let (item, _parent) = defaults.split_at(item_len);
let parent_from = item_len - substs.len();
let mut rem =
def_generics.iter_id().skip(substs.len()).map(param_to_err).collect::<Vec<_>>();
// Fill in defaults for type/const params
for (idx, default_ty) in item[substs.len()..].iter().enumerate() {
// each default can depend on the previous parameters
let substs_so_far = Substitution::from_iter(
Interner,
substs.iter().cloned().chain(rem[idx..].iter().cloned()),
);
substs.push(default_ty.clone().substitute(Interner, &substs_so_far));
}
// Fill in remaining parent params
substs.extend(rem.drain(parent_from..));
} else {
// Fill in remaining def params and parent params
substs.extend(def_generics.iter_id().skip(substs.len()).map(param_to_err));
}
assert_eq!(substs.len(), total_len, "expected {} substs, got {}", total_len, substs.len());
Substitution::from_iter(Interner, substs)
}
fn lower_trait_ref_from_path(
&self,
path: &Path,
explicit_self_ty: Option<Ty>,
) -> Option<TraitRef> {
let resolved = match self.resolver.resolve_path_in_type_ns_fully(self.db.upcast(), path)? {
// FIXME(trait_alias): We need to handle trait alias here.
TypeNs::TraitId(tr) => tr,
_ => return None,
};
let segment = path.segments().last().expect("path should have at least one segment");
Some(self.lower_trait_ref_from_resolved_path(resolved, segment, explicit_self_ty))
}
pub(crate) fn lower_trait_ref_from_resolved_path(
&self,
resolved: TraitId,
segment: PathSegment<'_>,
explicit_self_ty: Option<Ty>,
) -> TraitRef {
let substs = self.trait_ref_substs_from_path(segment, resolved, explicit_self_ty);
TraitRef { trait_id: to_chalk_trait_id(resolved), substitution: substs }
}
fn lower_trait_ref(
&self,
trait_ref: &HirTraitRef,
explicit_self_ty: Option<Ty>,
) -> Option<TraitRef> {
self.lower_trait_ref_from_path(&trait_ref.path, explicit_self_ty)
}
fn trait_ref_substs_from_path(
&self,
segment: PathSegment<'_>,
resolved: TraitId,
explicit_self_ty: Option<Ty>,
) -> Substitution {
self.substs_from_path_segment(segment, Some(resolved.into()), false, explicit_self_ty)
}
pub(crate) fn lower_where_predicate<'b>(
&'b self,
where_predicate: &'b WherePredicate,