-
Notifications
You must be signed in to change notification settings - Fork 380
/
ImplLookup.kt
1430 lines (1256 loc) · 61.2 KB
/
ImplLookup.kt
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 of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve
import com.intellij.openapi.project.Project
import com.intellij.util.SmartList
import gnu.trove.THashMap
import org.rust.lang.core.crate.Crate
import org.rust.lang.core.crate.hasTransitiveDependencyOrSelf
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.SelectionCandidate.*
import org.rust.lang.core.types.*
import org.rust.lang.core.types.consts.CtConstParameter
import org.rust.lang.core.types.consts.CtInferVar
import org.rust.lang.core.types.consts.FreshCtInferVar
import org.rust.lang.core.types.infer.*
import org.rust.lang.core.types.infer.TypeInferenceMarks.WinnowParamCandidateLoses
import org.rust.lang.core.types.infer.TypeInferenceMarks.WinnowParamCandidateWins
import org.rust.lang.core.types.ty.*
import org.rust.openapiext.hitOnTrue
import org.rust.openapiext.testAssert
import org.rust.stdext.buildList
import org.rust.stdext.exhaustive
import org.rust.stdext.swapRemoveAt
import kotlin.LazyThreadSafetyMode.NONE
import kotlin.LazyThreadSafetyMode.PUBLICATION
private val RsTraitItem.typeParamSingle: TyTypeParameter?
get() = typeParameters.singleOrNull()?.let { TyTypeParameter.named(it) }
const val DEFAULT_RECURSION_LIMIT = 128
sealed class TraitImplSource {
abstract val value: RsTraitOrImpl
open val implementedTrait: BoundElement<RsTraitItem>? get() = value.implementedTrait
/** For `impl T for Foo` returns union of impl members and trait `T` members that are not overridden by the impl */
abstract val implAndTraitExpandedMembers: Map<String, List<RsAbstractable>>
open val isInherent: Boolean get() = false
val requiredTraitInScope: RsTraitItem?
get() {
if (isInherent) return null
return when (this) {
is ExplicitImpl -> implementedTrait?.element
else -> value as RsTraitItem
}
}
val impl: RsImplItem?
get() = (this as? ExplicitImpl)?.value
/** An impl block, directly defined in the code */
data class ExplicitImpl(private val cachedImpl: RsCachedImplItem) : TraitImplSource() {
override val value: RsImplItem get() = cachedImpl.impl
override val isInherent: Boolean get() = cachedImpl.isInherent
override val implementedTrait: BoundElement<RsTraitItem>? get() = cachedImpl.implementedTrait
override val implAndTraitExpandedMembers: Map<String, List<RsAbstractable>>
get() = cachedImpl.implAndTraitExpandedMembers
val type: Ty? get() = cachedImpl.typeAndGenerics?.first
}
/** T: Trait */
data class TraitBound(override val value: RsTraitItem, override val isInherent: Boolean) : TraitImplSource() {
override val implAndTraitExpandedMembers: Map<String, List<RsAbstractable>> by lazyTraitMembers(value)
}
/**
* Like [TraitBound], but this is a bound for an associated type projection defined at the trait
* of the associated type.
* ```
* trait Foo where Self::Assoc: Bar {
* type Assoc; //^ the bound
* }
* ```
* or
* ```
* trait Foo {
* type Assoc: Bar;
* } //^ the bound
* ```
*/
data class ProjectionBound(override val value: RsTraitItem) : TraitImplSource() {
override val implAndTraitExpandedMembers: Map<String, List<RsAbstractable>> by lazyTraitMembers(value)
}
/** Trait is implemented for item via ```#[derive]``` attribute. */
data class Derived(override val value: RsTraitItem) : TraitImplSource() {
override val implAndTraitExpandedMembers: Map<String, List<RsAbstractable>> by lazyTraitMembers(value)
}
/** dyn/impl Trait or a closure */
data class Object(override val value: RsTraitItem) : TraitImplSource() {
override val implAndTraitExpandedMembers: Map<String, List<RsAbstractable>> by lazyTraitMembers(value)
override val isInherent: Boolean get() = true
}
/**
* Used only as a result of method pick. It means that method is resolved to multiple impls of the same trait
* (with different type parameter values), so we collapsed all impls to that trait. Specific impl
* will be selected during type inference.
*/
data class Collapsed(override val value: RsTraitItem) : TraitImplSource() {
override val implAndTraitExpandedMembers: Map<String, List<RsAbstractable>> by lazyTraitMembers(value)
}
/**
* A trait is directly referenced in UFCS path `TraitName::foo`, an impl should be selected
* during type inference
*/
data class Trait(override val value: RsTraitItem) : TraitImplSource() {
override val implAndTraitExpandedMembers: Map<String, List<RsAbstractable>> by lazyTraitMembers(value)
}
/** A built-in trait impl, like `Clone` impl for tuples */
data class Builtin(override val value: RsTraitItem) : TraitImplSource() {
override val implAndTraitExpandedMembers: Map<String, List<RsAbstractable>> by lazyTraitMembers(value)
}
companion object {
@JvmStatic
private fun lazyTraitMembers(trait: RsTraitItem): Lazy<THashMap<String, MutableList<RsAbstractable>>> =
lazy(PUBLICATION) { collectTraitMembers(trait) }
@JvmStatic
private fun collectTraitMembers(trait: RsTraitItem): THashMap<String, MutableList<RsAbstractable>> {
val membersMap = THashMap<String, MutableList<RsAbstractable>>()
for (member in trait.members?.expandedMembers.orEmpty()) {
val name = member.name ?: continue
membersMap.getOrPut(name) { SmartList() }.add(member)
}
return membersMap
}
}
}
/**
* When type checking, we use the `ParamEnv` to track details about the set of where-clauses
* that are in scope at this particular point.
* Note: ParamEnv of an associated item (method) also contains bounds of its trait/impl
* Note: callerBounds should have type `List<Predicate>` to also support lifetime bounds
*/
data class ParamEnv(val callerBounds: List<TraitRef>) {
fun boundsFor(ty: Ty): Sequence<BoundElement<RsTraitItem>> =
callerBounds.asSequence().filter { it.selfTy.isEquivalentTo(ty) }.map { it.trait }
fun isEmpty(): Boolean = callerBounds.isEmpty()
companion object {
val EMPTY: ParamEnv = ParamEnv(emptyList())
val LEGACY: ParamEnv = ParamEnv(emptyList())
fun buildFor(decl: RsGenericDeclaration): ParamEnv {
val rawBounds = buildList<TraitRef> {
addAll(decl.bounds)
if (decl is RsAbstractable) {
when (val owner = decl.owner) {
is RsAbstractableOwner.Trait -> {
add(TraitRef(TyTypeParameter.self(), owner.trait.withDefaultSubst()))
addAll(owner.trait.bounds)
}
is RsAbstractableOwner.Impl -> {
addAll(owner.impl.bounds)
}
else -> Unit
}
}
}.flatMap { ref -> ref.trait.flattenHierarchy.map { TraitRef(ref.selfTy, it) } }
.distinct()
when (rawBounds.size) {
0 -> return EMPTY
1 -> return ParamEnv(rawBounds)
}
val lookup = ImplLookup(decl.project, decl.containingCrate, decl.knownItems, ParamEnv(rawBounds))
val ctx = lookup.ctx
val bounds2 = rawBounds.map {
val (bound, obligations) = ctx.normalizeAssociatedTypesIn(it)
obligations.forEach(ctx.fulfill::registerPredicateObligation)
bound
}
ctx.fulfill.selectWherePossible()
return ParamEnv(bounds2.map { ctx.fullyResolve(it) })
}
}
}
class ImplLookup(
private val project: Project,
private val containingCrate: Crate?,
val items: KnownItems,
private val paramEnv: ParamEnv = ParamEnv.EMPTY
) {
// Non-concurrent HashMap and lazy(NONE) are safe here because this class isn't shared between threads
private val traitSelectionCache: MutableMap<TraitRef, SelectionResult<SelectionCandidate>> = hashMapOf()
private val findImplsAndTraitsCache: MutableMap<Ty, List<TraitImplSource>> = hashMapOf()
private val indexCache = RsImplIndexAndTypeAliasCache.getInstance(project)
private val fnTraits = listOfNotNull(items.Fn, items.FnMut, items.FnOnce)
private val fnOnceOutput: RsTypeAlias? by lazy(NONE) {
val trait = items.FnOnce ?: return@lazy null
trait.findAssociatedType("Output")
}
private val derefTraitAndTarget: Pair<RsTraitItem, RsTypeAlias>? = run {
val trait = items.Deref ?: return@run null
trait.findAssociatedType("Target")?.let { trait to it }
}
private val indexTraitAndOutput: Pair<RsTraitItem, RsTypeAlias>? by lazy(NONE) {
val trait = items.Index ?: return@lazy null
trait.findAssociatedType("Output")?.let { trait to it }
}
private val intoIteratorTraitAndOutput: Pair<RsTraitItem, RsTypeAlias>? by lazy(NONE) {
val trait = items.IntoIterator ?: return@lazy null
trait.findAssociatedType("Item")?.let { trait to it }
}
val ctx: RsInferenceContext by lazy(NONE) {
RsInferenceContext(project, this, items)
}
fun getEnvBoundTransitivelyFor(ty: Ty): Sequence<BoundElement<RsTraitItem>> {
if (paramEnv == ParamEnv.LEGACY && ty is TyTypeParameter) {
@Suppress("DEPRECATION")
return ty.getTraitBoundsTransitively().asSequence()
}
return paramEnv.boundsFor(ty)
}
/** Resulting sequence is ordered: inherent impls are placed to the head */
fun findImplsAndTraits(ty: Ty): Sequence<TraitImplSource> {
val cached = findImplsAndTraitsCache.getOrPut(freshen(ty)) { rawFindImplsAndTraits(ty) }
val isInherentBounds = ty is TyTypeParameter
val envBounds = getEnvBoundTransitivelyFor(ty)
.map { TraitImplSource.TraitBound(it.element, isInherent = isInherentBounds) }
return if (isInherentBounds) envBounds + cached.asSequence() else cached.asSequence() + envBounds
}
private fun rawFindImplsAndTraits(ty: Ty): List<TraitImplSource> {
val implsAndTraits = mutableListOf<TraitImplSource>()
when (ty) {
is TyTraitObject -> {
ty.getTraitBoundsTransitively().mapTo(implsAndTraits) { TraitImplSource.Object(it.element) }
findExplicitImpls(ty) { implsAndTraits += it.explicitImpl; false }
}
is TyFunction -> {
findExplicitImpls(ty) { implsAndTraits += it.explicitImpl; false }
implsAndTraits += fnTraits.map { TraitImplSource.Object(it) }
listOfNotNull(items.Clone, items.Copy).mapTo(implsAndTraits) { TraitImplSource.Builtin(it) }
}
is TyAnon -> {
ty.getTraitBoundsTransitively()
.distinctBy { it.element }
.mapTo(implsAndTraits) { TraitImplSource.Object(it.element) }
findBlanketImpls().forEach {
if (!it.isNegativeImpl) {
implsAndTraits += it.explicitImpl
}
}
}
is TyProjection -> {
val subst = ty.trait.subst + mapOf(TyTypeParameter.self() to ty.type).toTypeSubst()
implsAndTraits += ty.trait.element.bounds.asSequence()
.filter { ctx.probe { ctx.combineTypes(it.selfTy.substitute(subst), ty) }.isOk }
.flatMap { it.trait.flattenHierarchy.asSequence() }
.map { TraitImplSource.ProjectionBound(it.element) }
.distinct()
}
is TyUnknown -> Unit
else -> {
implsAndTraits += findDerivedTraits(ty).map { TraitImplSource.Derived(it) }
findExplicitImpls(ty) { implsAndTraits += it.explicitImpl; false }
if (ty is TyTuple || ty is TyUnit) {
listOfNotNull(items.Clone, items.Copy).mapTo(implsAndTraits) { TraitImplSource.Builtin(it) }
}
}
}
// Place inherent impls to the head of the list
implsAndTraits.sortBy { !it.isInherent }
testAssert { implsAndTraits.distinct().size == implsAndTraits.size }
return implsAndTraits
}
private fun findDerivedTraits(ty: Ty): Collection<RsTraitItem> {
return (ty as? TyAdt)?.item?.derivedTraits.orEmpty()
// select only std traits because we are sure
// that they are resolved correctly
.filter { it.isKnownDerivable }
}
private fun findExplicitImpls(selfTy: Ty, processor: RsProcessor<RsCachedImplItem>): Boolean {
return processTyFingerprintsWithAliases(selfTy) { tyFingerprint ->
findExplicitImplsWithoutAliases(selfTy, tyFingerprint, processor)
}
}
private fun findExplicitImplsWithoutAliases(selfTy: Ty, tyf: TyFingerprint, processor: RsProcessor<RsCachedImplItem>): Boolean {
val impls = findPotentialImpls(tyf)
return impls.any { cachedImpl ->
if (cachedImpl.isNegativeImpl) return@any false
val (type, generics, constGenerics) = cachedImpl.typeAndGenerics ?: return@any false
val isAppropriateImpl = canCombineTypes(selfTy, type, generics, constGenerics) &&
// Check that trait is resolved if it's not an inherent impl; checking it after types because
// we assume that unresolved trait is a rare case
(cachedImpl.isInherent || cachedImpl.implementedTrait != null)
isAppropriateImpl && processor(cachedImpl)
}
}
private fun processTyFingerprintsWithAliases(selfTy: Ty, processor: RsProcessor<TyFingerprint>): Boolean {
val fingerprint = TyFingerprint.create(selfTy)
if (fingerprint != null) {
val set = mutableSetOf(fingerprint)
if (processor(fingerprint)) return true
val aliases = findPotentialAliases(fingerprint)
val result = aliases.any {
val name = it.name ?: return@any false
val aliasFingerprint = TyFingerprint(name)
val isAppropriateAlias = set.add(aliasFingerprint) && run {
val (declaredType, generics, constGenerics) = it.typeAndGenerics
canCombineTypes(selfTy, declaredType, generics, constGenerics)
}
isAppropriateAlias && processor(aliasFingerprint)
}
if (result) return true
}
return processor(TyFingerprint.TYPE_PARAMETER_OR_MACRO_FINGERPRINT)
}
private fun findPotentialImpls(tyf: TyFingerprint): Sequence<RsCachedImplItem> =
indexCache.findPotentialImpls(tyf)
.asSequence()
.filter { useImplsFromCrate(it.containingCrate) }
private fun findPotentialAliases(tyf: TyFingerprint) =
indexCache.findPotentialAliases(tyf)
.asSequence()
.filter { useImplsFromCrate(it.containingCrate) }
private fun useImplsFromCrate(crate: Crate?): Boolean =
containingCrate == null || crate != null && containingCrate.hasTransitiveDependencyOrSelf(crate)
private fun canCombineTypes(
ty1: Ty,
ty2: Ty,
genericsForTy2: List<TyTypeParameter>,
constGenericsForTy2: List<CtConstParameter>
): Boolean {
// Optimization: early handle common cases in order to avoid heavier probe/substitute/ctx.combineTypes
if (genericsForTy2.size < 5) {
if (ty2 in genericsForTy2) return true
if (ty2 is TyReference && ty2.referenced in genericsForTy2) {
return ty1 is TyReference && ty1.mutability == ty2.mutability
}
}
val subst = Substitution(
typeSubst = genericsForTy2.associateWith { ctx.typeVarForParam(it) },
constSubst = constGenericsForTy2.associateWith { ctx.constVarForParam(it) }
)
// TODO: take into account the lifetimes (?)
return ctx.probe {
val (normTy2, _) = ctx.normalizeAssociatedTypesIn(ty2.substitute(subst))
ctx.combineTypes(normTy2, ty1).isOk
}
}
/** return impls for a generic type `impl<T> Trait for T {}` */
private fun findBlanketImpls(): Sequence<RsCachedImplItem> {
return findPotentialImpls(TyFingerprint.TYPE_PARAMETER_OR_MACRO_FINGERPRINT)
}
/**
* Checks that trait can be successfully selected on any deref level.
* E.g. for type `&&T` it try to select trait for `&&T`, `&T` and `T` types
* See [select]
*/
fun canSelectWithDeref(ref: TraitRef, recursionDepth: Int = 0): Boolean =
coercionSequence(ref.selfTy)
.any { canSelect(TraitRef(it, ref.trait), recursionDepth) }
/** Checks that trait can be successfully selected. See [select] */
fun canSelect(ref: TraitRef, recursionDepth: Int = 0): Boolean =
selectStrictWithoutConfirm(ref, recursionDepth).isOk()
/** Same as [select], but strictly evaluates all obligations (checks trait bounds) of impls */
fun selectStrict(ref: TraitRef, recursionDepth: Int = 0): SelectionResult<Selection> =
selectStrictWithoutConfirm(ref, recursionDepth).andThen { confirmCandidate(ref, it, recursionDepth) }
private fun selectStrictWithoutConfirm(ref: TraitRef, recursionDepth: Int): SelectionResult<SelectionCandidate> {
val result = selectWithoutConfirm(ref, BoundConstness.NotConst, recursionDepth)
val candidate = result.ok() ?: return result.map { error("unreachable") }
// TODO optimize it. Obligations may be already evaluated, so we don't need to re-evaluated it
if (!canEvaluateObligations(ref, candidate, recursionDepth)) return SelectionResult.Err
return result
}
fun select(ref: TraitRef, recursionDepth: Int = 0): SelectionResult<Selection> =
select(ref, BoundConstness.NotConst, recursionDepth)
/**
* If the TraitRef is a something like
* `T : Foo<U>`
* here we select an impl of the trait `Foo<U>` for the type `T`, i.e.
* `impl Foo<U> for T {}`
*/
fun select(ref: TraitRef, constness: BoundConstness, recursionDepth: Int = 0): SelectionResult<Selection> =
selectWithoutConfirm(ref, constness, recursionDepth).andThen { confirmCandidate(ref, it, recursionDepth) }
private fun selectWithoutConfirm(
ref: TraitRef,
constness: BoundConstness,
recursionDepth: Int
): SelectionResult<SelectionCandidate> {
if (recursionDepth > DEFAULT_RECURSION_LIMIT) {
TypeInferenceMarks.TraitSelectionOverflow.hit()
return SelectionResult.Err
}
testAssert { !ctx.hasResolvableTypeVars(ref) }
// BACKCOMPAT rustc 1.61.0: there are `~const Drop` bounds in stdlib that must be always satisfied in
// a non-const context. In newer rustc version these bounds are removed
if (constness == BoundConstness.ConstIfConst && ref.trait.element == items.Drop) {
return SelectionResult.Ok(ParamCandidate(BoundElement(ref.trait.element)))
}
return traitSelectionCache.getOrPut(freshen(ref)) { selectCandidate(ref, recursionDepth) }
}
private fun selectCandidate(ref: TraitRef, recursionDepth: Int): SelectionResult<SelectionCandidate> {
if (ref.selfTy is TyInfer.TyVar) {
return SelectionResult.Ambiguous
}
if (ref.selfTy is TyReference && ref.selfTy.referenced is TyInfer.TyVar) {
// This condition is related to TyFingerprint internals: TyFingerprint should not be created for
// TyInfer.TyVar, and TyReference is a single special case: it unwraps during TyFingerprint creation
return SelectionResult.Ambiguous
}
val candidateSet = assembleCandidates(ref)
if (candidateSet.ambiguous) {
return SelectionResult.Ambiguous
}
val candidates = candidateSet.list.filter { it !is ImplCandidate.ExplicitImpl || !it.isNegativeImpl }
return when (candidates.size) {
0 -> SelectionResult.Err
1 -> SelectionResult.Ok(candidates.single())
else -> {
val filtered = candidates.filterTo(mutableListOf()) {
canEvaluateObligations(ref, it, recursionDepth)
}
when (filtered.size) {
0 -> SelectionResult.Err
1 -> SelectionResult.Ok(filtered.single())
else -> {
var i = 0
while (i < filtered.size) {
val isDup = (0 until filtered.size).filter { it != i }.any {
candidateShouldBeDroppedInFavorOf(ref.selfTy, filtered[i], filtered[it])
}
if (isDup) {
filtered.swapRemoveAt(i)
} else {
i++
if (i > 1) {
return SelectionResult.Ambiguous
}
}
}
filtered.singleOrNull()
?.let { SelectionResult.Ok(it) }
?: SelectionResult.Ambiguous
}
}
}
}
}
/**
* When we doing an independent cache lookups we want to treat
* these types as the same (A & B is type variables)
* ` S<A, B, A> == S<B, A, B>`
*/
private fun <T : TypeFoldable<T>> freshen(ty: T): T {
val tyMap = hashMapOf<TyInfer, FreshTyInfer>()
val constMap = hashMapOf<CtInferVar, FreshCtInferVar>()
var counter = 0
return ty
.foldTyInferWith {
tyMap.getOrPut(it) {
when (it) {
is TyInfer.TyVar -> FreshTyInfer.TyVar(counter++)
is TyInfer.IntVar -> FreshTyInfer.IntVar(counter++)
is TyInfer.FloatVar -> FreshTyInfer.FloatVar(counter++)
}
}
}
.foldCtInferWith {
constMap.getOrPut(it) { FreshCtInferVar(counter++) }
}
}
private fun canEvaluateObligations(ref: TraitRef, candidate: SelectionCandidate, recursionDepth: Int): Boolean {
return ctx.probe {
val obligation = confirmCandidate(ref, candidate, recursionDepth).ok()?.nestedObligations ?: return false
val ff = FulfillmentContext(ctx, this)
obligation.forEach(ff::registerPredicateObligation)
ff.selectUntilError()
}
}
// https://github.com/rust-lang/rust/blob/3a90bedb332d/compiler/rustc_trait_selection/src/traits/select/mod.rs#L1522
private fun candidateShouldBeDroppedInFavorOf(
selfTy: Ty,
victim: SelectionCandidate,
other: SelectionCandidate
): Boolean {
if (victim.isEquivalentTo(other)) {
return true
}
return when {
other is BuiltinCandidate && !other.hasNested
|| other == ConstDestructCandidate -> true
victim is BuiltinCandidate && !victim.hasNested
|| victim == ConstDestructCandidate -> false
other is ParamCandidate && (
victim is ImplCandidate
// || victim is ClosureCandidate
// || victim is GeneratorCandidate
|| victim is FnPointerCandidate
// || victim is BuiltinObjectCandidate
|| victim is BuiltinUnsizeCandidate
// || victim is TraitUpcastingUnsizeCandidate
|| victim is BuiltinCandidate
// || victim is TraitAliasCandidate
|| victim is ObjectCandidate
|| victim is ProjectionCandidate
) -> WinnowParamCandidateWins.hitOnTrue(!(selfTy.isGlobal && other.bound.isGlobal))
(
other is ImplCandidate
// || other is ClosureCandidate
// || other is GeneratorCandidate
|| other is FnPointerCandidate
// || other is BuiltinObjectCandidate
|| other is BuiltinUnsizeCandidate
// || other is TraitUpcastingUnsizeCandidate
|| other is BuiltinCandidate
// || other is TraitAliasCandidate
|| other is ObjectCandidate
|| other is ProjectionCandidate
) && victim is ParamCandidate -> WinnowParamCandidateLoses.hitOnTrue(selfTy.isGlobal && victim.bound.isGlobal)
(other is ObjectCandidate || other is ProjectionCandidate) && (
victim is ImplCandidate
// || victim is ClosureCandidate
// || victim is GeneratorCandidate
|| victim is FnPointerCandidate
// || victim is BuiltinObjectCandidate
|| victim is BuiltinUnsizeCandidate
// || victim is TraitUpcastingUnsizeCandidate
|| victim is BuiltinCandidate
// || victim is TraitAliasCandidate
) -> TypeInferenceMarks.WinnowObjectOrProjectionCandidateWins.hitOnTrue(true)
(
other is ImplCandidate
// || other is ClosureCandidate
// || other is GeneratorCandidate
|| other is FnPointerCandidate
// || other is BuiltinObjectCandidate
|| other is BuiltinUnsizeCandidate
// || other is TraitUpcastingUnsizeCandidate
|| other is BuiltinCandidate
// || other is TraitAliasCandidate
) && (victim is ObjectCandidate || victim is ProjectionCandidate) -> false
// basic specialization
victim is ImplCandidate.ExplicitImpl && victim.formalSelfTy is TyTypeParameter
&& other is ImplCandidate.ExplicitImpl && other.formalSelfTy !is TyTypeParameter -> {
TypeInferenceMarks.WinnowSpecialization.hit()
true
}
else -> false
}
}
// https://github.com/rust-lang/rust/blob/3a90bedb332d/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs#L242
private fun assembleCandidates(ref: TraitRef): SelectionCandidateSet {
val candidates = SelectionCandidateSet()
val trait = ref.trait.element
when (trait) {
items.Copy -> {
assembleCandidatesFromImpls(ref, candidates)
assembleBuiltinBoundCandidates(copyCloneConditions(ref.selfTy), candidates)
}
items.Sized -> assembleBuiltinBoundCandidates(sizedConditions(ref), candidates)
items.Unsize -> assembleCandidatesForUnsizing(ref, candidates)
items.Destruct -> candidates.list.add(ConstDestructCandidate)
else -> {
if (trait == items.Clone) {
assembleBuiltinBoundCandidates(copyCloneConditions(ref.selfTy), candidates)
}
assembleFnPointerCandidates(ref, candidates)
assembleCandidatesFromImpls(ref, candidates)
assembleCandidatesFromObjectTy(ref, candidates)
}
}
assembleCandidatesFromProjectedTys(ref, candidates)
assembleCandidatesFromCallerBounds(ref, candidates)
// Auto implementations have lower priority, so we only consider triggering a default if
// there is no other impl that can apply. Note that `candidates.list` also contains negative
// impl like `impl !Sync for Foo {}`
if (candidates.list.isEmpty() && trait.isAuto) {
assembleCandidatesFromAutoImpls(ref, candidates)
}
return candidates
}
private fun assembleBuiltinBoundCandidates(conditions: BuiltinImplConditions, candidates: SelectionCandidateSet) {
when (conditions) {
is BuiltinImplConditions.Where -> {
candidates.list += BuiltinCandidate(hasNested = conditions.nested.isNotEmpty())
}
BuiltinImplConditions.None -> Unit
BuiltinImplConditions.Ambiguous -> candidates.ambiguous = true
}.exhaustive
}
// https://github.com/rust-lang/rust/blob/3a90bedb332d/compiler/rustc_trait_selection/src/traits/select/mod.rs#L1820
private fun copyCloneConditions(selfTy: Ty): BuiltinImplConditions {
return when (selfTy) {
is TyInfer.IntVar, is TyInfer.FloatVar, is TyFunction, TyUnknown, is TyUnit -> {
BuiltinImplConditions.Where(emptyList())
}
is TyInteger, is TyFloat, is TyBool, is TyChar, is TyPointer, is TyNever, is TyReference, is TyArray -> {
// Implementations provided in libcore
BuiltinImplConditions.None
}
is TyTuple -> BuiltinImplConditions.Where(selfTy.types)
else -> BuiltinImplConditions.None
}
}
/** See `org.rust.lang.core.type.RsImplicitTraitsTest` */
private fun sizedConditions(ref: TraitRef): BuiltinImplConditions {
return when (val selfTy = ref.selfTy) {
is TyInfer.IntVar,
is TyInfer.FloatVar,
is TyNumeric,
is TyBool,
is TyFunction,
is TyPointer,
is TyReference,
is TyChar,
is TyArray,
TyNever,
is TyUnit,
is TyUnknown -> BuiltinImplConditions.Where(emptyList())
is TyStr, is TySlice, is TyTraitObject /*is TyForeign*/ -> BuiltinImplConditions.None
is TyTuple -> BuiltinImplConditions.Where(listOf(selfTy.types.last()))
is TyAdt -> BuiltinImplConditions.Where(listOfNotNull(selfTy.structTail()))
is TyProjection, is TyTypeParameter, is TyAnon -> BuiltinImplConditions.None
is TyInfer.TyVar -> BuiltinImplConditions.Ambiguous
else -> BuiltinImplConditions.None
}
}
private fun assembleFnPointerCandidates(ref: TraitRef, candidates: SelectionCandidateSet) {
val element = ref.trait.element
getTyFunctionImpls(ref.selfTy).filter { be ->
be.element == element && ctx.probe {
ctx.combineTypePairs(be.subst.zipTypeValues(ref.trait.subst)).isOk &&
ctx.combineConstPairs(be.subst.zipConstValues(ref.trait.subst)).isOk
}
}.mapTo(candidates.list) { FnPointerCandidate }
}
// TODO simplify
private fun getTyFunctionImpls(ty: Ty): Collection<BoundElement<RsTraitItem>> {
if (ty is TyFunction) {
val fnOnceOutput = fnOnceOutput
val args = if (ty.paramTypes.isEmpty()) TyUnit.INSTANCE else TyTuple(ty.paramTypes)
val assoc = if (fnOnceOutput != null) mapOf(fnOnceOutput to ty.retType) else emptyMap()
return fnTraits.map { it.withSubst(args).copy(assoc = assoc) } +
listOfNotNull(items.Clone, items.Copy).map { BoundElement(it) }
}
return emptyList()
}
private fun assembleCandidatesFromObjectTy(ref: TraitRef, candidates: SelectionCandidateSet) {
if (ref.selfTy is TyTraitObject) {
ref.selfTy.getTraitBoundsTransitively().find { it.element == ref.trait.element }
?.let { candidates.list.add(ObjectCandidate) }
}
}
private fun assembleCandidatesFromProjectedTys(ref: TraitRef, candidates: SelectionCandidateSet) {
val selfTy = ref.selfTy
if (selfTy is TyProjection) {
val subst = selfTy.trait.subst + mapOf(TyTypeParameter.self() to selfTy.type).toTypeSubst()
selfTy.trait.element.bounds.asSequence()
.filter { ctx.probe { ctx.combineTypes(it.selfTy.substitute(subst), selfTy) }.isOk }
.flatMap { it.trait.flattenHierarchy.asSequence() }
.distinct()
.filter { ctx.probe { ctx.combineBoundElements(it.substitute(subst), ref.trait) } }
.forEach { candidates.list.add(ProjectionCandidate(it)) }
}
if (selfTy is TyAnon) {
selfTy.getTraitBoundsTransitively().find { it.element == ref.trait.element }
?.let { candidates.list.add(ObjectCandidate) }
}
}
private fun assembleCandidatesFromCallerBounds(ref: TraitRef, candidates: SelectionCandidateSet) {
getEnvBoundTransitivelyFor(ref.selfTy)
.filter { ctx.probe { ctx.combineBoundElements(it, ref.trait) } }
.mapTo(candidates.list) { ParamCandidate(it) }
}
private fun assembleCandidatesFromImpls(ref: TraitRef, candidates: SelectionCandidateSet) {
assembleDerivedCandidates(ref, candidates)
assembleCandidatesFromImpls(ref) {
candidates.list += it
false
}
}
private fun assembleCandidatesFromImpls(ref: TraitRef, processor: RsProcessor<SelectionCandidate>): Boolean {
return processTyFingerprintsWithAliases(ref.selfTy) { tyFingerprint ->
assembleImplCandidatesWithoutAliases(ref, tyFingerprint, processor)
}
}
private fun assembleImplCandidatesWithoutAliases(ref: TraitRef, tyf: TyFingerprint, processor: RsProcessor<SelectionCandidate>): Boolean {
val impls = findPotentialImpls(tyf)
return impls.any {
val candidate = it.trySelectCandidate(ref)
candidate != null && processor(candidate)
}
}
private fun RsCachedImplItem.trySelectCandidate(ref: TraitRef): SelectionCandidate? {
val formalTraitRef = implementedTrait ?: return null
if (formalTraitRef.element != ref.trait.element) return null
val (formalSelfTy, generics, constGenerics) = typeAndGenerics ?: return null
val probe = ctx.probe {
val (_, implTraitRef, _) =
prepareSubstAndTraitRefRaw(ctx, generics, constGenerics, formalSelfTy, formalTraitRef, ref.selfTy, 0)
ctx.combineTraitRefs(implTraitRef, ref)
}
if (!probe) return null
return ImplCandidate.ExplicitImpl(impl, formalSelfTy, formalTraitRef, isNegativeImpl)
}
private fun assembleDerivedCandidates(ref: TraitRef, candidates: SelectionCandidateSet) {
(ref.selfTy as? TyAdt)?.item?.derivedTraits.orEmpty()
// select only std traits because we are sure
// that they are resolved correctly
.filter { it.isKnownDerivable }
.filter { it == ref.trait.element }
.mapTo(candidates.list) { ImplCandidate.DerivedTrait(it) }
}
// Mirrors rustc's `assemble_candidates_for_unsizing`
// https://github.com/rust-lang/rust/blob/97d48bec2d/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs#L741
private fun assembleCandidatesForUnsizing(ref: TraitRef, candidates: SelectionCandidateSet) {
val source = ref.selfTy
val target = ref.trait.singleParamValue
when {
// Trait+Kx+'a -> Trait+Ky+'b (upcasts)
source is TyTraitObject && target is TyTraitObject -> {
candidates.list += BuiltinUnsizeCandidate // TODO
}
// `T` -> `Trait`
target is TyTraitObject -> candidates.list += BuiltinUnsizeCandidate
source is TyInfer.TyVar || target is TyInfer.TyVar -> {
candidates.ambiguous = true
}
// `[T; n]` -> `[T]`
source is TyArray && target is TySlice -> candidates.list += BuiltinUnsizeCandidate
// `Struct<T>` -> `Struct<U>`
source is TyAdt && target is TyAdt && source.item == target.item && source.item is RsStructItem
&& source.item.kind == RsStructKind.STRUCT -> candidates.list += BuiltinUnsizeCandidate
// `(.., T)` -> `(.., U)`
source is TyTuple && target is TyTuple && source.types.size == target.types.size ->
candidates.list += BuiltinUnsizeCandidate
}
}
private fun assembleCandidatesFromAutoImpls(ref: TraitRef, candidates: SelectionCandidateSet) {
// For now, just think that any type is Sync + Send
// TODO implement auto trait logic
candidates.list += ParamCandidate(BoundElement(ref.trait.element))
}
// https://github.com/rust-lang/rust/blob/3a90bedb332d/compiler/rustc_trait_selection/src/traits/select/confirmation.rs#L40
private fun confirmCandidate(
ref: TraitRef,
candidate: SelectionCandidate,
recursionDepth: Int
): SelectionResult<Selection> {
return when (candidate) {
is BuiltinCandidate -> {
SelectionResult.Ok(confirmBuiltinCandidate(ref, recursionDepth, candidate.hasNested))
}
is ParamCandidate -> {
SelectionResult.Ok(confirmParamCandidate(ref, candidate))
}
is ImplCandidate -> {
SelectionResult.Ok(confirmImplCandidate(ref, candidate, recursionDepth))
}
is ProjectionCandidate -> {
SelectionResult.Ok(confirmProjectionCandidate(ref, candidate))
}
ObjectCandidate -> {
SelectionResult.Ok(confirmObjectCandidate(ref))
}
BuiltinUnsizeCandidate -> {
confirmBuiltinUnsizeCandidate(ref, recursionDepth)
}
is FnPointerCandidate -> {
SelectionResult.Ok(confirmFnPointerCandidate(ref))
}
ConstDestructCandidate -> {
SelectionResult.Ok(Selection(ref.trait.element, emptyList()))
}
}
}
private fun confirmBuiltinCandidate(
ref: TraitRef,
recursionDepth: Int,
hasNested: Boolean,
): Selection {
val trait = ref.trait.element
val obligations = if (hasNested) {
val conditions = when (trait) {
items.Copy, items.Clone -> copyCloneConditions(ref.selfTy)
items.Sized -> sizedConditions(ref)
else -> {
error("unexpected builtin trait $trait")
}
} as? BuiltinImplConditions.Where ?: error("obligation $ref had matched a builtin impl but now doesn't")
collectPredicatesForTypes(recursionDepth + 1, trait, conditions.nested)
} else {
emptyList()
}
return Selection(trait, obligations)
}
private fun collectPredicatesForTypes(
recursionDepth: Int,
trait: RsTraitItem,
types: List<Ty>
): List<Obligation> {
return types.flatMap {
val (normTy, obligations) = ctx.normalizeAssociatedTypesIn(it, recursionDepth)
obligations + listOf(Obligation(recursionDepth, Predicate.Trait(TraitRef(normTy, trait.withSubst()))))
}
}
private fun confirmParamCandidate(ref: TraitRef, candidate: ParamCandidate): Selection {
testAssert { !candidate.bound.containsTyOfClass(TyInfer::class.java) }
ctx.combineBoundElements(candidate.bound, ref.trait)
return Selection(candidate.bound.element, emptyList())
}
private fun confirmImplCandidate(
ref: TraitRef,
candidate: ImplCandidate,
recursionDepth: Int
): Selection {
when (candidate) {
is ImplCandidate.DerivedTrait ->
return confirmDerivedCandidate(ref, candidate, recursionDepth)
is ImplCandidate.ExplicitImpl -> Unit
}
testAssert { !candidate.formalSelfTy.containsTyOfClass(TyInfer::class.java) }
testAssert { !candidate.formalTrait.containsTyOfClass(TyInfer::class.java) }
val (subst, preparedRef, typeObligations) = candidate.prepareSubstAndTraitRef(ctx, ref.selfTy, recursionDepth + 1)
ctx.combineTraitRefs(ref, preparedRef)
// pre-resolve type vars to simplify caching of already inferred obligation on fulfillment
val candidateSubst = ctx.resolveTypeVarsIfPossible(subst) +
mapOf(TyTypeParameter.self() to ref.selfTy).toTypeSubst()
val obligations = typeObligations +
ctx.instantiateBounds(candidate.impl.predicates, candidateSubst, recursionDepth + 1)
return Selection(candidate.impl, obligations, candidateSubst)
}
private fun confirmDerivedCandidate(
ref: TraitRef,
candidate: ImplCandidate.DerivedTrait,
recursionDepth: Int
): Selection {
val selfTy = ref.selfTy as TyAdt // Guaranteed by `assembleCandidates`
// For `#[derive(Clone)] struct S<T>(T);` add `T: Clone` obligation
val obligations = selfTy.typeArguments.map {
Obligation(recursionDepth + 1, Predicate.Trait(TraitRef(it, BoundElement(candidate.item))))
}
return Selection(candidate.item, obligations)
}
private fun confirmProjectionCandidate(ref: TraitRef, candidate: ProjectionCandidate): Selection {
ref.selfTy as TyProjection
val subst = ref.selfTy.trait.subst + mapOf(TyTypeParameter.self() to ref.selfTy.type).toTypeSubst()
ctx.combineTraitRefs(ref, TraitRef(ref.selfTy, candidate.bound.substitute(subst)))
return Selection(ref.trait.element, emptyList())
}
private fun confirmObjectCandidate(ref: TraitRef): Selection {
val traits = when (ref.selfTy) {
is TyTraitObject -> ref.selfTy.getTraitBoundsTransitively()
is TyAnon -> ref.selfTy.getTraitBoundsTransitively()
else -> error("unreachable")
}
// should be nonnull because already checked in `assembleCandidatesFromObjectTy`
val be = traits.find { it.element == ref.trait.element } ?: error("Corrupted trait selection")
ctx.combineBoundElements(be, ref.trait)
return Selection(be.element, emptyList())
}
// Mirrors rustc's `confirm_builtin_unsize_candidate`
// https://github.com/rust-lang/rust/blob/97d48bec2d/compiler/rustc_trait_selection/src/traits/select/confirmation.rs#L865
private fun confirmBuiltinUnsizeCandidate(
ref: TraitRef,
recursionDepth: Int
): SelectionResult<Selection> {
val unsizeTrait = ref.trait.element
val unsizeTypeParam = unsizeTrait.typeParamSingle ?: return SelectionResult.Err
val source = ctx.shallowResolve(ref.selfTy)
val target = ctx.shallowResolve(ref.trait.subst.typeSubst[unsizeTypeParam] ?: return SelectionResult.Err)
val okSelection = Selection(
impl = unsizeTrait,
nestedObligations = emptyList(),
subst = mapOf(unsizeTypeParam to target).toTypeSubst()
)
when {
// `T` -> `Trait`
target is TyTraitObject -> {
// TODO implement unsizing. Currently always allowed
TypeInferenceMarks.UnsizeToTraitObject.hit()
return SelectionResult.Ok(okSelection)
}
// `[T; n]` -> `[T]`
source is TyArray && target is TySlice -> {
if (ctx.combineTypes(target.elementType, source.base).isOk) {
TypeInferenceMarks.UnsizeArrayToSlice.hit()
return SelectionResult.Ok(okSelection)
}
}
// `Struct<T>` -> `Struct<U>`
source is TyAdt && target is TyAdt -> {
check(source.item == target.item) { "Guaranteed by assembleCandidates" }
check(source.item is RsStructItem) { "Guaranteed by assembleCandidates" }
val fields = source.item.fields
val lastField = fields.lastOrNull() ?: return SelectionResult.Err
val lastFieldType = lastField.typeReference?.type ?: return SelectionResult.Err
val unsizingParams = hashSetOf<TyTypeParameter>()
// TODO consider const params
lastFieldType.visitTypeParameters { ty ->
unsizingParams += ty
false
}
for (field in fields) {
if (field == lastField) break